Files
company-ai-platform/app/modules/work_assistant/bid_studio_quality.py
T
2026-11-27 14:43:37 +08:00

192 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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<len(raw.get('tables',[])):continue
else:
if index not in mapping:continue
for mapped in mapping[index]:
key=('paragraph',mapped)
if key not in used:
mapped_kind='heading' if mapped in headings or (kind=='heading' and len(mapping[index])==1 and len(paragraphs[mapped])<=80) else 'paragraph'
layout.append({'kind':mapped_kind,'index':mapped});used.add(key)
continue
key=('table' if kind=='table' else 'paragraph',index)
if key not in used:layout.append({'kind':kind,'index':index});used.add(key)
if layout:
for index in range(len(paragraphs)):
if ('paragraph',index) not in used:
after=next((i+1 for i,b in reversed(list(enumerate(layout))) if b['kind']!='table' and b['index']<index),0)
layout.insert(after,{'kind':'heading' if index in headings else 'paragraph','index':index})
layout.extend({'kind':'table','index':index} for index in range(len(raw.get('tables',[]))) if ('table',index) not in used)
if not layout:
layout=[{'kind':'heading' if index in headings else 'paragraph','index':index} for index in range(len(paragraphs))]
layout.extend({'kind':'table','index':index} for index in range(len(raw.get('tables',[]))))
return {**raw,'paragraphs':paragraphs,'layout':layout}
def validate_publishable(result, target, *, is_form=False):
prose = result['paragraphs'] + [t.get('title', '') for t in result['tables']] + [cell for t in result['tables'] for row in [t['columns']]+t['rows'] for cell in row] + [text for t in result['tables'] for text in t.get('before',[])+t.get('after',[])]
if any(META.search(text) for text in prose):
raise ValueError('正文混入生成过程或内部字段说明,请仅保留可直接提交的本节内容')
if any(re.search(r'@[SEC]\d+\b|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f-]{23}:\d+',text,re.I) for text in prose):
raise ValueError('正文或表格泄露内部来源编号,请删除编号及依据编号列,保留正式文稿')
for text in prose:
for sequence in re.findall(r'(?:\d+\s*[、,,]\s*){11,}\d+', text):
values = list(map(int,re.findall(r'\d+',sequence)))
if all(b-a==1 for a,b in zip(values,values[1:])):
raise ValueError('正文出现连续数字凑字数,请删除数字串并重写本节实质内容')
count = content_count(result)
if is_form and (not re.search(r'_{2,}|【待填写[^】]*】|\[待填写[^\]]*\]', '\n'.join(prose))):
raise ValueError('证明书/固定表式必须是可填写并签署的文件,未知值使用【待填写】或下划线。不要法律解读、编制教程或审查结论。')
if is_form and any(re.search(r'^(?:填写说明|签署责任|待补材料)[::]|已附(?:带)?(?:身份证|证件)|若.*(?:导致|视为).*(?:无效|不通过)',text) for text in prose):
raise ValueError('请只输出可签署的证明表式,删除编制教程与推导的审查结论。未取得的附件标为【待补充附件】,不能写成已附。')
# Operational response-size guard, independent of the user's reference length.
if count > 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('正文小标题过长,请将说明放入独立正文段落')