Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 790608f020 | |||
| 473424ae23 | |||
| 9b831f7d95 | |||
| 498b326e45 | |||
| 56e4efec94 | |||
| a07f069ad0 | |||
| da15d299e6 | |||
| 7ef7c3f676 |
1038
package-lock.json
generated
1038
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
12
package.json
12
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/ai-utils",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.7",
|
||||
"description": "AI Utility library",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
@@ -25,14 +25,14 @@
|
||||
"watch": "npx vite build --watch"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.67.0",
|
||||
"@anthropic-ai/sdk": "^0.78.0",
|
||||
"@tensorflow/tfjs": "^4.22.0",
|
||||
"@xenova/transformers": "^2.17.2",
|
||||
"@ztimson/node-utils": "^1.0.4",
|
||||
"@ztimson/utils": "^0.27.9",
|
||||
"@ztimson/node-utils": "^1.0.7",
|
||||
"@ztimson/utils": "^0.28.13",
|
||||
"cheerio": "^1.2.0",
|
||||
"openai": "^6.6.0",
|
||||
"tesseract.js": "^6.0.1",
|
||||
"openai": "^6.22.0",
|
||||
"tesseract.js": "^7.0.0",
|
||||
"wavefile": "^11.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
29
src/asr.ts
29
src/asr.ts
@@ -9,15 +9,20 @@ import wavefile from 'wavefile';
|
||||
|
||||
let whisperPipeline: any;
|
||||
|
||||
export async function canDiarization(): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const proc = spawn('python', ['-c', 'import pyannote.audio']);
|
||||
export async function canDiarization(): Promise<string | null> {
|
||||
const checkPython = (cmd: string) => {
|
||||
return new Promise<boolean>((resolve) => {
|
||||
const proc = spawn(cmd, ['-c', 'import pyannote.audio']);
|
||||
proc.on('close', (code: number) => resolve(code === 0));
|
||||
proc.on('error', () => resolve(false));
|
||||
});
|
||||
};
|
||||
if(await checkPython('python3')) return 'python3';
|
||||
if(await checkPython('python')) return 'python';
|
||||
return null;
|
||||
}
|
||||
|
||||
async function runDiarization(audioPath: string, dir: string, token: string): Promise<any[]> {
|
||||
async function runDiarization(binary: string, audioPath: string, dir: string, token: string): Promise<any[]> {
|
||||
const script = `
|
||||
import sys
|
||||
import json
|
||||
@@ -37,7 +42,7 @@ print(json.dumps(segments))
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let output = '';
|
||||
const proc = spawn('python', ['-c', script, audioPath]);
|
||||
const proc = spawn(binary, ['-c', script, audioPath]);
|
||||
proc.stdout.on('data', (data: Buffer) => output += data.toString());
|
||||
proc.stderr.on('data', (data: Buffer) => console.error(data.toString()));
|
||||
proc.on('close', (code: number) => {
|
||||
@@ -105,30 +110,28 @@ function prepareAudioBuffer(file: string): [string, Float32Array] {
|
||||
}
|
||||
|
||||
parentPort?.on('message', async ({ file, speaker, model, modelDir, token }) => {
|
||||
let tempFile = null;
|
||||
try {
|
||||
if(!whisperPipeline) whisperPipeline = await pipeline('automatic-speech-recognition', `Xenova/${model}`, {cache_dir: modelDir, quantized: true});
|
||||
|
||||
// Prepare audio file
|
||||
const [f, buffer] = prepareAudioBuffer(file);
|
||||
|
||||
// Fetch transcript and speakers
|
||||
const hasDiarization = speaker && await canDiarization();
|
||||
tempFile = f !== file ? f : null;
|
||||
const hasDiarization = await canDiarization();
|
||||
const [transcript, speakers] = await Promise.all([
|
||||
whisperPipeline(buffer, {return_timestamps: speaker ? 'word' : false}),
|
||||
(!speaker || !token || !hasDiarization) ? Promise.resolve(): runDiarization(f, modelDir, token),
|
||||
(!speaker || !token || !hasDiarization) ? Promise.resolve(): runDiarization(hasDiarization, f, modelDir, token),
|
||||
]);
|
||||
if(file != f) rmSync(f, { recursive: true, force: true });
|
||||
|
||||
// Return any results / errors if no more processing required
|
||||
const text = transcript.text?.trim() || null;
|
||||
if(!speaker) return parentPort?.postMessage({ text });
|
||||
if(!token) return parentPort?.postMessage({ text, error: 'HuggingFace token required' });
|
||||
if(!hasDiarization) return parentPort?.postMessage({ text, error: 'Speaker diarization unavailable' });
|
||||
|
||||
// Combine transcript and speakers
|
||||
const combined = combineSpeakerTranscript(transcript.chunks || [], speakers || []);
|
||||
parentPort?.postMessage({ text: combined });
|
||||
} catch (err: any) {
|
||||
parentPort?.postMessage({ error: err.stack || err.message });
|
||||
} finally {
|
||||
if(tempFile) rmSync(tempFile, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
74
src/audio.ts
74
src/audio.ts
@@ -5,44 +5,68 @@ import {canDiarization} from './asr.ts';
|
||||
import {dirname, join} from 'path';
|
||||
|
||||
export class Audio {
|
||||
private busy = false;
|
||||
private currentJob: any;
|
||||
private queue: Array<{file: string, model: string, speaker: boolean | 'id', modelDir: string, token: string, resolve: any, reject: any}> = [];
|
||||
private worker: Worker | null = null;
|
||||
|
||||
constructor(private ai: Ai) {}
|
||||
|
||||
private processQueue() {
|
||||
if(this.busy || !this.queue.length) return;
|
||||
|
||||
this.busy = true;
|
||||
const job = this.queue.shift()!;
|
||||
if(!this.worker) {
|
||||
this.worker = new Worker(join(dirname(fileURLToPath(import.meta.url)), 'asr.js'));
|
||||
this.worker.on('message', this.handleMessage.bind(this));
|
||||
this.worker.on('error', this.handleError.bind(this));
|
||||
}
|
||||
|
||||
this.currentJob = job;
|
||||
this.worker.postMessage({file: job.file, model: job.model, speaker: job.speaker, modelDir: job.modelDir, token: job.token});
|
||||
}
|
||||
|
||||
private handleMessage({text, warning, error}: any) {
|
||||
const job = this.currentJob!;
|
||||
this.busy = false;
|
||||
if(error) job.reject(new Error(error));
|
||||
else {
|
||||
if(warning) console.warn(warning);
|
||||
job.resolve(text);
|
||||
}
|
||||
this.processQueue();
|
||||
}
|
||||
|
||||
private handleError(err: Error) {
|
||||
if(this.currentJob) {
|
||||
this.currentJob.reject(err);
|
||||
this.busy = false;
|
||||
this.processQueue();
|
||||
}
|
||||
}
|
||||
|
||||
asr(file: string, options: { model?: string; speaker?: boolean | 'id' } = {}): AbortablePromise<string | null> {
|
||||
const { model = this.ai.options.asr || 'whisper-base', speaker = false } = options;
|
||||
let aborted = false;
|
||||
const abort = () => { aborted = true; };
|
||||
|
||||
let p = new Promise<string | null>((resolve, reject) => {
|
||||
const worker = new Worker(join(dirname(fileURLToPath(import.meta.url)), 'asr.js'));
|
||||
const handleMessage = ({ text, warning, error }: any) => {
|
||||
worker.terminate();
|
||||
if(aborted) return;
|
||||
if(error) reject(new Error(error));
|
||||
else {
|
||||
if(warning) console.warn(warning);
|
||||
resolve(text);
|
||||
}
|
||||
};
|
||||
const handleError = (err: Error) => {
|
||||
worker.terminate();
|
||||
if(!aborted) reject(err);
|
||||
};
|
||||
worker.on('message', handleMessage);
|
||||
worker.on('error', handleError);
|
||||
worker.on('exit', (code) => {
|
||||
if(code !== 0 && !aborted) reject(new Error(`Worker exited with code ${code}`));
|
||||
this.queue.push({file, model, speaker, modelDir: <string>this.ai.options.path, token: <string>this.ai.options.hfToken,
|
||||
resolve: (text: string | null) => !aborted && resolve(text),
|
||||
reject: (err: Error) => !aborted && reject(err)
|
||||
});
|
||||
worker.postMessage({file, model, speaker, modelDir: this.ai.options.path, token: this.ai.options.hfToken});
|
||||
this.processQueue();
|
||||
});
|
||||
|
||||
// Name speakers using AI
|
||||
if(options.speaker == 'id') {
|
||||
if(!this.ai.language.defaultModel) throw new Error('Configure an LLM for advanced ASR speaker detection');
|
||||
p = p.then(async transcript => {
|
||||
if(!transcript) return transcript;
|
||||
const names = await this.ai.language.json(transcript, '{1: "Detected Name"}', {
|
||||
system: 'Use this following transcript to identify speakers. Only identify speakers you are sure about',
|
||||
temperature: 0.2,
|
||||
let chunks = this.ai.language.chunk(transcript, 500, 0);
|
||||
if(chunks.length > 4) chunks = [...chunks.slice(0, 3), <string>chunks.at(-1)];
|
||||
const names = await this.ai.language.json(chunks.join('\n'), '{1: "Detected Name", 2: "Second Name"}', {
|
||||
system: 'Use the following transcript to identify speakers. Only identify speakers you are positive about, dont mention speakers you are unsure about in your response',
|
||||
temperature: 0.1,
|
||||
});
|
||||
Object.entries(names).forEach(([speaker, name]) => {
|
||||
transcript = (<string>transcript).replaceAll(`[Speaker ${speaker}]`, `[${name}]`);
|
||||
@@ -54,5 +78,5 @@ export class Audio {
|
||||
return Object.assign(p, { abort });
|
||||
}
|
||||
|
||||
canDiarization = canDiarization;
|
||||
canDiarization = () => canDiarization().then(resp => !!resp);
|
||||
}
|
||||
|
||||
20
src/llm.ts
20
src/llm.ts
@@ -255,11 +255,11 @@ class LLM {
|
||||
/**
|
||||
* Create a vector representation of a string
|
||||
* @param {object | string} target Item that will be embedded (objects get converted)
|
||||
* @param {number} maxTokens Chunking size. More = better context, less = more specific (Search by paragraphs or lines)
|
||||
* @param {number} overlapTokens Includes previous X tokens to provide continuity to AI (In addition to max tokens)
|
||||
* @param {maxTokens?: number, overlapTokens?: number} opts Options for embedding such as chunk sizes
|
||||
* @returns {Promise<Awaited<{index: number, embedding: number[], text: string, tokens: number}>[]>} Chunked embeddings
|
||||
*/
|
||||
embedding(target: object | string, maxTokens = 500, overlapTokens = 50) {
|
||||
async embedding(target: object | string, opts: {maxTokens?: number, overlapTokens?: number} = {}) {
|
||||
let {maxTokens = 500, overlapTokens = 50} = opts;
|
||||
const embed = (text: string): Promise<number[]> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const worker = new Worker(join(dirname(fileURLToPath(import.meta.url)), 'embedder.js'));
|
||||
@@ -279,13 +279,13 @@ class LLM {
|
||||
worker.postMessage({text, model: this.ai.options?.embedder || 'bge-small-en-v1.5', modelDir: this.ai.options.path});
|
||||
});
|
||||
};
|
||||
const chunks = this.chunk(target, maxTokens, overlapTokens);
|
||||
return Promise.all(chunks.map(async (text, index) => ({
|
||||
index,
|
||||
embedding: await embed(text),
|
||||
text,
|
||||
tokens: this.estimateTokens(text),
|
||||
})));
|
||||
const chunks = this.chunk(target, maxTokens, overlapTokens), results: any[] = [];
|
||||
for(let i = 0; i < chunks.length; i++) {
|
||||
const text= chunks[i];
|
||||
const embedding = await embed(text);
|
||||
results.push({index: i, embedding, text, tokens: this.estimateTokens(text)});
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,8 +2,26 @@ import {createWorker} from 'tesseract.js';
|
||||
import {AbortablePromise, Ai} from './ai.ts';
|
||||
|
||||
export class Vision {
|
||||
private worker: any = null;
|
||||
private queue: Array<{ path: string, resolve: any, reject: any }> = [];
|
||||
private busy = false;
|
||||
|
||||
constructor(private ai: Ai) { }
|
||||
constructor(private ai: Ai) {}
|
||||
|
||||
private async processQueue() {
|
||||
if(this.busy || !this.queue.length) return;
|
||||
this.busy = true;
|
||||
const job = this.queue.shift()!;
|
||||
if(!this.worker) this.worker = await createWorker(this.ai.options.ocr || 'eng', 2, {cachePath: this.ai.options.path});
|
||||
try {
|
||||
const {data} = await this.worker.recognize(job.path);
|
||||
job.resolve(data.text.trim() || null);
|
||||
} catch(err) {
|
||||
job.reject(err);
|
||||
}
|
||||
this.busy = false;
|
||||
this.processQueue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert image to text using Optical Character Recognition
|
||||
@@ -11,13 +29,16 @@ export class Vision {
|
||||
* @returns {AbortablePromise<string | null>} Promise of extracted text with abort method
|
||||
*/
|
||||
ocr(path: string): AbortablePromise<string | null> {
|
||||
let worker: any;
|
||||
const p = new Promise<string | null>(async res => {
|
||||
worker = await createWorker(this.ai.options.ocr || 'eng', 2, {cachePath: this.ai.options.path});
|
||||
const {data} = await worker.recognize(path);
|
||||
await worker.terminate();
|
||||
res(data.text.trim() || null);
|
||||
let aborted = false;
|
||||
const abort = () => { aborted = true; };
|
||||
const p = new Promise<string | null>((resolve, reject) => {
|
||||
this.queue.push({
|
||||
path,
|
||||
resolve: (text: string | null) => !aborted && resolve(text),
|
||||
reject: (err: Error) => !aborted && reject(err)
|
||||
});
|
||||
return Object.assign(p, {abort: () => worker?.terminate()});
|
||||
this.processQueue();
|
||||
});
|
||||
return Object.assign(p, {abort});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {defineConfig} from 'vite';
|
||||
import dts from 'vite-plugin-dts';
|
||||
import {resolve} from 'path';
|
||||
|
||||
export default defineConfig({
|
||||
build: {
|
||||
|
||||
Reference in New Issue
Block a user