zziang commited on
Commit
97e2893
·
verified ·
1 Parent(s): 0f5baba

director: six prefixed lines instead of JSON

Browse files
Files changed (1) hide show
  1. kaggle/director_probe.py +82 -61
kaggle/director_probe.py CHANGED
@@ -1,17 +1,20 @@
1
  """Director stage: turn a topic into a script the TTS front end can consume.
2
 
3
- Why the contract and not just "valid JSON": a line that parses can still be
4
- unusable. Five characters is short enough for the whisper voice to collapse into
5
- silence, digits and Latin words bypass the normaliser we turned off, and emoji
6
- break the text encoder. So the checks here are the ones the radio stage needs.
 
 
 
7
 
8
  Runs on transformers 5.x. Ming pins 4.46.3, so this is a separate process and
9
- leaves a JSON file behind rather than calling TTS directly.
10
 
11
  Modes (`MODE`):
12
  probe - N samples with the prompt as written, report pass rate
13
- collect - rejection-sample accepted scripts into sft.jsonl
14
- eval - score the current model on a fixed topic list
15
  """
16
  import json
17
  import os
@@ -23,12 +26,12 @@ ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
23
  MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B")
24
  ADAPTER = os.environ.get("ADAPTER", "")
25
  MODE = os.environ.get("MODE", "probe")
26
- N_SAMPLES = int(os.environ.get("N_SAMPLES", "6"))
27
  OUT = ROOT / "director"
28
 
29
- N_LINES = 6
30
- STYLES = ["开场", "叙述", "故事", "叙述", "耳语", "耳语"]
31
  MIN_CHARS, MAX_CHARS = 8, 40
 
32
  ALLOWED = re.compile(r"^[\u4e00-\u9fff,。?!、;:…——“”‘’「」《》]+$")
33
 
