zotdocx 0.2.0__tar.gz

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-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zotdocx contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
zotdocx-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.4
2
+ Name: zotdocx
3
+ Version: 0.2.0
4
+ Summary: Repair Zotero citation fields in .docx files: GB/T 7714, IEEE, Nature, Vancouver
5
+ Author: zotdocx contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/HbS66-pro/zotdocx
8
+ Project-URL: Repository, https://github.com/HbS66-pro/zotdocx
9
+ Project-URL: Issues, https://github.com/HbS66-pro/zotdocx/issues
10
+ Keywords: zotero,docx,citation,word,bibliography,gbt7714
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Text Processing :: Markup
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: lxml
22
+ Dynamic: license-file
23
+
24
+ # zotdocx
25
+
26
+ [![tests](https://github.com/HbS66-pro/zotdocx/actions/workflows/tests.yml/badge.svg)](https://github.com/HbS66-pro/zotdocx/actions/workflows/tests.yml)
27
+
28
+ **English** | [中文](README.zh-CN.md)
29
+
30
+ `zotdocx` repairs Zotero citation fields inside a `.docx`. It edits the file only: it does not touch the Zotero library, and it does not re-typeset the document.
31
+
32
+ It is built for numeric citation styles, where a citation is a number that has to stay in step with the tables, figures and notes around it — **GB/T 7714, IEEE, Nature, Vancouver**. Author–date styles such as APA or Harvard have no number to reorder, so `renumber` and `lift` do not apply to them.
33
+
34
+ ## Quick start
35
+
36
+ ```bash
37
+ pip install zotdocx
38
+ zotdocx demo
39
+ ```
40
+
41
+ `demo` writes `demo.docx` into the current directory — a synthetic document with two citation fields and a few known defects — then prints a read-only report and a dry run of `renumber`:
42
+
43
+ ```
44
+ demo.docx
45
+ 部件 7 个;document.xml 0.00 MB
46
+ 样式 未记录
47
+
48
+ 域 3 = 引注 2 + 书目 1 + 其他 0
49
+ 跨段落:引注 0 · 书目 0
50
+ 位置:正文 2
51
+ 条目 2 个
52
+ 编号 显示 1–2;同条目多编号 0;单条目编号不符 2;多条目编号不符 0
53
+ 纯文本 正文 1 · 表格 1 · 表注图注 1 · 图题表题 1
54
+ ```
55
+
56
+ Then point it at your own file:
57
+
58
+ ```bash
59
+ zotdocx status 论文.docx # read-only report; exit code 1 if something is off
60
+ zotdocx renumber 论文.docx # dry run, prints what would change
61
+ zotdocx renumber 论文.docx --apply
62
+ ```
63
+
64
+ Console labels are Chinese in this release. Numbers, exit codes and `--json` output are the parts meant for scripts.
65
+
66
+ ## What it fixes
67
+
68
+ - Citation fields split across paragraphs, with the field end in the next paragraph
69
+ - Numbers stored in a field that disagree with the numbers shown on the page
70
+ - Numbering that does not follow the order of first citation
71
+ - Plain-text citations in the body (`[3]`, `[12,13]`) that are not live fields
72
+ - Citation fields pointing to items removed from the library (broken links)
73
+ - Zotero's "Cannot delete range" error when refreshing
74
+
75
+ ## Commands
76
+
77
+ | Command | What it does |
78
+ |---|---|
79
+ | `demo` | Write a synthetic sample document and check it |
80
+ | `status` | Report field structure, item count, numbering consistency, plain-text citations |
81
+ | `heal` | Repair cross-paragraph citation fields; align stored and displayed numbers |
82
+ | `renumber` | Renumber by first citation and sync plain-text numbers in tables, captions and notes |
83
+ | `lift` | Turn plain-text citations in the body into live fields |
84
+ | `repair` | Relink broken citations by item key or title |
85
+ | `patch` | Inspect or reapply the Zotero `omni.ja` patch |
86
+
87
+ ## Install
88
+
89
+ ```bash
90
+ pip install zotdocx
91
+ ```
92
+
93
+ Python 3.9 or later; the only dependency is `lxml`. From a checkout, `pip install .`.
94
+
95
+ `repair`, and the broken-link part of `status`, need `zotero.sqlite`. It is looked up in this order: `--zotero-db`, the `ZOTERO_DB` environment variable, then `~/Zotero/zotero.sqlite`. If none is found, the document-side checks still run and the broken-link check is skipped.
96
+
97
+ ## Usage
98
+
99
+ Write commands are dry runs until `--apply` is given:
100
+
101
+ ```bash
102
+ zotdocx heal manuscript.docx # print what would change
103
+ zotdocx heal manuscript.docx --apply # write, original backed up as *.bak_<timestamp>
104
+ zotdocx lift manuscript.docx --apply --out new.docx
105
+ ```
106
+
107
+ Exit code is 1 when `status` finds a problem, 0 otherwise, and 2 for usage or file errors.
108
+
109
+ ## Scope
110
+
111
+ - Only `word/document.xml` is replaced; every other part of the package is preserved byte for byte.
112
+ - Numbers in table cells, captions and notes stay plain text; `renumber` syncs the digits and never turns them into fields.
113
+ - Caption, note and bibliography headings are recognised in both Chinese (图 / 表 / 注 / 参考文献) and English (Table / Figure / Note / References).
114
+ - The Zotero database is opened read-only, from a temporary copy.
115
+ - No wording changes, no layout, no conversion to a final plain-text manuscript.
116
+
117
+ ## Limitations
118
+
119
+ - Numeric CSL styles only. Author–date styles have no numbers to reorder.
120
+ - Verified on Windows with Word only.
121
+ - Citations split across several runs are reported, not lifted.
122
+ - `repair` matches by item key or exact title; anything else is reported, never guessed.
123
+ - `patch` requires a patched `integration.js` supplied by the user. See [docs/integration-patch.md](docs/integration-patch.md).
124
+
125
+ ## Tests
126
+
127
+ ```bash
128
+ python tests/run_all.py
129
+ ```
130
+
131
+ Tests run against synthetic documents built in the test process, in Chinese and English. No real manuscript or library content is included. The same suite runs on GitHub Actions for Python 3.9, 3.11 and 3.13.
132
+
133
+ ## Advanced: Zotero integration patch
134
+
135
+ If Zotero reports **Cannot delete range** and citation fields keep breaking, the cause is on the Zotero side, not in the document. [docs/integration-patch.md](docs/integration-patch.md) describes a small snippet for `integration.js` and the three steps to apply it with `zotdocx patch`. It is optional, it modifies Zotero rather than the document, and a Zotero update overwrites it.
136
+
137
+ ## License
138
+
139
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,116 @@
1
+ # zotdocx
2
+
3
+ [![tests](https://github.com/HbS66-pro/zotdocx/actions/workflows/tests.yml/badge.svg)](https://github.com/HbS66-pro/zotdocx/actions/workflows/tests.yml)
4
+
5
+ **English** | [中文](README.zh-CN.md)
6
+
7
+ `zotdocx` repairs Zotero citation fields inside a `.docx`. It edits the file only: it does not touch the Zotero library, and it does not re-typeset the document.
8
+
9
+ It is built for numeric citation styles, where a citation is a number that has to stay in step with the tables, figures and notes around it — **GB/T 7714, IEEE, Nature, Vancouver**. Author–date styles such as APA or Harvard have no number to reorder, so `renumber` and `lift` do not apply to them.
10
+
11
+ ## Quick start
12
+
13
+ ```bash
14
+ pip install zotdocx
15
+ zotdocx demo
16
+ ```
17
+
18
+ `demo` writes `demo.docx` into the current directory — a synthetic document with two citation fields and a few known defects — then prints a read-only report and a dry run of `renumber`:
19
+
20
+ ```
21
+ demo.docx
22
+ 部件 7 个;document.xml 0.00 MB
23
+ 样式 未记录
24
+
25
+ 域 3 = 引注 2 + 书目 1 + 其他 0
26
+ 跨段落:引注 0 · 书目 0
27
+ 位置:正文 2
28
+ 条目 2 个
29
+ 编号 显示 1–2;同条目多编号 0;单条目编号不符 2;多条目编号不符 0
30
+ 纯文本 正文 1 · 表格 1 · 表注图注 1 · 图题表题 1
31
+ ```
32
+
33
+ Then point it at your own file:
34
+
35
+ ```bash
36
+ zotdocx status 论文.docx # read-only report; exit code 1 if something is off
37
+ zotdocx renumber 论文.docx # dry run, prints what would change
38
+ zotdocx renumber 论文.docx --apply
39
+ ```
40
+
41
+ Console labels are Chinese in this release. Numbers, exit codes and `--json` output are the parts meant for scripts.
42
+
43
+ ## What it fixes
44
+
45
+ - Citation fields split across paragraphs, with the field end in the next paragraph
46
+ - Numbers stored in a field that disagree with the numbers shown on the page
47
+ - Numbering that does not follow the order of first citation
48
+ - Plain-text citations in the body (`[3]`, `[12,13]`) that are not live fields
49
+ - Citation fields pointing to items removed from the library (broken links)
50
+ - Zotero's "Cannot delete range" error when refreshing
51
+
52
+ ## Commands
53
+
54
+ | Command | What it does |
55
+ |---|---|
56
+ | `demo` | Write a synthetic sample document and check it |
57
+ | `status` | Report field structure, item count, numbering consistency, plain-text citations |
58
+ | `heal` | Repair cross-paragraph citation fields; align stored and displayed numbers |
59
+ | `renumber` | Renumber by first citation and sync plain-text numbers in tables, captions and notes |
60
+ | `lift` | Turn plain-text citations in the body into live fields |
61
+ | `repair` | Relink broken citations by item key or title |
62
+ | `patch` | Inspect or reapply the Zotero `omni.ja` patch |
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ pip install zotdocx
68
+ ```
69
+
70
+ Python 3.9 or later; the only dependency is `lxml`. From a checkout, `pip install .`.
71
+
72
+ `repair`, and the broken-link part of `status`, need `zotero.sqlite`. It is looked up in this order: `--zotero-db`, the `ZOTERO_DB` environment variable, then `~/Zotero/zotero.sqlite`. If none is found, the document-side checks still run and the broken-link check is skipped.
73
+
74
+ ## Usage
75
+
76
+ Write commands are dry runs until `--apply` is given:
77
+
78
+ ```bash
79
+ zotdocx heal manuscript.docx # print what would change
80
+ zotdocx heal manuscript.docx --apply # write, original backed up as *.bak_<timestamp>
81
+ zotdocx lift manuscript.docx --apply --out new.docx
82
+ ```
83
+
84
+ Exit code is 1 when `status` finds a problem, 0 otherwise, and 2 for usage or file errors.
85
+
86
+ ## Scope
87
+
88
+ - Only `word/document.xml` is replaced; every other part of the package is preserved byte for byte.
89
+ - Numbers in table cells, captions and notes stay plain text; `renumber` syncs the digits and never turns them into fields.
90
+ - Caption, note and bibliography headings are recognised in both Chinese (图 / 表 / 注 / 参考文献) and English (Table / Figure / Note / References).
91
+ - The Zotero database is opened read-only, from a temporary copy.
92
+ - No wording changes, no layout, no conversion to a final plain-text manuscript.
93
+
94
+ ## Limitations
95
+
96
+ - Numeric CSL styles only. Author–date styles have no numbers to reorder.
97
+ - Verified on Windows with Word only.
98
+ - Citations split across several runs are reported, not lifted.
99
+ - `repair` matches by item key or exact title; anything else is reported, never guessed.
100
+ - `patch` requires a patched `integration.js` supplied by the user. See [docs/integration-patch.md](docs/integration-patch.md).
101
+
102
+ ## Tests
103
+
104
+ ```bash
105
+ python tests/run_all.py
106
+ ```
107
+
108
+ Tests run against synthetic documents built in the test process, in Chinese and English. No real manuscript or library content is included. The same suite runs on GitHub Actions for Python 3.9, 3.11 and 3.13.
109
+
110
+ ## Advanced: Zotero integration patch
111
+
112
+ If Zotero reports **Cannot delete range** and citation fields keep breaking, the cause is on the Zotero side, not in the document. [docs/integration-patch.md](docs/integration-patch.md) describes a small snippet for `integration.js` and the three steps to apply it with `zotdocx patch`. It is optional, it modifies Zotero rather than the document, and a Zotero update overwrites it.
113
+
114
+ ## License
115
+
116
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "zotdocx"
7
+ version = "0.2.0"
8
+ description = "Repair Zotero citation fields in .docx files: GB/T 7714, IEEE, Nature, Vancouver"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ dependencies = ["lxml"]
14
+ keywords = ["zotero", "docx", "citation", "word", "bibliography", "gbt7714"]
15
+ authors = [{ name = "zotdocx contributors" }]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Environment :: Console",
19
+ "Intended Audience :: End Users/Desktop",
20
+ "Intended Audience :: Science/Research",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Topic :: Text Processing :: Markup",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/HbS66-pro/zotdocx"
28
+ Repository = "https://github.com/HbS66-pro/zotdocx"
29
+ Issues = "https://github.com/HbS66-pro/zotdocx/issues"
30
+
31
+ [project.scripts]
32
+ zotdocx = "zotdocx.cli:main"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,57 @@
1
+ # -*- coding: utf-8 -*-
2
+ """demo 命令:生成的合成文档可读、可修;干跑不落盘,--apply 后能过复检。
3
+
4
+ 断言:
5
+ * demo 写出文档并返回 0,同一路径二次运行被拒绝(返回 2);
6
+ * 对生成的文档 status 返回 1(故意留了编号不符);
7
+ * renumber 干跑不改文件字节;
8
+ * renumber --apply 备份原文件,之后 status 返回 0。
9
+ """
10
+ import hashlib
11
+ import os
12
+ import sys
13
+ import tempfile
14
+
15
+ HERE = os.path.dirname(os.path.abspath(__file__))
16
+ sys.path.insert(0, os.path.dirname(HERE))
17
+
18
+ from zotdocx.analyze import Document # noqa: E402
19
+ from zotdocx.cli import main # noqa: E402
20
+ from zotdocx.docxfile import DOC, Docx # noqa: E402
21
+
22
+
23
+ def digest(path):
24
+ with open(path, 'rb') as f:
25
+ return hashlib.sha256(f.read()).hexdigest()
26
+
27
+
28
+ def run():
29
+ d = tempfile.mkdtemp(prefix='zotdocx_demo_')
30
+ out = os.path.join(d, 'demo.docx')
31
+
32
+ assert main(['demo', '--out', out]) == 0, 'demo 未返回 0'
33
+ assert os.path.isfile(out), 'demo 没有生成文档'
34
+ assert main(['demo', '--out', out]) == 2, '已存在的文件应被拒绝覆盖'
35
+
36
+ with Docx(out) as z:
37
+ doc = Document(z.text(DOC).encode('utf-8'))
38
+ assert len(doc.items()) == 2 and len(doc.fields) == 3, '演示文档的域结构不对'
39
+
40
+ assert main(['status', out]) == 1, '故意留着的编号不符应让 status 返回 1'
41
+
42
+ before = digest(out)
43
+ assert main(['renumber', out]) == 0, '干跑应返回 0'
44
+ assert digest(out) == before, '干跑改动了文件'
45
+
46
+ assert main(['renumber', out, '--apply']) == 0, '写入应返回 0'
47
+ assert digest(out) != before, '写入后文件没变化'
48
+ baks = [n for n in os.listdir(d) if '.bak_' in n]
49
+ assert baks, '没有生成备份'
50
+
51
+ assert main(['status', out]) == 0, '修完再体检应返回 0'
52
+ print(f'演示 {out}:域 3 个,干跑不改盘,写入后复检通过')
53
+ print('PASS')
54
+
55
+
56
+ if __name__ == '__main__':
57
+ run()
@@ -0,0 +1,61 @@
1
+ # -*- coding: utf-8 -*-
2
+ """英文文档的段落语境识别与 lift 边界(全用合成稿)。
3
+
4
+ 断言:
5
+ * Table 1 / Figure 2 图题表题、Note: 表注、References 标题都能认出来;
6
+ * lift 只动正文里的纯文本引用,图题、表注、表格单元格、参考文献表一律不碰;
7
+ * 上宏前后每段可见文字不变。
8
+ """
9
+ import os
10
+ import sys
11
+
12
+ HERE = os.path.dirname(os.path.abspath(__file__))
13
+ sys.path.insert(0, os.path.dirname(HERE))
14
+ sys.path.insert(0, HERE)
15
+
16
+ from make_fixture import build # noqa: E402
17
+ from zotdocx.analyze import (BIBLIO, BODY, CAPTION, NOTE, TABLE, # noqa: E402
18
+ Document)
19
+ from zotdocx.docxfile import DOC, Docx # noqa: E402
20
+ from zotdocx.lift import lift_xml # noqa: E402
21
+
22
+
23
+ def main():
24
+ path = os.path.join(HERE, 'fixtures', 'en.docx')
25
+ build(path, plain_body=True, lang='en')
26
+ with Docx(path) as z:
27
+ xml = z.text(DOC)
28
+ doc = Document(xml.encode('utf-8'))
29
+
30
+ want = {
31
+ 'Synthetic paragraph one': BODY,
32
+ 'Table 1': CAPTION,
33
+ 'Figure 2': CAPTION,
34
+ 'Note:': NOTE,
35
+ 'References': BIBLIO,
36
+ }
37
+ seen = {}
38
+ for i, t in enumerate(doc.para_text):
39
+ for key in want:
40
+ if t.startswith(key):
41
+ seen[key] = doc.para_ctx[i]
42
+ for key, ctx in want.items():
43
+ assert seen.get(key) == ctx, f'{key!r} 判成了 {seen.get(key)!r},应为 {ctx}'
44
+
45
+ new_xml, rep = lift_xml(xml)
46
+ assert len(rep['lifted']) == 2, f'只该上宏正文两处,实际 {rep["lifted"]}'
47
+ for text, para in rep['lifted']:
48
+ assert doc.para_ctx[para] == BODY, f'{text} 在段{para},语境是 {doc.para_ctx[para]}'
49
+
50
+ after = Document(new_xml.encode('utf-8'))
51
+ assert after.para_text == doc.para_text, '上宏前后可见文字不一致'
52
+ for i, ctx in enumerate(doc.para_ctx):
53
+ if ctx != BODY:
54
+ assert after.para_text[i] == doc.para_text[i]
55
+
56
+ print(f'语境识别 {len(want)} 项通过;上宏 {len(rep["lifted"])} 处,均落在正文')
57
+ print('PASS')
58
+
59
+
60
+ if __name__ == '__main__':
61
+ main()
@@ -0,0 +1,96 @@
1
+ # -*- coding: utf-8 -*-
2
+ """heal 的回归测试(全用合成 docx,不含真实论文或库数据)。
3
+
4
+ 1) 生成合成基线;
5
+ 2) 人为制造「域尾掉进下一段」:把段末那个域的 </w:r> 搬到下一段开头;
6
+ 3) 跑 heal_xml;
7
+ 4) 断言:跨段域 1 → 0,域数不变,逐段文字与基线一致,XML 合法。
8
+ """
9
+ import os
10
+ import re
11
+ import sys
12
+
13
+ HERE = os.path.dirname(os.path.abspath(__file__))
14
+ ROOT = os.path.dirname(HERE)
15
+ sys.path.insert(0, ROOT)
16
+
17
+ from lxml import etree # noqa: E402
18
+ from make_fixture import build # noqa: E402
19
+ from zotdocx.analyze import Document # noqa: E402
20
+ from zotdocx.docxfile import Docx, DOC # noqa: E402
21
+ from zotdocx.heal import END, RUN_OPEN, field_spans, heal_xml # noqa: E402
22
+
23
+ PARA = re.compile(r'<w:p(?: [^>]*)?>')
24
+ PPR = re.compile(r'<w:pPr>.*?</w:pPr>', re.S)
25
+
26
+
27
+ def inject(xml):
28
+ """把第一个段的域的 end run 搬到下一段开头。"""
29
+ spans = [(a, b) for a, b in field_spans(xml) if xml[b:b + 6] == '</w:p>']
30
+ assert spans, '没有段末的域可注入'
31
+ rs, re_ = spans[0]
32
+ b = xml.rindex(END, rs, re_)
33
+ rs2 = [m.start() for m in RUN_OPEN.finditer(xml, 0, b)][-1]
34
+ run = xml[rs2:re_]
35
+ rest = xml[:rs2] + xml[re_:]
36
+ close = rest.index('</w:p>', rs2)
37
+ m = PARA.search(rest, close)
38
+ m2 = PPR.match(rest, m.end())
39
+ ins = m2.end() if m2 else m.end()
40
+ return rest[:ins] + run + rest[ins:]
41
+
42
+
43
+ def load(path):
44
+ with Docx(path) as z:
45
+ return z.text(DOC)
46
+
47
+
48
+ def texts(xml):
49
+ return Document(xml.encode('utf-8')).para_text
50
+
51
+
52
+ def main():
53
+ os.makedirs(os.path.join(HERE, 'fixtures'), exist_ok=True)
54
+ base = build(os.path.join(HERE, 'fixtures', 'synthetic.docx'))
55
+ xml0 = load(base)
56
+ n_fields0 = len(Document(xml0.encode('utf-8')).fields)
57
+
58
+ xml1 = inject(xml0)
59
+ d1 = Document(xml1.encode('utf-8'))
60
+ cross1 = sum(1 for f in d1.items() if f.cross)
61
+ print(f'注入后:域 {len(d1.fields)},跨段引注 {cross1}')
62
+ assert cross1 >= 1
63
+
64
+ xml2, rep = heal_xml(xml1)
65
+ etree.fromstring(xml2.encode('utf-8'))
66
+ d2 = Document(xml2.encode('utf-8'))
67
+ cross2 = sum(1 for f in d2.items() if f.cross)
68
+ print(f'heal:收回域尾 {rep["moved"]},同步编号 {rep["synced"]},问题 {rep["problems"]}')
69
+ print(f'修复后:域 {len(d2.fields)},跨段引注 {cross2}')
70
+ assert cross2 == 0, 'heal 没修干净'
71
+ assert len(d2.fields) == n_fields0, '域数变了'
72
+
73
+ t0, t2 = texts(xml0), texts(xml2)
74
+ assert len(t0) == len(t2), f'段落数变了 {len(t0)} -> {len(t2)}'
75
+ bad = [i for i, (a, b) in enumerate(zip(t0, t2)) if a != b]
76
+ if bad:
77
+ for i in bad[:5]:
78
+ print(f' 段{i}: 基线 {t0[i]!r}')
79
+ print(f' 修复 {t2[i]!r}')
80
+ raise AssertionError('修复改动了正文文字')
81
+ print('段落文字:逐段一致')
82
+
83
+ # ---- 第二项:域内编号与显示不一致 ----
84
+ xml3 = xml0.replace('"plainCitation":"[1]"', '"plainCitation":"[9]"', 1)
85
+ assert xml3 != xml0, '没造出编号不一致的样本'
86
+ xml4, rep4 = heal_xml(xml3)
87
+ d4 = Document(xml4.encode('utf-8'))
88
+ pc = d4.items()[0].plain_citation
89
+ print(f'编号同步:收回域尾 {rep4["moved"]},同步 {rep4["synced"]},修后 plainCitation={pc!r}')
90
+ assert rep4['synced'] == 1 and pc == '[1]', '编号没同步回来'
91
+
92
+ print('PASS')
93
+
94
+
95
+ if __name__ == '__main__':
96
+ main()
@@ -0,0 +1,74 @@
1
+ # -*- coding: utf-8 -*-
2
+ """lift 的回归测试(合成 docx)。
3
+
4
+ 构造:正文两段里各有一个纯文本引用 run([1] 和 [1,2]),文档别处已有
5
+ 对应条目的单条目活域。
6
+
7
+ 断言:
8
+ * 域数 +2(单条目一个、合并条目一个);
9
+ * 上宏后段落的可见文字没变;
10
+ * 合并出来的域里 citationItems 有 2 个、position 为 0/1、id 与 uris 一一对应;
11
+ * 表格 / 表注 / 图题里的纯文本一个都没被上宏(域数只增 2)。
12
+ """
13
+ import json
14
+ import os
15
+ import sys
16
+
17
+ HERE = os.path.dirname(os.path.abspath(__file__))
18
+ ROOT = os.path.dirname(HERE)
19
+ sys.path.insert(0, ROOT)
20
+
21
+ from lxml import etree # noqa: E402
22
+ from make_fixture import build # noqa: E402
23
+ from zotdocx.analyze import Document, BODY, TABLE, NOTE, CAPTION # noqa: E402
24
+ from zotdocx.docxfile import Docx, DOC # noqa: E402
25
+ from zotdocx.lift import lift_xml # noqa: E402
26
+
27
+
28
+ def main():
29
+ path = build(os.path.join(HERE, 'fixtures', 'synthetic_plain.docx'), plain_body=True)
30
+ with Docx(path) as z:
31
+ xml0 = z.text(DOC)
32
+
33
+ d0 = Document(xml0.encode('utf-8'))
34
+ plain0 = [p.text for p in d0.plains if p.ctx == BODY]
35
+ print('改前:域', len(d0.fields), '正文纯文本', plain0)
36
+ assert plain0 == ['[1]', '[1,2]'], plain0
37
+
38
+ xml1, rep = lift_xml(xml0)
39
+ etree.fromstring(xml1.encode('utf-8'))
40
+ d1 = Document(xml1.encode('utf-8'))
41
+
42
+ print('lift:上宏', rep['lifted'], '跳过', rep['skipped'])
43
+ print('改后:域', len(d1.fields), '正文纯文本', [p.text for p in d1.plains if p.ctx == BODY])
44
+ assert len(d1.fields) == len(d0.fields) + 2, '域数不对'
45
+ assert not [p for p in d1.plains if p.ctx == BODY], '正文还有纯文本残留'
46
+ assert [p.text for p in d1.plains if p.ctx == TABLE] == ['[3]'], '表格被误伤'
47
+ assert [p.text for p in d1.plains if p.ctx == NOTE] == ['[3]'], '表注被误伤'
48
+ assert [p.text for p in d1.plains if p.ctx == CAPTION] == ['[3]'], '图题被误伤'
49
+
50
+ # 可见文字不变
51
+ assert d0.para_text == d1.para_text, '上宏改了可见文字'
52
+
53
+ # 合并出来的域
54
+ multi = [f for f in d1.items() if len(f.ids) == 2]
55
+ assert len(multi) == 1, f'应该只有一个双条目域,实际 {len(multi)}'
56
+ m = multi[0]
57
+ items = m.data['citationItems']
58
+ print('双条目域:ids', m.ids, 'position', [i.get('position') for i in items],
59
+ 'display', m.display)
60
+ assert [i.get('position') for i in items] == [0, 1]
61
+ for it in items:
62
+ assert it['itemData']['id'] == it['id']
63
+ assert it['uris'][0].endswith('/items/' + {101: 'AAAAAAA1', 102: 'BBBBBBB2'}[it['id']])
64
+ assert m.display == '[1,2]'
65
+ assert m.plain_citation == '[1,2]'
66
+
67
+ # citationID 唯一
68
+ ids = [f.data.get('citationID') for f in d1.items()]
69
+ assert len(ids) == len(set(ids)), 'citationID 重复'
70
+ print('PASS')
71
+
72
+
73
+ if __name__ == '__main__':
74
+ main()
@@ -0,0 +1,60 @@
1
+ # -*- coding: utf-8 -*-
2
+ """patch 的回归测试:用合成 omni.ja(假 Zotero 包),不碰真实安装。"""
3
+ import os
4
+ import sys
5
+ import zipfile
6
+
7
+ HERE = os.path.dirname(os.path.abspath(__file__))
8
+ ROOT = os.path.dirname(HERE)
9
+ sys.path.insert(0, ROOT)
10
+
11
+ from zotdocx.patch import INNER, apply_patch, inspect, omni_path # noqa: E402
12
+
13
+ MARK = 'plainCitationFix'
14
+
15
+
16
+ def make_omni(path, inner_text):
17
+ with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) as z:
18
+ z.writestr('chrome/content/moz.build', 'FILES += []')
19
+ z.writestr(INNER, inner_text)
20
+ z.writestr('defaults/preferences/zotero.js', 'pref("a", 1);')
21
+
22
+
23
+ def main():
24
+ work = os.path.join(HERE, 'fixtures', 'fakezotero', 'app')
25
+ os.makedirs(work, exist_ok=True)
26
+ omni = omni_path(os.path.dirname(work))
27
+ make_omni(omni, 'function setText(t){ return t; }')
28
+ patched = os.path.join(HERE, 'fixtures', 'patched_integration.js')
29
+ with open(patched, 'w', encoding='utf-8') as f:
30
+ f.write('function _%s(t){ return t; }\nfunction setText(t){ return _%s(t); }\n' % (MARK, MARK))
31
+
32
+ st0 = inspect(omni, MARK)
33
+ print('打前:', st0['entries'], '条目', st0['inner_size'], 'B,标记在:', st0['has_marker'])
34
+ assert not st0['has_marker']
35
+
36
+ with open(patched, 'rb') as f:
37
+ data = f.read()
38
+ bak = apply_patch(omni, data, MARK)
39
+ print('备份:', os.path.basename(bak), '存在:', os.path.exists(bak))
40
+
41
+ st1 = inspect(omni, MARK)
42
+ print('打后:', st1['entries'], '条目', st1['inner_size'], 'B,标记在:', st1['has_marker'])
43
+ assert st1['has_marker'] and st1['entries'] == st0['entries']
44
+ assert st1['inner_sha'] == __import__('zotdocx.patch', fromlist=['sha']).sha(data)
45
+ with zipfile.ZipFile(omni) as z:
46
+ assert z.testzip() is None
47
+ assert z.read('chrome/content/moz.build') == b'FILES += []', '其他部件被改动了'
48
+
49
+ # 拒绝没有标记的文件
50
+ try:
51
+ apply_patch(omni, b'no marker here', MARK)
52
+ raise AssertionError('应该拒绝没有标记的补丁')
53
+ except ValueError as e:
54
+ print('拒绝无标记输入:', e)
55
+
56
+ print('PASS')
57
+
58
+
59
+ if __name__ == '__main__':
60
+ main()