mtkit 1.16.1__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.
@@ -0,0 +1,115 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ 技术方案 .docx 解析器(依赖 python-docx)。
4
+
5
+ 解析结果结构:
6
+ {
7
+ "root": 文档标题,
8
+ "sections": [
9
+ {"level": 标题级别, "title": 章节标题, "paragraphs": [段落文本], "tables": [[行单元格列表]]}
10
+ ],
11
+ "features": [功能点描述串] # 从段落/表格中提取的接口定义、权限点、按钮等
12
+ }
13
+
14
+ 功能点提取规则(针对"技术方案"类文档):
15
+ 1. 段落含 "url" / "method" / "权限点" 关键字 -> 整段为功能点
16
+ 2. 表格行含 "url" 字样 -> 该行(拼接头列)为功能点
17
+ """
18
+ import os
19
+ import re
20
+
21
+ # paragraph feature signature: url/permission definition lines (interface design chapter)
22
+ _FEATURE_PARAGRAPH_PATTERN = re.compile(r"(url|权限点)\s*[::]", re.IGNORECASE)
23
+ # table feature signature: cells containing url definitions
24
+ _URL_PATTERN = re.compile(r"url\s*[::]\s*\S+", re.IGNORECASE)
25
+
26
+
27
+ def _docx_modules():
28
+ """Lazy import python-docx (optional dependency): the CLI must run without it."""
29
+ try:
30
+ from docx import Document
31
+ from docx.table import Table
32
+ from docx.text.paragraph import Paragraph
33
+ except ImportError:
34
+ raise RuntimeError("解析 .docx 需要 python-docx,请先安装: pip install python-docx")
35
+ return Document, Paragraph, Table
36
+
37
+
38
+ def load_docx(path):
39
+ """解析技术方案 .docx 文档。
40
+
41
+ :param path: .docx 文件路径
42
+ :return: {"root", "sections", "features"} 结构
43
+ """
44
+ if not os.path.isfile(path):
45
+ raise ValueError("文档不存在: %s" % path)
46
+ Document, Paragraph, Table = _docx_modules()
47
+ doc = Document(path)
48
+
49
+ root = os.path.splitext(os.path.basename(path))[0]
50
+ sections = []
51
+ features = []
52
+ current = None
53
+
54
+ def ensure_section(title, level):
55
+ nonlocal current
56
+ for section in sections:
57
+ if section["title"] == title:
58
+ current = section
59
+ return
60
+ section = {"level": level, "title": title, "paragraphs": [], "tables": []}
61
+ sections.append(section)
62
+ current = section
63
+
64
+ def add_paragraph(text):
65
+ if not text:
66
+ return
67
+ if current is None:
68
+ ensure_section("文档概述", 1)
69
+ current["paragraphs"].append(text)
70
+ if _FEATURE_PARAGRAPH_PATTERN.search(text):
71
+ features.append(text)
72
+
73
+ def add_table(table):
74
+ rows = []
75
+ for row in table.rows:
76
+ cells = []
77
+ seen = set()
78
+ for cell in row.cells:
79
+ text = (cell.text or "").strip()
80
+ # merged cells repeat across rows: dedupe preserving order
81
+ if text and text not in seen:
82
+ seen.add(text)
83
+ cells.append(text)
84
+ else:
85
+ cells.append(text)
86
+ rows.append(cells)
87
+ if current is None:
88
+ ensure_section("文档概述", 1)
89
+ current["tables"].append(rows)
90
+ # table features: rows containing url definitions
91
+ for row in rows:
92
+ joined = " | ".join(row)
93
+ if _URL_PATTERN.search(joined):
94
+ features.append(joined)
95
+
96
+ # walk paragraphs and tables in document order (table belongs to the nearest heading paragraph)
97
+ for child in doc.element.body.iterchildren():
98
+ if child.tag.endswith("}p"):
99
+ paragraph = Paragraph(child, doc)
100
+ style = paragraph.style.name if paragraph.style is not None else ""
101
+ text = "".join(run.text or "" for run in paragraph.runs).strip()
102
+ if style.startswith("Heading"):
103
+ match = re.match(r"Heading\s+(\d+)", style)
104
+ level = int(match.group(1)) if match else 1
105
+ ensure_section(text, level)
106
+ # the first level-1 heading becomes the root title
107
+ if level == 1 and root == os.path.splitext(os.path.basename(path))[0]:
108
+ root = text
109
+ # headings are not features (chapter structure is already in sections)
110
+ else:
111
+ add_paragraph(text)
112
+ elif child.tag.endswith("}tbl"):
113
+ add_table(Table(child, doc))
114
+
115
+ return {"root": root, "sections": sections, "features": features}
@@ -0,0 +1,125 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Historical case .xmind parser: skeleton extraction and style sample extraction.
4
+
5
+ usage (case generation pipeline):
6
+ 1. skeleton_from_hist : historical case tree -> skeleton (chapter structure + case titles, description nodes replaced with placeholders)
7
+ 2. extract_style_sample: take the full structure text of the first N cases as few-shot style samples for LLM generation
8
+ """
9
+ import re
10
+
11
+ from ..builder import CASE_TITLE_PATTERN
12
+ from ..writer import read_tree
13
+
14
+
15
+ def load_xmind_tree(path):
16
+ """Read a historical case .xmind, return the case tree (reuses writer.read_tree).
17
+
18
+ :param path: .xmind file path
19
+ :return: [{t=..., c=[...]}, ...]
20
+ """
21
+ return read_tree(path)
22
+
23
+
24
+ def apply_replace_map(text, replace_map):
25
+ """Apply replacement rules to title text (e.g. {"员工报销": "客户报销"}).
26
+
27
+ :param text: original title
28
+ :param replace_map: {old word: new word}
29
+ :return: replaced title
30
+ """
31
+ if not replace_map:
32
+ return text
33
+ for old, new in replace_map.items():
34
+ text = text.replace(old, new)
35
+ return text
36
+
37
+
38
+ def skeleton_from_hist(tree, replace_map=None):
39
+ """Historical case tree -> case skeleton.
40
+
41
+ - chapter nodes and case titles kept (titles replaced by replace_map)
42
+ - case description nodes replaced with zen placeholder lines (pc:/步骤:/预期: 待补充)
43
+
44
+ :param tree: historical case tree
45
+ :param replace_map: title replacement rules {old word: new word}
46
+ :return: skeleton tree
47
+ """
48
+ out = []
49
+ for node in tree:
50
+ title = node.get("t") or ""
51
+ if CASE_TITLE_PATTERN.match(title):
52
+ out.append(
53
+ {
54
+ "t": apply_replace_map(title, replace_map),
55
+ "c": [
56
+ {"t": "pc: 待补充(参考历史用例)"},
57
+ {"t": "步骤: 待补充(参考历史用例)"},
58
+ {"t": "预期: 待补充(参考历史用例)"},
59
+ ],
60
+ }
61
+ )
62
+ else:
63
+ children = skeleton_from_hist(node.get("c") or [], replace_map)
64
+ item = {"t": apply_replace_map(title, replace_map)}
65
+ if children:
66
+ item["c"] = children
67
+ out.append(item)
68
+ return out
69
+
70
+
71
+ def _node_to_text(node, depth=0):
72
+ """Recursively render a node into indented text (for style samples)."""
73
+ lines = [" " * depth + (node.get("t") or "")]
74
+ for child in node.get("c") or []:
75
+ lines.extend(_node_to_text(child, depth + 1))
76
+ return lines
77
+
78
+
79
+ def extract_style_sample(tree, limit=3, max_chars=4000):
80
+ """Take the full structure text of the first `limit` cases as format samples for generation.
81
+
82
+ :param tree: historical case tree
83
+ :param limit: max number of cases to take
84
+ :param max_chars: max sample text length (truncated when exceeded)
85
+ :return: sample text
86
+ """
87
+ lines = []
88
+ count = 0
89
+
90
+ def walk(nodes):
91
+ nonlocal count
92
+ for node in nodes:
93
+ if CASE_TITLE_PATTERN.match(node.get("t") or ""):
94
+ if count >= limit:
95
+ continue
96
+ count += 1
97
+ lines.extend(_node_to_text(node))
98
+ lines.append("")
99
+ else:
100
+ walk(node.get("c") or [])
101
+
102
+ walk(tree)
103
+ text = "\n".join(lines)
104
+ if len(text) > max_chars:
105
+ text = text[:max_chars] + "\n...(样例过长已截断)"
106
+ return text
107
+
108
+
109
+ def parse_replace_map(spec):
110
+ """解析替换规则字符串 '旧词=新词,旧词2=新词2' 为 dict。
111
+
112
+ :param spec: 替换规则字符串
113
+ :return: {旧词: 新词}
114
+ """
115
+ replace_map = {}
116
+ if not spec:
117
+ return replace_map
118
+ for part in re.split(r"[,,]", spec):
119
+ if "=" in part:
120
+ old, new = part.split("=", 1)
121
+ old = old.strip()
122
+ new = new.strip()
123
+ if old and new:
124
+ replace_map[old] = new
125
+ return replace_map
@@ -0,0 +1,10 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ 生成层:用例内容生成。
4
+
5
+ - skeleton: 无 LLM 兜底生成(骨架 + 文档功能点清单)
6
+ - llm : LLM 驱动的用例生成(Provider 抽象/分片/重试)
7
+ """
8
+ from .skeleton import build_skeleton
9
+
10
+ __all__ = ["build_skeleton"]
mtkit/generate/llm.py ADDED
@@ -0,0 +1,360 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ LLM-driven case generation module.
4
+
5
+ Provider abstraction (pluggable):
6
+ - HttpLlmProvider: OpenAI compatible /v1/chat/completions endpoint (stdlib urllib, no third-party deps)
7
+ - CliLlmProvider : local coding agent CLI (command template + prompt argument)
8
+
9
+ generation flow:
10
+ 1. assemble prompt (system prompt + doc facts + historical sample + code facts + data contract)
11
+ 2. long docs are chunked by chapter/length, generated chunk by chunk
12
+ 3. parse the returned JSON contract; on structure validation failure auto-retry (feeding errors back to the model)
13
+ """
14
+ import json
15
+ import re
16
+ import subprocess
17
+ import urllib.error
18
+ import urllib.request
19
+
20
+ # max chars per chunk
21
+ DEFAULT_CHUNK_SIZE = 8000
22
+ # default retry count
23
+ DEFAULT_RETRY = 3
24
+
25
+ # LLM output data contract -> mtkit tree conversion (see contract_to_tree)
26
+
27
+
28
+ class LlmProvider:
29
+ """LLM provider abstract base class."""
30
+
31
+ def chat(self, messages, temperature=0.2):
32
+ """Send a chat request, return the model reply text.
33
+
34
+ :param messages: [{"role": "system|user", "content": text}]
35
+ :param temperature: sampling temperature
36
+ :return: model reply text
37
+ """
38
+ raise NotImplementedError
39
+
40
+
41
+ class HttpLlmProvider(LlmProvider):
42
+ """OpenAI compatible HTTP endpoint (chat/completions)."""
43
+
44
+ def __init__(self, endpoint, api_key="", model="", timeout=300):
45
+ """
46
+ :param endpoint: full endpoint, e.g. https://api.openai.com/v1/chat/completions
47
+ :param api_key: API key
48
+ :param model: model name (empty = follow the user/Qoder selected model, the tool does not decide)
49
+ :param timeout: request timeout (seconds)
50
+ """
51
+ self.endpoint = endpoint.rstrip("/")
52
+ self.api_key = api_key
53
+ self.model = model
54
+ self.timeout = timeout
55
+
56
+ def chat(self, messages, temperature=0.2):
57
+ body = {"messages": messages, "temperature": temperature}
58
+ if self.model:
59
+ # only send model when the user explicitly configured one;
60
+ # otherwise the service-side/Qoder-selected model applies
61
+ body["model"] = self.model
62
+ payload = json.dumps(body).encode("utf-8")
63
+ headers = {"Content-Type": "application/json"}
64
+ if self.api_key:
65
+ headers["Authorization"] = "Bearer " + self.api_key
66
+ request = urllib.request.Request(self.endpoint, data=payload, headers=headers, method="POST")
67
+ try:
68
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
69
+ data = json.loads(response.read().decode("utf-8"))
70
+ except urllib.error.HTTPError as exc:
71
+ detail = exc.read().decode("utf-8", errors="replace")
72
+ raise RuntimeError("LLM HTTP 请求失败(%s): %s" % (exc.code, detail[:500]))
73
+ choices = data.get("choices") or []
74
+ if not choices:
75
+ raise RuntimeError("LLM 响应缺少 choices: %s" % json.dumps(data, ensure_ascii=False)[:300])
76
+ return (choices[0].get("message") or {}).get("content") or ""
77
+
78
+
79
+ class CliLlmProvider(LlmProvider):
80
+ """Local coding agent CLI (subprocess, command template injects the prompt).
81
+
82
+ command template examples:
83
+ "qoder ask" -> run qoder ask <prompt>
84
+ "qoder -m model ask" -> run qoder -m model ask <prompt>
85
+ """
86
+
87
+ def __init__(self, cmd, timeout=900, env=None):
88
+ """
89
+ :param cmd: command template string (split by whitespace, prompt appended at the end)
90
+ :param timeout: subprocess timeout (seconds)
91
+ :param env: extra environment variables
92
+ """
93
+ if not cmd:
94
+ raise ValueError("CLI 命令模板不能为空(可用 --cli-cmd 指定或配置环境变量 MTKIT_LLM_CMD)")
95
+ self.cmd_parts = cmd.split()
96
+ self.timeout = timeout
97
+ self.env = env
98
+
99
+ def chat(self, messages, temperature=0.2):
100
+ # join all messages into a single prompt text
101
+ prompt = "\n\n".join(
102
+ ("[%s]\n%s" % (message.get("role") or "user", message.get("content") or ""))
103
+ for message in messages
104
+ )
105
+ try:
106
+ result = subprocess.run(
107
+ self.cmd_parts + [prompt],
108
+ capture_output=True,
109
+ text=True,
110
+ timeout=self.timeout,
111
+ env=self.env,
112
+ encoding="utf-8",
113
+ errors="replace",
114
+ )
115
+ except subprocess.TimeoutExpired:
116
+ raise RuntimeError("CLI LLM 调用超时(%d 秒)" % self.timeout)
117
+ if result.returncode != 0:
118
+ raise RuntimeError("CLI LLM 调用失败(exit=%d): %s" % (result.returncode, result.stderr[:500]))
119
+ return result.stdout or ""
120
+
121
+
122
+ def extract_json(text):
123
+ """Extract the JSON object from model output (tolerates ```json fences and thinking/design text before JSON).
124
+
125
+ strategy: prefer the code fence; otherwise try each `{` from right to left as the start, parsing until the last `}`,
126
+ until success -- compatible with the "design note + JSON" output shape.
127
+
128
+ :param text: raw model output
129
+ :return: parsed dict
130
+ """
131
+ text = (text or "").strip()
132
+ fenced = re.search(r"```(?:json)?\s*(.*?)```", text, re.DOTALL)
133
+ if fenced:
134
+ text = fenced.group(1).strip()
135
+ start = text.find("{")
136
+ while start >= 0:
137
+ end = text.rfind("}")
138
+ if end > start:
139
+ try:
140
+ return json.loads(text[start:end + 1])
141
+ except ValueError:
142
+ pass
143
+ next_start = text.find("{", start + 1)
144
+ if next_start < 0:
145
+ break
146
+ start = next_start
147
+ raise ValueError("未在模型输出中找到合法 JSON 对象")
148
+
149
+
150
+ def contract_to_tree(contract):
151
+ """Convert an LLM output contract into an mtkit zen style case tree.
152
+
153
+ contract structure:
154
+ {"chapters": [{"t": chapter, "cases": [{"t": case name, "pc": [...], "steps": [...],
155
+ "expects": [...], "sql": [...]}]}]}
156
+
157
+ :param contract: LLM output dict
158
+ :return: mtkit case tree
159
+ """
160
+ from ..parsers import circle_text
161
+
162
+ tree = []
163
+ for chapter in contract.get("chapters") or []:
164
+ cases = []
165
+ for case in chapter.get("cases") or []:
166
+ children = []
167
+ pc = case.get("pc") or []
168
+ if pc:
169
+ children.append({"t": "pc: " + circle_text("\n".join(str(item) for item in pc))})
170
+ else:
171
+ # placeholder when no precondition, satisfies the zen style pc-line requirement
172
+ children.append({"t": "pc: 无"})
173
+ steps = case.get("steps") or []
174
+ if steps:
175
+ children.append({"t": "步骤: " + circle_text("\n".join(str(item) for item in steps))})
176
+ expects = case.get("expects") or []
177
+ if expects:
178
+ children.append({"t": "预期: " + circle_text("\n".join(str(item) for item in expects))})
179
+ for sql in case.get("sql") or []:
180
+ text = str(sql).strip()
181
+ if text:
182
+ children.append({"t": "SQL核对: " + text})
183
+ cases.append({"t": case.get("t") or "tc-P1-功能测试:未命名用例", "c": children})
184
+ tree.append({"t": chapter.get("t") or "未命名章节", "c": cases})
185
+ return tree
186
+
187
+
188
+ def tree_to_contract(tree):
189
+ """Convert a case tree (zen/history style) into an LLM output contract, for regenerating legacy cases.
190
+
191
+ conversion rules:
192
+ - chapter nodes -> chapters entries; cases directly under the root go into a "未分组的用例" chapter
193
+ - pc flat lines/nodes -> pc list; 操作步骤/预期结果 nodes -> steps/expects lists
194
+ - SQL核对/数据库Checkpoint nodes -> sql list
195
+
196
+ :param tree: mtkit case tree
197
+ :return: {"chapters": [...]}
198
+ """
199
+ from ..builder import CASE_TITLE_PATTERN
200
+ from ..normalize import HISTORY_EXPECT_TITLES, HISTORY_STEP_TITLES, SQL_TEXT_PATTERN
201
+
202
+ chapters = []
203
+ pending_cases = []
204
+
205
+ def flush():
206
+ if pending_cases:
207
+ chapters.append({"t": "未分组的用例", "cases": pending_cases[:]})
208
+ pending_cases.clear()
209
+
210
+ def collect_cases(node):
211
+ """Recursively collect cases under nested chapters (W-07: multi-level chapter nesting supported)."""
212
+ if CASE_TITLE_PATTERN.match(node.get("t") or ""):
213
+ pending_cases.append(case_to_contract(node))
214
+ return
215
+ children = node.get("c") or []
216
+ if not children:
217
+ return
218
+ child_cases = [c for c in children if CASE_TITLE_PATTERN.match(c.get("t") or "")]
219
+ if child_cases:
220
+ chapters.append({"t": node.get("t"), "cases": [case_to_contract(c) for c in child_cases]})
221
+ # keep descending into non-case nodes (nested chapters)
222
+ for child in children:
223
+ if not CASE_TITLE_PATTERN.match(child.get("t") or ""):
224
+ collect_cases(child)
225
+
226
+ for node in tree:
227
+ collect_cases(node)
228
+ flush()
229
+ return {"chapters": chapters}
230
+
231
+
232
+ def case_to_contract(case_node):
233
+ """Single case node -> contract case object."""
234
+ from ..normalize import HISTORY_EXPECT_TITLES, HISTORY_STEP_TITLES, SQL_TEXT_PATTERN
235
+
236
+ case = {"t": case_node.get("t") or "", "pc": [], "steps": [], "expects": [], "sql": []}
237
+ for child in case_node.get("c") or []:
238
+ title = child.get("t") or ""
239
+ if title.startswith("pc:"):
240
+ case["pc"].append(title[3:].strip())
241
+ elif title in HISTORY_STEP_TITLES or title.startswith("步骤:"):
242
+ if title.startswith("步骤:"):
243
+ case["steps"].append(title[3:].strip())
244
+ else:
245
+ case["steps"].extend(c.get("t") or "" for c in child.get("c") or [])
246
+ elif title in HISTORY_EXPECT_TITLES or title.startswith("预期:"):
247
+ if title.startswith("预期:"):
248
+ case["expects"].append(title[3:].strip())
249
+ else:
250
+ case["expects"].extend(c.get("t") or "" for c in child.get("c") or [])
251
+ else:
252
+ # SQL check content: title contains SQL/Checkpoint or child text starts with SQL keyword
253
+ sub_texts = [c.get("t") or "" for c in child.get("c") or []]
254
+ is_sql = "SQL" in title or "Checkpoint" in title
255
+ for text in sub_texts:
256
+ if SQL_TEXT_PATTERN.search(text):
257
+ is_sql = True
258
+ break
259
+ if is_sql:
260
+ if sub_texts:
261
+ case["sql"].extend(text for text in sub_texts if text.strip())
262
+ elif title.strip():
263
+ case["sql"].append(title)
264
+ return case
265
+
266
+
267
+ def generate_cases_with_llm(doc_facts, provider, hist_sample="", code_facts=None,
268
+ retry=DEFAULT_RETRY, chunk_size=DEFAULT_CHUNK_SIZE):
269
+ """LLM-driven case generation: chunk -> generate per chunk -> contract conversion -> validate & retry.
270
+
271
+ :param doc_facts: docx_loader.load_docx result
272
+ :param provider: LlmProvider instance
273
+ :param hist_sample: historical case style sample text
274
+ :param code_facts: code_facts.scan_repo result (optional)
275
+ :param retry: max retries per chunk
276
+ :param chunk_size: chunk char cap
277
+ :return: mtkit zen style case tree
278
+ """
279
+ from .prompts import build_chunk_prompt, facts_to_text
280
+
281
+ doc_text = facts_to_text(doc_facts)
282
+ code_text = facts_to_text(code_facts) if code_facts else ""
283
+ chunks = split_doc_chunks(doc_facts, doc_text, chunk_size)
284
+ tree = []
285
+ for index, (chunk_title, chunk_text) in enumerate(chunks, 1):
286
+ prompt = build_chunk_prompt(
287
+ chunk_title, chunk_text, hist_sample, code_text, len(chunks), index
288
+ )
289
+ tree.extend(_generate_chunk_with_retry(provider, prompt, retry))
290
+ return tree
291
+
292
+
293
+ def _generate_chunk_with_retry(provider, prompt, retry):
294
+ """单分片生成:解析契约 + 结构校验,失败把错误反馈给模型重试。"""
295
+ from ..validator import check_tree
296
+
297
+ messages = [{"role": "user", "content": prompt}]
298
+ attempt = 1
299
+ while True:
300
+ try:
301
+ text = provider.chat(messages, temperature=0.2)
302
+ contract = extract_json(text)
303
+ tree = contract_to_tree(contract)
304
+ except Exception as exc:
305
+ feedback = "\n\n上次输出解析失败:%s\n请严格按 JSON 契约重新输出。" % exc
306
+ if attempt >= retry:
307
+ raise RuntimeError("LLM 生成失败:重试 %d 次后仍无法解析输出" % retry)
308
+ messages.append({"role": "assistant", "content": text if "text" in locals() else ""})
309
+ messages.append({"role": "user", "content": feedback})
310
+ attempt += 1
311
+ continue
312
+ errors = check_tree(tree, style="zen", require_sql=True)
313
+ if not errors:
314
+ return tree
315
+ if attempt >= retry:
316
+ raise RuntimeError(
317
+ "LLM 生成失败:重试 %d 次后结构校验仍不通过(%d 项)" % (retry, len(errors))
318
+ )
319
+ messages.append({"role": "assistant", "content": text})
320
+ messages.append(
321
+ {
322
+ "role": "user",
323
+ "content": "\n\n上次输出未通过校验:\n" + "\n".join("- " + error for error in errors)
324
+ + "\n请修正后重新输出完整 JSON。",
325
+ }
326
+ )
327
+ attempt += 1
328
+
329
+
330
+ def split_doc_chunks(doc_facts, doc_text, chunk_size):
331
+ """把文档按章节边界分片,返回 [(分片标题, 分片文本)]。
332
+
333
+ 优先按章节切分(每个一级/二级章节独立分片),超长章节再按字符截断。
334
+
335
+ :param doc_facts: 文档事实
336
+ :param doc_text: 完整文档文本(用于兜底截断)
337
+ :param chunk_size: 分片字符上限
338
+ :return: [(标题, 文本)]
339
+ """
340
+ chunks = []
341
+ for section in doc_facts.get("sections") or []:
342
+ lines = ["# " + section["title"]]
343
+ lines.extend(section.get("paragraphs") or [])
344
+ for table in section.get("tables") or []:
345
+ lines.append("| " + " | ".join(table[0]) + " |" if table else "")
346
+ lines.append("|" + "---|" * (len(table[0]) if table else 0))
347
+ for row in table[1:]:
348
+ lines.append("| " + " | ".join(row) + " |")
349
+ text = "\n".join(lines)
350
+ if len(text) > chunk_size:
351
+ # overlong chapters are truncated by chars into multiple chunks
352
+ for pos in range(0, len(text), chunk_size):
353
+ part = text[pos:pos + chunk_size]
354
+ if part.strip():
355
+ chunks.append((section["title"], part))
356
+ elif text.strip():
357
+ chunks.append((section["title"], text))
358
+ if not chunks and doc_text.strip():
359
+ chunks.append(("文档概述", doc_text))
360
+ return chunks