34
  TOPICS = [
@@ -37,18 +40,21 @@ TOPICS = [
37
  "一场没有下完的雨",
38
  ]
39
 
40
- SYSTEM = "你是深夜电台的编剧,只输出 JSON 数组,不解释,不用代码块。"
 
 
41
 
42
- RULES = """写一段约 60 秒的深夜电台串词。
43
 
44
- 规则:
45
- 1. 正好 6 组,style 依次是:开场、叙述、故事、叙述、耳语、耳语。
46
- 2. 每组是一个独立的大括号对象,形如 {"style":"叙述","text":"..."},六组之间用逗号隔开。
47
- 3. text 每句 8 到 40 个汉字,只能有汉字和,。?!这几种标点。
48
- 4. 不要数字、英文、emoji、引号、括号;不要提前结束,一定写满 6 组。"""
49
 
50
- SHOT = """例子:
51
- [{"style":"开场","text":"晚上好,这里是深夜频道,我是今晚陪你的人。"},{"style":"叙述","text":"窗外的雨下了一整晚,路灯把水汽照成一片模糊的黄。"},{"style":"故事","text":"很多年前这条街上有一家很小的唱片店,老板总在打烊前放同一首歌。"},{"style":"叙述","text":"如果你还醒着,就把灯关小一点,让声音替你把今天收好。"},{"style":"耳语","text":"后来店关了,歌还在。"},{"style":"耳语","text":"晚安,我们明天见。"}]"""
 
 
 
 
 
52
 
53
 
54
  def log(msg: str) -> None:
@@ -56,36 +62,52 @@ def log(msg: str) -> None:
56
 
57
 
58
  def build_prompt(topic: str, few_shot: bool = True) -> str:
59
- head = RULES if few_shot else "写一段约 60 秒的深夜电台串词,正好 6 组 style 依次是开场、叙述、故事、叙述、耳语、耳语。"
60
- body = f"{head}\n\n{SHOT}\n\n现在写「{topic}」。" if few_shot else f"{head}\n\n题目:{topic}。只输出 JSON 数组。"
61
- return body
62
-
63
-
64
- def parse(raw: str) -> list[dict]:
65
- """Pair-scan instead of json.loads.
66
-
67
- The 0.8B model reliably writes the fields and unreliably the braces: one
68
- observed answer opened a single object and repeated "style"/"text" six
69
- times. Scanning for the pairs survives that; json.loads cannot.
70
- """
71
- pairs = re.findall(r'"style"\s*:\s*"([^"]*)"\s*,\s*"text"\s*:\s*"([^"]*)"', raw)
72
- if not pairs:
73
- pairs = [(s, t) for t, s in re.findall(
74
- r'"text"\s*:\s*"([^"]*)"\s*,\s*"style"\s*:\s*"([^"]*)"', raw)]
75
- return [{"style": s, "text": t} for s, t in pairs if t.strip()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
 
78
  def check(lines: list[dict]) -> dict:
79
  bad = []
80
- if len(lines) != N_LINES:
81
  bad.append(f"count={len(lines)}")
82
  for i, l in enumerate(lines):
83
  t = l.get("text", "")
84
- if i < N_LINES and l.get("style") != STYLES[i]:
85
  bad.append(f"L{i}:style={l.get('style')!r}")
86
  if not (MIN_CHARS <= len(t) <= MAX_CHARS):
87
  bad.append(f"L{i}:len={len(t)}")
88
- if not ALLOWED.match(t):
89
  bad.append(f"L{i}:chars")
90
  return {"ok": not bad, "violations": bad}
91
 
@@ -119,7 +141,7 @@ def sample(tok, model, topic: str, few_shot: bool = True) -> dict:
119
  repetition_penalty=1.05,
120
  pad_token_id=tok.eos_token_id)
121
  raw = tok.decode(gen[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
122
- lines = parse(raw)
123
  return {"topic": topic, "seconds": round(time.time() - t0, 1),
124
  "n_tokens": int(gen.shape[1] - ids["input_ids"].shape[1]),
125
  "lines": lines, "raw": raw, **check(lines)}
@@ -129,7 +151,7 @@ def main() -> None:
129
  OUT.mkdir(parents=True, exist_ok=True)
130
  tok, model = load_model()
131
 
132
- if MODE == "probe":
133
  rows = [sample(tok, model, TOPICS[i % len(TOPICS)]) for i in range(N_SAMPLES)]
134
  for r in rows:
135
  log(f"{r['topic'][:8]:<10} {r['seconds']:>4}s n={len(r['lines'])} ok={r['ok']} {r['violations'][:3]}")
@@ -137,32 +159,31 @@ def main() -> None:
137
  log(f" [{l.get('style')}] {len(l.get('text',''))}字 {l.get('text')}")
138
  ok = sum(r["ok"] for r in rows)
139
  log(f"pass {ok}/{len(rows)}")
140
- (OUT / "probe.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
141
 
142
  elif MODE == "collect":
143
- target = int(os.environ.get("TARGET", "120"))
144
- got = []
145
- tries = 0
146
- ticks = 0
147
- while len(got) < target and ticks < 40:
148
- topic = TOPICS[ticks % len(TOPICS)]
149
  r = sample(tok, model, topic)
150
  tries += 1
151
- ticks += 1
152
- if r["ok"]:
153
- got.append({"topic": topic, "lines": r["lines"]})
154
- if tries % 10 == 0:
155
- log(f"{tries} tried, {len(got)} kept ({len(got)/tries:.0%})")
 
 
 
 
 
 
156
  with open(OUT / "sft.jsonl", "w") as f:
157
- for g in got:
158
  f.write(json.dumps(g, ensure_ascii=False) + "\n")
159
- log(f"kept {len(got)} of {tries}")
160
-
161
- elif MODE == "eval":
162
- rows = [sample(tok, model, TOPICS[i % len(TOPICS)]) for i in range(N_SAMPLES)]
163
- ok = sum(r["ok"] for r in rows)
164
- log(f"pass {ok}/{len(rows)}")
165
- (OUT / "eval.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
166
 
167
 
168
  if __name__ == "__main__":
 
1
  """Director stage: turn a topic into a script the TTS front end can consume.
2
 
3
+ The 0.8B model is good at prose and bad at JSON punctuation: zero-shot it wrote
4
+ the array as one object with repeated keys, and in 3 of 6 samples it closed the
5
+ bracket after a single line. Few-shot fixed the structure but not the counts.
6
+
7
+ So the director no longer writes JSON. It writes six prefixed lines, which is
8
+ pattern completion - the thing a small LM is actually reliable at - and the host
9
+ does the parsing. `parse_script` still accepts JSON if a model insists.
10
 
11
  Runs on transformers 5.x. Ming pins 4.46.3, so this is a separate process and
12
+ leaves a file behind rather than calling TTS directly.
13
 
14
  Modes (`MODE`):
15
  probe - N samples with the prompt as written, report pass rate
16
+ collect - keep accepted scripts (repairing lengths) into sft.jsonl
17
+ eval - score the current model on the fixed topic list
18
  """
19
  import json
20
  import os
 
26
  MODEL_ID = os.environ.get("DIRECTOR_MODEL", "Qwen/Qwen3.5-0.8B")
27
  ADAPTER = os.environ.get("ADAPTER", "")
28
  MODE = os.environ.get("MODE", "probe")
29
+ N_SAMPLES = int(os.environ.get("N_SAMPLES", "8"))
30
  OUT = ROOT / "director"
31
 
32
+ SLOTS = ["开场", "叙述", "故事", "叙述", "耳语", "耳语"]
 
33
  MIN_CHARS, MAX_CHARS = 8, 40
34
+ LATIN_OR_DIGIT = re.compile(r"[A-Za-z0-9]")
35
  ALLOWED = re.compile(r"^[\u4e00-\u9fff,。?!、;:…——“”‘’「」《》]+$")
36
 
37
  TOPICS = [
 
40
  "一场没有下完的雨",
41
  ]
42
 
43
+ SYSTEM = "你是深夜电台的编剧。按给定格式写串词,不解释,不加标题。"
44
+
45
+ RULES = """写一段约 60 秒的深夜电台串词。一共六行,每行以标签开头,格式是「标签:正文」。
46
 
47
+ 六行的标签依次是:开场、叙述、故事、叙述、耳语、耳语。
48
 
49
+ 正文规则:每行 8 到 40 个汉字;只能用汉字和,。?!这几种标点;不要数字、英文、emoji、引号、括号。"""
 
 
 
 
50
 
51
+ SHOT = """示例:
52
+ 开场:晚上好,这里是深夜频道,我是今晚陪你的人。
53
+ 叙述:窗外的雨下了一整晚,路灯把水汽照成一片模糊的黄。
54
+ 故事:很多年前这条街上有一家很小的唱片店,老板总在打烊前放同一首歌。
55
+ 叙述:如果你还醒着,就把灯关小一点,让声音替你把今天收好。
56
+ 耳语:后来店关了,歌还在。
57
+ 耳语:晚安,我们明天见。"""
58
 
59
 
60
  def log(msg: str) -> None:
 
62
 
63
 
64
  def build_prompt(topic: str, few_shot: bool = True) -> str:
65
+ head = f"{RULES}\n\n{SHOT}" if few_shot else RULES
66
+ return f"{head}\n\n现在写「{topic}」,只输出这六行。"
67
+
68
+
69
+ def parse_script(raw: str) -> list[dict]:
70
+ """Read either six prefixed lines or (if a model insists) a JSON array."""
71
+ out = []
72
+ for line in raw.splitlines():
73
+ line = line.strip().strip("`").strip()
74
+ if not line:
75
+ continue
76
+ m = re.match(r"^(开场|叙述|故事|耳语)\s*[::]\s*(.+)$", line)
77
+ if m:
78
+ out.append({"style": m.group(1), "text": m.group(2).strip()})
79
+ continue
80
+ m = re.search(r'"style"\s*:\s*"([^"]*)"\s*,\s*"text"\s*:\s*"([^"]*)"', line)
81
+ if m:
82
+ out.append({"style": m.group(1), "text": m.group(2)})
83
+ if not out:
84
+ pairs = re.findall(r'"style"\s*:\s*"([^"]*)"\s*,\s*"text"\s*:\s*"([^"]*)"', raw)
85
+ out = [{"style": s, "text": t} for s, t in pairs if t.strip()]
86
+ return out
87
+
88
+
89
+ def trim(text: str) -> str:
90
+ """Cut an over-long line at its last clause boundary under the limit."""
91
+ if len(text) <= MAX_CHARS:
92
+ return text
93
+ cut = text[:MAX_CHARS]
94
+ for i in range(len(cut) - 1, MIN_CHARS - 1, -1):
95
+ if cut[i] in ",。?!":
96
+ return cut[:i] + "。"
97
+ return cut[: MAX_CHARS - 1] + "。"
98
 
99
 
100
  def check(lines: list[dict]) -> dict:
101
  bad = []
102
+ if len(lines) != len(SLOTS):
103
  bad.append(f"count={len(lines)}")
104
  for i, l in enumerate(lines):
105
  t = l.get("text", "")
106
+ if i < len(SLOTS) and l.get("style") != SLOTS[i]:
107
  bad.append(f"L{i}:style={l.get('style')!r}")
108
  if not (MIN_CHARS <= len(t) <= MAX_CHARS):
109
  bad.append(f"L{i}:len={len(t)}")
110
+ if LATIN_OR_DIGIT.search(t) or not ALLOWED.match(t):
111
  bad.append(f"L{i}:chars")
112
  return {"ok": not bad, "violations": bad}
113
 
 
141
  repetition_penalty=1.05,
142
  pad_token_id=tok.eos_token_id)
143
  raw = tok.decode(gen[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
144
+ lines = parse_script(raw)
145
  return {"topic": topic, "seconds": round(time.time() - t0, 1),
146
  "n_tokens": int(gen.shape[1] - ids["input_ids"].shape[1]),
147
  "lines": lines, "raw": raw, **check(lines)}
 
151
  OUT.mkdir(parents=True, exist_ok=True)
152
  tok, model = load_model()
153
 
154
+ if MODE in ("probe", "eval"):
155
  rows = [sample(tok, model, TOPICS[i % len(TOPICS)]) for i in range(N_SAMPLES)]
156
  for r in rows:
157
  log(f"{r['topic'][:8]:<10} {r['seconds']:>4}s n={len(r['lines'])} ok={r['ok']} {r['violations'][:3]}")
 
159
  log(f" [{l.get('style')}] {len(l.get('text',''))}字 {l.get('text')}")
160
  ok = sum(r["ok"] for r in rows)
161
  log(f"pass {ok}/{len(rows)}")
162
+ (OUT / f"{MODE}.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
163
 
164
  elif MODE == "collect":
165
+ target = int(os.environ.get("TARGET", "160"))
166
+ max_tries = int(os.environ.get("MAX_TRIES", "600"))
167
+ kept, tries = [], 0
168
+ while len(kept) < target and tries < max_tries:
169
+ topic = TOPICS[tries % len(TOPICS)]
 
170
  r = sample(tok, model, topic)
171
  tries += 1
172
+ if len(r["lines"]) != len(SLOTS):
173
+ continue
174
+ # The label is positional anyway (it decides which voice speaks),
175
+ # so relabel by position and repair over-long lines instead of
176
+ # throwing the whole script away.
177
+ lines = [{"style": SLOTS[i], "text": trim(l["text"])} for i, l in enumerate(r["lines"])]
178
+ if any(LATIN_OR_DIGIT.search(l["text"]) or len(l["text"]) < MIN_CHARS for l in lines):
179
+ continue
180
+ kept.append({"topic": topic, "lines": lines})
181
+ if len(kept) % 10 == 0:
182
+ log(f"{tries} tried, {len(kept)} kept ({len(kept)/tries:.0%})")
183
  with open(OUT / "sft.jsonl", "w") as f:
184
+ for g in kept:
185
  f.write(json.dumps(g, ensure_ascii=False) + "\n")
186
+ log(f"kept {len(kept)} of {tries}")
 
 
 
 
 
 
187
 
188
 
189
  if __name__ == "__main__":