Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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",
|
"name": "@ztimson/ai-utils",
|
||||||
"version": "0.7.0",
|
"version": "0.7.4",
|
||||||
"description": "AI Utility library",
|
"description": "AI Utility library",
|
||||||
"author": "Zak Timson",
|
"author": "Zak Timson",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
@@ -25,14 +25,14 @@
|
|||||||
"watch": "npx vite build --watch"
|
"watch": "npx vite build --watch"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/sdk": "^0.67.0",
|
"@anthropic-ai/sdk": "^0.78.0",
|
||||||
"@tensorflow/tfjs": "^4.22.0",
|
"@tensorflow/tfjs": "^4.22.0",
|
||||||
"@xenova/transformers": "^2.17.2",
|
"@xenova/transformers": "^2.17.2",
|
||||||
"@ztimson/node-utils": "^1.0.4",
|
"@ztimson/node-utils": "^1.0.7",
|
||||||
"@ztimson/utils": "^0.27.9",
|
"@ztimson/utils": "^0.28.13",
|
||||||
"cheerio": "^1.2.0",
|
"cheerio": "^1.2.0",
|
||||||
"openai": "^6.6.0",
|
"openai": "^6.22.0",
|
||||||
"tesseract.js": "^6.0.1",
|
"tesseract.js": "^7.0.0",
|
||||||
"wavefile": "^11.0.0"
|
"wavefile": "^11.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
19
src/asr.ts
19
src/asr.ts
@@ -9,15 +9,20 @@ import wavefile from 'wavefile';
|
|||||||
|
|
||||||
let whisperPipeline: any;
|
let whisperPipeline: any;
|
||||||
|
|
||||||
export async function canDiarization(): Promise<boolean> {
|
export async function canDiarization(): Promise<string | null> {
|
||||||
return new Promise((resolve) => {
|
const checkPython = (cmd: string) => {
|
||||||
const proc = spawn('python', ['-c', 'import pyannote.audio']);
|
return new Promise<boolean>((resolve) => {
|
||||||
|
const proc = spawn(cmd, ['-c', 'import pyannote.audio']);
|
||||||
proc.on('close', (code: number) => resolve(code === 0));
|
proc.on('close', (code: number) => resolve(code === 0));
|
||||||
proc.on('error', () => resolve(false));
|
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 = `
|
const script = `
|
||||||
import sys
|
import sys
|
||||||
import json
|
import json
|
||||||
@@ -37,7 +42,7 @@ print(json.dumps(segments))
|
|||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let output = '';
|
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.stdout.on('data', (data: Buffer) => output += data.toString());
|
||||||
proc.stderr.on('data', (data: Buffer) => console.error(data.toString()));
|
proc.stderr.on('data', (data: Buffer) => console.error(data.toString()));
|
||||||
proc.on('close', (code: number) => {
|
proc.on('close', (code: number) => {
|
||||||
@@ -112,10 +117,10 @@ parentPort?.on('message', async ({ file, speaker, model, modelDir, token }) => {
|
|||||||
const [f, buffer] = prepareAudioBuffer(file);
|
const [f, buffer] = prepareAudioBuffer(file);
|
||||||
|
|
||||||
// Fetch transcript and speakers
|
// Fetch transcript and speakers
|
||||||
const hasDiarization = speaker && await canDiarization();
|
const hasDiarization = await canDiarization();
|
||||||
const [transcript, speakers] = await Promise.all([
|
const [transcript, speakers] = await Promise.all([
|
||||||
whisperPipeline(buffer, {return_timestamps: speaker ? 'word' : false}),
|
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 });
|
if(file != f) rmSync(f, { recursive: true, force: true });
|
||||||
|
|
||||||
|
|||||||
@@ -40,9 +40,11 @@ export class Audio {
|
|||||||
if(!this.ai.language.defaultModel) throw new Error('Configure an LLM for advanced ASR speaker detection');
|
if(!this.ai.language.defaultModel) throw new Error('Configure an LLM for advanced ASR speaker detection');
|
||||||
p = p.then(async transcript => {
|
p = p.then(async transcript => {
|
||||||
if(!transcript) return transcript;
|
if(!transcript) return transcript;
|
||||||
const names = await this.ai.language.json(transcript, '{1: "Detected Name"}', {
|
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"}', {
|
||||||
system: 'Use this following transcript to identify speakers. Only identify speakers you are sure about',
|
system: 'Use this following transcript to identify speakers. Only identify speakers you are sure about',
|
||||||
temperature: 0.2,
|
temperature: 0.1,
|
||||||
});
|
});
|
||||||
Object.entries(names).forEach(([speaker, name]) => {
|
Object.entries(names).forEach(([speaker, name]) => {
|
||||||
transcript = (<string>transcript).replaceAll(`[Speaker ${speaker}]`, `[${name}]`);
|
transcript = (<string>transcript).replaceAll(`[Speaker ${speaker}]`, `[${name}]`);
|
||||||
@@ -54,5 +56,5 @@ export class Audio {
|
|||||||
return Object.assign(p, { abort });
|
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
|
* Create a vector representation of a string
|
||||||
* @param {object | string} target Item that will be embedded (objects get converted)
|
* @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 {maxTokens?: number, overlapTokens?: number} opts Options for embedding such as chunk sizes
|
||||||
* @param {number} overlapTokens Includes previous X tokens to provide continuity to AI (In addition to max tokens)
|
|
||||||
* @returns {Promise<Awaited<{index: number, embedding: number[], text: string, tokens: number}>[]>} Chunked embeddings
|
* @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[]> => {
|
const embed = (text: string): Promise<number[]> => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const worker = new Worker(join(dirname(fileURLToPath(import.meta.url)), 'embedder.js'));
|
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});
|
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);
|
const chunks = this.chunk(target, maxTokens, overlapTokens), results: any[] = [];
|
||||||
return Promise.all(chunks.map(async (text, index) => ({
|
for(let i = 0; i < chunks.length; i++) {
|
||||||
index,
|
const text= chunks[i];
|
||||||
embedding: await embed(text),
|
const embedding = await embed(text);
|
||||||
text,
|
results.push({index: i, embedding, text, tokens: this.estimateTokens(text)});
|
||||||
tokens: this.estimateTokens(text),
|
}
|
||||||
})));
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import {defineConfig} from 'vite';
|
import {defineConfig} from 'vite';
|
||||||
import dts from 'vite-plugin-dts';
|
import dts from 'vite-plugin-dts';
|
||||||
import {resolve} from 'path';
|
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
build: {
|
build: {
|
||||||
|
|||||||
Reference in New Issue
Block a user