标书生成与审查
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
"""Two bounded extraction windows, with independently durable checkpoints."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextvars import copy_context
|
||||
from copy import deepcopy
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
|
||||
from .bid_progress import BidProgress, current_progress
|
||||
from .bid_timing import STEP_SECONDS
|
||||
from .review_jobs import JobDeferred, JobPaused, JobValidationBlocked
|
||||
|
||||
|
||||
def can_parallel(request, progress):
|
||||
if progress is None or request.action != 'extract':
|
||||
return False
|
||||
if progress.state.get('parallel_extraction'):
|
||||
return True
|
||||
# Resume old candidates in place; never throw away accepted work on upgrade.
|
||||
if progress.state.get('extraction_candidate') or progress.state.get('extraction_repair'):
|
||||
return False
|
||||
size = sum(len(b.text) for b in request.blocks + request.extraction_context + request.company)
|
||||
context_ids = {b.id for b in request.blocks + request.extraction_context}
|
||||
return len(request.blocks) >= 8 and size <= 20000 and len(context_ids) <= 80
|
||||
|
||||
|
||||
def _split(blocks):
|
||||
if len(blocks) > 1:
|
||||
middle = len(blocks) // 2
|
||||
return [blocks[:middle], blocks[middle:]]
|
||||
block = blocks[0]; text = block['text']
|
||||
if len(text) < 2:
|
||||
raise JobValidationBlocked('最小原文片段仍无法完整提取,请核实原文')
|
||||
middle = len(text) // 2
|
||||
cuts = [i for i in range(max(1,len(text)//4), max(2,len(text)*3//4)) if text[i-1] in '\n。;;!?']
|
||||
cut = min(cuts,key=lambda i:abs(i-middle)) if cuts else middle
|
||||
return [[dict(block,text=text[:cut])], [dict(block,text=text[cut:])]]
|
||||
|
||||
|
||||
def extract_parallel(request, parent, step, invoke):
|
||||
from .bid_writing import BidStep, RULE_VERSION, validate_result
|
||||
fingerprint = hashlib.sha256(json.dumps(request.model_dump(),sort_keys=True,ensure_ascii=False).encode()).hexdigest()
|
||||
plan = parent.state.get('parallel_extraction')
|
||||
if plan is None:
|
||||
plan = dict(version=1, fingerprint=fingerprint,
|
||||
nodes=[dict(blocks=blocks,checkpoint={}) for blocks in _split([b.model_dump() for b in request.blocks])])
|
||||
parent.state['parallel_extraction'] = plan
|
||||
parent.persist(True)
|
||||
if plan.get('version') != 1 or plan.get('fingerprint') != fingerprint:
|
||||
raise ValueError('并行提取检查点与原文不一致')
|
||||
deadline = time.monotonic() + STEP_SECONDS
|
||||
if parent.deadline is not None:deadline=min(deadline,parent.deadline)
|
||||
parent.deadline = deadline
|
||||
lock = threading.RLock()
|
||||
context = {}
|
||||
for block in request.extraction_context + request.blocks:
|
||||
prior = context.get(block.id)
|
||||
if prior is None or len(block.text) > len(prior['text']):context[block.id]=block.model_dump()
|
||||
|
||||
def save_node(node, state):
|
||||
with lock:
|
||||
node['checkpoint'] = deepcopy(state)
|
||||
if state.get('execution'):
|
||||
# Keep the existing UI contract: this is one current response,
|
||||
# never pretend that provisional tokens are completed source.
|
||||
parent.state['execution'] = deepcopy(state['execution'])
|
||||
parent.persist(True)
|
||||
|
||||
def process(node):
|
||||
focused = {b['id']:b['text'] for b in node['blocks']}
|
||||
# Exact focused blocks need no duplicate context; a split sentence still
|
||||
# receives its full original block. Only focused evidence may be cited.
|
||||
extra = [b for key,b in context.items() if focused.get(key)!=b['text']]
|
||||
body = request.model_dump()
|
||||
body.update(blocks=node['blocks'],extraction_context=extra)
|
||||
subrequest = BidStep.model_validate(body)
|
||||
child = BidProgress(subrequest,node['checkpoint'],lambda state:save_node(node,state),check=parent.check)
|
||||
child.deadline=deadline
|
||||
token=current_progress.set(child)
|
||||
try:
|
||||
return step(subrequest,invoke=invoke)
|
||||
finally:
|
||||
current_progress.reset(token)
|
||||
|
||||
while True:
|
||||
parent.check_active(True)
|
||||
pending=[node for node in plan['nodes'] if 'result' not in node]
|
||||
if not pending:break
|
||||
if deadline-time.monotonic()<5:raise JobDeferred()
|
||||
batch=pending[:2]
|
||||
with ThreadPoolExecutor(max_workers=2,thread_name_prefix='bid-extract') as executor:
|
||||
futures=[executor.submit(copy_context().run,process,node) for node in batch]
|
||||
errors=[]
|
||||
for node,future in zip(batch,futures):
|
||||
try:
|
||||
answer=future.result()
|
||||
with lock:
|
||||
if answer.get('split_required'):
|
||||
children=[dict(blocks=blocks,checkpoint={}) for blocks in _split(node['blocks'])]
|
||||
index=next(i for i,item in enumerate(plan['nodes']) if item is node)
|
||||
plan['nodes'][index:index+1]=children
|
||||
else:
|
||||
node['result']=answer
|
||||
node.pop('checkpoint',None)
|
||||
parent.persist(True)
|
||||
except Exception as exc:
|
||||
errors.append(exc)
|
||||
# Sibling success was persisted even if one call failed. Resume only the
|
||||
# unfinished sibling; never lose it or bypass pause/quality failures.
|
||||
if errors:raise next((exc for exc in errors if isinstance(exc,JobPaused)),errors[0])
|
||||
rows=[];conflicts=[]
|
||||
for node in plan['nodes']:
|
||||
rows.extend(node['result']['requirements'])
|
||||
conflicts.extend(node['result']['conflicts'])
|
||||
result=validate_result(request,dict(requirements=rows,conflicts=conflicts[:10],split_required=False))
|
||||
return dict(rule_version=RULE_VERSION,**result,extraction_complete=not conflicts)
|
||||
Reference in New Issue
Block a user