audit-e2w 0.0.0-stage → 1.11.7
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 +152 -3
- package/cordis.patch.yml +3 -0
- package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
- package/dsh_plugins/audit-e2w/lib/index.js +122 -0
- package/dsh_plugins/audit-e2w/lib/skill.js +42 -0
- package/excel_word/README.md +388 -0
- package/excel_word/qoder_engine.py +437 -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/ai/__init__.py +52 -0
- package/excel_word/wesync/ai/actions.py +369 -0
- package/excel_word/wesync/ai/client.py +340 -0
- package/excel_word/wesync/ai/config.py +291 -0
- package/excel_word/wesync/ai/docs.py +177 -0
- package/excel_word/wesync/ai/prompts.py +288 -0
- package/excel_word/wesync/ai/tasks/__init__.py +26 -0
- package/excel_word/wesync/ai/tasks/actions_task.py +97 -0
- package/excel_word/wesync/ai/tasks/combined.py +123 -0
- package/excel_word/wesync/ai/tasks/diff_note.py +61 -0
- package/excel_word/wesync/ai/tasks/headings.py +119 -0
- package/excel_word/wesync/ai/tasks/help_task.py +69 -0
- package/excel_word/wesync/ai/tasks/roles.py +128 -0
- package/excel_word/wesync/align.py +155 -0
- package/excel_word/wesync/api.py +1292 -0
- package/excel_word/wesync/backup_history.py +100 -0
- package/excel_word/wesync/changelog.py +58 -0
- package/excel_word/wesync/cli.py +191 -0
- package/excel_word/wesync/commands/__init__.py +8 -0
- package/excel_word/wesync/commands/blank_cmd.py +279 -0
- package/excel_word/wesync/commands/bookmark_cmd.py +146 -0
- package/excel_word/wesync/commands/clear_cmd.py +50 -0
- package/excel_word/wesync/commands/export_cmd.py +270 -0
- package/excel_word/wesync/commands/incremental_cmd.py +157 -0
- package/excel_word/wesync/commands/marks_cmd.py +160 -0
- package/excel_word/wesync/commands/placeholders_cmd.py +92 -0
- package/excel_word/wesync/commands/writeback_cmd.py +469 -0
- package/excel_word/wesync/config.py +97 -0
- package/excel_word/wesync/console.py +85 -0
- package/excel_word/wesync/docx_blank.py +156 -0
- package/excel_word/wesync/docx_bookmarks.py +294 -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 +399 -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 +200 -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 +502 -0
- package/excel_word/wesync/excel_export.py +143 -0
- package/excel_word/wesync/excel_marks.py +265 -0
- package/excel_word/wesync/excel_totals.py +53 -0
- package/excel_word/wesync/fsops.py +219 -0
- package/excel_word/wesync/gui/__init__.py +53 -0
- package/excel_word/wesync/gui/__main__.py +6 -0
- package/excel_word/wesync/gui/app.py +613 -0
- package/excel_word/wesync/gui/manual.py +70 -0
- package/excel_word/wesync/gui/pages/__init__.py +80 -0
- package/excel_word/wesync/gui/pages/_page.py +211 -0
- package/excel_word/wesync/gui/pages/ai_page.py +854 -0
- package/excel_word/wesync/gui/pages/batch_page.py +456 -0
- package/excel_word/wesync/gui/pages/blank_page.py +530 -0
- package/excel_word/wesync/gui/pages/bookmark_page.py +97 -0
- package/excel_word/wesync/gui/pages/export_page.py +141 -0
- package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
- package/excel_word/wesync/gui/pages/format_page.py +551 -0
- package/excel_word/wesync/gui/pages/help_page.py +158 -0
- package/excel_word/wesync/gui/pages/history_page.py +168 -0
- package/excel_word/wesync/gui/pages/marks_page.py +211 -0
- package/excel_word/wesync/gui/pages/settings_page.py +450 -0
- package/excel_word/wesync/gui/pages/writeback_page.py +473 -0
- package/excel_word/wesync/gui/resources.py +22 -0
- package/excel_word/wesync/gui/runner.py +90 -0
- package/excel_word/wesync/gui/store.py +50 -0
- package/excel_word/wesync/gui/theme.py +271 -0
- package/excel_word/wesync/gui/widgets/__init__.py +8 -0
- package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
- package/excel_word/wesync/gui/widgets/cards.py +139 -0
- package/excel_word/wesync/gui/widgets/chips.py +565 -0
- package/excel_word/wesync/gui/widgets/filebar.py +58 -0
- package/excel_word/wesync/gui/widgets/logpane.py +126 -0
- package/excel_word/wesync/gui/widgets/nav.py +294 -0
- package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
- package/excel_word/wesync/report_format.py +1585 -0
- package/excel_word/wesync/settings.py +35 -0
- package/excel_word/wesync/sort_rules.py +293 -0
- package/excel_word/wesync/valuefmt.py +485 -0
- package/package.json +53 -6
- package/packaging//344/275/277/347/224/250/350/257/264/346/230/216.txt +247 -0
- package/qoder_plugins/audit-toolbox/README.md +159 -0
- package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""AI 任务:一次请求同时产出标题级别、疑难角色与附注边界。
|
|
2
|
+
|
|
3
|
+
为什么合并:标题级别与疑难角色用的是同一份候选包(同一个 batch_id),
|
|
4
|
+
分成两次请求等于把同一批上下文发两遍。合并后往返次数减半、token 约省一半,
|
|
5
|
+
且两部分结果天然属于同一批次,不会出现"级别是新的、角色是旧的"错配。
|
|
6
|
+
|
|
7
|
+
安全边界与单独任务完全一致:输出仍逐项过白名单,越界一律丢弃。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from .. import prompts
|
|
13
|
+
from ..client import AiError, ChatClient, parse_json_block
|
|
14
|
+
from ..config import resolve_api_key
|
|
15
|
+
from .headings import MAX_CANDIDATES, _parse_levels, _trim as _trim_heading
|
|
16
|
+
from .roles import MAX_ITEMS, _parse as _parse_roles, _trim as _trim_role
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def suggest_combined(
|
|
20
|
+
package: dict,
|
|
21
|
+
*,
|
|
22
|
+
config: dict,
|
|
23
|
+
api_key: str = "",
|
|
24
|
+
transport=None,
|
|
25
|
+
client: ChatClient | None = None,
|
|
26
|
+
) -> dict:
|
|
27
|
+
"""一次请求同时返回 headingLevels、roleOverrides 与 regionStartId。
|
|
28
|
+
|
|
29
|
+
返回:
|
|
30
|
+
{"levels": {...}, "roles": {...}, "region_start_id": str,
|
|
31
|
+
"batch_id": str, "adopted": bool, "reason": str,
|
|
32
|
+
"elapsed_ms": int, "prompt_chars": int}
|
|
33
|
+
任何失败都返回 adopted=False 与空结果,由调用方沿用本地规则。
|
|
34
|
+
"""
|
|
35
|
+
batch_id = str(package.get("batch_id", "")) if isinstance(package, dict) else ""
|
|
36
|
+
candidates = package.get("candidates") if isinstance(package, dict) else None
|
|
37
|
+
role_candidates = package.get("role_candidates") if isinstance(package, dict) else None
|
|
38
|
+
boundary_candidates = package.get("boundary_candidates") if isinstance(package, dict) else None
|
|
39
|
+
result = {
|
|
40
|
+
"levels": {}, "roles": {}, "labels": {}, "region_start_id": "",
|
|
41
|
+
"batch_id": batch_id, "adopted": False, "reason": "",
|
|
42
|
+
"elapsed_ms": 0, "prompt_chars": 0,
|
|
43
|
+
}
|
|
44
|
+
if not batch_id:
|
|
45
|
+
result["reason"] = "候选批次编号缺失,请先重新扫描。"
|
|
46
|
+
return result
|
|
47
|
+
|
|
48
|
+
candidates = candidates if isinstance(candidates, list) else []
|
|
49
|
+
role_candidates = role_candidates if isinstance(role_candidates, list) else []
|
|
50
|
+
boundary_candidates = boundary_candidates if isinstance(boundary_candidates, list) else []
|
|
51
|
+
if not (candidates or role_candidates or boundary_candidates):
|
|
52
|
+
result["reason"] = "没有需要判断的候选段落。"
|
|
53
|
+
return result
|
|
54
|
+
|
|
55
|
+
# ID 到文字:界面显示用(标题取 text,段落取前 40 字摘要)
|
|
56
|
+
labels: dict[str, str] = {}
|
|
57
|
+
for item in list(candidates) + list(role_candidates) + list(boundary_candidates):
|
|
58
|
+
if not isinstance(item, dict) or not item.get("id"):
|
|
59
|
+
continue
|
|
60
|
+
text = str(item.get("text", "")).strip()
|
|
61
|
+
if text:
|
|
62
|
+
labels[str(item["id"])] = text
|
|
63
|
+
result["labels"] = labels
|
|
64
|
+
|
|
65
|
+
limit = int(config.get("max_context_chars", 200) or 200)
|
|
66
|
+
heading_allowed = {str(item.get("id", "")) for item in candidates[:MAX_CANDIDATES] if isinstance(item, dict)}
|
|
67
|
+
role_allowed = {
|
|
68
|
+
str(item.get("id", "")) for item in role_candidates[:MAX_ITEMS]
|
|
69
|
+
if isinstance(item, dict) and "table_title" in (item.get("options") or [])
|
|
70
|
+
}
|
|
71
|
+
boundary_allowed = {
|
|
72
|
+
str(item.get("id", "")) for item in boundary_candidates[:MAX_ITEMS] if isinstance(item, dict)
|
|
73
|
+
}
|
|
74
|
+
truncated = len(candidates) > MAX_CANDIDATES
|
|
75
|
+
|
|
76
|
+
messages = [
|
|
77
|
+
{"role": "system", "content": prompts.COMBINED_SYSTEM},
|
|
78
|
+
{
|
|
79
|
+
"role": "user",
|
|
80
|
+
"content": prompts.combined_user_prompt(
|
|
81
|
+
[_trim_heading(item, limit) for item in candidates[:MAX_CANDIDATES] if isinstance(item, dict)],
|
|
82
|
+
[_trim_role(item, limit) for item in role_candidates[:MAX_ITEMS] if isinstance(item, dict)],
|
|
83
|
+
[_trim_role(item, limit) for item in boundary_candidates[:MAX_ITEMS] if isinstance(item, dict)],
|
|
84
|
+
truncated=truncated,
|
|
85
|
+
),
|
|
86
|
+
},
|
|
87
|
+
]
|
|
88
|
+
try:
|
|
89
|
+
if client is None:
|
|
90
|
+
client = ChatClient(
|
|
91
|
+
base_url=str(config.get("base_url", "")),
|
|
92
|
+
model=str(config.get("model", "")),
|
|
93
|
+
api_key=api_key or resolve_api_key(config),
|
|
94
|
+
timeout=int(config.get("timeout_seconds", 60)),
|
|
95
|
+
temperature=float(config.get("temperature", 0.0)),
|
|
96
|
+
transport=transport,
|
|
97
|
+
# 判级是结构化任务,关掉思考:快 10 倍、省 token、结论更稳定
|
|
98
|
+
thinking=False,
|
|
99
|
+
json_mode=True,
|
|
100
|
+
)
|
|
101
|
+
# 合并请求输出更长,给足 max_tokens
|
|
102
|
+
reply = client.chat(messages, max_tokens=4096)
|
|
103
|
+
payload = parse_json_block(reply.text)
|
|
104
|
+
levels = _parse_levels(payload, heading_allowed)
|
|
105
|
+
roles, boundary = _parse_roles(payload, role_allowed, boundary_allowed)
|
|
106
|
+
except AiError as exc:
|
|
107
|
+
result["reason"] = str(exc)
|
|
108
|
+
return result
|
|
109
|
+
except Exception as exc:
|
|
110
|
+
result["reason"] = f"{type(exc).__name__}: {exc}"
|
|
111
|
+
return result
|
|
112
|
+
|
|
113
|
+
result.update({
|
|
114
|
+
"levels": levels,
|
|
115
|
+
"roles": roles,
|
|
116
|
+
"region_start_id": boundary,
|
|
117
|
+
"adopted": bool(levels or roles or boundary),
|
|
118
|
+
"elapsed_ms": reply.elapsed_ms,
|
|
119
|
+
"prompt_chars": reply.prompt_chars,
|
|
120
|
+
})
|
|
121
|
+
if not result["adopted"]:
|
|
122
|
+
result["reason"] = "模型没有给出可采用的判断,已沿用本地规则。"
|
|
123
|
+
return result
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""AI 任务:把逐格差异清单写成中文复核说明(纯文本,零写盘风险)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .. import prompts
|
|
6
|
+
from ..client import AiError, ChatClient
|
|
7
|
+
from ..config import resolve_api_key
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
MAX_RECORDS = 60
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def suggest_diff_note(
|
|
14
|
+
records: list[dict],
|
|
15
|
+
*,
|
|
16
|
+
config: dict,
|
|
17
|
+
api_key: str = "",
|
|
18
|
+
transport=None,
|
|
19
|
+
client: ChatClient | None = None,
|
|
20
|
+
) -> dict:
|
|
21
|
+
"""根据 scan_writeback_diff 的记录生成复核说明。
|
|
22
|
+
|
|
23
|
+
返回:{"note": str, "adopted": bool, "reason": str, "count": int}
|
|
24
|
+
纯文本输出,不参与任何写盘路径。
|
|
25
|
+
"""
|
|
26
|
+
result = {"note": "", "adopted": False, "reason": "", "count": 0}
|
|
27
|
+
if not isinstance(records, list) or not records:
|
|
28
|
+
result["reason"] = "没有差异记录可供复核。"
|
|
29
|
+
return result
|
|
30
|
+
result["count"] = len(records)
|
|
31
|
+
messages = [
|
|
32
|
+
{"role": "system", "content": prompts.DIFF_SYSTEM},
|
|
33
|
+
{"role": "user", "content": prompts.diff_user_prompt(records, limit=MAX_RECORDS)},
|
|
34
|
+
]
|
|
35
|
+
try:
|
|
36
|
+
if client is None:
|
|
37
|
+
client = ChatClient(
|
|
38
|
+
base_url=str(config.get("base_url", "")),
|
|
39
|
+
model=str(config.get("model", "")),
|
|
40
|
+
api_key=api_key or resolve_api_key(config),
|
|
41
|
+
timeout=int(config.get("timeout_seconds", 60)),
|
|
42
|
+
temperature=float(config.get("temperature", 0.0)),
|
|
43
|
+
transport=transport,
|
|
44
|
+
# 复核说明是自由文本,不需要 JSON 模式;但同样关掉思考以提速
|
|
45
|
+
thinking=False,
|
|
46
|
+
)
|
|
47
|
+
reply = client.chat(messages, max_tokens=1024)
|
|
48
|
+
except AiError as exc:
|
|
49
|
+
result["reason"] = str(exc)
|
|
50
|
+
return result
|
|
51
|
+
except Exception as exc:
|
|
52
|
+
result["reason"] = f"{type(exc).__name__}: {exc}"
|
|
53
|
+
return result
|
|
54
|
+
|
|
55
|
+
note = (reply.text or "").strip()
|
|
56
|
+
if not note:
|
|
57
|
+
result["reason"] = "模型没有返回复核说明,已沿用本地规则。"
|
|
58
|
+
return result
|
|
59
|
+
result["note"] = note
|
|
60
|
+
result["adopted"] = True
|
|
61
|
+
return result
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""AI 任务:把本地筛出的候选标题交给模型判级,再经本地白名单校验。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .. import prompts
|
|
6
|
+
from ..client import AiError, ChatClient, parse_json_block
|
|
7
|
+
from ..config import resolve_api_key
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
MAX_CANDIDATES = 300
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def trim_candidate(item: dict, limit: int) -> dict:
|
|
14
|
+
"""按配置裁剪上下文长度,保证发送量可控。"""
|
|
15
|
+
return {
|
|
16
|
+
"id": str(item.get("id", "")),
|
|
17
|
+
"text": str(item.get("text", ""))[:limit],
|
|
18
|
+
"before": str(item.get("before", ""))[:limit],
|
|
19
|
+
"after": str(item.get("after", ""))[:limit],
|
|
20
|
+
"style": item.get("style", ""),
|
|
21
|
+
"bold": item.get("bold"),
|
|
22
|
+
"size": item.get("size"),
|
|
23
|
+
"align": item.get("align", ""),
|
|
24
|
+
"numbered": item.get("numbered"),
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def parse_levels(payload: dict, allowed: set[str]) -> dict[str, int]:
|
|
29
|
+
"""只接受白名单里的编号与 1~4 的整数级别;其余静默丢弃。"""
|
|
30
|
+
items = payload.get("items")
|
|
31
|
+
if not isinstance(items, list):
|
|
32
|
+
return {}
|
|
33
|
+
result: dict[str, int] = {}
|
|
34
|
+
for entry in items:
|
|
35
|
+
if not isinstance(entry, dict):
|
|
36
|
+
continue
|
|
37
|
+
key = entry.get("id")
|
|
38
|
+
level = entry.get("level")
|
|
39
|
+
if not isinstance(key, str) or key not in allowed:
|
|
40
|
+
continue
|
|
41
|
+
if type(level) is not int or not 1 <= level <= 4:
|
|
42
|
+
continue
|
|
43
|
+
result[key] = level
|
|
44
|
+
return result
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# 兼容旧内部名
|
|
48
|
+
_trim = trim_candidate
|
|
49
|
+
_parse_levels = parse_levels
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def suggest_heading_levels(
|
|
53
|
+
package: dict,
|
|
54
|
+
*,
|
|
55
|
+
config: dict,
|
|
56
|
+
api_key: str = "",
|
|
57
|
+
transport=None,
|
|
58
|
+
client: ChatClient | None = None,
|
|
59
|
+
) -> dict:
|
|
60
|
+
"""根据 format-heading-candidates 的结果,返回可交给 format-apply 的级别映射。
|
|
61
|
+
|
|
62
|
+
返回:{"levels": {id: 1~4}, "labels": {id: 标题文字}, "batch_id": str,
|
|
63
|
+
"adopted": bool, "reason": str}
|
|
64
|
+
labels 只用于界面展示(让用户看得懂是哪段标题),不参与写盘。
|
|
65
|
+
任何失败都返回 adopted=False 与空 levels,由调用方沿用本地规则。
|
|
66
|
+
"""
|
|
67
|
+
batch_id = str(package.get("batch_id", "")) if isinstance(package, dict) else ""
|
|
68
|
+
candidates = package.get("candidates") if isinstance(package, dict) else None
|
|
69
|
+
result = {"levels": {}, "labels": {}, "batch_id": batch_id, "adopted": False, "reason": ""}
|
|
70
|
+
if not batch_id:
|
|
71
|
+
result["reason"] = "候选批次编号缺失,请先重新扫描。"
|
|
72
|
+
return result
|
|
73
|
+
if not isinstance(candidates, list) or not candidates:
|
|
74
|
+
result["reason"] = "没有可判级的候选标题。"
|
|
75
|
+
return result
|
|
76
|
+
if len(candidates) > MAX_CANDIDATES:
|
|
77
|
+
candidates = candidates[:MAX_CANDIDATES]
|
|
78
|
+
|
|
79
|
+
# ID 到标题文字的映射:界面显示用,避免只看到 b0046-053f76da56 这种编号
|
|
80
|
+
labels = {
|
|
81
|
+
str(item.get("id", "")): str(item.get("text", "")).strip()
|
|
82
|
+
for item in candidates
|
|
83
|
+
if isinstance(item, dict) and item.get("id")
|
|
84
|
+
}
|
|
85
|
+
result["labels"] = labels
|
|
86
|
+
|
|
87
|
+
limit = int(config.get("max_context_chars", 200) or 200)
|
|
88
|
+
allowed = {str(item.get("id", "")) for item in candidates if isinstance(item, dict)}
|
|
89
|
+
trimmed = [_trim(item, limit) for item in candidates if isinstance(item, dict)]
|
|
90
|
+
messages = [
|
|
91
|
+
{"role": "system", "content": prompts.HEADING_SYSTEM},
|
|
92
|
+
{"role": "user", "content": prompts.heading_user_prompt(trimmed, truncated=len(candidates) >= MAX_CANDIDATES)},
|
|
93
|
+
]
|
|
94
|
+
try:
|
|
95
|
+
if client is None:
|
|
96
|
+
client = ChatClient(
|
|
97
|
+
base_url=str(config.get("base_url", "")),
|
|
98
|
+
model=str(config.get("model", "")),
|
|
99
|
+
api_key=api_key or resolve_api_key(config),
|
|
100
|
+
timeout=int(config.get("timeout_seconds", 60)),
|
|
101
|
+
temperature=float(config.get("temperature", 0.0)),
|
|
102
|
+
transport=transport,
|
|
103
|
+
thinking=False,
|
|
104
|
+
json_mode=True,
|
|
105
|
+
)
|
|
106
|
+
reply = client.chat(messages, max_tokens=2048)
|
|
107
|
+
levels = _parse_levels(parse_json_block(reply.text), allowed)
|
|
108
|
+
except AiError as exc:
|
|
109
|
+
result["reason"] = str(exc)
|
|
110
|
+
return result
|
|
111
|
+
except Exception as exc: # 任何未预期异常都降级,不阻塞主流程
|
|
112
|
+
result["reason"] = f"{type(exc).__name__}: {exc}"
|
|
113
|
+
return result
|
|
114
|
+
|
|
115
|
+
result["levels"] = levels
|
|
116
|
+
result["adopted"] = bool(levels)
|
|
117
|
+
if not levels:
|
|
118
|
+
result["reason"] = "模型没有给出可采用的级别,已沿用本地规则。"
|
|
119
|
+
return result
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""AI 任务:内置使用说明问答(只读说明书片段,不碰用户报告)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .. import docs, prompts
|
|
6
|
+
from ..client import AiError, ChatClient
|
|
7
|
+
from ..config import resolve_api_key
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def ask_help(
|
|
11
|
+
question: str,
|
|
12
|
+
*,
|
|
13
|
+
config: dict,
|
|
14
|
+
api_key: str = "",
|
|
15
|
+
transport=None,
|
|
16
|
+
client: ChatClient | None = None,
|
|
17
|
+
) -> dict:
|
|
18
|
+
"""依据内置说明书回答"怎么用"的问题。
|
|
19
|
+
|
|
20
|
+
返回:{"answer": str, "snippets": [...], "adopted": bool, "reason": str}
|
|
21
|
+
只发送本地检索命中的说明书片段;没有任何命中时不发请求。
|
|
22
|
+
"""
|
|
23
|
+
text = str(question or "").strip()
|
|
24
|
+
result = {"answer": "", "snippets": [], "adopted": False, "reason": ""}
|
|
25
|
+
if not text:
|
|
26
|
+
result["reason"] = "请先输入问题。"
|
|
27
|
+
return result
|
|
28
|
+
if len(text) > 300:
|
|
29
|
+
result["reason"] = "问题过长(上限 300 字),请简短些。"
|
|
30
|
+
return result
|
|
31
|
+
|
|
32
|
+
snippets = docs.build_snippets(text)
|
|
33
|
+
result["snippets"] = snippets
|
|
34
|
+
if not snippets:
|
|
35
|
+
result["reason"] = (
|
|
36
|
+
"说明书里没找到相关内容。可以换些关键词,或直接看「使用说明」页的章节。"
|
|
37
|
+
)
|
|
38
|
+
return result
|
|
39
|
+
|
|
40
|
+
messages = [
|
|
41
|
+
{"role": "system", "content": prompts.HELP_SYSTEM},
|
|
42
|
+
{"role": "user", "content": prompts.help_user_prompt(text, snippets)},
|
|
43
|
+
]
|
|
44
|
+
try:
|
|
45
|
+
if client is None:
|
|
46
|
+
client = ChatClient(
|
|
47
|
+
base_url=str(config.get("base_url", "")),
|
|
48
|
+
model=str(config.get("model", "")),
|
|
49
|
+
api_key=api_key or resolve_api_key(config),
|
|
50
|
+
timeout=int(config.get("timeout_seconds", 60)),
|
|
51
|
+
temperature=float(config.get("temperature", 0.0)),
|
|
52
|
+
transport=transport,
|
|
53
|
+
thinking=False,
|
|
54
|
+
)
|
|
55
|
+
reply = client.chat(messages, max_tokens=1024)
|
|
56
|
+
except AiError as exc:
|
|
57
|
+
result["reason"] = str(exc)
|
|
58
|
+
return result
|
|
59
|
+
except Exception as exc:
|
|
60
|
+
result["reason"] = f"{type(exc).__name__}: {exc}"
|
|
61
|
+
return result
|
|
62
|
+
|
|
63
|
+
answer = (reply.text or "").strip()
|
|
64
|
+
if not answer:
|
|
65
|
+
result["reason"] = "模型没有返回答案。"
|
|
66
|
+
return result
|
|
67
|
+
result["answer"] = answer
|
|
68
|
+
result["adopted"] = True
|
|
69
|
+
return result
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""AI 任务:疑难段落角色(正文 / 表格标题)与附注起始边界判定。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .. import prompts
|
|
6
|
+
from ..client import AiError, ChatClient, parse_json_block
|
|
7
|
+
from ..config import resolve_api_key
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
MAX_ITEMS = 300
|
|
11
|
+
ALLOWED_ROLES = ("body", "table_title")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def trim_candidate(item: dict, limit: int) -> dict:
|
|
15
|
+
"""按配置裁剪上下文长度。"""
|
|
16
|
+
return {
|
|
17
|
+
"id": str(item.get("id", "")),
|
|
18
|
+
"text": str(item.get("text", ""))[:limit],
|
|
19
|
+
"before": str(item.get("before", ""))[:limit],
|
|
20
|
+
"after": str(item.get("after", ""))[:limit],
|
|
21
|
+
"current_role": item.get("current_role", ""),
|
|
22
|
+
"options": list(item.get("options") or []),
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def parse_roles(payload: dict, role_allowed: set[str], boundary_allowed: set[str]) -> tuple[dict, str]:
|
|
27
|
+
"""只接受白名单编号与候选自带的合法取值。"""
|
|
28
|
+
roles: dict[str, str] = {}
|
|
29
|
+
entries = payload.get("roles")
|
|
30
|
+
if isinstance(entries, list):
|
|
31
|
+
for entry in entries:
|
|
32
|
+
if not isinstance(entry, dict):
|
|
33
|
+
continue
|
|
34
|
+
key = entry.get("id")
|
|
35
|
+
role = entry.get("role")
|
|
36
|
+
if isinstance(key, str) and key in role_allowed and role in ALLOWED_ROLES:
|
|
37
|
+
roles[key] = role
|
|
38
|
+
boundary = payload.get("region_start_id")
|
|
39
|
+
if not isinstance(boundary, str) or boundary not in boundary_allowed:
|
|
40
|
+
boundary = ""
|
|
41
|
+
return roles, boundary
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# 兼容旧内部名
|
|
45
|
+
_trim = trim_candidate
|
|
46
|
+
_parse = parse_roles
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def suggest_role_overrides(
|
|
50
|
+
package: dict,
|
|
51
|
+
*,
|
|
52
|
+
config: dict,
|
|
53
|
+
api_key: str = "",
|
|
54
|
+
transport=None,
|
|
55
|
+
client: ChatClient | None = None,
|
|
56
|
+
) -> dict:
|
|
57
|
+
"""根据 format-heading-candidates 的结果,返回 role_overrides 与 region_start_id。
|
|
58
|
+
|
|
59
|
+
返回:{"roles": {...}, "region_start_id": str, "batch_id": str, "adopted": bool, "reason": str}
|
|
60
|
+
"""
|
|
61
|
+
batch_id = str(package.get("batch_id", "")) if isinstance(package, dict) else ""
|
|
62
|
+
role_candidates = package.get("role_candidates") if isinstance(package, dict) else None
|
|
63
|
+
boundary_candidates = package.get("boundary_candidates") if isinstance(package, dict) else None
|
|
64
|
+
result = {
|
|
65
|
+
"roles": {}, "labels": {}, "region_start_id": "",
|
|
66
|
+
"batch_id": batch_id, "adopted": False, "reason": "",
|
|
67
|
+
}
|
|
68
|
+
if not batch_id:
|
|
69
|
+
result["reason"] = "候选批次编号缺失,请先重新扫描。"
|
|
70
|
+
return result
|
|
71
|
+
role_candidates = role_candidates if isinstance(role_candidates, list) else []
|
|
72
|
+
boundary_candidates = boundary_candidates if isinstance(boundary_candidates, list) else []
|
|
73
|
+
if not role_candidates and not boundary_candidates:
|
|
74
|
+
result["reason"] = "没有需要判断的疑难段落或附注边界。"
|
|
75
|
+
return result
|
|
76
|
+
|
|
77
|
+
# ID 到文字:界面显示用,避免只看到编号
|
|
78
|
+
result["labels"] = {
|
|
79
|
+
str(item.get("id", "")): str(item.get("text", "")).strip()
|
|
80
|
+
for item in list(role_candidates) + list(boundary_candidates)
|
|
81
|
+
if isinstance(item, dict) and item.get("id") and item.get("text")
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
limit = int(config.get("max_context_chars", 200) or 200)
|
|
85
|
+
role_allowed = {
|
|
86
|
+
str(item.get("id", "")) for item in role_candidates[:MAX_ITEMS]
|
|
87
|
+
if isinstance(item, dict) and "table_title" in (item.get("options") or [])
|
|
88
|
+
}
|
|
89
|
+
boundary_allowed = {
|
|
90
|
+
str(item.get("id", "")) for item in boundary_candidates[:MAX_ITEMS] if isinstance(item, dict)
|
|
91
|
+
}
|
|
92
|
+
messages = [
|
|
93
|
+
{"role": "system", "content": prompts.ROLE_SYSTEM},
|
|
94
|
+
{
|
|
95
|
+
"role": "user",
|
|
96
|
+
"content": prompts.role_user_prompt(
|
|
97
|
+
[_trim(item, limit) for item in role_candidates[:MAX_ITEMS] if isinstance(item, dict)],
|
|
98
|
+
[_trim(item, limit) for item in boundary_candidates[:MAX_ITEMS] if isinstance(item, dict)],
|
|
99
|
+
),
|
|
100
|
+
},
|
|
101
|
+
]
|
|
102
|
+
try:
|
|
103
|
+
if client is None:
|
|
104
|
+
client = ChatClient(
|
|
105
|
+
base_url=str(config.get("base_url", "")),
|
|
106
|
+
model=str(config.get("model", "")),
|
|
107
|
+
api_key=api_key or resolve_api_key(config),
|
|
108
|
+
timeout=int(config.get("timeout_seconds", 60)),
|
|
109
|
+
temperature=float(config.get("temperature", 0.0)),
|
|
110
|
+
transport=transport,
|
|
111
|
+
thinking=False,
|
|
112
|
+
json_mode=True,
|
|
113
|
+
)
|
|
114
|
+
reply = client.chat(messages, max_tokens=2048)
|
|
115
|
+
roles, boundary = _parse(parse_json_block(reply.text), role_allowed, boundary_allowed)
|
|
116
|
+
except AiError as exc:
|
|
117
|
+
result["reason"] = str(exc)
|
|
118
|
+
return result
|
|
119
|
+
except Exception as exc:
|
|
120
|
+
result["reason"] = f"{type(exc).__name__}: {exc}"
|
|
121
|
+
return result
|
|
122
|
+
|
|
123
|
+
result["roles"] = roles
|
|
124
|
+
result["region_start_id"] = boundary
|
|
125
|
+
result["adopted"] = bool(roles or boundary)
|
|
126
|
+
if not result["adopted"]:
|
|
127
|
+
result["reason"] = "模型没有给出可采用的判断,已沿用本地规则。"
|
|
128
|
+
return result
|
|
@@ -0,0 +1,155 @@
|
|
|
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
|
+
ws = block.get("_ws") or ws
|
|
45
|
+
rows = block["grid_rows"]
|
|
46
|
+
col0 = block.get("col0", 2)
|
|
47
|
+
first_row = tuple(
|
|
48
|
+
_norm(display_cell(ws.cell(rows[0], col0 + c)))
|
|
49
|
+
for c in range(block["ncols"])
|
|
50
|
+
) if rows else ()
|
|
51
|
+
first_col = tuple(_norm(display_cell(ws.cell(r, col0))) for r in rows)
|
|
52
|
+
return (block["ncols"], len(rows), first_row, first_col)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def align_blocks_to_tables(doc, ws, blocks: dict) -> tuple[dict[str, int], list[int], list[str]]:
|
|
56
|
+
"""按内容签名把表块与 Word 表格 1:1 配对。
|
|
57
|
+
|
|
58
|
+
返回 ``(块编号→表序号, 未匹配的表序号, 未匹配的块编号)``。
|
|
59
|
+
"""
|
|
60
|
+
if not blocks:
|
|
61
|
+
return {}, list(range(len(doc.tables))), []
|
|
62
|
+
groups: dict[tuple, deque] = defaultdict(deque)
|
|
63
|
+
for code, block in blocks.items():
|
|
64
|
+
groups[block_signature(block, ws)].append(code)
|
|
65
|
+
|
|
66
|
+
mapping: dict[str, int] = {}
|
|
67
|
+
unmatched_tables: list[int] = []
|
|
68
|
+
for index, tab in enumerate(doc.tables):
|
|
69
|
+
queue = groups.get(table_signature(tab._tbl))
|
|
70
|
+
if queue:
|
|
71
|
+
mapping[queue.popleft()] = index
|
|
72
|
+
else:
|
|
73
|
+
unmatched_tables.append(index)
|
|
74
|
+
used = set(mapping)
|
|
75
|
+
unmatched_codes = [code for code in blocks if code not in used]
|
|
76
|
+
return mapping, unmatched_tables, unmatched_codes
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def plan_table_bookmarks(
|
|
80
|
+
doc,
|
|
81
|
+
ws,
|
|
82
|
+
blocks: dict,
|
|
83
|
+
recorded: dict[str, str],
|
|
84
|
+
*,
|
|
85
|
+
name_unmatched: bool = False,
|
|
86
|
+
) -> dict:
|
|
87
|
+
"""规划每张表的书签名。
|
|
88
|
+
|
|
89
|
+
- 能按内容对上的块:沿用工作簿记录的书签名(没有记录则新建一个 Table_ 名);
|
|
90
|
+
- ``name_unmatched=True`` 时,给“没对上任何块”的表也新建书签(用于首次导出);
|
|
91
|
+
否则这些表保持原样,只作为“未对齐”报告出来。
|
|
92
|
+
"""
|
|
93
|
+
mapping, unmatched_tables, unmatched_codes = align_blocks_to_tables(doc, ws, blocks)
|
|
94
|
+
fresh = set(bookmark_names(doc.element.body))
|
|
95
|
+
assignments: list[tuple[int, str]] = []
|
|
96
|
+
used: set[str] = set()
|
|
97
|
+
for code, index in sorted(mapping.items(), key=lambda item: item[1]):
|
|
98
|
+
name = (recorded.get(code) or "").strip()
|
|
99
|
+
if name and name in used:
|
|
100
|
+
log(f"[书签] {code} 记录的书签名 {name} 与其它表重复,已改用新的书签名")
|
|
101
|
+
name = ""
|
|
102
|
+
if not name:
|
|
103
|
+
name = new_cpah_name(fresh)
|
|
104
|
+
used.add(name)
|
|
105
|
+
assignments.append((index, name))
|
|
106
|
+
if name_unmatched:
|
|
107
|
+
for index in unmatched_tables:
|
|
108
|
+
assignments.append((index, new_cpah_name(fresh)))
|
|
109
|
+
return {
|
|
110
|
+
"assignments": assignments,
|
|
111
|
+
"mapping": mapping,
|
|
112
|
+
"unmatched_tables": unmatched_tables,
|
|
113
|
+
"unmatched_codes": unmatched_codes,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def apply_table_bookmarks(doc, assignments: list[tuple[int, str]], remove_names: set[str]) -> dict:
|
|
118
|
+
"""先删除 ``remove_names`` 里的旧书签,再把书签整表锚定到对应表格。"""
|
|
119
|
+
removed = 0
|
|
120
|
+
for name in sorted(remove_names):
|
|
121
|
+
if remove_bookmark(doc, name):
|
|
122
|
+
removed += 1
|
|
123
|
+
bookmark_id = next_bookmark_id(doc)
|
|
124
|
+
inserted = 0
|
|
125
|
+
for index, name in assignments:
|
|
126
|
+
if index < 0 or index >= len(doc.tables):
|
|
127
|
+
continue
|
|
128
|
+
if insert_table_bookmark(doc.tables[index]._tbl, name, bookmark_id):
|
|
129
|
+
bookmark_id += 1
|
|
130
|
+
inserted += 1
|
|
131
|
+
else:
|
|
132
|
+
log(f"[警告] 第 {index + 1} 张表无法插入书签 {name}(表格为空)")
|
|
133
|
+
return {"removed": removed, "inserted": inserted}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def split_bookmark_updates(
|
|
137
|
+
doc, assignments: list[tuple[int, str]], recorded: dict[str, str]
|
|
138
|
+
) -> tuple[list[tuple[int, str]], set[str]]:
|
|
139
|
+
"""区分“已正确锚定”与“需要重建”的书签。
|
|
140
|
+
|
|
141
|
+
返回 ``(需要重建的 (表序号, 名字), 需要移除的旧书签名)``:
|
|
142
|
+
已经锚定在目标表内部的书签不重建(保证重复运行幂等);
|
|
143
|
+
需要移除的是本工具自己的旧书签(工作簿记录的名字 + 早期 TBL_*)。
|
|
144
|
+
"""
|
|
145
|
+
target_names = [name for _, name in assignments]
|
|
146
|
+
in_table = table_index_map_by_bookmark(
|
|
147
|
+
doc, {name for name in recorded.values() if name} | set(target_names)
|
|
148
|
+
)
|
|
149
|
+
keep = {name for index, name in assignments if in_table.get(name) == index}
|
|
150
|
+
removals = {name for name in recorded.values() if name and name not in keep}
|
|
151
|
+
removals |= {
|
|
152
|
+
name for name in bookmark_names(doc.element.body) if LEGACY_BOOKMARK_RE.match(name)
|
|
153
|
+
}
|
|
154
|
+
updates = [(index, name) for index, name in assignments if name not in keep]
|
|
155
|
+
return updates, removals
|