"""Director stage: turn a topic into a script the TTS front end can consume. The 0.8B model is good at prose and bad at JSON punctuation: zero-shot it wrote the array as one object with repeated keys, and in 3 of 6 samples it closed the bracket after a single line. Few-shot fixed the structure but not the counts. So the director no longer writes JSON. It writes six prefixed lines, which is pattern completion - the thing a small LM is actually reliable at - and the host does the parsing. `parse_script` still accepts JSON if a model insists. Runs on transformers 5.x. Ming pins 4.46.3, so this is a separate process and leaves a file behind rather than calling TTS directly. Modes (`MODE`): probe - N samples with the prompt as written, report pass rate collect - keep accepted scripts (repairing lengths) into sft.jsonl eval - score the current model on the fixed topic list """ import json import os import re import time from pathlib import Path ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working")) MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B") ADAPTER = os.environ.get("ADAPTER", "") MODE = os.environ.get("MODE", "probe") N_SAMPLES = int(os.environ.get("N_SAMPLES", "8")) OUT = ROOT / "director" SLOTS = ["开场", "叙述", "故事", "叙述", "耳语", "耳语"] MIN_CHARS, MAX_CHARS = 8, 40 # Whisper slots get a tighter cap. Measured: 8-15 character whisper lines come # out clean, a 24 character one collapsed to 0.4 s of near-silence in both the # teacher and the student. SLOT_MAX = [40, 40, 40, 40, 15, 15] LATIN_OR_DIGIT = re.compile(r"[A-Za-z0-9]") ALLOWED = re.compile(r"^[\u4e00-\u9fff,。?!、;:…——“”‘’「」《》]+$") TOPICS = [ "雨夜的末班公交", "一家很老的唱片店", "海边的灯塔", "凌晨的便利店", "搬家时翻出的旧照片", "楼下那棵一直没有开花的树", "深夜的收音机", "一场没有下完的雨", "旧公寓的电梯", "凌晨四点的菜市场", "山顶的观景台", "一个人的火锅店", "医院走廊的灯", "江边的长椅", "落了灰的钢琴", "雨天的出租车", "深夜的洗衣房", "开在二楼的旧书店", "废弃的火车站", "冬天的第一个霜降", "阳台上的那盆绿萝", "深夜的加油站", "清晨的面包房", "海边的小旅馆", "老街的修表摊", "天台上的风", "没有寄出的信", "一只总在窗边的猫", "雨停之后的马路", "深夜的游泳池", "断电的夜晚", "巷子尽头的路灯", "夏天最后一场雨", "老式闹钟的指针", "凌晨的公交站", "一条很长的隧道", "停电的电梯间", "小城的电影院", "合上的日记本", "厨房里烧开的水", ] SYSTEM = "你是深夜电台的编剧。按给定格式写串词,不解释,不加标题。" RULES = """写一段约 60 秒的深夜电台串词。一共六行,每行以标签开头,格式是「标签:正文」。 六行的标签依次是:开场、叙述、故事、叙述、耳语、耳语。 正文规则:每行 8 到 40 个汉字;只能用汉字和,。?!这几种标点;不要数字、英文、emoji、引号、括号。""" SHOT = """示例: 开场:晚上好,这里是深夜频道,我是今晚陪你的人。 叙述:窗外的雨下了一整晚,路灯把水汽照成一片模糊的黄。 故事:很多年前这条街上有一家很小的唱片店,老板总在打烊前放同一首歌。 叙述:如果你还醒着,就把灯关小一点,让声音替你把今天收好。 耳语:后来店关了,歌还在。 耳语:晚安,我们明天见。""" def log(msg: str) -> None: print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) def build_prompt(topic: str, few_shot: bool = True) -> str: head = f"{RULES}\n\n{SHOT}" if few_shot else RULES return f"{head}\n\n现在写「{topic}」,只输出这六行。" def parse_script(raw: str) -> list[dict]: """Read either six prefixed lines or (if a model insists) a JSON array.""" out = [] for line in raw.splitlines(): line = line.strip().strip("`").strip() if not line: continue m = re.match(r"^(开场|叙述|故事|耳语)\s*[::]\s*(.+)$", line) if m: out.append({"style": m.group(1), "text": m.group(2).strip()}) continue m = re.search(r'"style"\s*:\s*"([^"]*)"\s*,\s*"text"\s*:\s*"([^"]*)"', line) if m: out.append({"style": m.group(1), "text": m.group(2)}) if not out: pairs = re.findall(r'"style"\s*:\s*"([^"]*)"\s*,\s*"text"\s*:\s*"([^"]*)"', raw) out = [{"style": s, "text": t} for s, t in pairs if t.strip()] return out def trim(text: str, limit: int = MAX_CHARS) -> str: """Cut an over-long line at its last clause boundary under the limit.""" if len(text) <= limit: return text cut = text[:limit] for i in range(len(cut) - 1, MIN_CHARS - 1, -1): if cut[i] in ",。?!": return cut[:i] + "。" return cut[: limit - 1] + "。" def check(lines: list[dict]) -> dict: bad = [] if len(lines) != len(SLOTS): bad.append(f"count={len(lines)}") for i, l in enumerate(lines): t = l.get("text", "") if i < len(SLOTS) and l.get("style") != SLOTS[i]: bad.append(f"L{i}:style={l.get('style')!r}") if not (MIN_CHARS <= len(t) <= SLOT_MAX[min(i, len(SLOT_MAX) - 1)]): bad.append(f"L{i}:len={len(t)}") if LATIN_OR_DIGIT.search(t) or not ALLOWED.match(t): bad.append(f"L{i}:chars") return {"ok": not bad, "violations": bad} def load_model(): import torch from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained(MODEL_ID) model = AutoModelForCausalLM.from_pretrained( MODEL_ID, dtype=torch.float16, device_map="cuda:0").eval() if ADAPTER and Path(ADAPTER).exists(): from peft import PeftModel model = PeftModel.from_pretrained(model, ADAPTER).eval() log(f"adapter {ADAPTER}") log(f"loaded {MODEL_ID} -> {sum(p.numel() for p in model.parameters())/1e6:.0f}M params") return tok, model def sample(tok, model, topic: str, few_shot: bool = True) -> dict: import torch msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": build_prompt(topic, few_shot)}] text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) ids = tok([text], return_tensors="pt").to("cuda") t0 = time.time() with torch.no_grad(): gen = model.generate(**ids, max_new_tokens=512, do_sample=True, temperature=0.8, top_p=0.9, top_k=20, repetition_penalty=1.05, pad_token_id=tok.eos_token_id) raw = tok.decode(gen[0][ids["input_ids"].shape[1]:], skip_special_tokens=True) lines = parse_script(raw) return {"topic": topic, "seconds": round(time.time() - t0, 1), "n_tokens": int(gen.shape[1] - ids["input_ids"].shape[1]), "lines": lines, "raw": raw, **check(lines)} def main() -> None: OUT.mkdir(parents=True, exist_ok=True) tok, model = load_model() if MODE in ("probe", "eval"): rows = [sample(tok, model, TOPICS[i % len(TOPICS)]) for i in range(N_SAMPLES)] for r in rows: log(f"{r['topic'][:8]:<10} {r['seconds']:>4}s n={len(r['lines'])} ok={r['ok']} {r['violations'][:3]}") for l in r["lines"]: log(f" [{l.get('style')}] {len(l.get('text',''))}字 {l.get('text')}") ok = sum(r["ok"] for r in rows) log(f"pass {ok}/{len(rows)}") (OUT / f"{MODE}.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1)) elif MODE == "collect": target = int(os.environ.get("TARGET", "160")) max_tries = int(os.environ.get("MAX_TRIES", "600")) kept, tries = [], 0 while len(kept) < target and tries < max_tries: topic = TOPICS[tries % len(TOPICS)] r = sample(tok, model, topic) tries += 1 if len(r["lines"]) != len(SLOTS): continue # The label is positional anyway (it decides which voice speaks), # so relabel by position and repair over-long lines instead of # throwing the whole script away. lines = [{"style": SLOTS[i], "text": trim(l["text"], SLOT_MAX[i])} for i, l in enumerate(r["lines"])] if any(LATIN_OR_DIGIT.search(l["text"]) or len(l["text"]) < MIN_CHARS for l in lines): continue kept.append({"topic": topic, "lines": lines}) if len(kept) % 10 == 0: log(f"{tries} tried, {len(kept)} kept ({len(kept)/tries:.0%})") with open(OUT / "sft.jsonl", "w") as f: for g in kept: f.write(json.dumps(g, ensure_ascii=False) + "\n") log(f"kept {len(kept)} of {tries}") elif MODE == "script": # One programme: keep sampling until a script satisfies the contract, # then hand the radio stage a file it can read directly. topic = os.environ.get("TOPIC") or TOPICS[0] best = None for attempt in range(int(os.environ.get("TRIES", "6"))): r = sample(tok, model, topic) log(f"try {attempt}: n={len(r['lines'])} ok={r['ok']} {r['violations'][:3]}") if r["ok"]: best = r break if best is None and len(r["lines"]) >= len(SLOTS) - 1: best = r if best is None: raise SystemExit("no script generated") lines = [{"style": SLOTS[i], "text": trim(l["text"], SLOT_MAX[i])} for i, l in enumerate(best["lines"][:len(SLOTS)])] doc = {"model": MODEL_ID, "topic": topic, "tries": attempt + 1, "lines": lines} (OUT / "script.json").write_text(json.dumps(doc, ensure_ascii=False, indent=1)) log(f"wrote {OUT/'script.json'} ({len(lines)} lines, {best.get('seconds')}s)") if __name__ == "__main__": main()