Datasets:
Download generation/batch1/worker.py from n4ze3m/tiny-voca: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/datasets/n4ze3m/tiny-voca/resolve/main/generation/batch1/worker.py
- Command line
-
hf download hf://datasets/n4ze3m/tiny-voca/generation/batch1/worker.py
-
curl -L -o worker.py https://huggingface.co/datasets/n4ze3m/tiny-voca/resolve/main/generation/batch1/worker.py
14 kB
| import os,time,json,pathlib,sqlite3,hashlib,random,io,re,traceback,subprocess,concurrent.futures,collections,signal | |
| os.environ['HF_HUB_DISABLE_XET']='1' | |
| import numpy as np,soundfile as sf,torch | |
| from scipy.signal import resample_poly | |
| from huggingface_hub import HfApi,hf_hub_download | |
| from datasets import Dataset,Audio | |
| from qwen_tts import Qwen3TTSModel | |
| from faster_whisper import WhisperModel | |
| from transformers.models.whisper.english_normalizer import EnglishTextNormalizer | |
| from jiwer import wer | |
| ROOT=pathlib.Path('/workspace/tiny-voca');OUT=ROOT/'release';AUDIO=ROOT/'audio';OUT.mkdir(exist_ok=True);AUDIO.mkdir(exist_ok=True);(OUT/'data').mkdir(exist_ok=True) | |
| REPO='n4ze3m/tiny-voca';SOURCE='n4ze3m/american-english-two-voice-tts-text-v01';SOURCE_REV='d9ec4bdb920a3b4b4e3bcb309a2c166bcbe034db';MODEL='Qwen/Qwen3-TTS-12Hz-1.7B-Base';START=time.time();BATCH=8 | |
| TOKEN=pathlib.Path('/workspace/hf-token') | |
| def token():return TOKEN.read_text().strip() | |
| os.environ['HF_TOKEN']=token() | |
| DB=sqlite3.connect(ROOT/'state.sqlite');DB.execute('CREATE TABLE IF NOT EXISTS clips(id TEXT PRIMARY KEY, status TEXT, attempts INTEGER, exported INTEGER DEFAULT 0, payload TEXT)');DB.commit() | |
| stop=False | |
| signal.signal(signal.SIGTERM,lambda *_:globals().__setitem__('stop',True)) | |
| def should_stop():return stop or (ROOT/'STOP').exists() | |
| def write_json(p,value): | |
| tmp=p.with_suffix(p.suffix+'.tmp');tmp.write_text(json.dumps(value,indent=2));os.replace(tmp,p) | |
| def progress(stage,extra=None): | |
| counts=dict(DB.execute('SELECT status,count(*) FROM clips GROUP BY status').fetchall());d={'project':'tiny-voca','status':stage,'target_clips':9810,'counts':counts,'processed':sum(counts.values()),'exported':DB.execute('SELECT count(*) FROM clips WHERE exported=1').fetchone()[0],'elapsed_seconds_this_run':round(time.time()-START),'updated_unix':time.time(),'repo':REPO} | |
| if extra:d.update(extra) | |
| write_json(ROOT/'progress.json',d);return d | |
| progress('initializing') | |
| api=HfApi(token=token());api.create_repo(REPO,repo_type='dataset',private=True,exist_ok=True) | |
| assert api.dataset_info(REPO).private | |
| rows=[] | |
| for split in ['train','validation','test']: | |
| p=hf_hub_download(SOURCE,split+'.jsonl',repo_type='dataset',revision=SOURCE_REV,token=token()) | |
| rows += [json.loads(l) for l in pathlib.Path(p).read_text().splitlines()] | |
| assert len(rows)==4905 | |
| jobs=[] | |
| for row in sorted(rows,key=lambda r:(r['character_count'],r['id'])): | |
| for voice in ['F2','M2']:jobs.append({'id':row['id']+'_'+voice,'voice':voice,'row':row}) | |
| refs={r['id']:r for r in json.loads(pathlib.Path('/workspace/auditions/release/voices.json').read_text())} | |
| (OUT/'references').mkdir(exist_ok=True) | |
| for v in ['F2','M2']:(OUT/'references'/(v+'.wav')).write_bytes(pathlib.Path('/workspace/auditions/release',v+'.wav').read_bytes()) | |
| write_json(OUT/'voices.json',{v:refs[v] for v in ['F2','M2']}) | |
| write_json(OUT/'generation_config.json',{'model':MODEL,'source':SOURCE,'source_revision':SOURCE_REV,'voices':['F2','M2'],'batch_size':BATCH,'seed':20261113,'sample_rate':24000,'format':'FLAC PCM16','max_new_tokens':600,'max_retries_per_clip':1,'normalized_wer_threshold':0.15,'minimum_duration':0.5,'maximum_duration':35,'requested_style':'neutral','human_review':'Only pilot manually approved by user; full corpus screened automatically.'}) | |
| (OUT/'worker.py').write_text(pathlib.Path(__file__).read_text()) | |
| (OUT/'requirements.txt').write_text(subprocess.check_output(['/venv/main/bin/python','-m','pip','freeze'],text=True)) | |
| (OUT/'README.md').write_text('''--- | |
| language: en | |
| task_categories: | |
| - text-to-speech | |
| license: other | |
| license_name: mixed-source-terms | |
| license_link: LICENSE.md | |
| configs: | |
| - config_name: default | |
| data_files: | |
| - split: train | |
| path: data/train-*.parquet | |
| - split: validation | |
| path: data/validation-*.parquet | |
| - split: test | |
| path: data/test-*.parquet | |
| --- | |
| # tiny-voca | |
| An American English synthetic two-voice TTS corpus, generated using Qwen3-TTS 1.7B Base with fixed original VoiceDesign references selected by the owner: **F2** (female) and **M2** (male). This is training data, not a trained small model. See progress.json for current completion status. Partial checkpoints are uploaded during generation. | |
| The target is 9,810 utterances: each of 4,905 scripts in both voices. Source text splits are preserved. Accepted audio is embedded as 24 kHz PCM16 FLAC inside Parquet shards with Hugging Face Audio feature metadata. The audio bytes are included; there are no dependencies on the Vast filesystem. Original source IDs and license labels are retained. Source: https://huggingface.co/datasets/n4ze3m/american-english-two-voice-tts-text-v01 . | |
| ## Quality screening | |
| Whisper small.en CPU int8 transcription is compared using English normalization and word error rate. Clips with normalized WER above 0.15, invalid samples, excessive silence, implausible speech rate or duration outside 0.5-35 seconds are flagged. Flagged clips get one new generation attempt; persistent failures are excluded from the training shards and listed in review.jsonl. ASR can make mistakes; this is screening, not a guarantee of speech fidelity, voice similarity or naturalness. No full-corpus human listening evaluation is claimed. Peak normalization does not change speed or pitch. Styles are not verified emotion labels. | |
| The voice references and exact prompts are included under references/ and voices.json. Each record contains its generation seed, batch and attempt. The approved pilot is https://huggingface.co/datasets/n4ze3m/tts-f2-m2-pilot-v01 . Qwen model: https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-Base . | |
| ## Loading | |
| ```python | |
| from datasets import load_dataset | |
| ds = load_dataset("n4ze3m/tiny-voca", token=True) | |
| ``` | |
| This repository is private. Consult LICENSE.md before redistribution. Text sources have mixed terms. Checkpoints and checksums are retained; resume logic is in worker.py. Environment versions are in requirements.txt. | |
| ''') | |
| (OUT/'LICENSE.md').write_text('''# Source-specific terms | |
| LibriTTS-R-derived text retains CC BY 4.0 attribution: Koizumi et al., LibriTTS-R: A Restored Multi-Speaker Text-to-Speech Corpus, Interspeech 2023, https://www.openslr.org/141/ . The original text, source revision and modifications are preserved in the parent text dataset. DeepSeek-generated text and edits obtained through Atlas Cloud are marked provider-terms; see https://www.atlascloud.ai/privacy and https://www.atlascloud.ai/acceptable-use . No blanket open license is asserted for this mixed corpus. | |
| Audio is synthetic, generated from original Qwen3-TTS VoiceDesign references with Apache-2.0 Qwen3-TTS Base weights. These references are not recordings of real speakers. A model-weight license is not a blanket license grant over every dataset component. This private dataset does not establish third-party commercial training rights. Parent terms: https://huggingface.co/datasets/n4ze3m/american-english-two-voice-tts-text-v01/blob/main/LICENSE.md . | |
| ''') | |
| def checkpoint(stage): | |
| pending=DB.execute("SELECT id,payload FROM clips WHERE status='accepted' AND exported=0").fetchall();created=[] | |
| for split in ['train','validation','test']: | |
| group=[(uid,json.loads(p)) for uid,p in pending if json.loads(p)['split']==split] | |
| if not group:continue | |
| ids=[uid for uid,p in group];digest=hashlib.sha256(''.join(sorted(ids)).encode()).hexdigest()[:12];name=f'{split}-{digest}.parquet';path=OUT/'data'/name | |
| values=[] | |
| for uid,p in group: | |
| p['audio']={'bytes':(AUDIO/(uid+'.flac')).read_bytes(),'path':uid+'.flac'};values.append(p) | |
| ds=Dataset.from_list(values).cast_column('audio',Audio(sampling_rate=24000));ds.to_parquet(path);created.append((name,ids)) | |
| report=progress(stage);report['exported_after_this_upload']=report['exported']+len(pending) | |
| report['accepted_audio_hours']=round(sum(json.loads(p)['duration_seconds'] for (p,) in DB.execute("SELECT payload FROM clips WHERE status='accepted'"))/3600,4) | |
| write_json(OUT/'progress.json',report) | |
| with (OUT/'review.jsonl').open('w') as f: | |
| for (p,) in DB.execute("SELECT payload FROM clips WHERE status!='accepted'"):f.write(p+'\n') | |
| # Rehash only lightweight manifests and new shards; persistent checksums include all shards. | |
| checks={} | |
| if (OUT/'SHA256SUMS').exists(): | |
| for l in (OUT/'SHA256SUMS').read_text().splitlines(): | |
| h,n=l.split(' ',1);checks[n]=h | |
| for p in OUT.rglob('*'): | |
| if p.is_file() and '.cache' not in p.parts and p.name!='SHA256SUMS': | |
| name=str(p.relative_to(OUT)) | |
| if name not in checks or p.suffix!='.parquet':checks[name]=hashlib.sha256(p.read_bytes()).hexdigest() | |
| (OUT/'SHA256SUMS').write_text('\n'.join(h+' '+n for n,h in sorted(checks.items()))+'\n') | |
| for attempt in range(3): | |
| env=os.environ.copy();env['HF_TOKEN']=token() | |
| p=subprocess.run(['/venv/main/bin/hf','upload',REPO,str(OUT),'.','--repo-type','dataset','--private','--exclude','.cache/**'],env=env,capture_output=True,text=True,timeout=900) | |
| if p.returncode==0:break | |
| if attempt==2:raise RuntimeError('HF checkpoint failed: '+p.stderr[-300:]) | |
| time.sleep(20) | |
| remote=set(HfApi(token=token()).list_repo_files(REPO,repo_type='dataset')) | |
| for name,ids in created: | |
| assert 'data/'+name in remote | |
| DB.executemany('UPDATE clips SET exported=1 WHERE id=?',[(uid,) for uid in ids]);DB.commit() | |
| for uid in ids:(AUDIO/(uid+'.flac')).unlink(missing_ok=True) | |
| print('CHECKPOINT',json.dumps(progress(stage)),flush=True) | |
| checkpoint('loading_model') | |
| torch.set_num_threads(6) | |
| model=Qwen3TTSModel.from_pretrained(MODEL,device_map='cuda:0',dtype=torch.bfloat16,attn_implementation='sdpa') | |
| prompts={v:model.create_voice_clone_prompt(ref_audio=str(OUT/'references'/(v+'.wav')),ref_text=refs[v]['text'],x_vector_only_mode=False)[0] for v in ['F2','M2']} | |
| asr=WhisperModel('small.en',device='cpu',compute_type='int8',cpu_threads=6) | |
| normalize=EnglishTextNormalizer({'cancelled':'canceled','colour':'color','favourite':'favorite','centre':'center'}) | |
| POOL=concurrent.futures.ThreadPoolExecutor(max_workers=1);futures=[];since_checkpoint=0 | |
| def analyze(batch,wavs,sr,attempt,seed,batch_id,generation_seconds): | |
| records=[] | |
| for job,wav in zip(batch,wavs): | |
| row=job['row'];w=np.asarray(wav);duration=len(w)/sr;peak=float(np.max(np.abs(w))) if len(w) else 0;reasons=[] | |
| if not np.isfinite(w).all() or peak<1e-5:reasons.append('invalid_or_silent_audio') | |
| if duration<0.5 or duration>35:reasons.append('duration') | |
| if duration>0 and not 0.5<=row['word_count']/duration<=7:reasons.append('speaking_rate') | |
| if len(w) and float(np.mean(np.abs(w)<1e-4))>.8:reasons.append('excessive_silence') | |
| transcript='';error=1.0 | |
| if not reasons: | |
| segments,_=asr.transcribe(resample_poly(w.astype('float32'),2,3),language='en',beam_size=3,condition_on_previous_text=False) | |
| transcript=' '.join(s.text.strip() for s in segments);error=wer(normalize(row['text']),normalize(transcript)) | |
| if error>.15:reasons.append('asr_mismatch') | |
| if np.isfinite(w).all() and peak>0: | |
| w=w*(.95/peak);sf.write(AUDIO/(job['id']+'.flac'),w,sr,subtype='PCM_16') | |
| payload={'id':job['id'],'text_id':row['id'],'voice_id':job['voice'],'text':row['text'],'split':row['split'],'category':row['category'],'origin':row['origin'],'source_id':row['source_id'],'source_license':row['source_license'],'source_url':row['source_url'],'duration_seconds':round(duration,4),'sample_rate':sr,'asr_transcript':transcript,'normalized_wer':round(error,4),'qc_reasons':reasons,'attempt':attempt,'seed':seed,'batch_id':batch_id,'generation_seconds_batch':generation_seconds,'requested_style':'neutral','teacher_model':MODEL,'reference_audio':job['voice']+'.wav'} | |
| records.append((job['id'],'review' if reasons else 'accepted',attempt,json.dumps(payload))) | |
| return records | |
| def collect(future): | |
| global since_checkpoint | |
| records=future.result() | |
| DB.executemany('INSERT INTO clips(id,status,attempts,payload) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET status=excluded.status, attempts=excluded.attempts,payload=excluded.payload',records);DB.commit();since_checkpoint+=len(records) | |
| print('BATCH_QC',len(records),'accepted',sum(r[1]=='accepted' for r in records),flush=True);progress('generating') | |
| def generate(batch,attempt,batch_id): | |
| seed=20261113+batch_id+attempt*100000;torch.manual_seed(seed);start=time.time() | |
| try: | |
| wavs,sr=model.generate_voice_clone(text=[j['row']['text'] for j in batch],language=['English']*len(batch),voice_clone_prompt=[prompts[j['voice']] for j in batch],max_new_tokens=600) | |
| except torch.cuda.OutOfMemoryError: | |
| torch.cuda.empty_cache() | |
| if len(batch)==1:raise | |
| mid=len(batch)//2;generate(batch[:mid],attempt,batch_id);generate(batch[mid:],attempt,batch_id+50000);return | |
| assert len(wavs)==len(batch) | |
| futures.append(POOL.submit(analyze,batch,wavs,sr,attempt,seed,batch_id,round(time.time()-start,3))) | |
| if len(futures)>=2:collect(futures.pop(0)) | |
| def run(): | |
| global since_checkpoint | |
| for attempt in [1,2]: | |
| existing={uid:(status,n) for uid,status,n in DB.execute('SELECT id,status,attempts FROM clips')} | |
| pending=[j for j in jobs if (attempt==1 and j['id'] not in existing) or (attempt==2 and j['id'] in existing and existing[j['id']][0]=='review' and existing[j['id']][1]<2)] | |
| for start in range(0,len(pending),BATCH if attempt==1 else 1): | |
| if should_stop():break | |
| batch=pending[start:start+(BATCH if attempt==1 else 1)] | |
| generate(batch,attempt,start//BATCH if attempt==1 else start+20000) | |
| if since_checkpoint>=128: | |
| while futures:collect(futures.pop(0)) | |
| checkpoint('generating');since_checkpoint=0 | |
| while futures:collect(futures.pop(0)) | |
| checkpoint('paused' if should_stop() else 'generating');since_checkpoint=0 | |
| if should_stop():return | |
| assert DB.execute('SELECT count(*) FROM clips').fetchone()[0]==9810 | |
| checkpoint('complete') | |
| try: | |
| run() | |
| except Exception as e: | |
| print(traceback.format_exc(),flush=True) | |
| try: | |
| while futures:collect(futures.pop(0)) | |
| checkpoint('failed') | |
| except Exception:pass | |
| progress('failed',{'error':type(e).__name__+': '+str(e)[:250]}) | |
| raise | |
| finally: | |
| POOL.shutdown(wait=True) | |
| print('FINISHED',json.dumps(progress('paused' if should_stop() else 'complete')),flush=True) | |