"""把历史文稿和对话整理成可下载的报告模版提纲。 估价模版智能体只产出章节或幻灯片的写作要求。下载文件由调用方交给用户本地修改, 不写入模版列表。 """ from __future__ import annotations import io import re from dataclasses import dataclass, field from docx import Document from pptx import Presentation from app.services.valuation_context import IMAGE_EXCERPT MAX_SECTIONS = 16 MAX_SOURCE = 12000 OUTLINE_LIMIT = 7500 _CN = "一二三四五六七八九十" _SKIP = { "甘肃省房地产价格评估行业协会", "辅助文稿 · 不构成正式评估意见", "辅助文稿,不构成正式评估意见", "本成稿为辅助文稿,不构成正式评估意见。", "本回答仅供参考,不构成正式评估意见。", } _CHAPTER = re.compile( r"^(?:第\s*[0-9一二三四五六七八九十百]+\s*[章节篇部分]|[一二三四五六七八九十百零]+\s*[、..])\s*\S" ) _SLIDE = re.compile(r"^第\s*\d+\s*页\s*$") _FACT = re.compile(r"\d[\d,,.]*|\d{4}\s*年|\d{1,2}\s*月|\d{1,2}\s*日|万元|元|㎡|平方米|亩|%|%") _NAME = re.compile(r"(?:模版|模板)?名称\s*(?:改成|改为|叫做|叫|是|为|:|:)\s*([^\s,。,;;]{1,40})") _DELETE = re.compile(r"(?:删除|删掉|去掉|不要)\s*第\s*([0-9一二三四五六七八九十]+)\s*[章节页]") _DELETE_QUOTED = re.compile(r"(?:删除|删掉|去掉)\s*[「“\"](.+?)[」”\"]") _ADD = re.compile(r"(?:增加|新增|加)(?:一)?(?:章|节|页)?\s*[:: ]\s*(.+)") _REQUIRE = re.compile(r"第\s*([0-9一二三四五六七八九十]+)\s*[章节页]\s*(?:要写|改成|改为|要求|写成)\s*(.+)") _LIST = re.compile(r"(?:要有|包括|分为|分成|章节(?:是|有)?)\s*(.+)") _FENCE = re.compile(r"```template\s*\n(.*?)```", re.IGNORECASE | re.DOTALL) _LEAD_NUM = re.compile( r"^(?:第\s*[0-9一二三四五六七八九十百]+\s*[章节篇部分]|[一二三四五六七八九十]+\s*[、..]|第\s*\d+\s*页)\s*" ) @dataclass class Section: title: str instruction: str @dataclass class Outline: name: str format: str sections: list[Section] = field(default_factory=list) def render(self) -> str: lines = [f"名称:{self.name}", f"格式:{self.format}"] for index, section in enumerate(self.sections, start=1): if self.format == "pptx": lines.append(f"第{index}页 {section.title}") else: lines.append(_chapter_title(index, section.title)) lines.append(section.instruction.strip()) text = "\n".join(lines).strip() return text[:OUTLINE_LIMIT] @dataclass class TurnPlan: mode: str reply: str outline: Outline | None prompt: str source_text: str fallback: Outline | None def name_from_filename(filename: str) -> str: stem = filename.rsplit("/", 1)[-1].rsplit(".", 1)[0] stem = re.sub(r"(终稿|正式稿|送审稿|演示稿|汇报材料)$", "", stem).strip() stem = re.sub(r"\s+", "", stem) return (stem or "估价模版")[:40] def merge_source(existing: str, excerpts: list[tuple[str, str]]) -> str: blocks = [existing.strip()] if existing.strip() else [] for name, body in excerpts: cleaned = body.strip() if not cleaned or cleaned == IMAGE_EXCERPT: continue header = f"【{name}】" if header in existing or header in "\n".join(blocks): continue blocks.append(f"{header}\n{cleaned}") return "\n\n".join(blocks)[:MAX_SOURCE] def outline_from_documents(excerpts: list[tuple[str, str, str]]) -> Outline | None: """excerpts: (filename, extension, text)。取第一份 docx 或 pptx 的结构。""" chosen: tuple[str, str, str] | None = None for item in excerpts: if item[1] in {"docx", "pptx"} and item[2].strip(): chosen = item break if chosen is None: return None filename, extension, text = chosen sections = sections_from_slides(text) if extension == "pptx" else sections_from_chapters(text) if not sections and text.strip(): title = "正文结构" sections = [Section(title, instruction_for(title, text[:800]))] if not sections: return None return Outline(name=name_from_filename(filename), format=extension, sections=sections[:MAX_SECTIONS]) def sections_from_slides(text: str) -> list[Section]: if not re.search(r"(?m)^第\s*\d+\s*页\s*$", text): return [] sections: list[Section] = [] for chunk in re.split(r"(?m)^第\s*\d+\s*页\s*$", text)[1:]: lines = _content_lines(chunk) if not lines: continue title = clean_title(lines[0]) sections.append(Section(title, instruction_for(title, "\n".join(lines[1:])))) if len(sections) >= MAX_SECTIONS: break return sections def sections_from_chapters(text: str) -> list[Section]: found: list[Section] = [] title = "" body: list[str] = [] def flush() -> None: if not title: return found.append(Section(title, instruction_for(title, "\n".join(body)))) for raw in text.splitlines(): line = raw.strip() if not line or line in _SKIP or _SLIDE.match(line): continue if _CHAPTER.match(line) and len(line) <= 40: flush() title = clean_title(line) body = [] if len(found) >= MAX_SECTIONS: break continue if title: body.append(line) flush() return found[:MAX_SECTIONS] def plan_turn( *, message: str, outline: Outline | None, source_text: str, excerpts: list[tuple[str, str, str]], ) -> TurnPlan: text = message.strip() source = merge_source(source_text, [(name, body) for name, _ext, body in excerpts]) file_outline = outline_from_documents(excerpts) previous = outline if outline and outline.sections else None base = file_outline or previous started = base is not None and bool(base.sections) before = base.render() if started else "" edited, recognized = apply_commands(base, text) if edited is not None: base = edited after = base.render() if base is not None and base.sections else "" freeform = bool(text) and not recognized if recognized and started and base is not None and not base.sections: reply = "这些章节已经去掉,当前没有可调整的提纲。可以再说「要有估价对象、估价方法」,或重新上传文稿。" return TurnPlan("local", reply, base, "", source, None) if file_outline is None and recognized and started and before and before == after: return TurnPlan("local", "没有找到要改的位置,当前提纲保持不变。", None, "", source, None) if file_outline is not None and not freeform: return _local_plan(base, source, lead="我按附件的结构") if recognized and base is not None and base.sections: return _local_plan(base, source, lead="已按你的说法") if recognized and (base is None or not base.sections): reply = "还没有可调整的提纲。请上传历史 docx 或 pptx,或直接说章节,例如「要有估价对象、估价方法、估价结果」。" return TurnPlan("local", reply, None, "", source, None) if file_outline is not None and freeform: return TurnPlan("model", "", None, model_prompt(text, file_outline, source), source, file_outline) if not text and file_outline is None: reply = "请输入要怎么整理模版,或上传一份历史文稿。" return TurnPlan("local", reply, outline if outline and outline.sections else None, "", source, None) return TurnPlan("model", "", None, model_prompt(text, outline, source), source, outline if outline and outline.sections else None) def apply_commands(outline: Outline | None, message: str) -> tuple[Outline | None, bool]: text = message.strip() if not text: return None, False recognized = False current = _copy(outline) if outline else None listed = _sections_from_request(text) if listed: recognized = True current = Outline( name=current.name if current else "估价模版", format=current.format if current else "docx", sections=listed, ) pasted = _pasted_sections(text) if pasted: recognized = True current = Outline( name=current.name if current else "估价模版", format=current.format if current else "docx", sections=pasted, ) fmt = _mentioned_format(text) if fmt: recognized = True if current is None: current = Outline(name="估价模版", format=fmt, sections=[]) else: current.format = fmt found_name = _NAME.search(text) if found_name: recognized = True if current is None: current = Outline(name=found_name.group(1).strip()[:40], format="docx", sections=[]) else: current.name = found_name.group(1).strip()[:40] if current is None: return None, recognized deleted = _DELETE.search(text) or _DELETE_QUOTED.search(text) if deleted: recognized = True if deleted.re is _DELETE: index = _ordinal(deleted.group(1)) if index and 1 <= index <= len(current.sections): del current.sections[index - 1] else: needle = deleted.group(1).strip() current.sections = [item for item in current.sections if needle not in item.title] added = _ADD.search(text) if added and "第" not in added.group(0)[:2]: recognized = True title, instruction = _split_requirement(added.group(1)) if len(current.sections) < MAX_SECTIONS: current.sections.append(Section(clean_title(title), instruction or instruction_for(title, ""))) required = _REQUIRE.search(text) if required: recognized = True index = _ordinal(required.group(1)) if index and 1 <= index <= len(current.sections): current.sections[index - 1].instruction = _as_instruction(required.group(2).strip()) if not current.sections: return (current if recognized else None), recognized return current, recognized def model_prompt(message: str, outline: Outline | None, source_text: str) -> str: current = outline.render() if outline and outline.sections else "尚无" source = (source_text or "无").strip()[:4000] return "\n".join( [ "你是估价模版智能体,只帮用户整理报告模版提纲,不回答估价问题,不写正式报告,不编造数据。", "先用一两句中文说明这次怎么调整。然后单独给出完整提纲,放在 ```template 代码块中。", "代码块第一行写「名称:」,第二行写「格式:docx」或「格式:pptx」。", "Word 每一章用「一、」「二、」单独成行作标题,下一行只写这一章要回答什么。", "PPT 每一页用「第1页 标题」单独成行,下一行只写这一页要回答什么。", "每条要求都写明没有依据时写「待补充」,禁止照抄历史文稿中的数字、日期、价格、面积和名称。", f"【当前提纲】\n{current}", f"【历史文稿摘录】\n{source}", f"【用户要求】\n{message.strip() or '请按附件整理成模版'}", ] ) def finish_model_answer(raw: str, *, fallback: Outline | None) -> tuple[str, Outline | None]: prose, block = split_coach_answer(raw) parsed = parse_outline_block(block) if block else None if parsed and parsed.sections: lead = prose.strip() if len(lead) > 180: lead = "" reply = lead or summary(parsed, lead="已按对话") if "下载后可以自己修改" not in reply: reply = f"{reply}\n{summary(parsed, lead='当前提纲')}" return reply.strip(), parsed if fallback and fallback.sections: return summary(fallback, lead="我按已有材料"), fallback return "没能整理出模版提纲。可以上传 docx 或 pptx,或直接说要有哪些章节。", None def split_coach_answer(raw: str) -> tuple[str, str]: match = _FENCE.search(raw or "") if match: prose = (raw[: match.start()] + raw[match.end() :]).strip() return prose, match.group(1).strip() parsed = parse_outline_block(raw or "") if parsed and parsed.sections: return "", raw.strip() return (raw or "").strip(), "" def parse_outline_block(text: str) -> Outline | None: name = "估价模版" fmt = "" sections: list[Section] = [] title = "" body: list[str] = [] def flush() -> None: if title: sections.append(Section(clean_title(title), _as_instruction(" ".join(body)) if body else instruction_for(title, ""))) for raw in (text or "").splitlines(): line = raw.strip() if not line or line.startswith("```"): continue if line.startswith("名称:") or line.startswith("名称:"): flush() title = "" body = [] name = line.split(":", 1)[-1].split(":", 1)[-1].strip()[:40] or name continue if line.startswith("格式:") or line.startswith("格式:"): flush() title = "" body = [] value = line.split(":", 1)[-1].split(":", 1)[-1].strip().lower() if value in {"docx", "pptx"}: fmt = value continue slide = re.match(r"^第\s*(\d+)\s*页\s*(.+)$", line) chapter = _CHAPTER.match(line) and len(line) <= 40 if slide or chapter: flush() title = slide.group(2) if slide else line if not fmt: fmt = "pptx" if slide else "docx" body = [] continue if title: body.append(line) flush() if not sections: return None return Outline(name=name or "估价模版", format=fmt or "docx", sections=sections[:MAX_SECTIONS]) def summary(outline: Outline, *, lead: str) -> str: kind = "PPT" if outline.format == "pptx" else "Word" unit = "页" if outline.format == "pptx" else "章" lines = [f"{lead}已整理为{kind}模版「{outline.name}」,共 {len(outline.sections)} {unit}:"] for index, section in enumerate(outline.sections, start=1): lines.append(f"{index}. {section.title}") lines.append("可以继续调整,例如「改成 PPT」「删除第2章」或「第1章要写坐落和用途」。") lines.append("下载后可以自己修改,再从模版列表上传。这里不会直接加入模版列表。") return "\n".join(lines) def prose_ready(buffer: str) -> str: """流式输出时先放出代码块之前的说明。""" if "```" not in buffer: hold = len(buffer) - len(buffer.rstrip("`")) return buffer[:-hold] if hold else buffer return buffer[: buffer.find("```")] def build_template_file(outline: Outline) -> tuple[bytes, str, str]: if outline.format == "pptx": return ( _build_pptx(outline), "application/vnd.openxmlformats-officedocument.presentationml.presentation", f"{outline.name}.pptx", ) return ( _build_docx(outline), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", f"{outline.name}.docx", ) def instruction_for(title: str, body: str) -> str: hints = _hint_lines(body) text = f"写明与「{title}」有关的事实和依据。不要照抄历史文稿中的数字、日期、价格、面积和名称;没有依据时写「待补充」。" if hints: text += "可涉及:" + "、".join(hints) + "。" return text[:400] def clean_title(title: str) -> str: bare = _LEAD_NUM.sub("", title.strip()) cleaned = _FACT.sub("", bare) cleaned = re.sub(r"\s+", "", cleaned).strip(",。、::;;") return (cleaned or "未命名")[:40] def _local_plan(outline: Outline, source: str, *, lead: str) -> TurnPlan: if not outline.sections: reply = "还没有可调整的提纲。请上传历史 docx 或 pptx,或直接说章节,例如「要有估价对象、估价方法、估价结果」。" return TurnPlan("local", reply, None, "", source, None) return TurnPlan("local", summary(outline, lead=lead), outline, "", source, None) def _copy(outline: Outline) -> Outline: return Outline( name=outline.name, format=outline.format if outline.format in {"docx", "pptx"} else "docx", sections=[Section(item.title, item.instruction) for item in outline.sections], ) def _chapter_title(index: int, title: str) -> str: if re.match(r"^[一二三四五六七八九十]+、", title): return title return f"{_cn(index)}、{title}" def _cn(index: int) -> str: if index <= 10: return "十" if index == 10 else _CN[index - 1] if index < 20: return "十" + _CN[index - 11] if index == 20: return "二十" return str(index) def _content_lines(chunk: str) -> list[str]: lines = [] for raw in chunk.splitlines(): line = raw.strip() if not line or line in _SKIP: continue line = re.sub(r"^备注[::]\s*", "", line).strip() if line: lines.append(line) return lines def _hint_lines(body: str) -> list[str]: hints: list[str] = [] for raw in body.splitlines(): line = re.sub(r"^[-•·]\s*", "", raw.strip()) line = re.sub(r"^备注[::]\s*", "", line) if not line or line in _SKIP: continue cleaned = _FACT.sub("", line) cleaned = re.sub(r"\s+", "", cleaned).strip(",。;;、,.") if not (2 <= len(cleaned) <= 18): continue if cleaned not in hints: hints.append(cleaned) if len(hints) >= 4: break return hints def _mentioned_format(message: str) -> str: hits: list[tuple[int, str]] = [] lowered = message.lower() for word, fmt in (("ppt", "pptx"), ("幻灯片", "pptx"), ("演示文稿", "pptx"), ("word", "docx")): index = lowered.find(word) if word in {"ppt", "word"} else message.find(word) if index >= 0: hits.append((index, fmt)) if not hits: return "" hits.sort() return hits[-1][1] def _sections_from_request(message: str) -> list[Section]: match = _LIST.search(message) if match is None: return [] parts = re.split(r"[、,,和及/]", match.group(1)) titles = [] for part in parts: title = clean_title(part.strip(" 。.")) if title and title not in titles and title != "未命名": titles.append(title) if len(titles) < 2: return [] return [Section(title, instruction_for(title, "")) for title in titles[:MAX_SECTIONS]] def _pasted_sections(message: str) -> list[Section]: if message.count("\n") < 1: return [] if message.lower().count("第") and re.search(r"(?m)^第\s*\d+\s*页", message): return sections_from_slides(message) chapters = sections_from_chapters(message) return chapters if len(chapters) >= 2 else [] def _split_requirement(text: str) -> tuple[str, str]: if ",要求" in text: title, instruction = text.split(",要求", 1) return title.strip(), _as_instruction(instruction.strip()) if ":" in text: title, instruction = text.split(":", 1) return title.strip(), _as_instruction(instruction.strip()) return text.strip(), "" def _as_instruction(text: str) -> str: cleaned = text.strip(" 。") if "待补充" not in cleaned: cleaned += "。没有依据时写「待补充」。" return cleaned[:400] def _ordinal(token: str) -> int | None: if token.isdigit(): value = int(token) return value if value > 0 else None if token == "十": return 10 if len(token) == 1 and token in _CN: return _CN.index(token) + 1 if token.startswith("十") and len(token) == 2 and token[1] in _CN: return 10 + _CN.index(token[1]) + 1 return None def _build_docx(outline: Outline) -> bytes: document = Document() document.add_heading(outline.name, level=1) for index, section in enumerate(outline.sections, start=1): document.add_heading(_chapter_title(index, section.title), level=2) document.add_paragraph(section.instruction) buffer = io.BytesIO() document.save(buffer) return buffer.getvalue() def _build_pptx(outline: Outline) -> bytes: presentation = Presentation() layout = presentation.slide_layouts[1] for section in outline.sections: slide = presentation.slides.add_slide(layout) slide.shapes.title.text = section.title slide.placeholders[1].text = section.instruction buffer = io.BytesIO() presentation.save(buffer) return buffer.getvalue()