vidSub / worker.js
vqh159's picture
Deploy upgraded vidSub 2.0 on free Static Space + FFmpeg.wasm + Cloud/Local hybrid support
7e1f9dd verified
Raw History Blame Contribute Delete
6.71 kB
import {pipeline,env,AutoProcessor,AutoModel,cos_sim} from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1/dist/transformers.min.js';
env.allowLocalModels=false;
env.backends.onnx.wasm.numThreads=1;
const status=message=>postMessage({status:message});
function loading(label){
status(label);
return {device:'wasm',dtype:'q8',progress_callback:p=>{
if(p.status==='progress'&&p.total)status(label+' · '+p.file+' '+Math.round(p.loaded/p.total*100)+'%');
}};
}
function normalize(v){
let s=0;for(let i=0;i<v.length;i++)s+=v[i]*v[i];
const n=Math.sqrt(s)||1;
const out=new Float32Array(v.length);
for(let i=0;i<v.length;i++)out[i]=v[i]/n;
return out;
}
async function transcribe(audio,count,whisperModel='tiny'){
const modelMap={tiny:'Xenova/whisper-tiny',base:'Xenova/whisper-base',small:'Xenova/whisper-small'};
const repo=modelMap[whisperModel]||'Xenova/whisper-tiny';
const asr=await pipeline('automatic-speech-recognition',repo,loading('Tải Whisper ('+whisperModel+')'));
status('Đang nhận lời thoại…');
const result=await asr(audio,{return_timestamps:true,chunk_length_s:30,stride_length_s:5,task:'transcribe'});
await asr.dispose();
const duration=audio.length/16000;
const rows=result.chunks.map((r,i)=>({start:r.timestamp[0]??0,end:Math.min(duration,r.timestamp[1]??result.chunks[i+1]?.timestamp[0]??duration),text:r.text.trim(),speaker:''})).filter(r=>r.text&&r.end>r.start);
if(rows.length<2)return rows;
const id='Xenova/wavlm-base-plus-sv', opts=loading('Tải model phân biệt giọng');
const proc=await AutoProcessor.from_pretrained(id), model=await AutoModel.from_pretrained(id,opts), samplesByTime=[];
for(const [i,r] of rows.entries()){
status('Ước lượng người nói · '+(i+1)+'/'+rows.length);
const clip=audio.subarray(Math.round(r.start*16000),Math.round(Math.min(r.end,r.start+6)*16000));
if(clip.length<12000)continue;
const {embeddings}=await model(await proc(clip)), vector=normalize(embeddings.data);
samplesByTime.push({i,vector});
}
const voices=[];
const samples=samplesByTime.sort((a,b)=>(rows[b.i].end-rows[b.i].start)-(rows[a.i].end-rows[a.i].start));
const seeds=samples.slice(0,1);
while(count>0&&seeds.length<Math.min(count,samples.length)){
const candidates=samples.filter(s=>!seeds.includes(s));
const distance=s=>Math.max(...seeds.map(v=>cos_sim(v.vector,s.vector)));
seeds.push(candidates.reduce((a,b)=>distance(a)<distance(b)?a:b));
}
if(count>0)for(const seed of seeds)voices.push({sum:Float32Array.from(seed.vector),members:[]});
for(const sample of samples){
const scores=voices.map(v=>cos_sim(normalize(v.sum),sample.vector));
const best=scores.length?Math.max(...scores):-1;
let voice=voices.length&&(count>0||best>=0.78)?voices[scores.indexOf(best)]:null;
if(!voice){voice={sum:new Float32Array(sample.vector.length),members:[]};voices.push(voice);}
for(let i=0;i<voice.sum.length;i++)voice.sum[i]+=sample.vector[i];
voice.members.push(sample.i);
}
voices.sort((a,b)=>Math.min(...a.members)-Math.min(...b.members));
voices.forEach((voice,k)=>voice.members.forEach(i=>{rows[i].speaker='Giọng '+(k+1);}));
await model.dispose();return rows;
}
self.onmessage=async({data})=>{
try{
const rows=data.rows??await transcribe(data.audio,data.count,data.whisperModel);
if(!rows.length)throw Error('Không tìm thấy lời thoại có thời gian.');
if(data.language==='vi'||data.method==='none'){rows.forEach(r=>{r.vi=r.text;});postMessage({rows});return;}
const englishWords=rows.map(r=>r.text).join(' ').match(/\b(?:the|i|you|we|your|my|hello|is|are|can|when|will|have|how|this|that|from|do|me)\b/gi)||[];
const isEnglish=data.language==='en'||(!data.language&&englishWords.length>=3&&!/[\u3040-\u30ff\uac00-\ud7af\u4e00-\u9fff]/.test(rows.map(r=>r.text).join('')));
if(isEnglish){
const mt=await pipeline('translation','Xenova/opus-mt-en-vi',loading('Tải model Anh → Việt'));
const speakers=[...new Set(rows.map(r=>r.speaker).filter(Boolean))];
const child=rows.find(r=>r.speaker&&/^(?:hey,?\s+)?(?:mom|mum|mother)[,!?.]/i.test(r.text))?.speaker;
const mother=speakers.find(s=>/^(mom|mum|mother|mẹ)$/i.test(s)) || (child&&speakers.length===2?speakers.find(s=>s!==child):null);
const family=mother&&speakers.length===2&&child&&child!==mother;
const profiles=new Map();
for(const line of data.notes.split('\n')){
const match=line.match(/^([^:]+):\s*([\p{L} ]+)\s*\/\s*([\p{L} ]+)$/u);
if(match)profiles.set(match[1].trim(),[match[2].trim(),match[3].trim()]);
}
for(const [i,row] of rows.entries()){
status('Dịch Anh → Việt · '+(i+1)+'/'+rows.length);
const sentence=/[\p{L}\p{N}]$/u.test(row.text)?row.text+'.':row.text;
const result=await mt(sentence,{max_new_tokens:Math.min(160,16+row.text.length*2),num_beams:3,no_repeat_ngram_size:3});
row.vi=result[0].translation_text.trim();
const profile=profiles.get(row.speaker)||(family?(row.speaker===mother?['mẹ','con']:['con','mẹ']):null);
if(data.method!=='en'&&profile&&row.speaker){
const [first,second]=profile;
row.vi=row.vi.replace(/(?<![\p{L}])(?:tôi|bạn|anh)(?![\p{L}]|\s+(?:trai|gái|bè|ấy|ta|họ|thân|em)(?![\p{L}]))/giu,(v,offset)=>{
const word=v.toLowerCase()==='tôi'?first:second;
return !offset&&v[0]===v[0].toUpperCase()?word[0].toUpperCase()+word.slice(1):word;
});
}
if(!row.vi)throw Error('Không dịch được đoạn '+(i+1));
}
postMessage({rows});return;
}
const translate=await pipeline('text-generation','onnx-community/Qwen2.5-0.5B-Instruct',{...loading('Tải model dịch Qwen'),dtype:'q4'});
for(const [i,r] of rows.entries()){
status('Dịch theo ngữ cảnh · '+(i+1)+'/'+rows.length);
const previous=rows.slice(Math.max(0,i-2),i).map(p=>(p.speaker||'')+' '+p.vi).join(' / ');
const messages=[{role:'system',content:'Translate the user sentence into Vietnamese. Output only the translation. Scene: '+data.notes+' Speaker: '+r.speaker+' Previous Vietnamese dialogue: '+previous},{role:'user',content:r.text}];
const response=await translate(messages,{max_new_tokens:180,do_sample:false,return_full_text:false});
const generated=response[0].generated_text;
r.vi=(Array.isArray(generated)?generated.at(-1)?.content:generated)?.trim().split(/\r?\n/)[0]?.trim();
if(!r.vi)throw Error('Model trả về câu trống ở đoạn '+(i+1));
}
postMessage({rows});
}catch(e){postMessage({error:e.message||String(e)});}
};