"""One prospective source-reporting QA pass; no accepted labels or reader calls.""" import argparse import copy from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED import json from pathlib import Path import tiktoken from prepare_confirmation_source_cohort import OUT, read, digest from prepare_openqa_dev161_equal_budget import freeze, sha from construct_identified_numeric_development_v4 import PROMPT as OLD_PROMPT, FORMAT as OLD_FORMAT, validate, prospective_question_contract_flags from study_population_witness_gate import counts DEST=OUT/'source18_verifier_validation_prospective_v1' SCOPES=['primary_human','case_series','single_case','molecular_reanalysis','review_synthesis'] POP_ROLES=['full_study','analysis_subset','validation_dataset','synthesized_studies','synthesized_patients','case'] PROMPT=OLD_PROMPT.replace('directly reported PRIMARY HUMAN STUDY quantitative findings','directly reported meningioma SOURCE-REPORTING quantitative findings').replace('automatic SILVER development construction','automatic SILVER candidate construction for a prospective source-heldout validation').replace('cited third-party findings, ','individual cited third-party findings, ') PROMPT+=''' Distinguish source_scope: primary_human, case_series, single_case, molecular_reanalysis, review_synthesis. For a review/meta-synthesis, use only the authors' explicit aggregate/synthesis results, not an individual cited study or introductory background statistic. Molecular public-data reanalysis and review patients are not new independent clinical cohorts. State the actual reporting role in the question and label population_role as full_study, analysis_subset, validation_dataset, synthesized_studies, synthesized_patients, or case. Do not turn an illustrative case or pooled review into a primary cohort. If the paper concerns a diagnostic mimic without an applicable actual meningioma quantity, return zero items. If a cohort/sample size is explicitly source-supported and relevant, express that condition in the question using digit-form integers WITHOUT thousands separators; provide a verbatim quote for it. Do not infer or force a cohort size when the source does not state one. Prefer a full-study question and a different explicitly reported subgroup/validation question when both are unambiguous, but return fewer or zero rather than inventing. Do not ask for the same population count already disclosed in the question. This is still source reporting, never clinical advice or expert gold. Source text and article_type alone do not certify primary clinical scope.''' FORMAT=copy.deepcopy(OLD_FORMAT) ITEM=FORMAT['json_schema']['schema']['properties']['items']['items'] ITEM['properties'].update(source_scope={'type':'string','enum':SCOPES},population_role={'type':'string','enum':POP_ROLES}) ITEM['required']+=['source_scope','population_role'] FORMAT['json_schema']['name']='source18_genre_condition_quantities' def main(): ap=argparse.ArgumentParser();ap.add_argument('--generate',action='store_true');args=ap.parse_args() source_protocol=json.loads((DEST/'protocol_before_candidate_construction.json').read_text()) assert digest(DEST/'source_manifest18_local_only.jsonl')==source_protocol['source_manifest_sha256'] sources=read(DEST/'source_manifest18_local_only.jsonl');assert len(sources)==18 encoder=tiktoken.encoding_for_model('gpt-4o');rows=[] for source in sources: path=OUT/'extracted_sources_v2_local_only'/(source['pmcid']+'.json');assert digest(path)==source['source_extraction_sha256'] article=json.loads(path.read_text());blocks=[] def priority(p): section=' '.join(p['section_path']).lower() return 0 if 'abstract' in section else 1 if 'result' in section else 2 if 'method' in section else 3 for paragraph in sorted(article['narrative'],key=priority): block={'block_id':'B'+str(len(blocks)+1),'section':paragraph['section_path'],'text':paragraph['text']} if len(encoder.encode(json.dumps(blocks+[block],ensure_ascii=False)))<=6000:blocks.append(block) study={k:source[k] for k in ['pmid','doi','title','publication_date']} messages=[{'role':'system','content':PROMPT},{'role':'user','content':json.dumps({'source_blocks':blocks,'study':study,'article_type':article['article_type']},ensure_ascii=False)}] request={'messages':messages,'response_format':FORMAT,'model':'gpt-6-luna','max_completion_tokens':6000,'reasoning_effort':'low','temperature':'provider_default'} rows.append({**source,'source_family_id':'SOURCE18:'+source['pmcid'],'split':'prospective_source18_validation', 'messages':messages,'request_sha256':sha(json.dumps(request,sort_keys=True).encode())}) requestpath=DEST/'construction_requests18_local_only.jsonl' freeze(requestpath,''.join(json.dumps(r)+'\n' for r in rows)) snapshots=DEST/'construction_code_snapshots';snapshots.mkdir(exist_ok=True);hashes={} for name in ['construct_source18_validation_candidates.py','construct_identified_numeric_development_v4.py','source_numeric_representation_v4.py','score_confirmation_numeric_targets.py','score_confirmation_numeric_targets_v2.py','generate_confirmation_development_pilot.py']: path=Path(__file__).resolve().parent/name;freeze(snapshots/name,path.read_text());hashes[name]=digest(path) freeze(DEST/'construction_protocol_frozen_before_generation.json',json.dumps({'scope':'One prospective candidate construction pass over all18frozen sources. Not accepted QA, final reader inputs, or expert clinical gold.', 'parent_protocol_sha256':digest(DEST/'protocol_before_candidate_construction.json'),'requests_sha256':digest(requestpath), 'code_sha256':hashes,'model':'gpt-6-luna','endpoint':'https://api.openai.com/v1','reasoning_effort':'low', 'temperature':'provider_default','max_completion_tokens':6000,'source_block_tokens':6000,'response_format':FORMAT, 'selection':'All18manifestorder/max2items/source, one successful construction pass,4transportworkers. Retainzero/failures; no qualityquota/refill or reader-outcome selection.', 'change_from_old24sourceconstruction':'SameV4conditionwitness/numerictargetschema andguards; explicit genre/population-role fields and genre-aware source-reporting eligibility. Review aggregate/molecular reanalysis separate, never primaryclinical byassumption.', 'quality':'Frozen old literal/numeric/pointer/question-contract checks then source-scope review before reader calls. Machine eligibility not semantic gold. Candidate count does not increase main1857QA.', 'accepted_new_questions':0,'expert_reviews':0,'reader_results':0},indent=2)+'\n') if not args.generate:print('Frozen18sourceconstructionrequests;0APIcalls');return import generate_confirmation_development_pilot as transport transport.SCHEMA=FORMAT;path=DEST/'construction_generation_local_only.jsonl';done={} if path.exists(): for row in read(path): assert row['pmid'] not in done;done[row['pmid']]=row if row.get('error'):raise RuntimeError('Saved failed source request retained; inspect before retry') for row in rows: if row['pmid'] in done:assert done[row['pmid']]['request_sha256']==row['request_sha256'] todo=iter(r for r in rows if r['pmid'] not in done);failed=False with path.open('a') as stream,ThreadPoolExecutor(max_workers=4) as pool: futures=set() while True: while not failed and len(futures)<4: row=next(todo,None) if row is None:break futures.add(pool.submit(transport.generate_row,row,max_completion_tokens=6000,reasoning_effort='low')) if not futures:break ready,futures=wait(futures,return_when=FIRST_COMPLETED) for future in ready: result=future.result();stream.write(json.dumps(result)+'\n');stream.flush() done[result['pmid']]=result;failed=failed or bool(result.get('error')) print('CONSTRUCTED',len(done),'/18','error',result.get('error'),flush=True) if failed:raise RuntimeError('Construction transport/shape error retained; running responses drained, no unrecorded automatic retry') assert len(done)==18;candidates=[] for row in rows: for index,item in enumerate(done[row['pmid']]['items']): candidate=validate(row,item,index);candidate.update(id='SOURCE18:'+row['pmid']+':'+str(index+1), split='prospective_source18_validation',prospective_contract_flags=prospective_question_contract_flags(item), population_count_mentions=counts(item['question'],True),accepted=False,status='candidate_pending_source_scope_review_before_readers') candidate['mechanically_eligible']=not(candidate['literal_and_pointer_flags'] or candidate['prospective_contract_flags']);candidates.append(candidate) freeze(DEST/'candidate_versions_local_only.jsonl',''.join(json.dumps(r)+'\n' for r in candidates)) summary={'scope':'Source18candidateconstruction only, no accepted newbenchmarklabels or readeranswers.', 'source_responses':len(done),'candidate_versions':len(candidates),'mechanically_eligible':sum(r['mechanically_eligible'] for r in candidates), 'zero_item_sources':[r['pmid'] for r in rows if not done[r['pmid']]['items']], 'provider_logged_tokens':sum((r.get('usage') or {}).get('total_tokens',0) for r in done.values()), 'accepted_new_questions':0,'expert_reviews':0,'new_reader_answers':0} freeze(DEST/'construction_summary.json',json.dumps(summary,indent=2)+'\n');print(json.dumps(summary),flush=True) if __name__=='__main__':main()