word-vane 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- batch_convert.py +112 -0
- batch_verify.py +111 -0
- math_latex.py +513 -0
- mcp_server.py +220 -0
- review_probe.py +258 -0
- verify_consistency.py +666 -0
- word2md.py +1798 -0
- word_vane-1.0.0.dist-info/METADATA +528 -0
- word_vane-1.0.0.dist-info/RECORD +13 -0
- word_vane-1.0.0.dist-info/WHEEL +5 -0
- word_vane-1.0.0.dist-info/entry_points.txt +7 -0
- word_vane-1.0.0.dist-info/licenses/LICENSE +21 -0
- word_vane-1.0.0.dist-info/top_level.txt +7 -0
batch_convert.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""批量 Word->Markdown 转换驱动。
|
|
3
|
+
|
|
4
|
+
用法:
|
|
5
|
+
python batch_convert.py <根目录> [--out 输出根目录] [--workers N]
|
|
6
|
+
|
|
7
|
+
行为:
|
|
8
|
+
- 递归扫描根目录下全部 .docx(跳过 ~$ 临时文件与输出目录自身)
|
|
9
|
+
- 按原相对目录结构镜像输出到 <输出根目录>/<相对路径去扩展名>/<同名>.md
|
|
10
|
+
- 每份文档的统计/耗时/异常写入 batch_convert_result.json
|
|
11
|
+
"""
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
import traceback
|
|
18
|
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
|
19
|
+
|
|
20
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
21
|
+
from word2md import convert_word_to_markdown # noqa: E402
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def collect(root, exclude_dirs):
|
|
25
|
+
jobs = []
|
|
26
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
27
|
+
dirnames[:] = sorted(
|
|
28
|
+
d for d in dirnames if os.path.join(dirpath, d) not in exclude_dirs
|
|
29
|
+
)
|
|
30
|
+
for fn in sorted(filenames):
|
|
31
|
+
if not fn.lower().endswith('.docx') or fn.startswith('~$'):
|
|
32
|
+
continue
|
|
33
|
+
src = os.path.join(dirpath, fn)
|
|
34
|
+
jobs.append(src)
|
|
35
|
+
return jobs
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def one(args_tuple):
|
|
39
|
+
src, root, out_root = args_tuple
|
|
40
|
+
t0 = time.time()
|
|
41
|
+
rec = {'src': os.path.basename(src), 'status': 'ok'}
|
|
42
|
+
try:
|
|
43
|
+
if out_root:
|
|
44
|
+
rel = os.path.relpath(os.path.dirname(src), root)
|
|
45
|
+
# Windows 会静默剥除路径段末尾空格(如 "文档A v1.0 .docx"),
|
|
46
|
+
# 导致后续 makedirs 路径与预期不一致 -> 显式 strip 后再拼接
|
|
47
|
+
stem = os.path.splitext(os.path.basename(src))[0].strip()
|
|
48
|
+
target = os.path.join(out_root, rel, stem)
|
|
49
|
+
else:
|
|
50
|
+
target = None
|
|
51
|
+
stats = convert_word_to_markdown(src, out_dir=target)
|
|
52
|
+
rec.update({
|
|
53
|
+
'md_path': stats['md_path'],
|
|
54
|
+
'headings': stats['headings'],
|
|
55
|
+
'tables': stats['tables'],
|
|
56
|
+
'tables_gfm': stats['tables_gfm'],
|
|
57
|
+
'tables_html': stats['tables_html'],
|
|
58
|
+
'images': stats['images'],
|
|
59
|
+
'code_blocks': stats['code_blocks'],
|
|
60
|
+
'formulas': stats['formulas'],
|
|
61
|
+
'toc_entries': stats['toc_entries'],
|
|
62
|
+
'warnings': stats['warnings'],
|
|
63
|
+
})
|
|
64
|
+
except Exception as e: # noqa: BLE001
|
|
65
|
+
rec['status'] = 'failed'
|
|
66
|
+
rec['error'] = f'{type(e).__name__}: {e}'
|
|
67
|
+
rec['traceback'] = traceback.format_exc()
|
|
68
|
+
rec['seconds'] = round(time.time() - t0, 1)
|
|
69
|
+
return rec
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def main():
|
|
73
|
+
ap = argparse.ArgumentParser()
|
|
74
|
+
ap.add_argument('root')
|
|
75
|
+
ap.add_argument('--out', default=None,
|
|
76
|
+
help='Markdown 输出根目录(镜像原目录结构); 缺省写在源文件旁')
|
|
77
|
+
ap.add_argument('--workers', type=int, default=4)
|
|
78
|
+
ap.add_argument('--json', default=None, help='结果 JSON 路径')
|
|
79
|
+
args = ap.parse_args()
|
|
80
|
+
|
|
81
|
+
root = os.path.abspath(args.root)
|
|
82
|
+
out_root = os.path.abspath(args.out) if args.out else None
|
|
83
|
+
jobs = collect(root, {os.path.join(root, '_converted')})
|
|
84
|
+
print(f'发现 {len(jobs)} 份 .docx, 并发 {args.workers}', flush=True)
|
|
85
|
+
|
|
86
|
+
results = []
|
|
87
|
+
with ProcessPoolExecutor(max_workers=args.workers) as ex:
|
|
88
|
+
futs = {ex.submit(one, (j, root, out_root)): j for j in jobs}
|
|
89
|
+
for i, fut in enumerate(as_completed(futs), 1):
|
|
90
|
+
rec = fut.result()
|
|
91
|
+
src = futs[fut]
|
|
92
|
+
rec['rel_dir'] = os.path.relpath(os.path.dirname(src), root).replace('\\', '/')
|
|
93
|
+
rec['root'] = rec['rel_dir'].split('/')[0]
|
|
94
|
+
results.append(rec)
|
|
95
|
+
mark = 'OK ' if rec['status'] == 'ok' else 'ERR'
|
|
96
|
+
print(f'[{i}/{len(jobs)}] {mark} {rec["rel_dir"]}/{rec["src"]} '
|
|
97
|
+
f'({rec["seconds"]}s)', flush=True)
|
|
98
|
+
|
|
99
|
+
results.sort(key=lambda r: (r['rel_dir'], r['src']))
|
|
100
|
+
ok = sum(1 for r in results if r['status'] == 'ok')
|
|
101
|
+
print(f'\n完成: 成功 {ok} / 失败 {len(results) - ok} / 总计 {len(results)}')
|
|
102
|
+
|
|
103
|
+
# 结果 JSON 默认写到当前工作目录, 而非输入目录 ——
|
|
104
|
+
# 输入目录常是只读的文档库/网盘挂载点, 写入会失败或污染源目录结构
|
|
105
|
+
json_path = args.json or os.path.join(os.getcwd(), 'batch_convert_result.json')
|
|
106
|
+
with open(json_path, 'w', encoding='utf-8') as f:
|
|
107
|
+
json.dump(results, f, ensure_ascii=False, indent=2)
|
|
108
|
+
print(f'结果已写入 {json_path}')
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == '__main__':
|
|
112
|
+
main()
|
batch_verify.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""批量一致性校验驱动: 对每份 docx 与其生成 md 运行 verify_consistency。"""
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
import traceback
|
|
9
|
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
|
10
|
+
|
|
11
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
12
|
+
from verify_consistency import verify # noqa: E402
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def one(pair):
|
|
16
|
+
docx_path, md_path = pair
|
|
17
|
+
t0 = time.time()
|
|
18
|
+
rec = {'docx': docx_path, 'md': md_path, 'status': 'ok'}
|
|
19
|
+
try:
|
|
20
|
+
rep = verify(docx_path, md_path)
|
|
21
|
+
rec.update(rep)
|
|
22
|
+
except Exception as e: # noqa: BLE001
|
|
23
|
+
rec['status'] = 'failed'
|
|
24
|
+
rec['error'] = f'{type(e).__name__}: {e}'
|
|
25
|
+
rec['traceback'] = traceback.format_exc()
|
|
26
|
+
rec['seconds'] = round(time.time() - t0, 1)
|
|
27
|
+
return rec
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def main(argv=None):
|
|
31
|
+
ap = argparse.ArgumentParser()
|
|
32
|
+
ap.add_argument('root')
|
|
33
|
+
ap.add_argument('--converted', required=True, help='Markdown 输出根目录(镜像原目录结构)')
|
|
34
|
+
ap.add_argument('--workers', type=int, default=4)
|
|
35
|
+
ap.add_argument('--json', default=None)
|
|
36
|
+
ap.add_argument('--fail-under', type=float, default=None, metavar='PCT',
|
|
37
|
+
help='任一份文档的表格或段落一致率低于该百分比即判定整体失败,'
|
|
38
|
+
'以退出码 1 结束,供 CI / 质量门禁使用')
|
|
39
|
+
args = ap.parse_args(argv)
|
|
40
|
+
|
|
41
|
+
root = os.path.abspath(args.root)
|
|
42
|
+
conv_root = os.path.abspath(args.converted)
|
|
43
|
+
pairs = []
|
|
44
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
45
|
+
dirnames[:] = [d for d in dirnames if not d.endswith('_md')]
|
|
46
|
+
for fn in sorted(filenames):
|
|
47
|
+
if not fn.lower().endswith('.docx') or fn.startswith('~$'):
|
|
48
|
+
continue
|
|
49
|
+
src = os.path.join(dirpath, fn)
|
|
50
|
+
rel = os.path.relpath(os.path.dirname(src), root)
|
|
51
|
+
stem = os.path.splitext(fn)[0]
|
|
52
|
+
cands = [
|
|
53
|
+
os.path.join(conv_root, rel, stem + '.md'),
|
|
54
|
+
os.path.join(conv_root, rel, stem + '_md', stem + '.md'),
|
|
55
|
+
os.path.join(conv_root, rel, stem, stem + '.md'),
|
|
56
|
+
os.path.join(conv_root, rel, stem, stem.strip() + '.md'),
|
|
57
|
+
os.path.join(conv_root, rel, stem.strip(), stem + '.md'),
|
|
58
|
+
os.path.join(conv_root, rel, stem.strip(), stem.strip() + '.md'),
|
|
59
|
+
]
|
|
60
|
+
md = next((c for c in cands if os.path.isfile(c)), cands[0])
|
|
61
|
+
pairs.append((src, md))
|
|
62
|
+
|
|
63
|
+
print(f'待校验 {len(pairs)} 份', flush=True)
|
|
64
|
+
results = []
|
|
65
|
+
with ProcessPoolExecutor(max_workers=args.workers) as ex:
|
|
66
|
+
futs = {ex.submit(one, p): p for p in pairs}
|
|
67
|
+
for i, fut in enumerate(as_completed(futs), 1):
|
|
68
|
+
rec = fut.result()
|
|
69
|
+
results.append(rec)
|
|
70
|
+
par = rec.get('paragraphs', {})
|
|
71
|
+
tab = rec.get('tables', {})
|
|
72
|
+
print(f'[{i}/{len(pairs)}] {os.path.basename(rec["docx"])[:44]:<46} '
|
|
73
|
+
f'段落 {par.get("pct", "-")}% 表格 {tab.get("pct", "-")}% '
|
|
74
|
+
f'pass={rec.get("pass")}', flush=True)
|
|
75
|
+
|
|
76
|
+
results.sort(key=lambda r: r['docx'])
|
|
77
|
+
npass = sum(1 for r in results if r.get('pass'))
|
|
78
|
+
print(f'\n校验完成: pass {npass} / {len(results)}')
|
|
79
|
+
|
|
80
|
+
# 同 batch_convert: 结果默认写当前工作目录, 不污染输入目录
|
|
81
|
+
json_path = args.json or os.path.join(os.getcwd(), 'batch_verify_result.json')
|
|
82
|
+
with open(json_path, 'w', encoding='utf-8') as f:
|
|
83
|
+
json.dump(results, f, ensure_ascii=False, indent=2)
|
|
84
|
+
print(f'结果已写入 {json_path}')
|
|
85
|
+
|
|
86
|
+
# 门禁判定: 两类失败都算不通过
|
|
87
|
+
# 1) verify 的 pass 为 False(有真实差异)
|
|
88
|
+
# 2) 一致率低于 --fail-under 指定阈值
|
|
89
|
+
if args.fail_under is not None:
|
|
90
|
+
below = []
|
|
91
|
+
for r in results:
|
|
92
|
+
par_pct = (r.get('paragraphs') or {}).get('pct')
|
|
93
|
+
tab_pct = (r.get('tables') or {}).get('pct')
|
|
94
|
+
for label, v in (('段落', par_pct), ('表格', tab_pct)):
|
|
95
|
+
if isinstance(v, (int, float)) and v < args.fail_under:
|
|
96
|
+
below.append(f'{os.path.basename(r["docx"])} {label} {v}%')
|
|
97
|
+
nfailed = len(results) - npass
|
|
98
|
+
if nfailed or below:
|
|
99
|
+
print(f'\n[门禁] 未通过: {nfailed} 份 pass=False'
|
|
100
|
+
+ (f',{len(below)} 项低于 {args.fail_under}%' if below else ''),
|
|
101
|
+
file=sys.stderr)
|
|
102
|
+
for b in below[:20]:
|
|
103
|
+
print(f' - {b}', file=sys.stderr)
|
|
104
|
+
return 1
|
|
105
|
+
print(f'\n[门禁] 通过: 全部 {len(results)} 份一致率 >= {args.fail_under}%',
|
|
106
|
+
file=sys.stderr)
|
|
107
|
+
return 0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == '__main__':
|
|
111
|
+
raise SystemExit(main())
|