import csv import html import io import posixpath import re import zipfile import httpx import xlsxwriter from docx import Document from docx.enum.text import WD_LINE_SPACING from docx.oxml import OxmlElement from docx.oxml.ns import qn from docx.shared import Cm, Pt, RGBColor from pptx import Presentation from pptx.dml.color import RGBColor as PptRGB from pptx.enum.shapes import MSO_SHAPE from pptx.enum.text import PP_ALIGN from pptx.util import Emu, Pt as PptPt RISK_LINE = "本成稿为辅助文稿,不构成正式评估意见。" ANSWER_NOTE = "本回答仅供参考,不构成正式评估意见。" LEGACY_ANSWER_NOTES = ( ("为演示性质,不构成正式评估意见", "仅供参考,不构成正式评估意见"), ("属于演示性质,不构成正式评估意见", "仅供参考,不构成正式评估意见"), ("演示回答不构成正式评估意见", ANSWER_NOTE), ) ALLOWED_EXTENSIONS = frozenset({"pdf", "docx", "txt", "md", "xlsx", "xls", "csv", "jpg", "jpeg", "png", "webp"}) IMAGE_EXTENSIONS = frozenset({"jpg", "jpeg", "png", "webp"}) MAX_FILES = 5 DOCUMENT_EXCERPT_LIMIT = 32000 IMAGE_EXCERPT = "图片附件。请识别随附图片中的文字和表格,依据图片内容回答,不要只根据文件名回答。" def file_kind(extension: str) -> str: return "image" if extension.lower() in IMAGE_EXTENSIONS else "document" WEB_RESULT_LIMIT = 8 WEB_SNIPPET_LIMIT = 500 WEB_UNAVAILABLE = "联网检索没有连上,本次没有取回网页摘录。" _SEARCH_HEADERS = { "User-Agent": ( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" ), "Accept-Language": "zh-CN,zh;q=0.9", } def _result_line(title: str, snippet: str, url: str) -> str: snippet = re.sub(r"(详情|\.\.\.)$", "", snippet).strip() return " ".join(part for part in (title, snippet, f"来源:{url}" if url else "") if part)[:WEB_SNIPPET_LIMIT] def _parse_sogou(page: str, limit: int) -> list[str]: chunks = re.split(r'(?=]*class="[^"]*vr-title)', page, flags=re.I) items: list[str] = [] seen: set[str] = set() for chunk in chunks[1:]: link = re.search(r']*href="(https?://[^"]+)"[^>]*>(.*?)', chunk, flags=re.I | re.S) if link is None: continue url = html.unescape(link.group(1)).strip() if not url or url in seen: continue title = _plain(re.sub(r"", "", link.group(2), flags=re.S)) summary = re.search(r'class="[^"]*summary[^"]*"[^>]*>(.*?)', chunk, flags=re.I | re.S) snippet = _plain(re.sub(r"", "", summary.group(1), flags=re.S)) if summary else "" line = _result_line(title, snippet, url) if not title and not snippet: continue seen.add(url) items.append(line) if len(items) >= limit: break return items def _parse_so(page: str, limit: int) -> list[str]: chunks = re.split(r'(?=]*class="[^"]*res-title)', page, flags=re.I) items: list[str] = [] seen: set[str] = set() for chunk in chunks[1:]: real = re.search(r'data-mdurl="(https?://[^"]+)"', chunk, flags=re.I) link = re.search(r']*href="(https?://[^"]+)"[^>]*>(.*?)', chunk, flags=re.I | re.S) if link is None: continue url = html.unescape((real.group(1) if real else link.group(1))).strip() if not url or url in seen or "so.com/link" in url: continue title = _plain(link.group(2)) summary = re.search(r'data-result-summary[^>]*>(.*?)', chunk, flags=re.I | re.S) if summary is None: summary = re.search(r'class="[^"]*res-desc[^"]*"[^>]*>(.*?)', chunk, flags=re.I | re.S) snippet = _plain(summary.group(1)) if summary else "" line = _result_line(title, snippet, url) if not title and not snippet: continue seen.add(url) items.append(line) if len(items) >= limit: break return items def parse_search_snippets(page: str, limit: int = WEB_RESULT_LIMIT) -> list[str]: if 'class="res-title"' in page or 'class="res-desc"' in page: found = _parse_so(page, limit) if found: return found return _parse_sogou(page, limit) def _fetch_search_page(url: str, params: dict[str, str]) -> str | None: try: response = httpx.get( url, params=params, headers=_SEARCH_HEADERS, timeout=httpx.Timeout(10.0, connect=5.0), follow_redirects=True, ) except httpx.HTTPError: return None if response.status_code >= 400 or "captcha" in str(response.url): return None return response.text def search_web(query: str) -> list[str]: text = query.strip()[:200] if not text: return [] pages = [ _fetch_search_page("https://www.sogou.com/web", {"query": text}), _fetch_search_page("https://www.so.com/s", {"q": text}), ] if all(page is None for page in pages): return [WEB_UNAVAILABLE] items: list[str] = [] seen: set[str] = set() for page in pages: if not page: continue for line in parse_search_snippets(page, WEB_RESULT_LIMIT): url = line.split("来源:", 1)[-1] if url in seen: continue seen.add(url) items.append(line) if len(items) >= WEB_RESULT_LIMIT: return items return items def extract_excerpt(extension: str, content: bytes, limit: int | None = None) -> str: kind = extension.lower().lstrip(".") if kind in {"txt", "md", "csv"}: text = _plain_bytes(content) elif kind == "docx": text = _docx_text(content) elif kind == "pptx": text = _pptx_text(content) elif kind == "xlsx": text = _xlsx_text(content) elif kind == "xls": text = _xls_text(content) elif kind == "pdf": text = _pdf_text(content) elif kind in IMAGE_EXTENSIONS: text = IMAGE_EXCERPT else: text = "" cap = DOCUMENT_EXCERPT_LIMIT if limit is None else limit text = text.replace("\x00", "") text = text.replace("\r\n", "\n").replace("\r", "\n") text = re.sub(r"[^\S\n]+", " ", text) text = re.sub(r"\n{3,}", "\n\n", text).strip() return text[:cap] def _plain_bytes(content: bytes) -> str: for encoding in ("utf-8-sig", "gb18030"): try: return content.decode(encoding) except UnicodeDecodeError: continue return content.decode("utf-8", errors="ignore") def wants_document(query: str) -> bool: text = query.strip() if not text: return False if "按模版生成" in text or "按模板生成" in text: return True verbs = ("生成", "起草", "撰写", "写成", "编写", "出一份", "写一份", "做一份", "帮忙写", "帮我写", "请写") nouns = ( "文档", "文稿", "报告", "说明", "模版", "模板", "幻灯片", "演示", "课件", "PPT", "ppt", "表格", "参数表", "电子表", "Excel", "excel", "CSV", "csv", "Markdown", "markdown", "纯文本", ) return any(word in text for word in verbs) and any(word in text for word in nouns) def draft_prompt( *, template_name: str, outline: str, question: str, file_excerpts: list[tuple[str, str]], web: bool, web_snippets: list[str], template_format: str = "docx", ) -> str: if template_name and outline.strip() and template_format == "pptx": lead = ( "请检索知识库,严格按模版中的幻灯片顺序写一份演示文稿。" "每一页以「第N页」单独一行开始,下一行只写该页标题,随后每行一个要点并以「- 」开头。" "页数和顺序与模版一致。只根据本次要求和检索结果撰写,不要把此前会话闲聊写入正文。" ) template_block = f"【模版】{template_name}\n{outline.strip()}" elif template_name and outline.strip(): lead = ( "请检索知识库,严格按模版章节写一份辅助文稿。只根据本次要求和检索结果撰写,不要把此前会话闲聊写入正文。" "正文用 Markdown 表达结构:文档标题用「# 」,章节用「## 」,小节用「### 」,说明写成段落,并列项用「- 」,关键词用「**」。" ) template_block = f"【模版】{template_name}\n{outline.strip()}" else: lead = ( "请检索知识库,按本次要求生成辅助文稿,不必套用固定模版。" "请根据本次要求决定成品类型,不要默认成某一种。" "可交付类型:Word(docx)、PPT(pptx)、Excel(xlsx)、CSV(csv)、Markdown(md)、纯文本(txt)。" "用户指定了类型就用该类型;没有指定时,按内容选择最合适的一种。" "正文第一行必须单独写成「格式:docx」「格式:pptx」「格式:xlsx」「格式:csv」「格式:md」或「格式:txt」,后面再写正文。" "Word 按章节写,并用 Markdown 表达结构:文档标题用「# 」,章节用「## 」,小节用「### 」,说明写成段落,并列项用「- 」,关键词用「**」。" "PPT 每一页以「第N页」单独一行开始,下一行只写标题,随后每行一个要点并以「- 」开头。" "Excel 和 CSV 用「|」分隔单元格,第一行写表头。" "Markdown 和纯文本按本次要求直接写正文。" "只根据本次要求和检索结果撰写,不要把此前会话闲聊写入正文。" ) template_block = "【模版】未指定。请根据本次要求决定成品类型。" parts = [ lead, "没有依据的数据写「待补充」,不要编造。", f"文末必须原样包含:{RISK_LINE}", template_block, "【本次要求】" + (question.strip() or "请根据知识库检索结果生成文档。"), ] if file_excerpts: blocks = [] for name, body in file_excerpts: cleaned = body.strip() blocks.append(f"{name}\n{cleaned}" if cleaned else f"{name}(未能提取正文)") parts.append("【附件】\n" + "\n\n".join(blocks)) if web: if web_snippets: parts.append("【联网摘录】\n" + "\n".join(f"- {item}" for item in web_snippets)) else: parts.append("【联网摘录】没有检索到可用结果。") return "\n".join(parts) def with_risk_line(text: str) -> str: cleaned = text.strip() if RISK_LINE in cleaned: return cleaned return f"{cleaned}\n\n{RISK_LINE}" if cleaned else RISK_LINE def ensure_answer_note(text: str) -> str: cleaned = text.strip() for legacy, replacement in LEGACY_ANSWER_NOTES: cleaned = cleaned.replace(legacy, replacement) cleaned = cleaned.replace(f"{ANSWER_NOTE}。", ANSWER_NOTE) duplicate = f"{ANSWER_NOTE}\n\n{ANSWER_NOTE}" while duplicate in cleaned: cleaned = cleaned.replace(duplicate, ANSWER_NOTE) if ANSWER_NOTE in cleaned or RISK_LINE in cleaned: return cleaned return f"{cleaned}\n\n{ANSWER_NOTE}" if cleaned else ANSWER_NOTE _MD_BOLD = re.compile(r"\*\*(.+?)\*\*") _HEADING_LINE = re.compile(r"^(#{1,3})\s+(.+)$") _BULLET_LINE = re.compile(r"^[-*•]\s+(.+)$") _NUMBER_LINE = re.compile(r"^\d+[.、]\s+(.+)$") _QUOTE_LINE = re.compile(r"^>\s?(.+)$") _CHAPTER_LINE = re.compile(r"^[一二三四五六七八九十]+、\S") def _docx_blocks(text: str): for raw in text.splitlines(): line = raw.strip() if not line or line in {"---", "***"} or line.startswith("```"): continue heading = _HEADING_LINE.match(line) if heading: yield f"h{len(heading.group(1))}", heading.group(2).strip() continue bullet = _BULLET_LINE.match(line) if bullet: yield "bullet", bullet.group(1).strip() continue number = _NUMBER_LINE.match(line) if number: yield "number", number.group(1).strip() continue quote = _QUOTE_LINE.match(line) if quote: yield "quote", quote.group(1).strip() continue if _CHAPTER_LINE.match(line) and len(line) <= 40: yield "h2", line continue yield "p", line def _set_word_font(run, name: str, size: float, *, bold: bool = False, color: str = "1F2937") -> None: run.bold = bold run.font.size = Pt(size) run.font.color.rgb = RGBColor.from_string(color) run.font.name = name fonts = run._element.get_or_add_rPr().get_or_add_rFonts() fonts.set(qn("w:ascii"), name) fonts.set(qn("w:hAnsi"), name) fonts.set(qn("w:eastAsia"), name) def _fill_word_runs(paragraph, text: str, *, size: float, color: str = "1F2937", name: str = "微软雅黑") -> None: parts = _MD_BOLD.split(text.replace("`", "")) if not parts: parts = [text] for index, part in enumerate(parts): if not part: continue run = paragraph.add_run(part) _set_word_font(run, name, size, bold=index % 2 == 1, color=color) def _shade_paragraph(paragraph, fill: str) -> None: props = paragraph._p.get_or_add_pPr() shade = OxmlElement("w:shd") shade.set(qn("w:val"), "clear") shade.set(qn("w:color"), "auto") shade.set(qn("w:fill"), fill) props.append(shade) def build_docx(text: str) -> bytes: document = Document() section = document.sections[0] section.page_width = Cm(21) section.page_height = Cm(29.7) section.top_margin = Cm(2.2) section.bottom_margin = Cm(2.2) section.left_margin = Cm(2.5) section.right_margin = Cm(2.5) header = section.header.paragraphs[0] header.alignment = 1 _fill_word_runs(header, "甘肃省房地产价格评估行业协会", size=9, color="64748B") footer = section.footer.paragraphs[0] footer.alignment = 1 _fill_word_runs(footer, "辅助文稿 · 不构成正式评估意见", size=9, color="94A3B8") normal = document.styles["Normal"] normal.font.name = "微软雅黑" normal.font.size = Pt(12) normal._element.get_or_add_rPr().get_or_add_rFonts().set(qn("w:eastAsia"), "微软雅黑") for kind, content in _docx_blocks(text or "待补充"): if kind == "h1": paragraph = document.add_paragraph(style="Heading 1") paragraph.paragraph_format.space_before = Pt(6) paragraph.paragraph_format.space_after = Pt(10) _fill_word_runs(paragraph, content, size=20, color="1E3A5F", name="微软雅黑") elif kind == "h2": paragraph = document.add_paragraph(style="Heading 2") paragraph.paragraph_format.space_before = Pt(14) paragraph.paragraph_format.space_after = Pt(6) _fill_word_runs(paragraph, content, size=15, color="1E3A5F") elif kind == "h3": paragraph = document.add_paragraph(style="Heading 3") paragraph.paragraph_format.space_before = Pt(10) paragraph.paragraph_format.space_after = Pt(4) _fill_word_runs(paragraph, content, size=13, color="334155") elif kind == "bullet": paragraph = document.add_paragraph(style="List Bullet") paragraph.paragraph_format.space_after = Pt(3) _fill_word_runs(paragraph, content, size=12) elif kind == "number": paragraph = document.add_paragraph(style="List Number") paragraph.paragraph_format.space_after = Pt(3) _fill_word_runs(paragraph, content, size=12) elif kind == "quote": paragraph = document.add_paragraph() paragraph.paragraph_format.left_indent = Cm(0.6) paragraph.paragraph_format.space_after = Pt(6) _shade_paragraph(paragraph, "F4F7FB") _fill_word_runs(paragraph, content, size=11, color="475569") else: paragraph = document.add_paragraph() paragraph.paragraph_format.space_after = Pt(8) paragraph.paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE if content == RISK_LINE: _shade_paragraph(paragraph, "FFF7ED") _fill_word_runs(paragraph, content, size=11, color="9A3412") else: _fill_word_runs(paragraph, content, size=12) buffer = io.BytesIO() document.save(buffer) return buffer.getvalue() _SLIDE_HEADING = re.compile(r"^第\s*\d+\s*页\s*$") _SLIDE_XML = re.compile(r"^ppt/slides/slide(\d+)\.xml$") DRAFT_FORMATS = frozenset({"docx", "pptx", "xlsx", "csv", "md", "txt"}) _TITLE_PREFIX = re.compile(r"^(?:请)?(?:帮忙|帮我)?(?:生成|起草|撰写|写成|编写|写|做)(?:一份|一个)?") def draft_title(template_name: str, question: str) -> str: raw = template_name.strip() or _TITLE_PREFIX.sub("", question.strip()) cleaned = re.sub(r'[\\/:*?"<>|]+', "", raw) cleaned = re.sub(r"\s+", " ", cleaned).strip(" ,。,.") return cleaned[:40] or "辅助文稿" _FORMAT_LINE = re.compile(r"^\s*格式\s*[::]\s*(docx|pptx|xlsx|csv|md|txt)\s*$", re.IGNORECASE) def infer_free_format(question: str) -> str: text = question.strip() lowered = text.lower() if any(word in text for word in ("幻灯片", "演示文稿", "课件")) or "ppt" in lowered: return "pptx" if "csv" in lowered: return "csv" if any(word in text for word in ("表格", "电子表", "参数表", "工作表")) or "excel" in lowered or "xlsx" in lowered: return "xlsx" if "markdown" in lowered: return "md" if any(word in text for word in ("纯文本", "文本文件")) or re.search(r"(? tuple[str, str]: if not finished and "\n" not in buffer and len(buffer) < 24: return "", "" first, _separator, rest = buffer.partition("\n") match = _FORMAT_LINE.match(first) if match: return match.group(1).lower(), rest.lstrip("\n") return infer_free_format(question), buffer def slide_blocks(text: str) -> list[tuple[str, list[str]]]: groups: list[list[str]] = [[]] started = False for raw in text.splitlines(): line = raw.strip() if not line: continue if _SLIDE_HEADING.match(line): if started and groups[-1]: groups.append([]) elif not started: groups[-1] = [] started = True continue groups[-1].append(line) groups = [group for group in groups if group] or [["辅助文稿"]] slides: list[tuple[str, list[str]]] = [] for group in groups[:40]: title = re.sub(r"^标题[::]\s*", "", group[0])[:120] or "未命名" body = [re.sub(r"^[-•·]\s*", "", line)[:400] for line in group[1:]] slides.append((title, body)) if len(groups) > 40: title, body = slides[-1] extra = [line for group in groups[40:] for line in group] slides[-1] = (title, body + extra[:30]) return slides def _plain_slide_text(value: str) -> str: text = _MD_BOLD.sub(r"\1", value.replace("`", "")) text = re.sub(r"^#{1,3}\s+", "", text.strip()) return text or "待补充" def _paint_shape(shape, color: str) -> None: shape.fill.solid() shape.fill.fore_color.rgb = PptRGB.from_string(color) shape.line.fill.background() def _write_slide_text(paragraph, text: str, *, size: int, color: str, bold: bool = False) -> None: paragraph.clear() paragraph.alignment = PP_ALIGN.LEFT run = paragraph.add_run() run.text = text run.font.size = PptPt(size) run.font.bold = bold run.font.color.rgb = PptRGB.from_string(color) run.font.name = "微软雅黑" def build_pptx(text: str) -> bytes: presentation = Presentation() presentation.slide_width = Emu(12192000) presentation.slide_height = Emu(6858000) blank = presentation.slide_layouts[6] slides = slide_blocks(text) for index, (title, lines) in enumerate(slides, start=1): slide = presentation.slides.add_slide(blank) background = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, 0, presentation.slide_width, presentation.slide_height) _paint_shape(background, "F7F9FC") bar = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, 0, presentation.slide_width, Emu(1320000)) _paint_shape(bar, "1E3A5F") accent = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, Emu(1320000), presentation.slide_width, Emu(70000)) _paint_shape(accent, "C4A35A") title_box = slide.shapes.add_textbox(Emu(520000), Emu(280000), Emu(10000000), Emu(820000)) _write_slide_text(title_box.text_frame.paragraphs[0], _plain_slide_text(title), size=28, color="FFFFFF", bold=True) page_box = slide.shapes.add_textbox(Emu(10600000), Emu(360000), Emu(1100000), Emu(500000)) page = page_box.text_frame.paragraphs[0] page.alignment = PP_ALIGN.RIGHT run = page.add_run() run.text = f"{index:02d}" run.font.size = PptPt(18) run.font.bold = True run.font.color.rgb = PptRGB.from_string("C4A35A") run.font.name = "微软雅黑" body = slide.shapes.add_textbox(Emu(640000), Emu(1680000), Emu(10900000), Emu(4400000)) frame = body.text_frame frame.word_wrap = True usable = [_plain_slide_text(line) for line in lines] or ["待补充"] for line_index, line in enumerate(usable): paragraph = frame.paragraphs[0] if line_index == 0 else frame.add_paragraph() paragraph.clear() paragraph.level = 0 paragraph.space_after = PptPt(14) mark = paragraph.add_run() mark.text = "▸ " mark.font.size = PptPt(20) mark.font.color.rgb = PptRGB.from_string("C4A35A") mark.font.name = "微软雅黑" content = paragraph.add_run() content.text = line content.font.size = PptPt(20) content.font.color.rgb = PptRGB.from_string("1F2937") content.font.name = "微软雅黑" foot = slide.shapes.add_textbox(Emu(520000), Emu(6320000), Emu(11000000), Emu(360000)) _write_slide_text( foot.text_frame.paragraphs[0], "甘肃省房地产价格评估行业协会 · 辅助文稿,不构成正式评估意见", size=11, color="94A3B8", ) buffer = io.BytesIO() presentation.save(buffer) return buffer.getvalue() def _table_rows(text: str) -> list[list[str]]: rows: list[list[str]] = [] for raw in text.splitlines(): line = raw.strip() if not line or line == RISK_LINE or line.startswith("工作表"): continue if "|" in line: cells = [cell.strip() for cell in line.strip("|").split("|")] elif "\t" in line: cells = [cell.strip() for cell in line.split("\t")] else: cells = [line] if cells and all(set(cell) <= set("-: ") and cell for cell in cells): continue rows.append(cells) return rows or [["待补充"]] def build_xlsx(text: str) -> bytes: buffer = io.BytesIO() workbook = xlsxwriter.Workbook(buffer, {"in_memory": True}) sheet = workbook.add_worksheet("文稿") for row_index, cells in enumerate(_table_rows(text)): for column_index, value in enumerate(cells): sheet.write(row_index, column_index, value) workbook.close() return buffer.getvalue() def build_csv(text: str) -> bytes: buffer = io.StringIO() writer = csv.writer(buffer) writer.writerows(_table_rows(text)) return buffer.getvalue().encode("utf-8-sig") def build_text(text: str) -> bytes: return (text.strip() or "待补充").encode("utf-8") def build_draft_file(fmt: str, text: str) -> tuple[bytes, str, str]: if fmt == "pptx": media = "application/vnd.openxmlformats-officedocument.presentationml.presentation" return build_pptx(text), media, "辅助文稿.pptx" if fmt == "xlsx": media = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" return build_xlsx(text), media, "辅助文稿.xlsx" if fmt == "csv": return build_csv(text), "text/csv; charset=utf-8", "辅助文稿.csv" if fmt == "md": return build_text(text), "text/markdown; charset=utf-8", "辅助文稿.md" if fmt == "txt": return build_text(text), "text/plain; charset=utf-8", "辅助文稿.txt" media = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" return build_docx(text), media, "辅助文稿.docx" def _drawing_lines(payload: bytes) -> list[str]: xml = payload.decode("utf-8", "ignore") lines = [] for paragraph in re.findall(r"", xml, flags=re.DOTALL): parts = re.findall(r"]*>(.*?)", paragraph) line = html.unescape("".join(parts)).strip() if line: lines.append(line) return lines def _slide_notes(archive: zipfile.ZipFile, slide_name: str) -> list[str]: rels_name = "ppt/slides/_rels/" + slide_name.rsplit("/", 1)[-1] + ".rels" if rels_name not in archive.namelist(): return [] xml = archive.read(rels_name).decode("utf-8", "ignore") match = re.search(r'relationships/notesSlide"\s+Target="([^"]+)"', xml) if match is None: match = re.search(r'Target="([^"]+)"[^>]*relationships/notesSlide"', xml) if match is None: return [] path = posixpath.normpath(posixpath.join("ppt/slides", match.group(1))) if path not in archive.namelist(): return [] return _drawing_lines(archive.read(path)) def _pptx_text(content: bytes) -> str: try: archive = zipfile.ZipFile(io.BytesIO(content)) except zipfile.BadZipFile: return "" with archive: slides = [] for name in archive.namelist(): match = _SLIDE_XML.match(name) if match: slides.append((int(match.group(1)), name)) slides.sort() blocks = [] for number, name in slides: lines = [f"第{number}页", *_drawing_lines(archive.read(name))] notes = _slide_notes(archive, name) if notes: lines.append("备注:" + " ".join(notes)) blocks.append("\n".join(line for line in lines if line)) return "\n\n".join(blocks) def compose_query( question: str, *, file_names: list[str], web: bool, web_snippets: list[str], file_excerpts: list[tuple[str, str]] | None = None, ) -> str: text = question.strip() or "请结合附件说明要点。" excerpts = file_excerpts or [] if not file_names and not excerpts and not web: return text parts = [] if excerpts: blocks = [] for name, body in excerpts: cleaned = body.strip() blocks.append(f"{name}\n{cleaned}" if cleaned else f"{name}(未能提取正文,请阅读随附文件)") parts.append("【附件】\n" + "\n\n".join(blocks)) elif file_names: parts.append("【附件】" + "、".join(file_names)) if web: if web_snippets: parts.append("【联网摘录】\n" + "\n".join(f"- {item}" for item in web_snippets)) else: parts.append("【联网摘录】没有检索到可用结果。") parts.append("【问题】" + text) parts.append("请在依据中标明来自知识库、附件或联网;使用了联网摘录时写上来源网址。没有对应材料时不要编造。") return "\n".join(parts) def _docx_text(content: bytes) -> str: try: with zipfile.ZipFile(io.BytesIO(content)) as archive: names = [ name for name in archive.namelist() if name.startswith("word/") and ( name.endswith("/document.xml") or name.rsplit("/", 1)[-1].startswith(("header", "footer", "footnotes", "endnotes")) ) ] names.sort(key=lambda name: (not name.endswith("/document.xml"), name)) parts = [] for name in names: xml = archive.read(name).decode("utf-8", "ignore") xml = re.sub(r"", "\n", xml) xml = re.sub(r"]*/>", "\t", xml) parts.append(html.unescape(re.sub(r"<[^>]+>", "", xml))) except zipfile.BadZipFile: return "" return "\n".join(parts) def _xlsx_text(content: bytes) -> str: try: with zipfile.ZipFile(io.BytesIO(content)) as archive: names = archive.namelist() shared = _xlsx_shared_strings(archive, names) lines = [] for name in sorted(item for item in names if item.startswith("xl/worksheets/sheet") and item.endswith(".xml")): xml = archive.read(name).decode("utf-8", "ignore") for row in re.findall(r"]*>(.*?)", xml, flags=re.S): cells = [_xlsx_cell(attrs, inner, shared) for attrs, inner in re.findall(r"]*)>(.*?)", row, flags=re.S)] line = "\t".join(cell for cell in cells if cell) if line: lines.append(line) except zipfile.BadZipFile: return "" return "\n".join(lines) def _xlsx_shared_strings(archive: zipfile.ZipFile, names: list[str]) -> list[str]: if "xl/sharedStrings.xml" not in names: return [] xml = archive.read("xl/sharedStrings.xml").decode("utf-8", "ignore") values = [] for item in re.findall(r"", xml, flags=re.S): texts = re.findall(r"]*>(.*?)", item, flags=re.S) values.append(html.unescape("".join(texts))) return values def _xlsx_cell(attrs: str, inner: str, shared: list[str]) -> str: if 't="s"' in attrs: index = re.search(r"(\d+)", inner) if index and int(index.group(1)) < len(shared): return shared[int(index.group(1))] return "" if 't="inlineStr"' in attrs: texts = re.findall(r"]*>(.*?)", inner, flags=re.S) return html.unescape("".join(texts)) value = re.search(r"(.*?)", inner) return html.unescape(value.group(1)) if value else "" def _xls_text(content: bytes) -> str: import xlrd try: book = xlrd.open_workbook(file_contents=content) except Exception: return "" lines = [] for sheet in book.sheets(): for row_idx in range(sheet.nrows): cells = [] for col_idx in range(sheet.ncols): cell = sheet.cell(row_idx, col_idx) if cell.ctype in (xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK): continue if cell.ctype == xlrd.XL_CELL_DATE: try: cells.append(xlrd.xldate_as_datetime(cell.value, book.datemode).strftime("%Y-%m-%d")) continue except Exception: pass if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer(): cells.append(str(int(cell.value))) continue text = str(cell.value).strip() if text: cells.append(text) if cells: lines.append("\t".join(cells)) return "\n".join(lines) def _pdf_text(content: bytes) -> str: from pypdf import PdfReader try: reader = PdfReader(io.BytesIO(content)) if reader.is_encrypted: reader.decrypt("") except Exception: return "" pages: list[str] = [] for page in reader.pages: try: pages.append(page.extract_text() or "") except Exception: continue return "\n".join(pages) def _xml_escape(value: str) -> str: return value.replace("&", "&").replace("<", "<").replace(">", ">") def _plain(value: str) -> str: cleaned = re.sub(r"<[^>]+>", " ", html.unescape(value)) return re.sub(r"\s+", " ", cleaned).strip()