import json, subprocess, hashlib, os, re, sys, numpy as np, soundfile as sf import pick from pick import K, frames, after_okay, SR, ph, fade, asr, clean_onset_plain import difflib from expr import excite from kokoro_onnx import Kokoro pick.FB.update({"fifi":"fˈifi","vinny":"vˈɪni","woohoo":"wˌuhˈu","vroom":"vɹˈum","nom":"nˈɑm","pup":"pˈʌp","snore":"snˈɔɹ","dino":"dˈInO","ta":"tə","da":"dˈɑ","mmm":"mˈʌm","woof":"wˈʊf","wanna":"wˈɑnə","boing":"bˈɔɪŋ","munchy":"mˈʌnʧi","glug":"ɡlˈʌɡ","slurp":"slˈɜɹp","yippee":"jˈɪpi","hiss":"hˈɪs","fifi’s":"fˈifiz","fifi's":"fˈifiz","vinny’s":"vˈɪniz","vinny's":"vˈɪniz","sunny’s":"sˈʌniz","sunny's":"sˈʌniz"}) L=json.load(open('/tmp/squad_lines.json')) def key(t): t=t.lower().replace("’","'"); t=re.sub(r"[^a-z0-9' ]+"," ",t); return re.sub(r"\s+"," ",t).strip() gap=lambda s:np.zeros(int(s*SR),np.float32) def wclip(w,slow=False,mid=False): w=w.lower() cands=([f"/tmp/words/n_{w}.wav"] if mid else [])+[f"/tmp/words/{'slow_' if slow else 'w_'}{w}.wav",f"/tmp/words/w_{w}.wav"] for p in cands: if os.path.exists(p): a,_=sf.read(p,dtype='float32'); return a raise SystemExit("no clip "+w) TARGET=["thunder's","thunder","fifi's","fifi","vinny's","vinny","sunny's","sunny","teeth","mouth","thumb","three","think","bath","fish","fan","feet","fox","fork","five","van","vase","violin","volcano","sun","sock","soap","soup","six","sandwich"] TRE=re.compile(r"\b("+"|".join(re.escape(w).replace("'","[’']") for w in TARGET)+r")\b",re.I) _NC={} def _sc(t,a): n=lambda x:re.sub(r"[^a-z ]","",x.lower().replace("’","'").replace("'","")).split() return difflib.SequenceMatcher(None,n(t),n(asr(a))).ratio() MODE={'calm':(.9,1.7,1.5),'hype':(.97,2.1,2.0)} CUR=['hype'] CALM=re.compile(r"(Your turn|tongue|teeth|lip|blow|[Ss]mile|hiss out|motor|Listen|[Tt]ap |Say each|Make .*sound|Open wide|Keep your|together|Put them|For (Thunder|Fifi|Vinny|Sunny)|make it long|can’t hear)") def narr_chunk(t,speed=None): sp,g,sh=MODE[CUR[0]] key=(t,CUR[0]) if key in _NC: return _NC[key] _NC[key]=excite(_narr_raw(t,sp),g,sh) return _NC[key] def _narr_raw(t,speed=.9): a,_=K().create("ˈOkA. "+ph(t),voice="af_heart",speed=speed,is_phonemes=True,trim=False) a=after_okay(a); f,e,z=frames(a); pk=e.max(); idx=np.where(e>0.01*pk)[0] c1=fade(a[max(0,idx[0]-1)*f:min(len(a),(idx[-1]+6)*f)],25) b,_=K().create(ph(t),voice="af_heart",speed=speed,is_phonemes=True,trim=False) c2=fade(clean_onset_plain(b),25) s1,s2=_sc(t,c1),_sc(t,c2) return c1 if s1>=s2 else c2 def sentence(p): """One sentence: Kokoro for the words around, verified clips for the target sounds.""" out=[];pos=0;ms=list(TRE.finditer(p)) for i,m in enumerate(ms): before=p[pos:m.start()].strip() if re.search(r"[A-Za-z]",before): out.append(narr_chunk(before)); out.append(gap(.12 if before[-1] not in ",.!?:" else .3)) w=m.group(1).lower().replace("’","'") nxt=p[m.end():].strip() out.append(wclip(w,mid=bool(re.match(r"[a-z]",nxt)))) pos=m.end() rest=p[pos:].lstrip() if re.search(r"[A-Za-z]",rest): out.append(gap(.35 if rest[:1] in ",.!?:" else .1)) pos=m.end() # drop punctuation right after the word mm=re.match(r"\s*[,.!?:]+",p[pos:]); if mm: pos+=mm.end() tail=p[pos:].strip() if re.search(r"[A-Za-z]",tail): out.append(narr_chunk(tail)) return np.concatenate(out) def narr(t): parts=[p.strip() for p in re.findall(r'[^.!?:]+[.!?:]*',t) if p.strip()] out=[] for i,p in enumerate(parts): out.append(sentence(p)) if ibest[0]+.05: best=(sc,y,strength) if sc>=.85: return y if best[0]>=.7: break print(' friend best',round(best[0],2),'strength',best[2],text,flush=True) return best[1] def build(text,pre): if pre in("w:","slow:"): return wclip(text,pre=="slow:") if pre.startswith("v_"): return friend(text,pre[2:-1]) CUR[0]='calm' if CALM.search(text) else 'hype' m=re.fullmatch(r"Your turn! Say: (.+)\.",text) if m: return np.concatenate([narr("Your turn! Say:"),gap(.35),wclip(m.group(1))]) return narr(text) out=sys.argv[1]; os.makedirs(out,exist_ok=True) if not os.environ.get('ONLY'): for f in os.listdir(out): if f!="silence.mp3": os.remove(os.path.join(out,f)) os.makedirs("/tmp/sqclips",exist_ok=True) man={};log={} ONLY=os.environ.get('ONLY') if ONLY: man=json.load(open(sys.argv[2])); log=json.load(open('/tmp/sqcliplog.json')) for text,pre in L: kk=pre+key(text) if ONLY and not pre.startswith(ONLY): continue if kk in man and not ONLY: continue a=np.concatenate([gap(.04),build(text,pre),gap(.05)]).astype(np.float32) a=a/max(1e-6,np.abs(a).max())*0.89 fn=hashlib.md5(kk.encode()).hexdigest()[:10] wav=f"/tmp/sqclips/{fn}.wav"; sf.write(wav,a,SR) subprocess.run(["ffmpeg","-y","-loglevel","error","-i",wav,"-ac","1","-b:a","64k",f"{out}/{fn}.mp3"],check=True) man[kk]=fn+".mp3"; log[kk]=(text,wav) print(len(man),text[:70],flush=True) json.dump(man,open(sys.argv[2],"w")); json.dump(log,open("/tmp/sqcliplog.json","w")) print("clips",len(man))