import com.alibaba.fastjson2.*; import com.cmvr.tts.domain.TtsSynthesizeTask; import com.cmvr.tts.service.impl.*; import io.minio.*; import javax.sound.sampled.*; import java.io.*; import java.math.*; import java.nio.*; import java.nio.channels.*; import java.nio.file.*; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.sql.Connection; import java.time.Instant; import java.util.*; /** Self-model corpus: 3000 unique texts, five requested emotions, MinIO primary/E backup. */ public class EmotionProduction { static final String BATCH="emotion3000-20261115"; static final Path ROOT=Path.of("data/tts-pilot",BATCH); static final Path AUDIO=Path.of("E:/cmvr-audio-backup/tts-pilot",BATCH,"audio"); static final List EMOTIONS=List.of("happy","sad","angry","fearful","surprised"); static List jobs=new ArrayList<>();static int completed,attempted;static long started;static String planHash; static JSONObject config; static void save(Path p,JSONObject value)throws IOException{Files.createDirectories(p.getParent());Path temp=p.resolveSibling(p.getFileName()+".tmp");Files.writeString(temp,value.toJSONString());Files.move(temp,p,StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.ATOMIC_MOVE);} static String sha(byte[] b)throws Exception{return CorpusDatabase.sha(b);} static String key(String t){return java.text.Normalizer.normalize(t,java.text.Normalizer.Form.NFKC).toLowerCase(Locale.ROOT).replaceAll("[\\p{P}\\p{Z}\\s]+", "");} static TtsSynthesizeTask task(JSONObject j){var t=new TtsSynthesizeTask();t.setText(j.getString("text"));t.setModel("voxcpm2");t.setVoice("default");t.setLanguage("zh-CN");t.setDialect("普通话");t.setEmotion(j.getString("emotion"));t.setInstructions("");t.setSampleRate("48000");t.setOutputFormat("wav");t.setSpeed(BigDecimal.valueOf(50));t.setPitch(BigDecimal.valueOf(50));t.setVolume(BigDecimal.valueOf(50));return t;} static void plan(Connection db)throws Exception{ Path file=ROOT.resolve("plan.jsonl"); config=JSON.parseObject(Files.readString(Path.of("tools/corpus/production_plan.json"))); if(!Files.exists(file)){ var source=Path.of("data/tts-pilot/corpus50000-20261114/reviewed-chinese.json");JSONArray pool=JSON.parseArray(Files.readString(source)); Set used=new HashSet<>();for(Object o:CorpusDatabase.query(db,"SELECT text FROM tts_corpus_info WHERE voice='default' AND language='zh-CN'"))used.add(key(((JSONObject)o).getString("text"))); for(int ci=0;ci<10;ci++){ List group=new ArrayList<>();for(Object o:pool){JSONObject r=(JSONObject)o;if(r.getIntValue("category_index")==ci)group.add(r);} group.sort(Comparator.comparingInt((JSONObject r)->r.getIntValue("variant")).thenComparing(r->r.getString("id"))); int n=0;for(JSONObject r:group){if(n==300)break;String text=r.getString("text");if(!used.add(key(text)))continue; JSONObject j=new JSONObject();String id=HexFormat.of().formatHex(MessageDigest.getInstance("MD5").digest((BATCH+"\0"+text).getBytes(StandardCharsets.UTF_8))); j.put("id",id);j.put("text",text);j.put("model","voxcpm2");j.put("voice","default");j.put("language","zh-CN");j.put("dialect","普通话");j.put("emotion",EMOTIONS.get((n+ci)%5));j.put("category_index",ci);j.put("category",config.getJSONArray("categories").getJSONObject(ci).getString("name"));j.put("source_id",r.getString("id"));j.put("text_reviewed",true);jobs.add(j);n++; }if(n!=300)throw new IOException("Insufficient reviewed unique source text"); } try(BufferedWriter w=Files.newBufferedWriter(file)){for(JSONObject j:jobs){w.write(j.toJSONString());w.newLine();}} JSONObject sourceInfo=new JSONObject();sourceInfo.put("reviewed_chinese_sha256",sha(Files.readAllBytes(source)));sourceInfo.put("text_pool_review","existing independently reviewed Chinese pool");sourceInfo.put("authorization","User approved 3000 additional items, five emotions x600; keep original 50000");save(ROOT.resolve("source-review.json"),sourceInfo); }else for(String line:Files.readAllLines(file))jobs.add(JSON.parseObject(line)); if(jobs.size()!=3000)throw new IOException("Plan must contain exactly 3000 items"); Set texts=new HashSet<>(),ids=new HashSet<>();Map emotions=new HashMap<>();int[] categories=new int[10];TtsCapabilities capabilities=new TtsCapabilities(); for(JSONObject j:jobs){capabilities.normalize(task(j),"voxcpm2");if(!texts.add(key(j.getString("text")))||!ids.add(j.getString("id")))throw new IOException("Duplicate plan text/id");emotions.merge(j.getString("emotion"),1,Integer::sum);categories[j.getIntValue("category_index")]++;} for(String e:EMOTIONS)if(emotions.getOrDefault(e,0)!=600)throw new IOException("Emotion allocation mismatch");for(int n:categories)if(n!=300)throw new IOException("Category allocation mismatch"); planHash=sha(Files.readAllBytes(file));if(Files.exists(ROOT.resolve("progress.json"))&&!planHash.equals(JSON.parseObject(Files.readString(ROOT.resolve("progress.json"))).getString("plan_sha256")))throw new IOException("Plan changed after synthesis started"); JSONObject quality=new JSONObject();quality.put("state","TEXT_READY");quality.put("target",3000);quality.put("emotions",emotions);quality.put("categories",categories);quality.put("duplicates",0);quality.put("plan_sha256",planHash);quality.put("emotion_verification","requested via instructions; sample audition accepted by user, not per-clip human emotion annotation");save(ROOT.resolve("text-quality-summary.json"),quality); } static void category(Connection c,String id,String name,String parent,int order)throws Exception{ if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_category WHERE id=?",id)==0)CorpusDatabase.update(c,"INSERT INTO tts_corpus_category(id,create_by,create_time,remark,parent_id,category_name,sort_order) VALUES(?,'admin',NOW(),?,?,?,?)",id,BATCH,parent,name,order); else if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_category WHERE id=? AND category_name=? AND parent_id=? AND remark=?",id,name,parent,BATCH)!=1)throw new IOException("Category conflicts with batch"); } static JSONObject quality(byte[] bytes)throws Exception{ byte[] pcm;AudioFormat f;try(AudioInputStream in=AudioSystem.getAudioInputStream(new ByteArrayInputStream(bytes))){f=in.getFormat();pcm=in.readAllBytes();} if(f.getSampleRate()!=48000||f.getChannels()!=1||f.getSampleSizeInBits()!=16||f.isBigEndian()||!AudioFormat.Encoding.PCM_SIGNED.equals(f.getEncoding())||pcm.length%2!=0)throw new IOException("Unexpected self-model WAV format"); double seconds=pcm.length/96000d;if(seconds<0.35||seconds>30)throw new IOException("Audio duration outside quality range");long power=0,active=0,clipped=0;ByteBuffer b=ByteBuffer.wrap(pcm).order(ByteOrder.LITTLE_ENDIAN);while(b.hasRemaining()){int v=b.getShort();power+=(long)v*v;if(Math.abs(v)>100)active++;if(Math.abs(v)>=32760)clipped++;}int samples=pcm.length/2;double rms=Math.sqrt(power/(double)samples),activeRatio=active/(double)samples,clipRatio=clipped/(double)samples; if(rms<10||activeRatio<0.02||clipRatio>0.02)throw new IOException("Silence or clipping quality gate failed");JSONObject q=new JSONObject();q.put("sample_rate",48000);q.put("channels",1);q.put("bits",16);q.put("duration_seconds",BigDecimal.valueOf(seconds).setScale(3,RoundingMode.HALF_UP));q.put("rms",rms);q.put("active_ratio",activeRatio);q.put("clipping_ratio",clipRatio);return q; } static void process(Connection c,MinioClient minio,String bucket,VoxCpmTtsClient client,JSONObject j)throws Exception{ String id=j.getString("id"),object="tts/"+BATCH+"/"+j.getString("emotion")+"/"+id+".wav";Path backup=AUDIO.resolve(j.getString("emotion")).resolve(id+".wav"),rp=ROOT.resolve("receipts").resolve(id+".json"),attempt=ROOT.resolve("attempts").resolve(id+".json"); JSONObject receipt=Files.exists(rp)?JSON.parseObject(Files.readString(rp)):new JSONObject(); if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE id=?",id)>0){if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE id=? AND remark=? AND model='voxcpm2' AND text=? AND emotion=? AND audio_file_path=?",id,BATCH,j.getString("text"),j.getString("emotion"),object)!=1)throw new IOException("Existing corpus conflicts with plan");if(!"IMPORTED".equals(receipt.getString("state")))throw new IOException("Import reconciliation required");return;} var task=task(j);Files.createDirectories(backup.getParent()); if(!Files.exists(backup)){ if(Files.exists(attempt))throw new IOException("Previously attempted synthesis has no saved audio; no automatic retry"); if(attempted>=3000)throw new IOException("3000-request hard limit reached"); if(Files.getFileStore(AUDIO).getUsableSpace()<2L*1024*1024*1024)throw new IOException("E backup drive low on space"); if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE voice='default' AND language='zh-CN' AND text=?",j.getString("text"))>0)throw new IOException("Existing same-voice/language/text duplicate"); if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_synthesize_task WHERE id=?",id)==0)CorpusDatabase.update(c,"INSERT INTO tts_synthesize_task(id,create_by,create_time,remark,task_code,text,language,dialect,voice,emotion,model,instructions,speed,volume,pitch,sample_rate,output_format,status) VALUES(?,'admin',NOW(),?,?,?,'zh-CN','普通话','default',?,'voxcpm2','',50,50,50,48000,'wav','1')",id,BATCH,id,j.getString("text"),j.getString("emotion")); JSONObject request=VoxCpmTtsClient.request(task);JSONObject marker=new JSONObject();marker.put("id",id);marker.put("request",request);marker.put("at",Instant.now().toString()); try(FileChannel out=FileChannel.open(attempt,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){ByteBuffer data=ByteBuffer.wrap(marker.toJSONString().getBytes(StandardCharsets.UTF_8));while(data.hasRemaining())out.write(data);out.force(true);}attempted++; long before=System.nanoTime();byte[] audio=client.synthesize(task).bytes();Path temp=backup.resolveSibling(id+".tmp");Files.write(temp,audio,StandardOpenOption.CREATE_NEW);Files.move(temp,backup,StandardCopyOption.ATOMIC_MOVE);receipt.put("tts_ms",(System.nanoTime()-before)/1_000_000);receipt.put("request",request); } byte[] audio=Files.readAllBytes(backup);JSONObject q=quality(audio);String hash=sha(audio); receipt.put("id",id);receipt.put("model","voxcpm2");receipt.put("emotion",j.getString("emotion"));receipt.put("text",j.getString("text"));receipt.put("voice","default");receipt.put("language","zh-CN");receipt.put("backup_file",backup.toString());receipt.put("object_path",object);receipt.put("storage_provider","minio");receipt.put("sha256",hash);receipt.put("quality",q);receipt.put("state","AUDIO_VALIDATED");save(rp,receipt); minio.putObject(PutObjectArgs.builder().bucket(bucket).object(object).contentType("audio/wav").stream(new ByteArrayInputStream(audio),audio.length,-1).build());try(InputStream in=minio.getObject(GetObjectArgs.builder().bucket(bucket).object(object).build())){if(!hash.equals(sha(in.readAllBytes())))throw new IOException("MinIO content hash mismatch");} receipt.put("state","STORAGE_VERIFIED");save(rp,receipt);c.setAutoCommit(false); try{ if(CorpusDatabase.update(c,"UPDATE tts_synthesize_task SET status='2',audio_file_path=?,audio_duration=?,file_size=?,error_msg='',update_time=NOW(),update_by='admin' WHERE id=? AND remark=?",object,q.getBigDecimal("duration_seconds"),audio.length,id,BATCH)!=1)throw new IOException("Task update mismatch"); CorpusDatabase.update(c,"INSERT INTO tts_corpus_info(id,create_by,create_time,remark,text,category_id,language,dialect,emotion,voice,speaker,scene,model,audio_file_path,audio_duration,file_size) VALUES(?,'admin',NOW(),?,?,?,'zh-CN','普通话',?,'default','自研默认音色',?,'voxcpm2',?,?,?)",id,BATCH,j.getString("text"),BATCH+"-c"+j.getIntValue("category_index"),j.getString("emotion"),j.getString("category"),object,q.getBigDecimal("duration_seconds"),audio.length);c.commit(); }catch(Exception failure){c.rollback();throw failure;}finally{c.setAutoCommit(true);} receipt.put("state","IMPORTED");receipt.put("imported_at",Instant.now().toString());save(rp,receipt); } static void progress(String state,String error)throws Exception{JSONObject p=new JSONObject();p.put("batch",BATCH);p.put("state",state);p.put("target",3000);p.put("completed",completed);p.put("attempted",attempted);p.put("plan_sha256",planHash);p.put("updated_at",Instant.now().toString());p.put("elapsed_ms",(System.nanoTime()-started)/1_000_000);if(error!=null)p.put("error",error);save(ROOT.resolve("progress.json"),p);} static void audit(Connection c)throws Exception{ if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE remark=?",BATCH)!=3000||CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_synthesize_task WHERE remark=? AND status='2'",BATCH)!=3000)throw new IOException("Final row count mismatch"); for(String e:EMOTIONS)if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE remark=? AND emotion=? AND model='voxcpm2'",BATCH,e)!=600)throw new IOException("Final emotion count mismatch"); for(int ci=0;ci<10;ci++)if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE remark=? AND category_id=?",BATCH,BATCH+"-c"+ci)!=300)throw new IOException("Final category mismatch"); if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM (SELECT voice,language,text FROM tts_corpus_info WHERE voice='default' AND language='zh-CN' GROUP BY voice,language,text HAVING COUNT(*)>1) d")!=0)throw new IOException("Final duplicates"); JSONObject a=new JSONObject();a.put("completed_at",Instant.now().toString());a.put("corpus",3000);a.put("emotions",CorpusDatabase.query(c,"SELECT emotion,COUNT(*) AS n FROM tts_corpus_info WHERE remark=? GROUP BY emotion",BATCH));a.put("categories",CorpusDatabase.query(c,"SELECT category_id,COUNT(*) AS n FROM tts_corpus_info WHERE remark=? GROUP BY category_id",BATCH));a.put("original_corpus",CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE remark='corpus50000-20261114'"));a.put("total_corpus",CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info"));a.put("storage","minio primary / E backup");save(ROOT.resolve("database-audit.json"),a); } public static void main(String[] args)throws Exception{ if(args.length>0&&!Set.of("check","run").contains(args[0]))throw new IllegalArgumentException("Expected check or run"); System.setOut(new PrintStream(System.out,true,StandardCharsets.UTF_8));Files.createDirectories(ROOT);Files.createDirectories(ROOT.resolve("receipts"));Files.createDirectories(ROOT.resolve("attempts"));CorpusDatabase.init(); try(FileChannel lock=FileChannel.open(ROOT.resolve("production.lock"),StandardOpenOption.CREATE,StandardOpenOption.WRITE);FileLock held=lock.tryLock()){ if(held==null)throw new IOException("Emotion production already running");try(Connection c=CorpusDatabase.connect()){ plan(c);if(args.length==0||args[0].equals("check")){System.out.println("PLAN_VALID 3000 unique texts; five emotions x600; ten categories x300; no synthesis");System.exit(0);} Files.createDirectories(AUDIO);category(c,BATCH,"自研多情绪语料3000 20261115","0",1);for(int ci=0;ci<10;ci++)category(c,BATCH+"-c"+ci,config.getJSONArray("categories").getJSONObject(ci).getString("name"),BATCH,ci+1); try(var entries=Files.list(ROOT.resolve("attempts"))){attempted=(int)entries.count();}started=System.nanoTime();progress("RUNNING",null);MinioClient minio=CorpusDatabase.minio();String bucket=CorpusDatabase.property("minio.bucketName");var client=new VoxCpmTtsClient(CorpusDatabase.property("tts.voxcpm2.url"),240); for(JSONObject j:jobs){if(Files.exists(ROOT.resolve("STOP"))){progress("STOP_REQUESTED",null);System.exit(0);}try{process(c,minio,bucket,client,j);completed++;}catch(Exception e){CorpusDatabase.update(c,"UPDATE tts_synthesize_task SET status='3',error_msg=? WHERE id=? AND remark=? AND status<>'2'",e.getMessage(),j.getString("id"),BATCH);progress("STOPPED_ON_ERROR",j.getString("id")+": "+e.getMessage());throw e;}if(completed%20==0){progress("RUNNING",null);System.out.println("PROGRESS "+completed+"/3000");}} audit(c);progress("COMPLETE",null);Path meta=AUDIO.getParent().resolve("metadata");Files.createDirectories(meta);for(String name:List.of("plan.jsonl","source-review.json","text-quality-summary.json","database-audit.json","progress.json"))Files.copy(ROOT.resolve(name),meta.resolve(name),StandardCopyOption.REPLACE_EXISTING);System.out.println("COMPLETE 3000 imported; five emotions x600; original 50000 retained"); } }System.exit(0); } }