import com.alibaba.fastjson2.*; import io.minio.*; import org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor; import org.springframework.core.env.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.security.MessageDigest; import java.sql.*; import java.util.*; import java.util.zip.*; /** Local production tooling; loads existing configuration without printing credentials. */ public class CorpusDatabase { static final String PILOT = "pilot100-20261113-x4-yezi"; static final Path ROOT = Path.of("data/tts-pilot/corpus50000-20261114"); static StandardEnvironment env; static String property(String key) { return env.getRequiredProperty(key); } static void init() { env = new StandardEnvironment(); env.getPropertySources().addFirst(new MapPropertySource("production", Map.of("spring.config.location", "file:cmvr-iot-admin/src/main/resources/application.yml"))); ConfigDataEnvironmentPostProcessor.applyTo(env); if (!"xfyun".equals(env.getProperty("tts.provider"))) throw new IllegalStateException("Expected xfyun provider"); } static Connection connect() throws Exception { Connection c = DriverManager.getConnection(property("spring.datasource.druid.master.url"), property("spring.datasource.druid.master.username"), property("spring.datasource.druid.master.password")); if (!"cmvr-iot-chengzhi".equals(c.getCatalog())) { c.close(); throw new IllegalStateException("Unexpected database; refusing writes"); } return c; } static MinioClient minio() { return MinioClient.builder().endpoint(property("minio.url")).credentials(property("minio.accessKey"), property("minio.secretKey")).build(); } static JSONArray query(Connection c, String sql, Object... params) throws Exception { try (PreparedStatement s = c.prepareStatement(sql)) { for (int i=0;iLong.parseLong(x.toString())).findFirst().orElseThrow(); } static String sha(byte[] bytes) throws Exception { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } public static void main(String[] args) throws Exception { System.setOut(new PrintStream(System.out,true,StandardCharsets.UTF_8)); init(); try (Connection c=connect()) { if (args.length==0 || "inspect".equals(args[0])) { for (String table: List.of("tts_synthesize_task","tts_corpus_info","tts_corpus_category")) { System.out.println(table+" "+query(c,"SELECT remark,COUNT(*) AS n FROM "+table+" GROUP BY remark")); System.out.println("SCHEMA "+table+" "+query(c,"SHOW COLUMNS FROM "+table)); } System.out.println("DICTIONARIES "+query(c,"SELECT dict_type,dict_label,dict_value,status FROM sys_dict_data WHERE dict_type IN ('tts_language','tts_voice','tts_emotion')")); } else if ("delete-pilot".equals(args[0])) deletePilot(c); else if ("generator-config".equals(args[0])) { Files.createDirectories(ROOT); JSONObject config=new JSONObject();config.put("base_url",property("tts.generalization.base-url"));config.put("model",property("tts.generalization.model"));config.put("api_key",env.getProperty("tts.generalization.api-key","")); Files.writeString(ROOT.resolve("runtime-config.json"),JSON.toJSONString(config)); System.out.println("Generator runtime configuration exported to ignored batch directory; credentials not printed."); } else throw new IllegalArgumentException("Unknown mode"); } System.exit(0); } static void deletePilot(Connection c) throws Exception { Path oldDir=Path.of("data/tts-pilot",PILOT), backupDir=ROOT.resolve("backup"); Files.createDirectories(backupDir); JSONObject manifest=JSON.parseObject(Files.readString(oldDir.resolve("manifest.json"))); JSONArray items=manifest.getJSONArray("items"); if (!PILOT.equals(manifest.getString("batch")) || items.size()!=100) throw new IllegalStateException("Unexpected pilot manifest"); JSONArray tasks=query(c,"SELECT * FROM tts_synthesize_task WHERE remark=?",PILOT); JSONArray corpus=query(c,"SELECT * FROM tts_corpus_info WHERE remark=?",PILOT); JSONArray categories=query(c,"SELECT * FROM tts_corpus_category WHERE remark=?",PILOT); Path backup=backupDir.resolve("pilot100-database-and-audio.zip"); if (tasks.isEmpty() && corpus.isEmpty() && categories.isEmpty()) { if (!Files.isRegularFile(backup)) throw new IllegalStateException("Records absent without a verified backup"); } else { if (tasks.size()!=100 || corpus.size()!=100 || categories.size()!=11) throw new IllegalStateException("Pilot row count changed; refusing partial deletion"); Map byTask=new HashMap<>(),byCorpus=new HashMap<>(); for(Object o:tasks){JSONObject r=(JSONObject)o;byTask.put(r.getString("id"),r);} for(Object o:corpus){JSONObject r=(JSONObject)o;byCorpus.put(r.getString("id"),r);} for(Object o:items){JSONObject item=(JSONObject)o; JSONObject task=byTask.get(item.getString("task_id")), row=byCorpus.get(item.getString("corpus_id")); if(task==null||row==null)throw new IllegalStateException("Pilot IDs no longer match"); for(JSONObject r:List.of(task,row)) if(!item.getString("text").equals(r.getString("text")) || !item.getString("object_path").equals(r.getString("audio_file_path")) || !"x4_yezi".equals(r.getString("voice")))throw new IllegalStateException("Pilot content changed; refusing deletion"); } for(Object o:categories){JSONObject cat=(JSONObject)o; if(count(c,"SELECT COUNT(*) FROM tts_corpus_info WHERE category_id=? AND COALESCE(remark,'')<>?",cat.getString("id"),PILOT)!=0 || count(c,"SELECT COUNT(*) FROM tts_corpus_category WHERE parent_id=? AND COALESCE(remark,'')<>?",cat.getString("id"),PILOT)!=0)throw new IllegalStateException("Pilot category used by other data"); } JSONObject database=new JSONObject();database.put("tts_synthesize_task",tasks);database.put("tts_corpus_info",corpus);database.put("tts_corpus_category",categories); Path temporary=backupDir.resolve("pilot100-backup.tmp.zip"); try(ZipOutputStream zip=new ZipOutputStream(Files.newOutputStream(temporary),StandardCharsets.UTF_8)){ zipEntry(zip,"database.json",JSON.toJSONBytes(database));zipEntry(zip,"manifest.json",Files.readAllBytes(oldDir.resolve("manifest.json"))); for(Object o:items){JSONObject item=(JSONObject)o;byte[] audio=Files.readAllBytes(oldDir.resolve("audio").resolve(item.getString("task_id")+".wav")); if(!sha(audio).equals(item.getString("sha256")))throw new IllegalStateException("Pilot local audio hash mismatch"); zipEntry(zip,"audio/"+item.getString("task_id")+".wav",audio); } } try(ZipFile zip=new ZipFile(temporary.toFile(),StandardCharsets.UTF_8)){ if(zip.size()!=102)throw new IllegalStateException("Backup entry count mismatch"); for(Object o:items){JSONObject item=(JSONObject)o;try(InputStream input=zip.getInputStream(zip.getEntry("audio/"+item.getString("task_id")+".wav"))){if(!sha(input.readAllBytes()).equals(item.getString("sha256")))throw new IllegalStateException("Backup audio verification failed");}} } Files.move(temporary,backup,StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.ATOMIC_MOVE); c.setAutoCommit(false); try { // Recheck under locks before deleting exactly the backed-up IDs. if(query(c,"SELECT id FROM tts_synthesize_task WHERE remark=? FOR UPDATE",PILOT).size()!=100 || query(c,"SELECT id FROM tts_corpus_info WHERE remark=? FOR UPDATE",PILOT).size()!=100)throw new IllegalStateException("Concurrent pilot changes"); for(Object o:items){JSONObject item=(JSONObject)o; if(update(c,"DELETE FROM tts_corpus_info WHERE id=? AND remark=?",item.getString("corpus_id"),PILOT)!=1)throw new IllegalStateException("Corpus delete mismatch"); if(update(c,"DELETE FROM tts_synthesize_task WHERE id=? AND remark=?",item.getString("task_id"),PILOT)!=1)throw new IllegalStateException("Task delete mismatch"); } for(Object o:categories){JSONObject cat=(JSONObject)o;if(update(c,"DELETE FROM tts_corpus_category WHERE id=? AND remark=?",cat.getString("id"),PILOT)!=1)throw new IllegalStateException("Category delete mismatch");} c.commit(); }catch(Exception e){c.rollback();throw e;}finally{c.setAutoCommit(true);} } MinioClient minio=minio();String bucket=property("minio.bucketName");int removed=0; for(Object o:items){JSONObject item=(JSONObject)o;String object=item.getString("object_path"); if(!object.matches("tts/2026/11/13/[A-Za-z0-9-]+\\.wav"))throw new IllegalStateException("Unexpected pilot object path"); for(String table:List.of("tts_synthesize_task","tts_corpus_info"))if(count(c,"SELECT COUNT(*) FROM "+table+" WHERE audio_file_path=?",object)!=0)throw new IllegalStateException("Audio still referenced; refusing removal"); minio.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(object).build()); try{minio.statObject(StatObjectArgs.builder().bucket(bucket).object(object).build());throw new IllegalStateException("Pilot object still exists");} catch(io.minio.errors.ErrorResponseException missing){if(!Set.of("NoSuchKey","NoSuchObject").contains(missing.errorResponse().code()))throw missing;} removed++; } JSONObject receipt=new JSONObject();receipt.put("deleted_tasks",100);receipt.put("deleted_corpus",100);receipt.put("deleted_categories",11);receipt.put("removed_remote_audio",removed);receipt.put("backup",backup.toString());receipt.put("deleted_at",java.time.Instant.now().toString()); Files.writeString(backupDir.resolve("deletion-receipt.json"),JSON.toJSONString(receipt)); System.out.println("PILOT_REMOVED "+receipt); } static void zipEntry(ZipOutputStream zip,String name,byte[] bytes)throws Exception{zip.putNextEntry(new ZipEntry(name));zip.write(bytes);zip.closeEntry();} }