Chinese_Debate_Documents / scripts /extract_transcripts.py
DBWBD's picture
updated
6342c6d
"""Extract speaker-segmented Chinese debate transcripts from .doc / .docx files
into a JSONL dataset.
Source layout in this repo:
docs/ — 107 .doc files (legacy OLE Word97-2003)
机器-订单转写结果-*/ — 43 folders × ~45 .docx files (modern OOXML)
Each file is an ASR transcription of a single debate session. Word's text-export
delimits the speaker-tagged segments with `\r` between segments and `\v` (VT,
0x0B) between the header (`说话人N HH:MM`) and the body text.
We extract via Word COM (works for both .doc and .docx) because the alternative
Python-only paths (python-docx, mammoth) only handle .docx and pip cannot reach
PyPI from this network.
Output: data/_train_raw.jsonl with one record per file.
"""
from __future__ import annotations
import json
import re
import sys
import time
import traceback
from pathlib import Path
import pythoncom
import win32com.client
REPO = Path(__file__).resolve().parent.parent
OUT_DIR = REPO / "data"
OUT_JSONL = OUT_DIR / "_train_raw.jsonl"
ERR_LOG = OUT_DIR / "_extract_errors.log"
# ---------- filename metadata parsers ----------
# Three filename patterns observed across the two source generations.
#
# Format A (docs/ named files): "<topic>丨<round> <team_a>vs<team_b>_音频.<ext>..."
# 丨 is U+FF5C — the full-width vertical bar separator used in the original titles.
FORMAT_A_RE = re.compile(
r"^(?P<topic>.+?)丨(?P<round>.+?) (?P<team_a>.+?)vs(?P<team_b>.+?)_音频",
re.IGNORECASE,
)
# Format B (early order folders): "<id>-<round> <team_a> VS <team_b> <topic>-<NNN>P ..."
# Uppercase `VS` surrounded by whitespace; topic follows the teams.
FORMAT_B_RE = re.compile(
r"^(?P<id>\d+)-(?P<round>\S+?)\s+(?P<team_a>\S+?)\s+VS\s+(?P<team_b>\S+?)\s+(?P<topic>.+?)-\d{3,4}P"
)
# Format C (later order folders): "<id>-<date>日 <round-tag> <topic> <team_a>vs<team_b>-<NNN>P"
# Lowercase `vs` glued to team names; an optional `<N月N日>` date prefix on
# the round-tag (e.g. `7月27日 中学团队赛`); topic precedes the teams.
FORMAT_C_RE = re.compile(
r"^(?P<id>\d+)-(?P<head>.+?)\s+(?P<team_a>\S+?)vs(?P<team_b>\S+?)-\d{3,4}P"
)
FORMAT_C_DATE_RE = re.compile(r"^(?P<date>\d+月\d+\s*日)\s+(?P<rest>.+)$")
def parse_filename(stem: str) -> dict:
"""Return metadata dict from a filename stem. Always has the four keys;
values are None when no pattern matches."""
out = {"topic": None, "round": None, "team_a": None, "team_b": None}
m = FORMAT_A_RE.search(stem)
if m:
out.update({
"topic": m["topic"].strip(),
"round": m["round"].strip(),
"team_a": m["team_a"].strip(),
"team_b": m["team_b"].strip(),
})
return out
m = FORMAT_B_RE.search(stem)
if m:
out.update({
"topic": m["topic"].strip(),
"round": m["round"].strip(),
"team_a": m["team_a"].strip(),
"team_b": m["team_b"].strip(),
})
return out
m = FORMAT_C_RE.search(stem)
if m:
head = m["head"].strip()
out["team_a"] = m["team_a"].strip()
out["team_b"] = m["team_b"].strip()
date_m = FORMAT_C_DATE_RE.match(head)
if date_m:
rest = date_m["rest"].strip()
parts = rest.split(maxsplit=1)
if len(parts) == 2:
out["round"] = f"{date_m['date'].strip()} {parts[0].strip()}"
out["topic"] = parts[1].strip()
else:
out["round"] = f"{date_m['date'].strip()} {rest}"
else:
# No date prefix — take the first whitespace-delimited token as
# round, remainder as topic.
parts = head.split(maxsplit=1)
if len(parts) == 2:
out["round"] = parts[0].strip()
out["topic"] = parts[1].strip()
else:
out["round"] = head
return out
return out
# ---------- transcript segmentation ----------
# Header inside one segment: "说话人N HH:MM" then VT then body
SEGMENT_HEADER_RE = re.compile(r"^\s*说话人(\d+)\s+(\d{1,2}:\d{2})\v(.*)$", re.DOTALL)
def parse_segments(text: str) -> list[dict]:
"""Split Word-exported text into a list of {speaker_id, timestamp, text}."""
segs: list[dict] = []
for chunk in text.split("\r"):
m = SEGMENT_HEADER_RE.match(chunk)
if not m:
continue
body = m.group(3).strip()
body = body.replace("\v", " ").replace("\x07", "") # strip stray VT/BEL
segs.append({
"speaker_id": int(m.group(1)),
"timestamp": m.group(2),
"text": body,
})
return segs
def normalize_full_text(text: str) -> str:
"""Flatten Word's `\r` / `\v` line separators to regular newlines so the raw
transcript column is human-readable."""
return text.replace("\v", "\n").replace("\r", "\n").strip()
# ---------- iteration ----------
def iter_source_files() -> list[tuple[Path, str]]:
"""Return (path, source_collection) tuples for every transcript file."""
items: list[tuple[Path, str]] = []
docs = REPO / "docs"
if docs.is_dir():
for f in sorted(docs.iterdir()):
if f.name.startswith("~$") or not f.is_file():
continue
if f.suffix.lower() in {".doc", ".docx"}:
items.append((f, "docs"))
for d in sorted(REPO.iterdir()):
if not (d.is_dir() and d.name.startswith("机器-订单")):
continue
for f in sorted(d.iterdir()):
if f.name.startswith("~$") or not f.is_file():
continue
if f.suffix.lower() in {".doc", ".docx"}:
items.append((f, d.name))
return items
# ---------- main extract loop ----------
def _record_id(path: Path, source: str) -> str:
return f"{source}/{path.stem}" if source != "docs" else path.stem
def _load_done_ids() -> set[str]:
"""Resume support: any id already in OUT_JSONL is considered done."""
if not OUT_JSONL.exists():
return set()
ids: set[str] = set()
with open(OUT_JSONL, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
ids.add(json.loads(line)["id"])
except Exception:
pass
return ids
def _spawn_word():
word = win32com.client.gencache.EnsureDispatch("Word.Application")
word.Visible = False
word.DisplayAlerts = False
return word
def _quit_word(word) -> None:
try:
word.Quit(SaveChanges=False)
except Exception:
pass
def main() -> int:
OUT_DIR.mkdir(exist_ok=True)
sources = iter_source_files()
done = _load_done_ids()
todo = [(p, s) for (p, s) in sources if _record_id(p, s) not in done]
print(
f"Found {len(sources)} source files; {len(done)} already extracted; "
f"{len(todo)} to do.",
flush=True,
)
pythoncom.CoInitialize()
word = _spawn_word()
written = len(done)
failed: list[tuple[str, str]] = []
consecutive_word_restarts = 0
t0 = time.time()
# Append mode so resumes don't truncate prior progress.
with open(OUT_JSONL, "a", encoding="utf-8") as out:
for i, (path, source) in enumerate(todo, 1):
attempt = 0
text: str | None = None
while attempt < 3:
attempt += 1
try:
doc = word.Documents.Open(
str(path), ReadOnly=True, AddToRecentFiles=False
)
try:
text = doc.Range().Text
finally:
doc.Close(SaveChanges=False)
break
except Exception as e:
msg = repr(e)
print(f" retry {attempt} on {path.name}: {msg}", flush=True)
# Likely Word died — kill and respawn.
_quit_word(word)
try:
word = _spawn_word()
consecutive_word_restarts += 1
except Exception as e2:
failed.append((str(path), f"respawn failed: {e2!r}"))
text = None
break
# If Word has died too many times in a row, bail.
if consecutive_word_restarts > 5:
failed.append((str(path), "too many consecutive Word restarts"))
text = None
break
if text is None:
failed.append((str(path), "exhausted retries"))
continue
else:
consecutive_word_restarts = 0
meta = parse_filename(path.stem)
segs = parse_segments(text)
rec = {
"id": _record_id(path, source),
"source_collection": source,
"source_file": path.name,
"source_format": path.suffix.lower().lstrip("."),
"topic": meta["topic"],
"round": meta["round"],
"team_a": meta["team_a"],
"team_b": meta["team_b"],
"num_segments": len(segs),
"num_chars": len(normalize_full_text(text)),
"transcript": normalize_full_text(text),
"segments": segs,
}
out.write(json.dumps(rec, ensure_ascii=False) + "\n")
out.flush()
written += 1
if i % 25 == 0:
rate = i / max(time.time() - t0, 0.001)
print(
f" {i}/{len(todo)} (+{written - len(done)} this run, "
f"{rate:.1f}/s, last: {path.name[:60]})",
flush=True,
)
_quit_word(word)
if failed:
with open(ERR_LOG, "a", encoding="utf-8") as ef:
for p, err in failed:
ef.write(f"{p}\t{err}\n")
elapsed = time.time() - t0
print(
f"\nDone. {written} total records in JSONL, "
f"{written - len(done)} new this run, {len(failed)} failed. "
f"Elapsed {elapsed:.1f}s. → {OUT_JSONL}",
flush=True,
)
if failed:
print(f" failures logged at {ERR_LOG}", flush=True)
return 0 if written else 1
if __name__ == "__main__":
try:
sys.exit(main())
except Exception:
traceback.print_exc()
sys.exit(2)