audit-e2w 0.0.0-stage → 1.11.2
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.
- package/LICENSE +21 -0
- package/README.md +147 -2
- package/cordis.patch.yml +3 -0
- package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
- package/dsh_plugins/audit-e2w/lib/index.js +114 -0
- package/dsh_plugins/audit-e2w/lib/skill.js +41 -0
- package/excel_word/README.md +380 -0
- package/excel_word/qoder_engine.py +438 -0
- package/excel_word/requirements.txt +4 -0
- package/excel_word/wesync/__init__.py +19 -0
- package/excel_word/wesync/__main__.py +6 -0
- package/excel_word/wesync/align.py +154 -0
- package/excel_word/wesync/api.py +840 -0
- package/excel_word/wesync/backup_history.py +65 -0
- package/excel_word/wesync/changelog.py +58 -0
- package/excel_word/wesync/cli.py +173 -0
- package/excel_word/wesync/commands/__init__.py +8 -0
- package/excel_word/wesync/commands/blank_cmd.py +250 -0
- package/excel_word/wesync/commands/bookmark_cmd.py +115 -0
- package/excel_word/wesync/commands/clear_cmd.py +48 -0
- package/excel_word/wesync/commands/export_cmd.py +220 -0
- package/excel_word/wesync/commands/marks_cmd.py +152 -0
- package/excel_word/wesync/commands/placeholders_cmd.py +87 -0
- package/excel_word/wesync/commands/writeback_cmd.py +513 -0
- package/excel_word/wesync/config.py +96 -0
- package/excel_word/wesync/console.py +78 -0
- package/excel_word/wesync/docx_blank.py +156 -0
- package/excel_word/wesync/docx_bookmarks.py +287 -0
- package/excel_word/wesync/docx_columns.py +257 -0
- package/excel_word/wesync/docx_edit.py +77 -0
- package/excel_word/wesync/docx_grid.py +212 -0
- package/excel_word/wesync/docx_marks.py +291 -0
- package/excel_word/wesync/docx_meta.py +157 -0
- package/excel_word/wesync/docx_newtable.py +220 -0
- package/excel_word/wesync/docx_placeholders.py +161 -0
- package/excel_word/wesync/docx_rows.py +67 -0
- package/excel_word/wesync/errors.py +5 -0
- package/excel_word/wesync/excel_blocks.py +543 -0
- package/excel_word/wesync/excel_export.py +136 -0
- package/excel_word/wesync/excel_marks.py +193 -0
- package/excel_word/wesync/excel_totals.py +53 -0
- package/excel_word/wesync/fsops.py +214 -0
- package/excel_word/wesync/gui/__init__.py +34 -0
- package/excel_word/wesync/gui/__main__.py +6 -0
- package/excel_word/wesync/gui/app.py +399 -0
- package/excel_word/wesync/gui/manual.py +68 -0
- package/excel_word/wesync/gui/pages/__init__.py +31 -0
- package/excel_word/wesync/gui/pages/_page.py +89 -0
- package/excel_word/wesync/gui/pages/batch_page.py +423 -0
- package/excel_word/wesync/gui/pages/blank_page.py +465 -0
- package/excel_word/wesync/gui/pages/bookmark_page.py +37 -0
- package/excel_word/wesync/gui/pages/export_page.py +88 -0
- package/excel_word/wesync/gui/pages/format_page.py +429 -0
- package/excel_word/wesync/gui/pages/help_page.py +92 -0
- package/excel_word/wesync/gui/pages/history_page.py +145 -0
- package/excel_word/wesync/gui/pages/marks_page.py +178 -0
- package/excel_word/wesync/gui/pages/writeback_page.py +452 -0
- package/excel_word/wesync/gui/resources.py +22 -0
- package/excel_word/wesync/gui/runner.py +74 -0
- package/excel_word/wesync/gui/store.py +34 -0
- package/excel_word/wesync/gui/theme.py +100 -0
- package/excel_word/wesync/gui/widgets/__init__.py +8 -0
- package/excel_word/wesync/gui/widgets/cards.py +20 -0
- package/excel_word/wesync/gui/widgets/filebar.py +58 -0
- package/excel_word/wesync/gui/widgets/logpane.py +110 -0
- package/excel_word/wesync/gui/widgets/nav.py +39 -0
- package/excel_word/wesync/report_format.py +1577 -0
- package/excel_word/wesync/sort_rules.py +244 -0
- package/excel_word/wesync/valuefmt.py +462 -0
- package/package.json +49 -4
- package/qoder_plugins/audit-toolbox/README.md +156 -0
- package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
"""Qoder 插件无窗口引擎:从 stdin 读 JSON 请求,向 stdout 输出 JSONL 日志与结果。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import datetime as dt
|
|
7
|
+
import io
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from wesync import __version__, api
|
|
13
|
+
from wesync.console import reset_log_state, set_log_sink
|
|
14
|
+
from wesync.errors import SyncError
|
|
15
|
+
|
|
16
|
+
QUERY_OPERATIONS = {
|
|
17
|
+
"blank-scan", "deleted-list", "blank-batch-scan", "diff", "table-list",
|
|
18
|
+
"sort-list", "template-scan", "backup-list", "format-scan",
|
|
19
|
+
"format-heading-candidates",
|
|
20
|
+
}
|
|
21
|
+
RUN_OPERATIONS = {
|
|
22
|
+
"export", "writeback", "bookmark", "rejudge", "clear-bookmarks", "marks",
|
|
23
|
+
"marks-sync", "placeholders", "placeholders-sync", "blank-delete",
|
|
24
|
+
"restore-tables", "blank-batch-delete", "diff-export", "append-table",
|
|
25
|
+
"sort-set", "sort-clear", "batch-writeback", "template-batch",
|
|
26
|
+
"fill-placeholders", "backup-restore", "format-apply",
|
|
27
|
+
}
|
|
28
|
+
DRY_RUN_OPERATIONS = {
|
|
29
|
+
"export", "writeback", "bookmark", "rejudge", "clear-bookmarks", "marks",
|
|
30
|
+
"marks-sync", "placeholders", "placeholders-sync", "blank-delete",
|
|
31
|
+
"restore-tables", "blank-batch-delete", "batch-writeback", "template-batch",
|
|
32
|
+
"format-apply",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _emit(request_id: str, kind: str, **payload) -> None:
|
|
37
|
+
message = {"id": request_id, "type": kind, **payload}
|
|
38
|
+
data = (json.dumps(message, ensure_ascii=False) + "\n").encode("utf-8")
|
|
39
|
+
sys.stdout.buffer.write(data)
|
|
40
|
+
sys.stdout.buffer.flush()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _required_path(request: dict, key: str, suffixes: tuple[str, ...]) -> str:
|
|
44
|
+
value = request.get(key)
|
|
45
|
+
if not isinstance(value, str) or not value.strip():
|
|
46
|
+
raise SyncError(f"缺少{key}路径")
|
|
47
|
+
value = value.strip()
|
|
48
|
+
if any(ord(ch) < 32 for ch in value):
|
|
49
|
+
raise SyncError(f"{key}路径含有控制字符")
|
|
50
|
+
path = Path(value).expanduser()
|
|
51
|
+
if not path.is_absolute():
|
|
52
|
+
raise SyncError(f"{key}必须使用绝对路径")
|
|
53
|
+
if suffixes and path.suffix.lower() not in suffixes:
|
|
54
|
+
raise SyncError(f"{key}只支持 {'/'.join(suffixes)} 文件")
|
|
55
|
+
return str(path)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _optional_path(request: dict, key: str, suffixes: tuple[str, ...]) -> str | None:
|
|
59
|
+
value = request.get(key)
|
|
60
|
+
if value in (None, ""):
|
|
61
|
+
return None
|
|
62
|
+
return _required_path(request, key, suffixes)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _path_list(request: dict, key: str, suffixes: tuple[str, ...]) -> list[str]:
|
|
66
|
+
values = request.get(key)
|
|
67
|
+
if not isinstance(values, list) or not values:
|
|
68
|
+
raise SyncError(f"请至少选择一个{key}文件")
|
|
69
|
+
if len(values) > 200:
|
|
70
|
+
raise SyncError(f"{key}一次最多处理 200 个文件")
|
|
71
|
+
result = []
|
|
72
|
+
for value in values:
|
|
73
|
+
if not isinstance(value, str):
|
|
74
|
+
raise SyncError(f"{key}必须是路径数组")
|
|
75
|
+
result.append(_required_path({key: value}, key, suffixes))
|
|
76
|
+
return result
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _text(request: dict, key: str, label: str) -> str:
|
|
80
|
+
value = request.get(key)
|
|
81
|
+
if not isinstance(value, str) or not value.strip():
|
|
82
|
+
raise SyncError(f"请填写{label}")
|
|
83
|
+
return value.strip()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _flag(request: dict, key: str, default: bool = False) -> bool:
|
|
87
|
+
value = request.get(key, default)
|
|
88
|
+
if not isinstance(value, bool):
|
|
89
|
+
raise SyncError(f"{key}必须是布尔值")
|
|
90
|
+
return value
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _integer(request: dict, key: str, label: str, minimum: int, maximum: int) -> int:
|
|
94
|
+
value = request.get(key)
|
|
95
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
96
|
+
raise SyncError(f"{label}必须是整数")
|
|
97
|
+
if not minimum <= value <= maximum:
|
|
98
|
+
raise SyncError(f"{label}必须在 {minimum}~{maximum} 之间")
|
|
99
|
+
return value
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _contents(request: dict, default: tuple[str, ...]) -> tuple[str, ...]:
|
|
103
|
+
raw = request.get("contents") or {}
|
|
104
|
+
if not isinstance(raw, dict):
|
|
105
|
+
raise SyncError("同步内容格式不正确")
|
|
106
|
+
selected = tuple(name for name in ("tables", "marks", "placeholders") if raw.get(name, name in default))
|
|
107
|
+
if not selected:
|
|
108
|
+
raise SyncError("同步内容至少勾选一项")
|
|
109
|
+
return selected
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _jsonable(value):
|
|
113
|
+
if isinstance(value, Path):
|
|
114
|
+
return str(value)
|
|
115
|
+
if isinstance(value, (dt.datetime, dt.date, dt.time)):
|
|
116
|
+
return value.isoformat()
|
|
117
|
+
if isinstance(value, dict):
|
|
118
|
+
return {str(key): _jsonable(item) for key, item in value.items()}
|
|
119
|
+
if isinstance(value, (list, tuple)):
|
|
120
|
+
return [_jsonable(item) for item in value]
|
|
121
|
+
if isinstance(value, set):
|
|
122
|
+
return [_jsonable(item) for item in sorted(value, key=str)]
|
|
123
|
+
if value is None or isinstance(value, (str, int, float, bool)):
|
|
124
|
+
return value
|
|
125
|
+
return str(value)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _blank_candidates(items: list[dict]) -> list[dict]:
|
|
129
|
+
keys = ("no", "index", "code", "kind", "nrows", "ncols", "caption_text")
|
|
130
|
+
return [{key: item.get(key) for key in keys} for item in items]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _template_items(request: dict, template_count: int) -> list[dict]:
|
|
134
|
+
raw = request.get("items")
|
|
135
|
+
if not isinstance(raw, list) or not raw:
|
|
136
|
+
raise SyncError("请至少添加一个 Excel 工作簿")
|
|
137
|
+
if len(raw) > 200:
|
|
138
|
+
raise SyncError("一次最多生成 200 份报告")
|
|
139
|
+
result = []
|
|
140
|
+
for item in raw:
|
|
141
|
+
if not isinstance(item, dict):
|
|
142
|
+
raise SyncError("模板清单格式不正确")
|
|
143
|
+
excel = _required_path(item, "excel", (".xlsx", ".xlsm"))
|
|
144
|
+
template = item.get("template")
|
|
145
|
+
if isinstance(template, bool) or not isinstance(template, int) or not 1 <= template <= template_count:
|
|
146
|
+
raise SyncError("请为每个工作簿选择有效的所属模板")
|
|
147
|
+
result.append({"excel": excel, "template": template})
|
|
148
|
+
return result
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _blank_batch_items(request: dict) -> list[dict]:
|
|
152
|
+
raw = request.get("items")
|
|
153
|
+
if not isinstance(raw, list) or not raw:
|
|
154
|
+
raise SyncError("请先批量扫描并勾选要删除的空白表格")
|
|
155
|
+
if len(raw) > 200:
|
|
156
|
+
raise SyncError("一次最多处理 200 份报告")
|
|
157
|
+
result = []
|
|
158
|
+
for item in raw:
|
|
159
|
+
if not isinstance(item, dict):
|
|
160
|
+
raise SyncError("批量删除清单格式不正确")
|
|
161
|
+
docx = _required_path(item, "docx", (".docx", ".docm"))
|
|
162
|
+
pick = _text(item, "pick", "候选编号")
|
|
163
|
+
keep_for = item.get("keepCaptionFor")
|
|
164
|
+
if keep_for is not None and not isinstance(keep_for, str):
|
|
165
|
+
raise SyncError("保留标题编号必须是文本")
|
|
166
|
+
excel = _optional_path(item, "excel", (".xlsx", ".xlsm"))
|
|
167
|
+
reversible = item.get("reversible", True)
|
|
168
|
+
if not isinstance(reversible, bool):
|
|
169
|
+
raise SyncError("reversible 必须是布尔值")
|
|
170
|
+
result.append({
|
|
171
|
+
"docx": docx,
|
|
172
|
+
"pick": pick,
|
|
173
|
+
"keep_caption_for": keep_for,
|
|
174
|
+
"reversible": reversible,
|
|
175
|
+
"excel": excel,
|
|
176
|
+
})
|
|
177
|
+
return result
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _format_args(request: dict) -> dict:
|
|
181
|
+
profile_name = request.get("profileName")
|
|
182
|
+
if profile_name is not None and (not isinstance(profile_name, str) or not profile_name.strip()):
|
|
183
|
+
raise SyncError("profileName 必须是非空文本")
|
|
184
|
+
levels = request.get("headingLevels")
|
|
185
|
+
if levels is not None:
|
|
186
|
+
if not isinstance(levels, dict) or len(levels) > 300:
|
|
187
|
+
raise SyncError("headingLevels 必须是候选编号到 1~4 级标题的映射,且最多 300 项")
|
|
188
|
+
if any(not isinstance(key, str) or type(value) is not int or not 1 <= value <= 4 for key, value in levels.items()):
|
|
189
|
+
raise SyncError("headingLevels 的级别必须是 1~4 的整数")
|
|
190
|
+
batch_id = request.get("headingBatchId")
|
|
191
|
+
if batch_id is not None and (not isinstance(batch_id, str) or not batch_id):
|
|
192
|
+
raise SyncError("headingBatchId 必须是非空文本")
|
|
193
|
+
role_batch_id = request.get("roleBatchId")
|
|
194
|
+
if role_batch_id is not None and (not isinstance(role_batch_id, str) or not role_batch_id):
|
|
195
|
+
raise SyncError("roleBatchId 必须是非空文本")
|
|
196
|
+
role_overrides = request.get("roleOverrides")
|
|
197
|
+
if role_overrides is not None:
|
|
198
|
+
if not isinstance(role_overrides, dict) or len(role_overrides) > 300:
|
|
199
|
+
raise SyncError("roleOverrides 必须是最多 300 项的疑难角色映射")
|
|
200
|
+
if any(not isinstance(key, str) or value not in ("body", "table_title") for key, value in role_overrides.items()):
|
|
201
|
+
raise SyncError("roleOverrides 的角色只能是 body 或 table_title")
|
|
202
|
+
region_start_id = request.get("regionStartId")
|
|
203
|
+
if region_start_id is not None and (not isinstance(region_start_id, str) or not region_start_id):
|
|
204
|
+
raise SyncError("regionStartId 必须是非空文本")
|
|
205
|
+
return {
|
|
206
|
+
"template": _optional_path(request, "template", (".docx", ".docm")),
|
|
207
|
+
"profile_name": profile_name.strip() if profile_name is not None else None,
|
|
208
|
+
"scope": request.get("scope"),
|
|
209
|
+
"heading_batch_id": batch_id,
|
|
210
|
+
"heading_levels": levels,
|
|
211
|
+
"role_batch_id": role_batch_id,
|
|
212
|
+
"role_overrides": role_overrides,
|
|
213
|
+
"region_start_id": region_start_id,
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _dispatch(request: dict):
|
|
218
|
+
operation = request["operation"]
|
|
219
|
+
docx = _optional_path(request, "docx", (".docx", ".docm"))
|
|
220
|
+
excel = _optional_path(request, "excel", (".xlsx", ".xlsm"))
|
|
221
|
+
dry_run = _flag(request, "dryRun")
|
|
222
|
+
force = _flag(request, "force")
|
|
223
|
+
if dry_run and operation not in DRY_RUN_OPERATIONS:
|
|
224
|
+
raise SyncError("该操作不支持预演")
|
|
225
|
+
|
|
226
|
+
if operation in QUERY_OPERATIONS:
|
|
227
|
+
if operation == "blank-scan":
|
|
228
|
+
return _blank_candidates(api.scan_blank_tables(_required_path(request, "docx", (".docx", ".docm"))))
|
|
229
|
+
if operation == "deleted-list":
|
|
230
|
+
return api.list_deleted_blocks(_required_path(request, "docx", (".docx", ".docm")), excel)
|
|
231
|
+
if operation == "blank-batch-scan":
|
|
232
|
+
results = api.scan_blank_batch(_path_list(request, "paths", (".docx", ".docm")))
|
|
233
|
+
for item in results:
|
|
234
|
+
item["candidates"] = _blank_candidates(item.get("candidates", []))
|
|
235
|
+
return results
|
|
236
|
+
if operation == "diff":
|
|
237
|
+
return api.scan_writeback_diff(_required_path(request, "docx", (".docx", ".docm")), excel)
|
|
238
|
+
if operation == "table-list":
|
|
239
|
+
return api.list_table_blocks(_required_path(request, "docx", (".docx", ".docm")), excel)
|
|
240
|
+
if operation == "sort-list":
|
|
241
|
+
return api.list_table_sorts(_required_path(request, "docx", (".docx", ".docm")), excel)
|
|
242
|
+
if operation == "template-scan":
|
|
243
|
+
return api.scan_template_placeholders(_required_path(request, "docx", (".docx", ".docm")))
|
|
244
|
+
if operation == "backup-list":
|
|
245
|
+
return api.scan_backups(_required_path(request, "docx", (".docx", ".docm")), excel)
|
|
246
|
+
if operation == "format-heading-candidates":
|
|
247
|
+
return api.scan_format_heading_candidates(_required_path(request, "docx", (".docx", ".docm")))
|
|
248
|
+
if operation == "format-scan":
|
|
249
|
+
return api.scan_report_format(
|
|
250
|
+
_required_path(request, "docx", (".docx", ".docm")),
|
|
251
|
+
**_format_args(request),
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
if operation == "format-apply":
|
|
255
|
+
if not dry_run and not _flag(request, "confirmed"):
|
|
256
|
+
raise SyncError("正式应用格式前必须取得用户确认,并传 confirmed=true")
|
|
257
|
+
return api.run_report_format(
|
|
258
|
+
_required_path(request, "docx", (".docx", ".docm")),
|
|
259
|
+
output=_optional_path(request, "output", (".docx", ".docm")),
|
|
260
|
+
dry_run=dry_run,
|
|
261
|
+
**_format_args(request),
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
if operation == "backup-restore":
|
|
265
|
+
backup = _required_path(request, "backupPath", (".docx", ".docm", ".xlsx", ".xlsm"))
|
|
266
|
+
target = _required_path(request, "target", (".docx", ".docm", ".xlsx", ".xlsm"))
|
|
267
|
+
if Path(backup).suffix.lower() != Path(target).suffix.lower():
|
|
268
|
+
raise SyncError("备份文件与目标文件类型必须一致")
|
|
269
|
+
return api.run_restore_backup(backup, target)
|
|
270
|
+
|
|
271
|
+
if operation == "template-batch":
|
|
272
|
+
templates = _path_list(request, "templates", (".docx", ".docm"))
|
|
273
|
+
items = _template_items(request, len(templates))
|
|
274
|
+
out_dir = _required_path(request, "outDir", ())
|
|
275
|
+
return api.run_template_batch(
|
|
276
|
+
templates,
|
|
277
|
+
items,
|
|
278
|
+
out_dir,
|
|
279
|
+
dry_run=dry_run,
|
|
280
|
+
contents=_contents(request, ("tables", "placeholders")),
|
|
281
|
+
keep_highlight=_flag(request, "keepHighlight", True),
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
if operation == "fill-placeholders":
|
|
285
|
+
template = _required_path(request, "docx", (".docx", ".docm"))
|
|
286
|
+
return api.fill_placeholder_sheets(template, _path_list(request, "paths", (".xlsx", ".xlsm")))
|
|
287
|
+
|
|
288
|
+
if operation == "blank-batch-delete":
|
|
289
|
+
return api.run_blank_batch(_blank_batch_items(request), dry_run=dry_run, force=force)
|
|
290
|
+
|
|
291
|
+
if operation == "batch-writeback":
|
|
292
|
+
return api.run_batch_writeback(
|
|
293
|
+
_path_list(request, "paths", (".docx", ".docm")),
|
|
294
|
+
dry_run=dry_run,
|
|
295
|
+
backup=_flag(request, "backup", True),
|
|
296
|
+
force=force,
|
|
297
|
+
contents=_contents(request, ("tables",)),
|
|
298
|
+
keep_highlight=_flag(request, "keepHighlight", True),
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
if docx is None:
|
|
302
|
+
raise SyncError("缺少 docx 路径")
|
|
303
|
+
backup = _flag(request, "backup", not _flag(request, "noBackup"))
|
|
304
|
+
if operation == "export":
|
|
305
|
+
return api.run_export(
|
|
306
|
+
docx, excel, dry_run=dry_run, force=force,
|
|
307
|
+
with_excel_links=_flag(request, "withExcelLinks", True),
|
|
308
|
+
totals_formula=_flag(request, "totalsFormula", True), backup=backup,
|
|
309
|
+
)
|
|
310
|
+
if operation == "writeback":
|
|
311
|
+
contents = request.get("contents") or {"tables": True, "marks": False, "placeholders": False}
|
|
312
|
+
return api.run_sync_content(
|
|
313
|
+
docx, excel,
|
|
314
|
+
tables=_flag(contents, "tables", True),
|
|
315
|
+
marks=_flag(contents, "marks"),
|
|
316
|
+
placeholders=_flag(contents, "placeholders"),
|
|
317
|
+
keep_highlight=_flag(contents, "keepHighlight", True),
|
|
318
|
+
dry_run=dry_run, force=force, backup=backup,
|
|
319
|
+
changelog=_flag(request, "changelog"),
|
|
320
|
+
delete_empty_rows=_flag(request, "deleteEmptyRows"),
|
|
321
|
+
)
|
|
322
|
+
if operation == "bookmark":
|
|
323
|
+
return api.run_bookmark(
|
|
324
|
+
docx, excel, dry_run=dry_run, force=force,
|
|
325
|
+
with_excel_links=_flag(request, "withExcelLinks", True),
|
|
326
|
+
)
|
|
327
|
+
if operation == "rejudge":
|
|
328
|
+
return api.run_rejudge(docx, excel, dry_run=dry_run, force=force, backup=backup)
|
|
329
|
+
if operation == "clear-bookmarks":
|
|
330
|
+
return api.run_clear_bookmarks(docx, dry_run=dry_run, force=force)
|
|
331
|
+
if operation == "marks":
|
|
332
|
+
return api.run_marks(docx, excel, dry_run=dry_run, force=force)
|
|
333
|
+
if operation == "marks-sync":
|
|
334
|
+
return api.run_marks_sync(
|
|
335
|
+
docx, excel, dry_run=dry_run, force=force,
|
|
336
|
+
keep_highlight=_flag(request, "keepHighlight"),
|
|
337
|
+
)
|
|
338
|
+
if operation == "placeholders":
|
|
339
|
+
return api.run_placeholder_export(docx, excel, dry_run=dry_run, force=force)
|
|
340
|
+
if operation == "placeholders-sync":
|
|
341
|
+
return api.run_placeholder_sync(docx, excel, dry_run=dry_run, force=force)
|
|
342
|
+
if operation == "blank-delete":
|
|
343
|
+
return api.run_blank_tables(
|
|
344
|
+
docx, dry_run=dry_run, force=force,
|
|
345
|
+
pick=_text(request, "pick", "候选编号"),
|
|
346
|
+
keep_caption=_flag(request, "keepCaption"),
|
|
347
|
+
keep_caption_for=request.get("keepCaptionFor"),
|
|
348
|
+
reversible=_flag(request, "reversible", True), excel=excel,
|
|
349
|
+
)
|
|
350
|
+
if operation == "restore-tables":
|
|
351
|
+
return api.run_restore_tables(
|
|
352
|
+
docx, excel, pick=_text(request, "pick", "恢复编号"),
|
|
353
|
+
dry_run=dry_run, force=force,
|
|
354
|
+
)
|
|
355
|
+
if operation == "diff-export":
|
|
356
|
+
records = api.scan_writeback_diff(docx, excel)
|
|
357
|
+
return api.export_diff_report(docx, excel, records)
|
|
358
|
+
if operation == "append-table":
|
|
359
|
+
return api.run_append_table_block(
|
|
360
|
+
docx, excel,
|
|
361
|
+
name=_text(request, "name", "表名"),
|
|
362
|
+
nrows=_integer(request, "nrows", "行数", 1, 200),
|
|
363
|
+
ncols=_integer(request, "ncols", "列数", 1, 30),
|
|
364
|
+
after=request.get("after") or None,
|
|
365
|
+
)
|
|
366
|
+
if operation == "sort-set":
|
|
367
|
+
return api.set_table_sort(
|
|
368
|
+
docx, excel,
|
|
369
|
+
code=_text(request, "code", "表块编号"),
|
|
370
|
+
column=_text(request, "column", "排序列"),
|
|
371
|
+
descending=_flag(request, "descending", True),
|
|
372
|
+
)
|
|
373
|
+
if operation == "sort-clear":
|
|
374
|
+
return api.clear_table_sort(docx, excel, code=_text(request, "code", "表块编号"))
|
|
375
|
+
raise SyncError(f"不支持的操作:{operation}")
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _run(request: dict, request_id: str) -> int:
|
|
379
|
+
operation = request.get("operation")
|
|
380
|
+
if operation == "version":
|
|
381
|
+
_emit(request_id, "result", code=0, version=__version__)
|
|
382
|
+
return 0
|
|
383
|
+
if operation not in QUERY_OPERATIONS | RUN_OPERATIONS:
|
|
384
|
+
_emit(request_id, "log", level="error", message=f"不支持的操作:{operation}")
|
|
385
|
+
_emit(request_id, "result", code=2, operation=str(operation or "unknown"), version=__version__)
|
|
386
|
+
return 2
|
|
387
|
+
|
|
388
|
+
stderr = io.StringIO()
|
|
389
|
+
|
|
390
|
+
def sink(message: str) -> None:
|
|
391
|
+
level = "warning" if message.startswith("警告:") else "info"
|
|
392
|
+
_emit(request_id, "log", level=level, message=message)
|
|
393
|
+
|
|
394
|
+
set_log_sink(sink)
|
|
395
|
+
reset_log_state()
|
|
396
|
+
try:
|
|
397
|
+
with contextlib.redirect_stderr(stderr):
|
|
398
|
+
data = _dispatch(request)
|
|
399
|
+
code = 0
|
|
400
|
+
except (SyncError, OSError, ValueError) as exc:
|
|
401
|
+
_emit(request_id, "log", level="error", message=str(exc))
|
|
402
|
+
data = None
|
|
403
|
+
code = 2
|
|
404
|
+
except Exception as exc:
|
|
405
|
+
_emit(request_id, "log", level="error", message=f"引擎异常:{type(exc).__name__}: {exc}")
|
|
406
|
+
data = None
|
|
407
|
+
code = 2
|
|
408
|
+
finally:
|
|
409
|
+
set_log_sink(None)
|
|
410
|
+
reset_log_state()
|
|
411
|
+
|
|
412
|
+
for line in stderr.getvalue().splitlines():
|
|
413
|
+
if line.strip():
|
|
414
|
+
_emit(request_id, "log", level="error", message=line.strip())
|
|
415
|
+
_emit(request_id, "result", code=int(code), operation=operation, version=__version__, data=_jsonable(data))
|
|
416
|
+
return int(code)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def main() -> int:
|
|
420
|
+
for raw_line in sys.stdin.buffer:
|
|
421
|
+
line = raw_line.decode("utf-8")
|
|
422
|
+
if not line.strip():
|
|
423
|
+
continue
|
|
424
|
+
try:
|
|
425
|
+
request = json.loads(line)
|
|
426
|
+
if not isinstance(request, dict):
|
|
427
|
+
raise ValueError("请求必须是 JSON 对象")
|
|
428
|
+
request_id = str(request.get("id") or "engine")
|
|
429
|
+
except (ValueError, TypeError) as exc:
|
|
430
|
+
_emit("engine", "log", level="error", message=f"请求格式错误:{exc}")
|
|
431
|
+
_emit("engine", "result", code=2, operation="unknown", version=__version__)
|
|
432
|
+
continue
|
|
433
|
+
_run(request, request_id)
|
|
434
|
+
return 0
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
if __name__ == "__main__":
|
|
438
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Word 表格 ⇄ Excel 双向同步工具(结构化包)。
|
|
2
|
+
|
|
3
|
+
模块职责:
|
|
4
|
+
config / errors / console —— 常量、异常、中文日志
|
|
5
|
+
fsops / valuefmt —— 文件操作、数值与公式处理
|
|
6
|
+
docx_* —— Word 侧:网格解析、书签、单元格写入、行列结构
|
|
7
|
+
excel_* —— Excel 侧:导出工作簿、解析表块与元数据
|
|
8
|
+
commands / cli —— 各子命令与命令行入口
|
|
9
|
+
|
|
10
|
+
对外入口:``from wesync import main`` 或 ``python -m wesync.cli <子命令> ...``
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
__version__ = "1.11.2"
|
|
16
|
+
|
|
17
|
+
from .cli import main
|
|
18
|
+
|
|
19
|
+
__all__ = ["main", "__version__"]
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""内容签名与书签对齐:把工作簿表块与 Word 表格按内容精确配对,并把书签整表锚定。
|
|
2
|
+
|
|
3
|
+
签名 = (列数, 行数, 首行文本, 首列文本),两侧文本都先做空白归一化。
|
|
4
|
+
只接受**完全一致**的签名,不做模糊猜测;签名相同的重复表按文档顺序 1:1 消歧。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections import defaultdict, deque
|
|
10
|
+
|
|
11
|
+
from .console import log
|
|
12
|
+
from .config import LEGACY_BOOKMARK_RE
|
|
13
|
+
from .docx_bookmarks import (
|
|
14
|
+
bookmark_names,
|
|
15
|
+
insert_table_bookmark,
|
|
16
|
+
new_cpah_name,
|
|
17
|
+
next_bookmark_id,
|
|
18
|
+
remove_bookmark,
|
|
19
|
+
table_index_map_by_bookmark,
|
|
20
|
+
)
|
|
21
|
+
from .docx_grid import build_cellmap, cell_text
|
|
22
|
+
from .valuefmt import display_cell
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _norm(text) -> str:
|
|
26
|
+
return " ".join(str(text if text is not None else "").split()).strip()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def table_signature(tbl) -> tuple:
|
|
30
|
+
"""Word 表格的内容签名。"""
|
|
31
|
+
trs, cellmap, ncols = build_cellmap(tbl)
|
|
32
|
+
first_row = tuple(
|
|
33
|
+
_norm(cell_text(cellmap[0][c].tc)) if cellmap[0][c] is not None and cellmap[0][c].owner else ""
|
|
34
|
+
for c in range(ncols)
|
|
35
|
+
)
|
|
36
|
+
first_col = tuple(
|
|
37
|
+
_norm(cell_text(row[0].tc)) if row[0] is not None and row[0].owner else "" for row in cellmap
|
|
38
|
+
)
|
|
39
|
+
return (ncols, len(trs), first_row, first_col)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def block_signature(block: dict, ws) -> tuple:
|
|
43
|
+
"""工作簿表块的内容签名(数值按 Excel 显示文本比较)。"""
|
|
44
|
+
rows = block["grid_rows"]
|
|
45
|
+
col0 = block.get("col0", 2)
|
|
46
|
+
first_row = tuple(
|
|
47
|
+
_norm(display_cell(ws.cell(rows[0], col0 + c)))
|
|
48
|
+
for c in range(block["ncols"])
|
|
49
|
+
) if rows else ()
|
|
50
|
+
first_col = tuple(_norm(display_cell(ws.cell(r, col0))) for r in rows)
|
|
51
|
+
return (block["ncols"], len(rows), first_row, first_col)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def align_blocks_to_tables(doc, ws, blocks: dict) -> tuple[dict[str, int], list[int], list[str]]:
|
|
55
|
+
"""按内容签名把表块与 Word 表格 1:1 配对。
|
|
56
|
+
|
|
57
|
+
返回 ``(块编号→表序号, 未匹配的表序号, 未匹配的块编号)``。
|
|
58
|
+
"""
|
|
59
|
+
if not blocks:
|
|
60
|
+
return {}, list(range(len(doc.tables))), []
|
|
61
|
+
groups: dict[tuple, deque] = defaultdict(deque)
|
|
62
|
+
for code, block in blocks.items():
|
|
63
|
+
groups[block_signature(block, ws)].append(code)
|
|
64
|
+
|
|
65
|
+
mapping: dict[str, int] = {}
|
|
66
|
+
unmatched_tables: list[int] = []
|
|
67
|
+
for index, tab in enumerate(doc.tables):
|
|
68
|
+
queue = groups.get(table_signature(tab._tbl))
|
|
69
|
+
if queue:
|
|
70
|
+
mapping[queue.popleft()] = index
|
|
71
|
+
else:
|
|
72
|
+
unmatched_tables.append(index)
|
|
73
|
+
used = set(mapping)
|
|
74
|
+
unmatched_codes = [code for code in blocks if code not in used]
|
|
75
|
+
return mapping, unmatched_tables, unmatched_codes
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def plan_table_bookmarks(
|
|
79
|
+
doc,
|
|
80
|
+
ws,
|
|
81
|
+
blocks: dict,
|
|
82
|
+
recorded: dict[str, str],
|
|
83
|
+
*,
|
|
84
|
+
name_unmatched: bool = False,
|
|
85
|
+
) -> dict:
|
|
86
|
+
"""规划每张表的书签名。
|
|
87
|
+
|
|
88
|
+
- 能按内容对上的块:沿用工作簿记录的书签名(没有记录则新建一个 Table_ 名);
|
|
89
|
+
- ``name_unmatched=True`` 时,给“没对上任何块”的表也新建书签(用于首次导出);
|
|
90
|
+
否则这些表保持原样,只作为“未对齐”报告出来。
|
|
91
|
+
"""
|
|
92
|
+
mapping, unmatched_tables, unmatched_codes = align_blocks_to_tables(doc, ws, blocks)
|
|
93
|
+
fresh = set(bookmark_names(doc.element.body))
|
|
94
|
+
assignments: list[tuple[int, str]] = []
|
|
95
|
+
used: set[str] = set()
|
|
96
|
+
for code, index in sorted(mapping.items(), key=lambda item: item[1]):
|
|
97
|
+
name = (recorded.get(code) or "").strip()
|
|
98
|
+
if name and name in used:
|
|
99
|
+
log(f"[书签] {code} 记录的书签名 {name} 与其它表重复,已改用新的书签名")
|
|
100
|
+
name = ""
|
|
101
|
+
if not name:
|
|
102
|
+
name = new_cpah_name(fresh)
|
|
103
|
+
used.add(name)
|
|
104
|
+
assignments.append((index, name))
|
|
105
|
+
if name_unmatched:
|
|
106
|
+
for index in unmatched_tables:
|
|
107
|
+
assignments.append((index, new_cpah_name(fresh)))
|
|
108
|
+
return {
|
|
109
|
+
"assignments": assignments,
|
|
110
|
+
"mapping": mapping,
|
|
111
|
+
"unmatched_tables": unmatched_tables,
|
|
112
|
+
"unmatched_codes": unmatched_codes,
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def apply_table_bookmarks(doc, assignments: list[tuple[int, str]], remove_names: set[str]) -> dict:
|
|
117
|
+
"""先删除 ``remove_names`` 里的旧书签,再把书签整表锚定到对应表格。"""
|
|
118
|
+
removed = 0
|
|
119
|
+
for name in sorted(remove_names):
|
|
120
|
+
if remove_bookmark(doc, name):
|
|
121
|
+
removed += 1
|
|
122
|
+
bookmark_id = next_bookmark_id(doc)
|
|
123
|
+
inserted = 0
|
|
124
|
+
for index, name in assignments:
|
|
125
|
+
if index < 0 or index >= len(doc.tables):
|
|
126
|
+
continue
|
|
127
|
+
if insert_table_bookmark(doc.tables[index]._tbl, name, bookmark_id):
|
|
128
|
+
bookmark_id += 1
|
|
129
|
+
inserted += 1
|
|
130
|
+
else:
|
|
131
|
+
log(f"[警告] 第 {index + 1} 张表无法插入书签 {name}(表格为空)")
|
|
132
|
+
return {"removed": removed, "inserted": inserted}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def split_bookmark_updates(
|
|
136
|
+
doc, assignments: list[tuple[int, str]], recorded: dict[str, str]
|
|
137
|
+
) -> tuple[list[tuple[int, str]], set[str]]:
|
|
138
|
+
"""区分“已正确锚定”与“需要重建”的书签。
|
|
139
|
+
|
|
140
|
+
返回 ``(需要重建的 (表序号, 名字), 需要移除的旧书签名)``:
|
|
141
|
+
已经锚定在目标表内部的书签不重建(保证重复运行幂等);
|
|
142
|
+
需要移除的是本工具自己的旧书签(工作簿记录的名字 + 早期 TBL_*)。
|
|
143
|
+
"""
|
|
144
|
+
target_names = [name for _, name in assignments]
|
|
145
|
+
in_table = table_index_map_by_bookmark(
|
|
146
|
+
doc, {name for name in recorded.values() if name} | set(target_names)
|
|
147
|
+
)
|
|
148
|
+
keep = {name for index, name in assignments if in_table.get(name) == index}
|
|
149
|
+
removals = {name for name in recorded.values() if name and name not in keep}
|
|
150
|
+
removals |= {
|
|
151
|
+
name for name in bookmark_names(doc.element.body) if LEGACY_BOOKMARK_RE.match(name)
|
|
152
|
+
}
|
|
153
|
+
updates = [(index, name) for index, name in assignments if name not in keep]
|
|
154
|
+
return updates, removals
|