"""Publication checks and explicit block order for the bid document editor.""" import re from typing import Literal from pydantic import Field from .bid_writing import Strict, Draft class ContentBlock(Strict): kind: Literal['paragraph', 'heading', 'table'] index: int = Field(ge=0) class StudioDraft(Draft): layout: list[ContentBlock] = Field(default_factory=list, max_length=80) def prose_budget(target, is_form=False): """A shared ceiling for generation, repair and publication validation.""" return min(target, 500) if is_form else target def minimum_content(target, is_form=False): # Word counts are guidance, never a reason to stall a complete section. return 0 def text_count(text): # Unicode code points, punctuation included; whitespace is not content. return len(re.sub(r'[\s\u200b\ufeff]', '', text)) def table_text(table): title = table.get('title', '') parts = list(table.get('before', [])) + list(table.get('after', [])) if title.startswith(('【流程图】', '【智能图形】', '【资料配图】')): parts.append(title.split('】', 1)[1]) if not title.startswith('【资料配图】'): parts.extend(cell for row in table.get('rows', []) for cell in row) else: parts += [title] + table.get('columns', []) parts.extend(cell for row in table.get('rows', []) for cell in row) return ''.join(parts) def content_count(result): """Editor body only: section title/material checklist are separate UI fields.""" return text_count(''.join(result.get('paragraphs', [])) + ''.join(table_text(t) for t in result.get('tables', []))) def visual_counts(result): counts = dict(tables=0, flowcharts=0, diagrams=0, images=0) for table in result.get('tables', []): title = table.get('title', '') key = next((key for prefix, key in [('【流程图】', 'flowcharts'), ('【智能图形】', 'diagrams'), ('【资料配图】', 'images')] if title.startswith(prefix)), 'tables') counts[key] += 1 return counts def validate_options(result, options, existing=None): """Hard switches/density caps survive normal, repair and continuation calls.""" if not options: return counts = visual_counts(result) for key, count in counts.items(): mode = options.get(key, 'moderate' if key == 'tables' else 'none') maximum = {'none': 0, 'low': 1, 'moderate': 2, 'source': 2, 'many': 3, 'high': 3}.get(mode, 0) if options.get('layout') == 'text' or (key == 'images' and options.get('bidMode') == 'anonymous'): maximum = 0 if count + (existing or {}).get(key, 0) > maximum: raise ValueError(f'用户设置{key}={mode},本节数量上限{maximum},请按设置重写,不得增加未启用的图表') class DraftLengthExceeded(ValueError): def __init__(self, actual, maximum): self.actual, self.maximum = actual, maximum super().__init__(f'正文篇幅共{actual}字,本次上限{maximum}字;需保留必要响应并压缩重复内容') META = re.compile(r'company_basis|missing_materials|source_context|target_words|candidate_to_repair|maximum_prose_characters|maximum_content_characters|minimum_content_characters|recommended_content_characters|existing_visual_counts|existing_draft|' r'recovery_feedback|subsection_topics|completed_topics|\bcompany数组|\bguidance\b|part\s*\d+\s*of\s*\d+|' r'本[小章]节(?:已|未|严格|内容至此|结束)|后续(?:章节|将进入|将依次)|' r'(?:本文|此内容)由\s*AI|(?:遵循|符合).{0,20}(?:排版版式|提示词)|' r'本[小章]节.{0,20}(?:没有|未包含|不包含).{0,10}(?:表格|图片|流程图)') def form_section(title): return bool(re.search(r'身份证|资格证明书|授权委托书|营业执照|证书复印件|身份证明|报价一览表', title)) def prepare_draft(raw): """Remove standalone generator notes; repair only block references, never facts.""" if (not isinstance(raw, dict) or not isinstance(raw.get('paragraphs'), list) or any(not isinstance(text, str) for text in raw['paragraphs']) or not isinstance(raw.get('tables', []), list) or not isinstance(raw.get('missing_materials', []), list) or not isinstance(raw.get('layout', []), list)): raise ValueError('正文结构不完整,请返回段落、表格及排版引用列表') paragraphs, mapping, headings = [], {}, set() material_notes=False material_text={str(v).strip(' \"\',,。[]') for v in raw.get('missing_materials',[])} for index,text in enumerate(raw.get('paragraphs',[])): lines=[] for line in text.splitlines(): stripped=line.strip().lstrip('((【 ') # A standalone layout placeholder carries no source fact. Drop it # before remapping block indices instead of retrying the chapter. if re.fullmatch(r'table\d*_title_placeholder', line.strip(), re.I): continue if re.match(r'^missing_materials\s*[::]',stripped): material_notes=True continue if material_notes: if stripped.strip(' \"\',,。[]') in material_text or stripped.strip() in {']','],',''}:continue material_notes=False if META.search(line) and re.match(r'(?:本小节|本章节|本节|本章|注[::]|再强调|因company|由于company|此内容|本文由|后续章节|后续将)',stripped): continue lines.append(line) mapping[index]=[] for line in lines: value=line.strip() if not value:continue heading=bool(re.match(r'^#{1,6}\s+',value)) or (len(value)<=65 and bool(re.match(r'^(?:[((][一二三四五六七八九十\d]+[))]|[一二三四五六七八九十]+、)',value))) if heading: value=re.sub(r'^#{1,6}\s+','',value) headings.add(len(paragraphs)) mapping[index].append(len(paragraphs));paragraphs.append(value) if not paragraphs: raise ValueError('生成结果只有过程说明,缺少可用正文,请重写本节') layout=[];used=set() for block in raw.get('layout',[]): if not isinstance(block, dict): continue kind,index=block.get('kind'),block.get('index') if kind not in {'heading','paragraph','table'} or type(index) is not int:continue if kind=='table': if not 0<=index 16000: raise DraftLengthExceeded(count, 16000) layout=result.get('layout',[]) if not layout: layout=[{'kind':'heading' if len(p.strip())<=65 and re.match(r'^(?:[((][一二三四五六七八九十\d]+[))]|[一二三四五六七八九十]+、|#{1,3}\s)',p.strip()) else 'paragraph', 'index':i} for i,p in enumerate(result['paragraphs'])] layout.extend({'kind':'table','index':i} for i in range(len(result['tables']))) result['layout']=layout paragraphs=[b['index'] for b in layout if b['kind']!='table'] tables=[b['index'] for b in layout if b['kind']=='table'] if sorted(paragraphs)!=list(range(len(result['paragraphs']))) or sorted(tables)!=list(range(len(result['tables']))): raise ValueError('文档排版须将每个段落和图表各引用一次,不能缺失或重复') if any(len(result['paragraphs'][b['index']])>80 for b in layout if b['kind']=='heading'): raise ValueError('正文小标题过长,请将说明放入独立正文段落')