zotdocx 0.2.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.
zotdocx/__init__.py ADDED
@@ -0,0 +1 @@
1
+
zotdocx/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
zotdocx/analyze.py ADDED
@@ -0,0 +1,209 @@
1
+ # -*- coding: utf-8 -*-
2
+ """解析层:把 docx 里的 Zotero 域、纯文本引用、段落语境一次算清。
3
+
4
+ 所有子命令都只调这里,避免旧脚本那套「每个脚本自己拆一遍 zip」。
5
+ 只读,不改任何东西。
6
+ """
7
+ import json
8
+ import re
9
+ from dataclasses import dataclass, field
10
+
11
+ from lxml import etree
12
+
13
+ W = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
14
+ NS = {'w': W}
15
+ _Q = lambda n: '{%s}%s' % (W, n)
16
+ TAG_P, TAG_TBL, TAG_FLD = _Q('p'), _Q('tbl'), _Q('fldChar')
17
+ TAG_INSTR, TAG_T = _Q('instrText'), _Q('t')
18
+
19
+ BODY, TABLE, CAPTION, NOTE, BIBLIO = 'body', 'table', 'caption', 'note', 'biblio'
20
+ CTX_CN = {BODY: '正文', TABLE: '表格', CAPTION: '图题表题', NOTE: '表注图注', BIBLIO: '参考文献表'}
21
+
22
+ NUM_RE = re.compile(r'\[\s*(\d+(?:\s*[,,\-–]\s*\d+)*)\s*\]')
23
+ CAP_RE = re.compile(r'^\s*(图|表|Table|Figure|Fig\.?|Tab\.)\s*\d', re.I)
24
+ NOTE_RE = re.compile(r'^\s*(注|Note|Notes)\s*[::]', re.I)
25
+ BIBLIO_HEAD_RE = re.compile(
26
+ r'^\s*(参考文献|References?|Bibliography|Literature Cited|Works Cited)\s*$', re.I)
27
+
28
+
29
+ @dataclass
30
+ class Field:
31
+ idx: int
32
+ kind: str # 'item' | 'bibl' | 'other'
33
+ ctx: str
34
+ p0: int
35
+ p1: int
36
+ instr: str
37
+ data: dict = None
38
+ ids: list = field(default_factory=list)
39
+ display: str = ''
40
+ nums: list = field(default_factory=list)
41
+
42
+ @property
43
+ def cross(self):
44
+ return self.p0 != self.p1
45
+
46
+ @property
47
+ def plain_citation(self):
48
+ return (self.data or {}).get('properties', {}).get('plainCitation')
49
+
50
+
51
+ @dataclass
52
+ class Plain:
53
+ ctx: str
54
+ p: int
55
+ text: str
56
+ nums: list
57
+
58
+
59
+ def nums_of(s):
60
+ """'[1, 3-5]' → [1,3,4,5]"""
61
+ out = []
62
+ for part in re.split(r'[,,]', s):
63
+ part = part.strip().replace('–', '-')
64
+ if '-' in part:
65
+ try:
66
+ a, b = part.split('-')
67
+ if 0 < int(b) - int(a) < 100:
68
+ out.extend(range(int(a), int(b) + 1))
69
+ continue
70
+ except ValueError:
71
+ pass
72
+ if part.isdigit():
73
+ out.append(int(part))
74
+ return out
75
+
76
+
77
+ def _in_table(el):
78
+ node = el.getparent()
79
+ while node is not None:
80
+ if node.tag == TAG_TBL:
81
+ return True
82
+ node = node.getparent()
83
+ return False
84
+
85
+
86
+ def _json_of(instr):
87
+ m = re.search(r'CSL_CITATION\s*(\{.*\})\s*$', instr.strip(), re.S)
88
+ if not m:
89
+ return None
90
+ try:
91
+ return json.loads(m.group(1))
92
+ except Exception:
93
+ return None
94
+
95
+
96
+ class Document:
97
+ def __init__(self, xml_bytes):
98
+ self.root = etree.fromstring(xml_bytes)
99
+ self.body = self.root.find('w:body', NS)
100
+ if self.body is None:
101
+ raise ValueError('document.xml 里没有 w:body')
102
+ self._paras = list(self.body.iter(TAG_P))
103
+ self.para_text = []
104
+ self.para_table = []
105
+ self.para_ctx = []
106
+ self.fields = []
107
+ self.plains = []
108
+ self._walk()
109
+ self._classify_paragraphs()
110
+ self._collect_plains()
111
+ self._attach_numbers()
112
+
113
+ # ---------- 一次遍历:段落、域、域外文字 ----------
114
+ def _walk(self):
115
+ stack = []
116
+ buf, depth, cur = [], 0, -1
117
+ for el in self.body.iter():
118
+ if el.tag == TAG_P:
119
+ cur += 1
120
+ self.para_text.append([])
121
+ self.para_table.append(_in_table(el))
122
+ elif el.tag == TAG_FLD:
123
+ t = el.get(_Q('fldCharType'))
124
+ if t == 'begin':
125
+ stack.append({'instr': [], 'disp': [], 'sep': False,
126
+ 'p0': cur, 'table': _in_table(el)})
127
+ depth += 1
128
+ elif t == 'separate' and stack:
129
+ stack[-1]['sep'] = True
130
+ elif t == 'end' and stack:
131
+ f = stack.pop()
132
+ depth -= 1
133
+ instr = ''.join(f['instr'])
134
+ kind = 'item' if 'ZOTERO_ITEM' in instr else (
135
+ 'bibl' if 'ZOTERO_BIBL' in instr else 'other')
136
+ data = _json_of(instr) if kind == 'item' else None
137
+ ids = [c.get('id') for c in (data or {}).get('citationItems', [])]
138
+ self.fields.append(Field(
139
+ idx=len(self.fields), kind=kind, ctx=None,
140
+ p0=f['p0'], p1=cur, instr=instr, data=data, ids=ids,
141
+ display=''.join(f['disp'])))
142
+ elif el.tag == TAG_INSTR:
143
+ if stack:
144
+ stack[-1]['instr'].append(el.text or '')
145
+ # 域代码不是可见文字,不进 para_text
146
+ elif el.tag == TAG_T:
147
+ txt = el.text or ''
148
+ if stack and stack[-1]['sep']:
149
+ stack[-1]['disp'].append(txt)
150
+ if cur >= 0:
151
+ self.para_text[cur].append(txt)
152
+
153
+ # ---------- 段落语境:表格 / 图题表题 / 注 / 参考文献 ----------
154
+ def _classify_paragraphs(self):
155
+ texts = [''.join(t) for t in self.para_text]
156
+ self.para_text = texts
157
+ biblio_from = len(texts)
158
+ for i, t in enumerate(texts):
159
+ if BIBLIO_HEAD_RE.match(t):
160
+ biblio_from = i
161
+ break
162
+ for i, t in enumerate(texts):
163
+ if self.para_table[i]:
164
+ self.para_ctx.append(TABLE)
165
+ elif i >= biblio_from:
166
+ self.para_ctx.append(BIBLIO)
167
+ elif CAP_RE.match(t):
168
+ self.para_ctx.append(CAPTION)
169
+ elif NOTE_RE.match(t):
170
+ self.para_ctx.append(NOTE)
171
+ else:
172
+ self.para_ctx.append(BODY)
173
+ for f in self.fields:
174
+ f.ctx = self.para_ctx[f.p0] if f.p0 < len(self.para_ctx) else BODY
175
+
176
+ # ---------- 域外纯文本引用 ----------
177
+ def _collect_plains(self):
178
+ for p, (txt, ctx) in enumerate(zip(self.para_text, self.para_ctx)):
179
+ outside = self._text_outside_fields(p)
180
+ for m in NUM_RE.finditer(outside):
181
+ nums = nums_of(m.group(1))
182
+ if not nums or any(n >= 1000 for n in nums):
183
+ continue # 访问日期 [2026-05-17] 之类,不是引用编号
184
+ self.plains.append(Plain(ctx=ctx, p=p, text=m.group(0), nums=nums))
185
+
186
+ def _text_outside_fields(self, p_idx):
187
+ """重扫该段落,只取不在域内的文字。"""
188
+ p = self._paras[p_idx]
189
+ out, depth = [], 0
190
+ for el in p.iter():
191
+ if el.tag == TAG_FLD:
192
+ t = el.get(_Q('fldCharType'))
193
+ depth += 1 if t == 'begin' else (-1 if t == 'end' else 0)
194
+ elif el.tag == TAG_T and depth == 0:
195
+ out.append(el.text or '')
196
+ return ''.join(out)
197
+
198
+ # ---------- 编号 ----------
199
+ def _attach_numbers(self):
200
+ for f in self.fields:
201
+ if f.kind != 'item':
202
+ continue
203
+ nums = []
204
+ for m in NUM_RE.finditer(f.display or ''):
205
+ nums.extend(nums_of(m.group(1)))
206
+ f.nums = nums
207
+
208
+ def items(self):
209
+ return [f for f in self.fields if f.kind == 'item']
zotdocx/cli.py ADDED
@@ -0,0 +1,465 @@
1
+ # -*- coding: utf-8 -*-
2
+ """zotdocx 命令入口。"""
3
+ import argparse
4
+ import json
5
+ import os
6
+ import re
7
+ import shutil
8
+ import sys
9
+ import zipfile
10
+ from collections import defaultdict, OrderedDict
11
+
12
+ from .analyze import Document, CTX_CN
13
+ from .docxfile import Docx, DOC
14
+ from .heal import heal_xml
15
+ from .renumber import renumber_xml
16
+ from .lift import lift_xml
17
+ from .library import Library, default_db
18
+ from .repair import repair_xml
19
+ from .patch import omni_path, inspect, apply_patch
20
+
21
+ __version__ = '0.2.0'
22
+
23
+
24
+ def db_path(args):
25
+ """--zotero-db 优先,其次 ZOTERO_DB 环境变量,再次常见安装位置;都没有返回 None。"""
26
+ if getattr(args, 'no_lib', False):
27
+ return None
28
+ return getattr(args, 'zotero_db', None) or default_db()
29
+
30
+
31
+ # ---------------- status ----------------
32
+ def cmd_status(args):
33
+ with Docx(args.docx) as z:
34
+ xml = z.text(DOC)
35
+ names = len(z.names)
36
+ try:
37
+ custom = z.read('docProps/custom.xml').decode('utf-8', 'replace')
38
+ except KeyError:
39
+ custom = ''
40
+ m = re.search(r'zotero\.org/styles/([^"<]+)', custom)
41
+ style = m.group(1) if m else '未记录'
42
+ doc = Document(xml.encode('utf-8'))
43
+ items = doc.items()
44
+ bibl = [f for f in doc.fields if f.kind == 'bibl']
45
+ other = [f for f in doc.fields if f.kind == 'other']
46
+
47
+ # 域位置分布
48
+ by_ctx = defaultdict(int)
49
+ for f in items:
50
+ by_ctx[CTX_CN.get(f.ctx, f.ctx)] += 1
51
+
52
+ # 条目与编号
53
+ ids_seen = OrderedDict()
54
+ per_id_nums = defaultdict(set)
55
+ for f in items:
56
+ for i in f.ids:
57
+ ids_seen.setdefault(i, len(ids_seen) + 1)
58
+ for n in f.nums:
59
+ pass
60
+ for f in items:
61
+ for i in f.ids:
62
+ if len(f.nums) == 1:
63
+ per_id_nums[i].add(f.nums[0])
64
+
65
+ canon = {i: k for k, i in enumerate(ids_seen, 1)}
66
+ mismatch = 0
67
+ multi_mismatch = 0
68
+ for f in items:
69
+ want = sorted(canon[i] for i in f.ids if i in canon)
70
+ got = sorted(f.nums)
71
+ if want != got:
72
+ if len(f.ids) > 1:
73
+ multi_mismatch += 1
74
+ else:
75
+ mismatch += 1
76
+
77
+ multi_num_ids = [i for i, s in per_id_nums.items() if len(s) > 1]
78
+ all_nums = sorted({n for f in items for n in f.nums})
79
+
80
+ # 纯文本
81
+ plain_by_ctx = defaultdict(int)
82
+ for p in doc.plains:
83
+ plain_by_ctx[CTX_CN.get(p.ctx, p.ctx)] += 1
84
+
85
+ # 文献库
86
+ db = db_path(args)
87
+ lib = Library(db) if db else None
88
+ id_kinds = defaultdict(int)
89
+ broken = {}
90
+ if lib:
91
+ for i in ids_seen:
92
+ k = lib.classify(i)
93
+ id_kinds[k] += 1
94
+ if k not in ('存在', '会话号(可解析)'):
95
+ broken.setdefault(k, []).append(i)
96
+
97
+ # ---------------- 输出 ----------------
98
+ base = os.path.basename(args.docx)
99
+ print(f'{base}')
100
+ print(f' 部件 {names} 个;document.xml {len(xml.encode("utf-8")) / 1048576:.2f} MB')
101
+ print(f' 样式 {style}')
102
+ print()
103
+ print(f'域 {len(doc.fields)} = 引注 {len(items)} + 书目 {len(bibl)} + 其他 {len(other)}')
104
+ print(f' 跨段落:引注 {sum(1 for f in items if f.cross)} · 书目 {sum(1 for f in bibl if f.cross)}')
105
+ print(' 位置:' + ' · '.join(f'{k} {v}' for k, v in by_ctx.items()))
106
+ print(f'条目 {len(ids_seen)} 个' + (
107
+ '(' + ' · '.join(f'{k} {v}' for k, v in id_kinds.items()) + ')' if lib else ''))
108
+ print(f'编号 显示 {all_nums[0] if all_nums else 0}–{all_nums[-1] if all_nums else 0}'
109
+ f';同条目多编号 {len(multi_num_ids)};单条目编号不符 {mismatch};多条目编号不符 {multi_mismatch}')
110
+ print('纯文本 ' + ' · '.join(f'{k} {v}' for k, v in plain_by_ctx.items()))
111
+ if lib is None and not getattr(args, 'no_lib', False):
112
+ print('断链 跳过(没找到 zotero.sqlite;用 --zotero-db 或 ZOTERO_DB 指一个)')
113
+
114
+ if broken:
115
+ print()
116
+ print('断链:')
117
+ for k, v in broken.items():
118
+ print(f' {k} {len(v)} 个:{v[:10]}')
119
+
120
+ if args.show_text:
121
+ print()
122
+ print('纯文本引用明细:')
123
+ for p in doc.plains:
124
+ print(f' 段{p.p} [{CTX_CN.get(p.ctx, p.ctx)}] {p.text} {doc.para_text[p.p][:50]}')
125
+ if multi_num_ids:
126
+ print('同条目多编号的 id:', multi_num_ids[:20])
127
+
128
+ if args.json:
129
+ print(json.dumps({
130
+ 'file': base,
131
+ 'fields': {'total': len(doc.fields), 'item': len(items),
132
+ 'bibl': len(bibl), 'other': len(other)},
133
+ 'cross_item': sum(1 for f in items if f.cross),
134
+ 'items': len(ids_seen),
135
+ 'plain': dict(plain_by_ctx),
136
+ 'broken': {k: [str(x) for x in v] for k, v in broken.items()},
137
+ }, ensure_ascii=False, indent=2))
138
+
139
+ bad = bool(broken) or mismatch > 0 or any(f.cross for f in items)
140
+ return 1 if bad else 0
141
+
142
+
143
+ def _validate(xml):
144
+ from lxml import etree
145
+ etree.fromstring(xml.encode('utf-8'))
146
+
147
+
148
+ def cmd_heal(args):
149
+ with Docx(args.docx) as z:
150
+ xml = z.text(DOC)
151
+ before = Document(xml.encode('utf-8'))
152
+ new_xml, rep = heal_xml(xml)
153
+ _validate(new_xml)
154
+ after = Document(new_xml.encode('utf-8'))
155
+
156
+ print(os.path.basename(args.docx))
157
+ print(f' 跨段引注域:{sum(1 for f in before.items() if f.cross)} → '
158
+ f'{sum(1 for f in after.items() if f.cross)}')
159
+ print(f' 域内编号不一致:{before_problems(before)} → {after_problems(after)}')
160
+ print(f' 收回域尾 {rep["moved"]} 个;同步编号 {rep["synced"]} 处;跳过书目域 {rep["skipped_bibl"]}')
161
+ for pc, disp in rep.get('pairs', []):
162
+ print(f' 域内 {pc!r} → 显示 {disp!r}')
163
+ for p in rep['problems']:
164
+ print(f' ! {p}')
165
+ if not (rep['moved'] or rep['synced']):
166
+ print(' 无需改动')
167
+ return 0
168
+ if not args.apply:
169
+ print('(干跑,未写入;加 --apply 生效)')
170
+ return 0
171
+
172
+ out = args.out or args.docx
173
+ if out == args.docx:
174
+ import datetime
175
+ bak = args.docx + datetime.datetime.now().strftime('.bak_%Y%m%d_%H%M%S')
176
+ shutil.copy2(args.docx, bak)
177
+ print(f' 备份:{bak}')
178
+ with Docx(args.docx) as z:
179
+ z.save_as(out, new_xml)
180
+ print(f' 已写入:{out}')
181
+ return 0
182
+
183
+
184
+ def cmd_lift(args):
185
+ with Docx(args.docx) as z:
186
+ xml = z.text(DOC)
187
+ new_xml, rep = lift_xml(xml)
188
+ _validate(new_xml)
189
+
190
+ print(os.path.basename(args.docx))
191
+ print(f' 域 {rep["fields_before"]} → {rep["fields_after"]}')
192
+ if rep['lifted']:
193
+ print(' 上宏:' + ' '.join(f'{t}(段{p})' for t, p in rep['lifted']))
194
+ if rep.get('left'):
195
+ print(f' ! 正文还剩 {len(rep["left"])} 处纯文本没上宏(多半是编号被拆成多个 run):{rep["left"][:6]}')
196
+ for t, why in rep['skipped']:
197
+ print(f' 跳过 {t}:{why}')
198
+ if not rep['lifted']:
199
+ print(' 无需改动')
200
+ return 0
201
+ if not args.apply:
202
+ print('(干跑,未写入;加 --apply 生效)')
203
+ return 0
204
+ out = args.out or args.docx
205
+ if out == args.docx:
206
+ import datetime
207
+ bak = args.docx + datetime.datetime.now().strftime('.bak_%Y%m%d_%H%M%S')
208
+ shutil.copy2(args.docx, bak)
209
+ print(f' 备份:{bak}')
210
+ with Docx(args.docx) as z:
211
+ z.save_as(out, new_xml)
212
+ print(f' 已写入:{out}')
213
+ return 0
214
+
215
+
216
+ def cmd_renumber(args):
217
+ with Docx(args.docx) as z:
218
+ xml = z.text(DOC)
219
+ new_xml, rep = renumber_xml(xml, skip_note=args.skip_note)
220
+ _validate(new_xml)
221
+ after = Document(new_xml.encode('utf-8'))
222
+ mismatch = sum(1 for f in after.items()
223
+ if f.nums and [n for n in f.nums] != sorted(f.nums))
224
+
225
+ print(os.path.basename(args.docx))
226
+ print(f' 条目 {rep["canon"]} 个;显示编号改写 {rep["rewritten"]} 处;仅同步域内编号 {rep["sync_only"]} 处')
227
+ if rep['plain']:
228
+ from .analyze import CTX_CN
229
+ print(' 纯文本编号同步:' + ' · '.join(
230
+ f'{CTX_CN.get(k, k)} {v}' for k, v in rep['plain'].items()))
231
+ if rep['mapping']:
232
+ pairs = ' '.join(f'{a}→{b}' for a, b in sorted(rep['mapping'].items()) if a != b)
233
+ print(f' 映射(仅列出变动):{pairs or "无"}')
234
+ if rep.get('unmapped'):
235
+ print(f' ! 这些纯文本编号在文档里没有对应的单条目域,未同步:{rep["unmapped"]}')
236
+ if rep['ambiguous']:
237
+ print(f' ! 多条目域里映射不唯一的旧号,已跳过:{rep["ambiguous"]}')
238
+ for p in rep['problems']:
239
+ print(f' ! {p}')
240
+ print(f' 自查:改写后仍乱序的引注域 {mismatch} 个')
241
+
242
+ if rep['fields'] == 0 and not rep['plain']:
243
+ print(' 无需改动')
244
+ return 0
245
+ if not args.apply:
246
+ print('(干跑,未写入;加 --apply 生效)')
247
+ return 0
248
+ out = args.out or args.docx
249
+ if out == args.docx:
250
+ import datetime
251
+ bak = args.docx + datetime.datetime.now().strftime('.bak_%Y%m%d_%H%M%S')
252
+ shutil.copy2(args.docx, bak)
253
+ print(f' 备份:{bak}')
254
+ with Docx(args.docx) as z:
255
+ z.save_as(out, new_xml)
256
+ print(f' 已写入:{out}')
257
+ return 0
258
+
259
+
260
+ def before_problems(doc):
261
+ return sum(1 for f in doc.items() if f.plain_citation and f.nums
262
+ and f.plain_citation.replace(' ', '') != f.display.replace(' ', ''))
263
+
264
+
265
+ def after_problems(doc):
266
+ return before_problems(doc)
267
+
268
+
269
+ def cmd_repair(args):
270
+ db = db_path(args)
271
+ if not db:
272
+ print('! repair 需要 zotero.sqlite 才能判断条目还在不在')
273
+ print(' 自动查找过:~/Zotero/zotero.sqlite')
274
+ print(' 用 --zotero-db 指定路径,或设 ZOTERO_DB 环境变量')
275
+ return 2
276
+ lib = Library(db)
277
+ with Docx(args.docx) as z:
278
+ xml = z.text(DOC)
279
+ new_xml, rep = repair_xml(xml, lib)
280
+ _validate(new_xml)
281
+
282
+ print(os.path.basename(args.docx))
283
+ print(f' 文献库 {db}')
284
+ print(f' 正常条目 {rep["ok"]} 个;重连 {len(rep["relinked"])} 处;无法修复 {len(rep["unrecoverable"])} 处')
285
+ for old, new, why in rep['relinked']:
286
+ print(f' 重连 {old} → {new}(依据:{why})')
287
+ for old, why, title in rep['unrecoverable']:
288
+ print(f' ! 无法修复 {old}({why}):{title}')
289
+ for p in rep['problems']:
290
+ print(f' ! {p}')
291
+ if not rep['relinked']:
292
+ print(' 无需改动')
293
+ return 0
294
+ if not args.apply:
295
+ print('(干跑,未写入;加 --apply 生效)')
296
+ return 0
297
+ out = args.out or args.docx
298
+ if out == args.docx:
299
+ import datetime
300
+ bak = args.docx + datetime.datetime.now().strftime('.bak_%Y%m%d_%H%M%S')
301
+ shutil.copy2(args.docx, bak)
302
+ print(f' 备份:{bak}')
303
+ with Docx(args.docx) as z:
304
+ z.save_as(out, new_xml)
305
+ print(f' 已写入:{out}(回 Word 里点一次 Refresh 让 Zotero 重新渲染)')
306
+ return 0
307
+
308
+
309
+ def cmd_patch(args):
310
+ import zipfile
311
+ from .patch import sha as _sha
312
+ omni = omni_path(args.zotero_dir)
313
+ if not os.path.isfile(omni):
314
+ print(f'! 找不到 omni.ja:{omni}')
315
+ print(r' --zotero-dir 应指向 Zotero 程序目录(里面是 app\omni.ja),例如 C:\Program Files\Zotero')
316
+ return 2
317
+ try:
318
+ st = inspect(omni, args.marker)
319
+ except (KeyError, zipfile.BadZipFile, OSError) as e:
320
+ print(f'! 这个包读不出来:{e}')
321
+ return 2
322
+ print(f'包 {st["omni"]}')
323
+ print(f' 大小 {st["size"]:,} B;条目 {st["entries"]}')
324
+ print(f'内层 {st["inner_size"]:,} B sha256[:16] {st["inner_sha"]}')
325
+ print(f'补丁 标记 {args.marker!r}:{"在" if st["has_marker"] else "不在"}')
326
+
327
+ if not args.patched:
328
+ if not st['has_marker']:
329
+ print(' 只查模式:当前是原版。要打补丁请加 --patched <已修补的 integration.js>')
330
+ return 0
331
+
332
+ with open(args.patched, 'rb') as f:
333
+ patched = f.read()
334
+ print(f'补丁文件 {args.patched}')
335
+ print(f' {len(patched):,} B sha256[:16] {_sha(patched)}')
336
+ if st['has_marker'] and not args.force:
337
+ print(' 当前已是补丁版;确需覆盖请加 --force')
338
+ return 0
339
+ if not args.apply:
340
+ print('(干跑,未写入;加 --apply 生效)')
341
+ return 0
342
+
343
+ bak = apply_patch(omni, patched, args.marker)
344
+ st2 = inspect(omni, args.marker)
345
+ print(f' 备份 {bak}')
346
+ print(f' 已写入:条目 {st2["entries"]};内层 sha256[:16] {st2["inner_sha"]};标记在:{st2["has_marker"]}')
347
+ print(' 重启 Zotero 才生效')
348
+ return 0
349
+
350
+
351
+ def cmd_demo(args):
352
+ from .demo import build
353
+ out = args.out
354
+ if os.path.exists(out) and not args.force:
355
+ print(f'! {out} 已存在;换一个文件名(--out),或加 --force 覆盖')
356
+ return 2
357
+ build(out)
358
+ print(f'已生成 {out}(合成文档:假段落 + 假引用,不含任何真实文献)')
359
+ print()
360
+ print('== status:只读体检 ==')
361
+ cmd_status(argparse.Namespace(docx=out, zotero_db=None, no_lib=True,
362
+ show_text=False, json=False))
363
+ print()
364
+ print('== renumber:干跑,不写盘 ==')
365
+ cmd_renumber(argparse.Namespace(docx=out, apply=False, out=None, skip_note=False))
366
+ print()
367
+ print('要真正改这份文件:')
368
+ print(f' zotdocx renumber {os.path.basename(out)} --apply')
369
+ return 0
370
+
371
+
372
+ def build_parser():
373
+ ap = argparse.ArgumentParser(
374
+ prog='zotdocx',
375
+ description='Zotero 稿件端质检与修复(只读优先,写操作需 --apply)',
376
+ epilog='第一次用先跑 zotdocx demo:生成一份合成文档并立刻检查一遍。')
377
+ ap.add_argument('-V', '--version', action='version', version=__version__)
378
+ sub = ap.add_subparsers(dest='cmd')
379
+
380
+ p = sub.add_parser('demo', help='生成一份合成演示文档,并立刻跑一遍检查')
381
+ p.add_argument('--out', metavar='PATH', default='demo.docx', help='输出路径(默认 ./demo.docx)')
382
+ p.add_argument('--force', action='store_true', help='已存在时覆盖')
383
+ p.set_defaults(func=cmd_demo)
384
+
385
+ p = sub.add_parser('status', help='体检:域结构、条目、编号、纯文本引用')
386
+ p.add_argument('docx')
387
+ p.add_argument('--zotero-db', metavar='PATH',
388
+ help='zotero.sqlite 路径;不给则找 ~/Zotero/zotero.sqlite,再读 ZOTERO_DB')
389
+ p.add_argument('--show-text', action='store_true', help='打印纯文本引用所在段落(默认不打印正文)')
390
+ p.add_argument('--json', action='store_true')
391
+ p.set_defaults(func=cmd_status)
392
+
393
+ p = sub.add_parser('heal', help='修跨段落引注域与域内编号不一致(结构修复)')
394
+ p.add_argument('docx')
395
+ p.add_argument('--apply', action='store_true', help='实际写入;默认只干跑')
396
+ p.add_argument('--out', metavar='PATH', help='写到新文件(默认原地写,并自动备份)')
397
+ p.set_defaults(func=cmd_heal)
398
+
399
+ p = sub.add_parser('renumber', help='按首次被引顺序统一编号,并同步表格/图题/表注里的纯文本编号')
400
+ p.add_argument('docx')
401
+ p.add_argument('--apply', action='store_true', help='实际写入;默认只干跑')
402
+ p.add_argument('--out', metavar='PATH', help='写到新文件(默认原地写,并自动备份)')
403
+ p.add_argument('--skip-note', action='store_true', help='不动表注图注里的纯文本编号')
404
+ p.set_defaults(func=cmd_renumber)
405
+
406
+ p = sub.add_parser('lift', help='把正文里的纯文本引用编号补成 Zotero 活域(多条目自动合并)')
407
+ p.add_argument('docx')
408
+ p.add_argument('--apply', action='store_true', help='实际写入;默认只干跑')
409
+ p.add_argument('--out', metavar='PATH', help='写到新文件(默认原地写,并自动备份)')
410
+ p.set_defaults(func=cmd_lift)
411
+
412
+ p = sub.add_parser('repair', help='修断链:把指向不存在条目的引用域重新连到正确条目')
413
+ p.add_argument('docx')
414
+ p.add_argument('--zotero-db', metavar='PATH',
415
+ help='zotero.sqlite 路径;不给则找 ~/Zotero/zotero.sqlite,再读 ZOTERO_DB')
416
+ p.add_argument('--apply', action='store_true', help='实际写入;默认只干跑')
417
+ p.add_argument('--out', metavar='PATH', help='写到新文件(默认原地写,并自动备份)')
418
+ p.set_defaults(func=cmd_repair)
419
+
420
+ p = sub.add_parser('patch', help='检查/重打 Zotero 的 omni.ja 补丁(不携带任何 Zotero 代码)',
421
+ epilog='补丁片段与三步做法见仓库里的 docs/integration-patch.md')
422
+ p.add_argument('--zotero-dir', metavar='DIR', required=True, help='Zotero 程序目录(含 app/omni.ja)')
423
+ p.add_argument('--patched', metavar='FILE', help='已修补的 integration.js;不给则只查')
424
+ p.add_argument('--marker', default='plainCitationFix', help='补丁标记字符串(默认 plainCitationFix)')
425
+ p.add_argument('--apply', action='store_true', help='实际写入;默认只干跑')
426
+ p.add_argument('--force', action='store_true', help='已是补丁版时仍覆盖')
427
+ p.set_defaults(func=cmd_patch)
428
+ return ap
429
+
430
+
431
+ def _utf8_stdio():
432
+ """管道/重定向时也按 UTF-8 输出,避免中文乱码(控制台本就是 UTF-8)。"""
433
+ for stream in (sys.stdout, sys.stderr):
434
+ try:
435
+ stream.reconfigure(encoding='utf-8', errors='replace')
436
+ except (AttributeError, ValueError):
437
+ pass
438
+
439
+
440
+ def main(argv=None):
441
+ _utf8_stdio()
442
+ ap = build_parser()
443
+ args = ap.parse_args(argv)
444
+ if not getattr(args, 'func', None):
445
+ ap.print_help()
446
+ return 2
447
+ try:
448
+ return args.func(args)
449
+ except FileNotFoundError as e:
450
+ print(f'! 找不到文件:{e}')
451
+ return 2
452
+ except zipfile.BadZipFile:
453
+ print('! 这不是 .docx(zip 打不开),或者文件已损坏')
454
+ return 2
455
+ except KeyError as e:
456
+ print(f'! 包里缺部件:{e}')
457
+ return 2
458
+ except PermissionError as e:
459
+ print(f'! 没有权限或文件被占用:{e}')
460
+ print(' 在 Word 里关掉这个文档再试')
461
+ return 2
462
+
463
+
464
+ if __name__ == '__main__':
465
+ sys.exit(main())