File size: 10,619 Bytes
6342c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"""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)