from __future__ import annotations import os import subprocess import sys import threading import time import ctypes from pathlib import Path def _list_winword_pids() -> set[int]: if os.name != "nt": return set() try: proc = subprocess.run( ["tasklist", "/FO", "CSV", "/NH", "/FI", "IMAGENAME eq WINWORD.EXE"], capture_output=True, text=True, check=False, ) except Exception: return set() out: set[int] = set() for line in (proc.stdout or "").splitlines(): line = line.strip() if not line or line.startswith("INFO:"): continue cols = [part.strip().strip('"') for part in line.split('","')] if len(cols) < 2: cols = [part.strip().strip('"') for part in line.split(",")] if len(cols) < 2: continue try: out.add(int(cols[1])) except ValueError: continue return out def _kill_winword_pids(pids: set[int]) -> None: if os.name != "nt": return for pid in sorted(pids): try: subprocess.run( ["taskkill", "/PID", str(pid), "/F"], capture_output=True, text=True, check=False, ) except Exception: continue def _word_timeout_sec() -> int: raw = str(os.environ.get("EDKB_WORD_TIMEOUT_SEC", "120")).strip() try: value = int(raw) except ValueError: value = 120 return max(value, 10) def _should_accept_word_dialog( window_title: str, child_texts: list[str], button_texts: list[str] ) -> bool: text_blob = "\n".join(x.strip().lower() for x in child_texts if x.strip()) if not text_blob: return False has_repair_prompt = any( token in text_blob for token in [ "出现严重错误", "是否仍要打开", "serious error", "do you still want to open", ] ) if not has_repair_prompt: return False return any( text.strip().lower().startswith(("是", "yes")) or "&y" in text.lower() for text in button_texts ) def _start_word_dialog_watcher() -> tuple[threading.Event, threading.Thread | None]: stop_event = threading.Event() if os.name != "nt": return stop_event, None def _window_text(user32, hwnd: int) -> str: length = user32.GetWindowTextLengthW(hwnd) if length <= 0: return "" buf = ctypes.create_unicode_buffer(length + 1) user32.GetWindowTextW(hwnd, buf, length + 1) return buf.value def _class_name(user32, hwnd: int) -> str: buf = ctypes.create_unicode_buffer(256) user32.GetClassNameW(hwnd, buf, 255) return buf.value def _click_yes_if_needed() -> None: user32 = ctypes.windll.user32 bm_click = 0x00F5 vk_return = 0x0D wm_keydown = 0x0100 wm_keyup = 0x0101 while not stop_event.is_set(): windows: list[int] = [] @ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) def enum_windows(hwnd, lparam): windows.append(int(hwnd)) return True user32.EnumWindows(enum_windows, 0) for hwnd in windows: title = _window_text(user32, hwnd) cls = _class_name(user32, hwnd).lower() if "Microsoft Word" not in title and cls != "#32770": continue child_hwnds: list[int] = [] @ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) def enum_children(child_hwnd, lparam): child_hwnds.append(int(child_hwnd)) return True user32.EnumChildWindows(hwnd, enum_children, 0) child_texts = [_window_text(user32, child) for child in child_hwnds] button_hwnds = [ child for child in child_hwnds if _class_name(user32, child).lower() == "button" ] button_texts = [_window_text(user32, child) for child in button_hwnds] if not _should_accept_word_dialog(title, child_texts, button_texts): continue user32.SetForegroundWindow(hwnd) for child, text in zip(button_hwnds, button_texts): normalized = text.strip().lower() if normalized.startswith(("是", "yes")) or "&y" in normalized: user32.SendMessageW(child, bm_click, 0, 0) break else: user32.PostMessageW(hwnd, wm_keydown, vk_return, 0) user32.PostMessageW(hwnd, wm_keyup, vk_return, 0) stop_event.wait(0.5) thread = threading.Thread(target=_click_yes_if_needed, daemon=True) thread.start() return stop_event, thread def convert_with_word(path: Path, output: Path, file_format: int) -> Path: timeout = _word_timeout_sec() before_pids = _list_winword_pids() cmd = [ sys.executable, "-m", "edkb_system.skills.word_bridge", str(path), str(output), str(file_format), ] try: proc = subprocess.run( cmd, capture_output=True, text=True, timeout=timeout, check=False, ) except subprocess.TimeoutExpired as exc: after_pids = _list_winword_pids() _kill_winword_pids(after_pids - before_pids) raise RuntimeError( f"Word conversion timed out after {timeout}s: {path.name}" ) from exc if proc.returncode != 0: err = (proc.stderr or proc.stdout or "unknown error").strip() raise RuntimeError(f"Word conversion failed: {err}") if not output.exists() or output.stat().st_size <= 0: raise RuntimeError(f"Word conversion produced no output: {output}") return output def _child_main(argv: list[str]) -> int: if len(argv) != 4: print("usage: word_bridge ", file=sys.stderr) return 2 src = Path(argv[1]).resolve() out = Path(argv[2]).resolve() file_format = int(argv[3]) out.parent.mkdir(parents=True, exist_ok=True) stop_event, watcher = _start_word_dialog_watcher() word = None doc = None try: from win32com.client import DispatchEx word = DispatchEx("Word.Application") word.Visible = False word.DisplayAlerts = 0 try: word.Options.SaveNormalPrompt = False except Exception: pass doc = word.Documents.Open( FileName=str(src), ReadOnly=True, AddToRecentFiles=False, ConfirmConversions=False, NoEncodingDialog=True, OpenAndRepair=True, ) doc.SaveAs(str(out), FileFormat=file_format) finally: stop_event.set() if watcher is not None: watcher.join(timeout=1) if doc is not None: try: doc.Close(False) except Exception: pass if word is not None: try: word.Quit() except Exception: pass return 0 if __name__ == "__main__": raise SystemExit(_child_main(sys.argv))