"""docx4j HTTP 客户端 — POST 一份 docx,返回 HTML 字符串""" import os import uuid import json import urllib.request from db.database import load_config def _config(): return load_config()['wordparse'] def post_docx(path: str, timeout: int | None = None) -> str: """返回 HTML 字符串(原始,未做 MathJax/导航注入)""" cfg = _config() url = cfg['url'] timeout = timeout or cfg.get('timeout', 600) boundary = '----WP' + uuid.uuid4().hex with open(path, 'rb') as f: data = f.read() fn = os.path.basename(path) body = ( f'--{boundary}\r\n'.encode() + f'Content-Disposition: form-data; name="file"; filename="{fn}"\r\n'.encode('utf-8') + b'Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document\r\n\r\n' + data + b'\r\n' + f'--{boundary}--\r\n'.encode() ) req = urllib.request.Request(url, data=body, headers={ 'Content-Type': f'multipart/form-data; boundary={boundary}', 'Content-Length': str(len(body)), }) with urllib.request.urlopen(req, timeout=timeout) as r: resp = json.loads(r.read().decode('utf-8')) return resp.get('content') or '' def health() -> bool: cfg = _config() try: with urllib.request.urlopen(cfg['health_url'], timeout=5) as r: j = json.loads(r.read().decode('utf-8')) return j.get('status') == 'ok' except Exception: return False