262 lines
27 KiB
Java
262 lines
27 KiB
Java
|
|
import com.alibaba.fastjson2.*;
|
||
|
|
import com.cmvr.tts.domain.TtsSynthesizeTask;
|
||
|
|
import com.cmvr.tts.service.impl.XfyunTtsClient;
|
||
|
|
import io.minio.*;
|
||
|
|
import java.io.*;
|
||
|
|
import java.math.BigDecimal;
|
||
|
|
import java.nio.*;
|
||
|
|
import java.nio.channels.*;
|
||
|
|
import java.nio.charset.StandardCharsets;
|
||
|
|
import java.nio.file.*;
|
||
|
|
import java.text.Normalizer;
|
||
|
|
import java.time.Instant;
|
||
|
|
import java.sql.Connection;
|
||
|
|
import java.util.*;
|
||
|
|
|
||
|
|
/** Sequential, checkpointed production. A paid attempt is never automatically repeated. */
|
||
|
|
public class CorpusProduction {
|
||
|
|
static final String BATCH="corpus50000-20261114";
|
||
|
|
static final Path ROOT=CorpusDatabase.ROOT;
|
||
|
|
static JSONObject plan;
|
||
|
|
static Map<String,JSONObject> voices=new LinkedHashMap<>();
|
||
|
|
static List<JSONObject> jobs=new ArrayList<>();
|
||
|
|
static long runStarted;
|
||
|
|
static int completed;
|
||
|
|
static long attempted;
|
||
|
|
static String planHash;
|
||
|
|
|
||
|
|
public static void main(String[] args)throws Exception{
|
||
|
|
System.setOut(new PrintStream(System.out,true,StandardCharsets.UTF_8));
|
||
|
|
plan=JSON.parseObject(Files.readString(Path.of("tools/corpus/production_plan.json")));
|
||
|
|
for(Object voice:plan.getJSONArray("voices")){JSONObject v=(JSONObject)voice;voices.put(v.getString("vcn"),v);}
|
||
|
|
if(args.length>0&&args[0].equals("self-test")){selfTest();return;}
|
||
|
|
if(args.length>0&&args[0].equals("database-preflight")){databasePreflight();return;}
|
||
|
|
if(args.length>0&&args[0].equals("status")){status();return;}
|
||
|
|
loadAndValidate();
|
||
|
|
if(args.length==0||args[0].equals("check")){System.out.println("PLAN_VALID total=50000 voices=15 languages=6 categories=10 duplicates=0; paid calls=0");return;}
|
||
|
|
if(!args[0].equals("run"))throw new IllegalArgumentException("Expected check/run/self-test");
|
||
|
|
JSONObject quota=JSON.parseObject(Files.readString(ROOT.resolve("quota-confirmed.json")));
|
||
|
|
if(!quota.getBooleanValue("confirmed")||quota.getIntValue("authorized_max_calls")!=50000)throw new IllegalStateException("50k quota confirmation is required before synthesis");
|
||
|
|
Files.createDirectories(ROOT.resolve("receipts"));Files.createDirectories(ROOT.resolve("attempts"));Files.createDirectories(audioRoot());
|
||
|
|
try(FileChannel lock=FileChannel.open(ROOT.resolve("production.lock"),StandardOpenOption.CREATE,StandardOpenOption.WRITE);FileLock held=lock.tryLock()){
|
||
|
|
if(held==null)throw new IllegalStateException("Production is already running");
|
||
|
|
CorpusDatabase.init();
|
||
|
|
try(Connection database=CorpusDatabase.connect()){
|
||
|
|
if(CorpusDatabase.count(database,"SELECT COUNT(*) FROM tts_corpus_info WHERE remark=?",CorpusDatabase.PILOT)!=0)throw new IllegalStateException("Old pilot still present");
|
||
|
|
MinioClient minio=CorpusDatabase.minio();String bucket=CorpusDatabase.property("minio.bucketName");
|
||
|
|
if(!minio.bucketExists(BucketExistsArgs.builder().bucket(bucket).build()))throw new IllegalStateException("Storage bucket unavailable");
|
||
|
|
categories(database);
|
||
|
|
try(var entries=Files.list(ROOT.resolve("attempts"))){attempted=entries.count();}
|
||
|
|
try(XfyunTtsClient client=new XfyunTtsClient(CorpusDatabase.property("tts.xfyun.url"),CorpusDatabase.property("tts.xfyun.app-id"),CorpusDatabase.property("tts.xfyun.api-key"),CorpusDatabase.property("tts.xfyun.api-secret"),"x4_yezi",60)){
|
||
|
|
runStarted=System.nanoTime();completed=0;progress("RUNNING",null);
|
||
|
|
for(JSONObject job:jobs){
|
||
|
|
if(Files.exists(ROOT.resolve("STOP"))){progress("STOP_REQUESTED",null);System.out.println("Stopped between records by STOP marker");return;}
|
||
|
|
try{process(database,minio,bucket,client,job);completed++;}
|
||
|
|
catch(Exception failure){
|
||
|
|
try{CorpusDatabase.update(database,"UPDATE tts_synthesize_task SET status='3',error_msg=? WHERE id=? AND remark=? AND status<>'2'",failure.getMessage(),job.getString("id"),BATCH);}catch(Exception recordFailure){failure.addSuppressed(recordFailure);}
|
||
|
|
progress("STOPPED_ON_ERROR",job.getString("id")+": "+failure.getMessage());System.out.println("STOPPED no automatic TTS retry; id="+job.getString("id")+" voice="+job.getString("voice")+" reason="+failure.getMessage());throw failure;
|
||
|
|
}
|
||
|
|
if(completed%25==0){progress("RUNNING",null);System.out.println("PROGRESS "+completed+"/50000 elapsed_seconds="+((System.nanoTime()-runStarted)/1_000_000_000));}
|
||
|
|
}
|
||
|
|
auditDatabase(database);progress("COMPLETE",null);System.out.println("COMPLETE: 50000 imported and storage hashes verified");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
System.exit(0);
|
||
|
|
}
|
||
|
|
static void loadAndValidate()throws Exception{
|
||
|
|
JSONObject quality=JSON.parseObject(Files.readString(ROOT.resolve("text-quality-summary.json")));
|
||
|
|
planHash=CorpusDatabase.sha(Files.readAllBytes(ROOT.resolve("plan.jsonl")));
|
||
|
|
if(!"TEXT_READY".equals(quality.getString("state"))||!planHash.equals(quality.getString("plan_sha256")))throw new IllegalStateException("Reviewed plan hash mismatch");
|
||
|
|
if(Files.exists(ROOT.resolve("progress.json"))){
|
||
|
|
JSONObject previous=JSON.parseObject(Files.readString(ROOT.resolve("progress.json")));
|
||
|
|
if(!planHash.equals(previous.getString("plan_sha256")))throw new IllegalStateException("Reviewed plan changed after production began; refusing new paid calls");
|
||
|
|
}
|
||
|
|
Set<String> keys=new HashSet<>(),ids=new HashSet<>();Map<String,Integer> counts=new HashMap<>(),categories=new HashMap<>();
|
||
|
|
for(String line:Files.readAllLines(ROOT.resolve("plan.jsonl"))){
|
||
|
|
JSONObject j=JSON.parseObject(line);validateJob(j);
|
||
|
|
String key=j.getString("voice")+"\0"+j.getString("language")+"\0"+normalize(j.getString("text"));
|
||
|
|
if(!keys.add(key)||!ids.add(j.getString("id")))throw new IllegalStateException("Duplicate tuple or id");
|
||
|
|
counts.merge(j.getString("voice"),1,Integer::sum);categories.merge(j.getString("voice")+":"+j.getIntValue("category_index"),1,Integer::sum);jobs.add(j);
|
||
|
|
}
|
||
|
|
if(jobs.size()!=50000)throw new IllegalStateException("Expected exactly 50000 jobs");
|
||
|
|
for(JSONObject voice:voices.values()){
|
||
|
|
String v=voice.getString("vcn");int target=voice.getIntValue("count");
|
||
|
|
if(counts.getOrDefault(v,0)!=target)throw new IllegalStateException("Voice allocation mismatch");
|
||
|
|
for(int ci=0;ci<10;ci++)if(categories.getOrDefault(v+":"+ci,0)!=target/10)throw new IllegalStateException("Category allocation mismatch");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
static String normalize(String text){return Normalizer.normalize(text,Normalizer.Form.NFKC).toLowerCase(Locale.ROOT).replaceAll("[\\p{P}\\p{Z}\\s]+","");}
|
||
|
|
static void validateJob(JSONObject j){
|
||
|
|
JSONObject v=voices.get(j.getString("voice"));
|
||
|
|
if(v==null||!v.getString("language").equals(j.getString("language"))||!v.getString("dialect").equals(j.getString("dialect")))throw new IllegalArgumentException("Voice/language/dialect mismatch");
|
||
|
|
if(!BATCH.equals(j.getString("batch"))||!j.getBooleanValue("text_reviewed")||!j.getString("id").matches("[a-f0-9]{32}"))throw new IllegalArgumentException("Unreviewed or invalid record");
|
||
|
|
int ci=j.getIntValue("category_index");
|
||
|
|
if(ci<0||ci>=10||!plan.getJSONArray("categories").getJSONObject(ci).getString("name").equals(j.getString("category")))throw new IllegalArgumentException("Category mismatch");
|
||
|
|
validateText(j.getString("text"),j.getString("language"));
|
||
|
|
}
|
||
|
|
static void validateText(String text,String language){
|
||
|
|
if(text==null||text.isBlank()||!text.equals(text.trim())||text.codePointCount(0,text.length())>100||text.matches("(?s).*[\\r\\n\\t<>\\[\\]{}].*"))throw new IllegalArgumentException("Invalid text length/format");
|
||
|
|
boolean letters=false,nativeScript=false;
|
||
|
|
for(int cp:text.codePoints().toArray())if(Character.isLetter(cp)){
|
||
|
|
letters=true;Character.UnicodeScript script=Character.UnicodeScript.of(cp);boolean ok;
|
||
|
|
switch(language){
|
||
|
|
case "zh-CN" -> {ok=script==Character.UnicodeScript.HAN;nativeScript|=ok;}
|
||
|
|
case "ja-JP" -> {boolean kana=script==Character.UnicodeScript.HIRAGANA||script==Character.UnicodeScript.KATAKANA;nativeScript|=kana;ok=kana||script==Character.UnicodeScript.HAN||cp==0x30fc;}
|
||
|
|
case "ko-KR" -> {ok=script==Character.UnicodeScript.HANGUL;nativeScript|=ok;}
|
||
|
|
case "ru-RU" -> {ok=script==Character.UnicodeScript.CYRILLIC;nativeScript|=ok;}
|
||
|
|
case "en-US","de-DE" -> {ok=script==Character.UnicodeScript.LATIN;nativeScript|=ok;}
|
||
|
|
default -> throw new IllegalArgumentException("Unknown language");
|
||
|
|
}
|
||
|
|
if(!ok)throw new IllegalArgumentException("Text contains characters from wrong language");
|
||
|
|
}
|
||
|
|
if(!letters||!nativeScript)throw new IllegalArgumentException("Missing native-language text");
|
||
|
|
}
|
||
|
|
static void categories(Connection c)throws Exception{
|
||
|
|
ensureCategory(c,BATCH,"正式语料50000 20261114","0",0);
|
||
|
|
for(int i=0;i<10;i++)ensureCategory(c,categoryId(i),plan.getJSONArray("categories").getJSONObject(i).getString("name"),BATCH,i+1);
|
||
|
|
}
|
||
|
|
static String categoryId(int ci){return BATCH+String.format(Locale.ROOT,"-c%02d",ci);}
|
||
|
|
static void ensureCategory(Connection c,String id,String name,String parent,int sort)throws Exception{
|
||
|
|
JSONArray existing=CorpusDatabase.query(c,"SELECT category_name,parent_id,remark FROM tts_corpus_category WHERE id=?",id);
|
||
|
|
if(!existing.isEmpty()){
|
||
|
|
JSONObject row=existing.getJSONObject(0);if(!name.equals(row.getString("category_name"))||!parent.equals(row.getString("parent_id"))||!BATCH.equals(row.getString("remark")))throw new IllegalStateException("Category conflict");return;
|
||
|
|
}
|
||
|
|
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,sort);
|
||
|
|
}
|
||
|
|
static void process(Connection c,MinioClient minio,String bucket,XfyunTtsClient client,JSONObject j)throws Exception{
|
||
|
|
validateJob(j);String id=j.getString("id"),voice=j.getString("voice"),object="tts/"+BATCH+"/"+voice+"/"+id+".wav";
|
||
|
|
Path receiptPath=ROOT.resolve("receipts").resolve(id+".json"),audioPath=audioRoot().resolve(voice).resolve(id+".wav"),attemptPath=ROOT.resolve("attempts").resolve(id+".json");
|
||
|
|
Files.createDirectories(audioPath.getParent());
|
||
|
|
JSONObject receipt=Files.exists(receiptPath)?JSON.parseObject(Files.readString(receiptPath)):new JSONObject();
|
||
|
|
JSONArray existing=CorpusDatabase.query(c,"SELECT id,text,voice,language,audio_file_path,remark FROM tts_corpus_info WHERE id=?",id);
|
||
|
|
if(!existing.isEmpty()){
|
||
|
|
JSONObject row=existing.getJSONObject(0);
|
||
|
|
if(!j.getString("text").equals(row.getString("text"))||!voice.equals(row.getString("voice"))||!j.getString("language").equals(row.getString("language"))||!BATCH.equals(row.getString("remark"))||!object.equals(row.getString("audio_file_path")))throw new IllegalStateException("Existing corpus record conflicts with plan");
|
||
|
|
if(!"IMPORTED".equals(receipt.getString("state"))){
|
||
|
|
if(!Files.exists(audioPath)||!receipt.containsKey("sha256"))throw new IllegalStateException("Imported corpus missing saved audio/hash; manual reconciliation required");
|
||
|
|
String savedHash=CorpusDatabase.sha(Files.readAllBytes(audioPath));
|
||
|
|
if(!savedHash.equals(receipt.getString("sha256")))throw new IOException("Recovery local audio hash mismatch");
|
||
|
|
try(InputStream in=minio.getObject(GetObjectArgs.builder().bucket(bucket).object(object).build())){if(!savedHash.equals(CorpusDatabase.sha(in.readAllBytes())))throw new IOException("Recovery remote audio hash mismatch");}
|
||
|
|
if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_synthesize_task WHERE id=? AND remark=? AND status='2' AND audio_file_path=?",id,BATCH,object)!=1)throw new IllegalStateException("Recovery task state mismatch");
|
||
|
|
receipt.put("state","IMPORTED");receipt.put("recovered_at",Instant.now().toString());save(receiptPath,receipt);
|
||
|
|
}
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
if(!Files.exists(audioPath)){
|
||
|
|
if(Files.exists(attemptPath))throw new IllegalStateException("Previously attempted item has no saved audio; paid retry forbidden");
|
||
|
|
if(Files.getFileStore(audioPath.getParent()).getUsableSpace()<2L*1024*1024*1024)throw new IOException("Less than 2GiB backup storage available");
|
||
|
|
if(attempted>=50000)throw new IllegalStateException("50000-attempt hard limit reached");
|
||
|
|
if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE voice=? AND language=? AND text=?",voice,j.getString("language"),j.getString("text"))!=0)throw new IllegalStateException("Existing same-voice/language/text duplicate");
|
||
|
|
if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_synthesize_task WHERE id=?",id)==0)registerTask(c,j);
|
||
|
|
JSONObject attempt=new JSONObject();attempt.put("id",id);attempt.put("voice",voice);attempt.put("language",j.getString("language"));attempt.put("text",j.getString("text"));attempt.put("at",Instant.now().toString());
|
||
|
|
// Force the attempt marker to durable storage before opening a paid connection.
|
||
|
|
try(FileChannel f=FileChannel.open(attemptPath,StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE)){ByteBuffer b=ByteBuffer.wrap(JSON.toJSONBytes(attempt));while(b.hasRemaining())f.write(b);f.force(true);}
|
||
|
|
attempted++;
|
||
|
|
TtsSynthesizeTask task=new TtsSynthesizeTask();task.setText(j.getString("text"));task.setVoice(voice);task.setLanguage(j.getString("language"));task.setSampleRate("16000");task.setOutputFormat("wav");task.setSpeed(BigDecimal.valueOf(50));task.setVolume(BigDecimal.valueOf(50));task.setPitch(BigDecimal.valueOf(50));
|
||
|
|
long started=System.nanoTime();
|
||
|
|
try{
|
||
|
|
XfyunTtsClient.Audio audio=client.synthesize(task);
|
||
|
|
Path temporary=audioPath.resolveSibling(id+".tmp");Files.write(temporary,audio.bytes(),StandardOpenOption.CREATE_NEW);Files.move(temporary,audioPath,StandardCopyOption.ATOMIC_MOVE);
|
||
|
|
receipt.put("tts_ms",(System.nanoTime()-started)/1_000_000);receipt.put("state","SYNTHESIZED");save(receiptPath,receipt);
|
||
|
|
}catch(Exception failure){
|
||
|
|
CorpusDatabase.update(c,"UPDATE tts_synthesize_task SET status='3',error_msg=? WHERE id=? AND remark=?",failure.getMessage(),id,BATCH);
|
||
|
|
receipt.put("state","FAILED");receipt.put("error",failure.getMessage());save(receiptPath,receipt);throw failure;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
byte[] audio=Files.readAllBytes(audioPath);JSONObject audioQuality=checkAudio(audio);String sha=CorpusDatabase.sha(audio);
|
||
|
|
if(receipt.containsKey("sha256")&&!sha.equals(receipt.getString("sha256")))throw new IOException("Saved audio hash changed");
|
||
|
|
receipt.put("id",id);receipt.put("voice",voice);receipt.put("language",j.getString("language"));receipt.put("text",j.getString("text"));receipt.remove("audio_file");receipt.put("storage_provider","minio");receipt.put("backup_file",audioPath.toString());receipt.put("object_path",object);receipt.put("sha256",sha);receipt.put("quality",audioQuality);receipt.put("state","AUDIO_VALIDATED");save(receiptPath,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(!sha.equals(CorpusDatabase.sha(in.readAllBytes())))throw new IOException("Remote audio hash mismatch");}
|
||
|
|
receipt.put("state","STORAGE_VERIFIED");save(receiptPath,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_by='admin',update_time=NOW() WHERE id=? AND remark=?",object,audioQuality.getBigDecimal("duration_seconds"),audio.length,id,BATCH)!=1)throw new IllegalStateException("Task update mismatch");
|
||
|
|
insertCorpus(c,j,object,audioQuality.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(receiptPath,receipt);
|
||
|
|
}
|
||
|
|
static void registerTask(Connection c,JSONObject j)throws Exception{
|
||
|
|
String id=j.getString("id");
|
||
|
|
if(CorpusDatabase.update(c,"INSERT INTO tts_synthesize_task(id,create_by,create_time,remark,task_code,text,language,dialect,voice,emotion,speed,volume,pitch,sample_rate,output_format,status) VALUES(?,'admin',NOW(),?,?,?,?,?,?,?,50,50,50,16000,'wav','1')",id,BATCH,id,j.getString("text"),j.getString("language"),j.getString("dialect"),j.getString("voice"),"neutral")!=1)throw new IllegalStateException("Task insert mismatch");
|
||
|
|
}
|
||
|
|
static Path backupBase()throws IOException{
|
||
|
|
JSONObject policy=JSON.parseObject(Files.readString(ROOT.resolve("storage-policy.json")));
|
||
|
|
if(!"minio".equals(policy.getString("primary")))throw new IOException("Primary storage must be MinIO");
|
||
|
|
Path backup=Path.of(policy.getString("backup_base")).toAbsolutePath().normalize();
|
||
|
|
if(!backup.getRoot().toString().equalsIgnoreCase("E:\\"))throw new IOException("Audio backup must use the configured E drive");
|
||
|
|
return backup;
|
||
|
|
}
|
||
|
|
static Path audioRoot()throws IOException{return backupBase().resolve(BATCH).resolve("audio");}
|
||
|
|
static void insertCorpus(Connection c,JSONObject j,String object,BigDecimal duration,long bytes)throws Exception{
|
||
|
|
if(CorpusDatabase.update(c,"INSERT INTO tts_corpus_info(id,create_by,create_time,remark,text,category_id,language,dialect,emotion,voice,speaker,scene,audio_file_path,audio_duration,file_size) VALUES(?,'admin',NOW(),?,?,?,?,?,'neutral',?,?,?,?,?,?)",j.getString("id"),BATCH,j.getString("text"),categoryId(j.getIntValue("category_index")),j.getString("language"),j.getString("dialect"),j.getString("voice"),j.getString("speaker"),j.getString("category"),object,duration,bytes)!=1)throw new IllegalStateException("Corpus insert mismatch");
|
||
|
|
}
|
||
|
|
static void databasePreflight()throws Exception{
|
||
|
|
CorpusDatabase.init();try(Connection c=CorpusDatabase.connect()){
|
||
|
|
JSONObject j=new JSONObject();String id=UUID.randomUUID().toString().replace("-","");
|
||
|
|
j.put("id",id);j.put("batch",BATCH);j.put("voice","x4_enus_ryan_assist");j.put("speaker","Ryan");j.put("language","en-US");j.put("dialect","");j.put("category_index",1);j.put("category",plan.getJSONArray("categories").getJSONObject(1).getString("name"));j.put("text","Please turn on the air conditioning.");j.put("text_reviewed",true);validateJob(j);
|
||
|
|
c.setAutoCommit(false);try{
|
||
|
|
categories(c);registerTask(c,j);insertCorpus(c,j,"tts/preflight/"+id+".wav",new BigDecimal("2.50"),80044);
|
||
|
|
JSONArray rows=CorpusDatabase.query(c,"SELECT c.text,c.voice,c.language,c.category_id,t.status FROM tts_corpus_info c JOIN tts_synthesize_task t ON t.id=c.id WHERE c.id=?",id);
|
||
|
|
if(rows.size()!=1||!j.getString("text").equals(rows.getJSONObject(0).getString("text"))||!"en-US".equals(rows.getJSONObject(0).getString("language"))||!j.getString("voice").equals(rows.getJSONObject(0).getString("voice")))throw new IllegalStateException("Database round-trip mapping failed");
|
||
|
|
}finally{c.rollback();c.setAutoCommit(true);}
|
||
|
|
for(String table:List.of("tts_corpus_info","tts_synthesize_task"))if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM "+table+" WHERE id=?",id)!=0)throw new IllegalStateException("Preflight rollback failed");
|
||
|
|
}
|
||
|
|
System.out.println("DATABASE_PREFLIGHT_OK real task/corpus/category inserts and language round trip passed; transaction rolled back; paid calls=0");
|
||
|
|
}
|
||
|
|
static JSONObject checkAudio(byte[] audio)throws IOException{
|
||
|
|
if(audio.length<44||!new String(audio,0,4,StandardCharsets.US_ASCII).equals("RIFF")||!new String(audio,8,8,StandardCharsets.US_ASCII).equals("WAVEfmt "))throw new IOException("Invalid WAV header");
|
||
|
|
ByteBuffer b=ByteBuffer.wrap(audio).order(ByteOrder.LITTLE_ENDIAN);
|
||
|
|
if(b.getInt(4)!=audio.length-8||b.getShort(20)!=1||b.getShort(22)!=1||b.getInt(24)!=16000||b.getShort(34)!=16||b.getInt(40)!=audio.length-44||(audio.length-44)%2!=0)throw new IOException("Invalid WAV length or PCM format");
|
||
|
|
double duration=(audio.length-44)/32000.0;if(duration<0.35||duration>30)throw new IOException("Audio duration outside quality range");
|
||
|
|
long power=0,active=0,clipped=0;int samples=(audio.length-44)/2;b.position(44);
|
||
|
|
while(b.hasRemaining()){int value=b.getShort();power+=(long)value*value;if(Math.abs(value)>100)active++;if(Math.abs(value)>=32760)clipped++;}
|
||
|
|
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("Audio silence/volume/clipping quality check failed");
|
||
|
|
JSONObject q=new JSONObject();q.put("duration_seconds",BigDecimal.valueOf(duration).setScale(2,java.math.RoundingMode.HALF_UP));q.put("rms",rms);q.put("active_ratio",activeRatio);q.put("clipping_ratio",clipRatio);q.put("sample_rate",16000);q.put("channels",1);q.put("bits",16);return q;
|
||
|
|
}
|
||
|
|
static void save(Path path,JSONObject value)throws IOException{Path temporary=path.resolveSibling(path.getFileName()+".tmp");Files.writeString(temporary,JSON.toJSONString(value));Files.move(temporary,path,StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.ATOMIC_MOVE);}
|
||
|
|
static void progress(String state,String error)throws Exception{
|
||
|
|
JSONObject p=new JSONObject();p.put("batch",BATCH);p.put("state",state);p.put("target",50000);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()-runStarted)/1_000_000);if(error!=null)p.put("error",error);save(ROOT.resolve("progress.json"),p);
|
||
|
|
}
|
||
|
|
static void auditDatabase(Connection c)throws Exception{
|
||
|
|
for(String table:List.of("tts_synthesize_task","tts_corpus_info"))if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM "+table+" WHERE remark=?",BATCH)!=50000)throw new IllegalStateException("Final row count mismatch");
|
||
|
|
if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_synthesize_task WHERE remark=? AND status='2'",BATCH)!=50000)throw new IllegalStateException("Final success count mismatch");
|
||
|
|
if(CorpusDatabase.count(c,"SELECT COUNT(*) FROM (SELECT voice,language,text FROM tts_corpus_info WHERE remark=? GROUP BY voice,language,text HAVING COUNT(*)>1) d",BATCH)!=0)throw new IllegalStateException("Final duplicates found");
|
||
|
|
Map<String,JSONObject> actual=new HashMap<>();
|
||
|
|
for(Object o:CorpusDatabase.query(c,"SELECT id,text,voice,language,dialect,category_id,emotion,audio_file_path,audio_duration,file_size FROM tts_corpus_info WHERE remark=?",BATCH)){JSONObject row=(JSONObject)o;actual.put(row.getString("id"),row);}
|
||
|
|
for(JSONObject job:jobs){
|
||
|
|
JSONObject row=actual.remove(job.getString("id"));
|
||
|
|
if(row==null)throw new IllegalStateException("Final planned corpus missing");
|
||
|
|
for(String field:List.of("text","voice","language","dialect","emotion"))if(!job.getString(field).equals(row.getString(field)))throw new IllegalStateException("Final corpus differs from reviewed plan: "+field);
|
||
|
|
String expectedObject="tts/"+BATCH+"/"+job.getString("voice")+"/"+job.getString("id")+".wav";
|
||
|
|
if(!categoryId(job.getIntValue("category_index")).equals(row.getString("category_id"))||!expectedObject.equals(row.getString("audio_file_path"))||row.getBigDecimal("audio_duration").signum()<=0||row.getLongValue("file_size")<=44)throw new IllegalStateException("Final category/audio metadata mismatch");
|
||
|
|
}
|
||
|
|
if(!actual.isEmpty())throw new IllegalStateException("Unexpected corpus outside reviewed plan");
|
||
|
|
JSONObject audit=new JSONObject();audit.put("voices",CorpusDatabase.query(c,"SELECT voice,language,dialect,COUNT(*) AS n FROM tts_corpus_info WHERE remark=? GROUP BY voice,language,dialect",BATCH));audit.put("categories",CorpusDatabase.query(c,"SELECT category_id,COUNT(*) AS n FROM tts_corpus_info WHERE remark=? GROUP BY category_id",BATCH));audit.put("completed_at",Instant.now().toString());save(ROOT.resolve("database-audit.json"),audit);
|
||
|
|
}
|
||
|
|
static void status()throws Exception{
|
||
|
|
CorpusDatabase.init();try(Connection c=CorpusDatabase.connect()){
|
||
|
|
JSONObject s=new JSONObject();s.put("batch",BATCH);s.put("old_pilot_corpus",CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE remark=?",CorpusDatabase.PILOT));
|
||
|
|
s.put("corpus",CorpusDatabase.count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE remark=?",BATCH));s.put("tasks",CorpusDatabase.query(c,"SELECT status,COUNT(*) AS n FROM tts_synthesize_task WHERE remark=? GROUP BY status",BATCH));
|
||
|
|
s.put("voices",CorpusDatabase.query(c,"SELECT voice,language,dialect,COUNT(*) AS n FROM tts_corpus_info WHERE remark=? GROUP BY voice,language,dialect",BATCH));
|
||
|
|
s.put("categories",CorpusDatabase.query(c,"SELECT category_id,COUNT(*) AS n FROM tts_corpus_info WHERE remark=? GROUP BY category_id",BATCH));s.put("checked_at",Instant.now().toString());
|
||
|
|
save(ROOT.resolve("database-status.json"),s);System.out.println("DATABASE_STATUS "+s);
|
||
|
|
}
|
||
|
|
System.exit(0);
|
||
|
|
}
|
||
|
|
static void selfTest()throws Exception{
|
||
|
|
for(String language:List.of("en-US","ja-JP","ko-KR","ru-RU","de-DE")){
|
||
|
|
try{validateText("请打开空调。",language);throw new AssertionError("Chinese passed as "+language);}catch(IllegalArgumentException expected){}
|
||
|
|
}
|
||
|
|
Map<String,String> good=Map.of("zh-CN","请打开空调。","en-US","Please turn on the air conditioning.","ja-JP","エアコンをつけてください。","ko-KR","에어컨을 켜 주세요.","ru-RU","Включите кондиционер.","de-DE","Bitte schalten Sie die Klimaanlage ein.");
|
||
|
|
for(var sample:good.entrySet())validateText(sample.getValue(),sample.getKey());
|
||
|
|
try{checkAudio(new byte[44]);throw new AssertionError("Invalid audio passed");}catch(IOException expected){}
|
||
|
|
Path trial=Path.of("data/tts-pilot/voice15-20261114");JSONObject summary=JSON.parseObject(Files.readString(trial.resolve("summary.json")));
|
||
|
|
for(Object o:summary.getJSONArray("items")){JSONObject item=(JSONObject)o;Path audio=trial.resolve(item.getString("audio_file"));if(!Files.exists(audio))audio=backupBase().resolve("voice15-20261114").resolve(item.getString("audio_file"));checkAudio(Files.readAllBytes(audio));}
|
||
|
|
System.out.println("SELF_TEST_OK wrong-language gates reject Chinese for all five foreign voices; valid native texts pass; all 15 real trial WAVs pass audio quality checks; paid calls=0");
|
||
|
|
}
|
||
|
|
}
|