Download code/prepare_confirmation_source_reporting_readers.py from dfdu233/MeningiomaBench: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/dfdu233/MeningiomaBench/resolve/main/code/prepare_confirmation_source_reporting_readers.py
- Command line
-
hf download hf://datasets/dfdu233/MeningiomaBench/code/prepare_confirmation_source_reporting_readers.py
-
curl -L -o prepare_confirmation_source_reporting_readers.py https://huggingface.co/datasets/dfdu233/MeningiomaBench/resolve/main/code/prepare_confirmation_source_reporting_readers.py
10.6 kB
| """Freeze seven-method source-reporting confirmation inputs before answer calls.""" | |
| import json | |
| import re | |
| import sqlite3 | |
| import sys | |
| import argparse | |
| from pathlib import Path | |
| import tiktoken | |
| from prepare_confirmation_source_cohort import OUT, read, digest | |
| from prepare_openqa_dev161_equal_budget import freeze, sha | |
| DEST=OUT/'confirmation_candidates_prospective_v1' | |
| GRAPH=OUT/'packed_graph_common42_low_reasoning_bounded_retry_v3' | |
| METHODS=['no_rag','bm25_identified','native_hybrid_source_units', | |
| 'routed_native_hybrid_source_units','packed_graph_candidate_question_bm25_source_units', | |
| 'packed_graph_source12000_candidate_question_bm25_source_units','oracle_reference_units_upper_bound'] | |
| def main(): | |
| global DEST,METHODS | |
| parser=argparse.ArgumentParser();parser.add_argument('--validation-source18',action='store_true');args=parser.parse_args() | |
| if args.validation_source18: | |
| DEST=OUT/'source18_verifier_validation_prospective_v1' | |
| METHODS=[m for m in METHODS if m!='packed_graph_candidate_question_bm25_source_units'] | |
| n=8 if args.validation_source18 else 7 | |
| prefix='source18_' if args.validation_source18 else 'confirmation_' | |
| queries=read(DEST/f'source_only_reader_queries{n}_local_only.jsonl');assert len(queries)==n | |
| corpus_path=OUT/'numeric_rag_development_smoke_v2/corpus_source_only_local.jsonl' | |
| units={r['source_id']:r for r in read(corpus_path)} | |
| native=read(DEST/f'native_rankings{2*n}_source_only_local.jsonl');assert len(native)==2*n | |
| marker=json.loads((DEST/f'native_rankings{2*n}_complete.json').read_text()) | |
| assert marker['output_sha256']==digest(DEST/f'native_rankings{2*n}_source_only_local.jsonl') | |
| rank={(r['id'],r['method']):list(dict.fromkeys(x['source_id'] for x in r['sources'])) for r in native} | |
| tokenize=lambda text:' '.join(re.findall(r'[a-z0-9]+',text.lower())) | |
| db=sqlite3.connect(':memory:');db.execute('CREATE VIRTUAL TABLE sources USING fts5(source_id UNINDEXED,title,body)') | |
| for k,u in units.items():db.execute('INSERT INTO sources VALUES(?,?,?)',(k,tokenize(u['title']),tokenize(u['text']))) | |
| def lexical(text,weights): | |
| query=' OR '.join('"'+x+'"' for x in list(dict.fromkeys(tokenize(text).split()))[:120]) | |
| return [r[0] for r in db.execute('SELECT source_id FROM sources WHERE sources MATCH ? ORDER BY bm25(sources,'+weights+'),source_id',(query,))] | |
| articles={r['source_id']:r for r in read(GRAPH/'corpus.jsonl')} | |
| pre={r['chunk_id']:r for r in read(OUT/'shared42_source_index_preflight_v1/packed_chunk_unit_provenance_local.jsonl')} | |
| from openqa_graph_source_adapter import BEGIN, END, SOURCE_ROW | |
| sys.path.insert(0,'/home/dbw/MedicalGraphRAG-deploy/MedicalGraphRAG-linux-x86_64/app') | |
| from nano_graphrag._utils import list_of_list_to_csv | |
| chunks=json.loads((GRAPH/'graph/kv_store_text_chunks.json').read_text()) | |
| lookup={list_of_list_to_csv([[0,r['content']]])[4:-1]:k for k,r in chunks.items()};assert len(lookup)==len(chunks) | |
| expanded_protocol=json.loads((GRAPH/'expanded_source12000_development_protocol.json').read_text()) | |
| assert digest(GRAPH/'official_transport_usage.jsonl')==expanded_protocol['official_transport_sha256_before'] | |
| graph_rows={} | |
| for limit in ([12000] if args.validation_source18 else [4000,12000]): | |
| path=GRAPH/f'{prefix}source{limit}_contexts{n}_local_only.jsonl' | |
| marker=json.loads((GRAPH/f'{prefix}source{limit}_queries{n}_complete.json').read_text()) | |
| assert marker['questions']==n and marker['query_source_token_limit_override']==limit | |
| graph_rows[limit]={r['id']:r for r in read(path)} | |
| assert set(graph_rows[limit])=={q['id'] for q in queries} | |
| graph_candidates=[] | |
| for q in queries: | |
| ident=q['id'];full=f"Article: {q['study']['title']} PMID:{q['study']['pmid']}. Question: {q['question']}" | |
| rank[ident,'no_rag']=[];rank[ident,'bm25_identified']=lexical(full,'0,1,1')[:8] | |
| priority={k:n for n,k in enumerate(lexical(q['question'],'0,0,1'))} | |
| for limit,method in [(4000,'packed_graph_candidate_question_bm25_source_units'),(12000,'packed_graph_source12000_candidate_question_bm25_source_units')]: | |
| if method not in METHODS:continue | |
| section=graph_rows[limit][ident]['context'].partition('-----Sources-----')[2].rstrip() | |
| if not section: | |
| chunk_ids=[] | |
| else: | |
| assert section.startswith(BEGIN) and section.endswith(END) | |
| fields=SOURCE_ROW.split(section[len(BEGIN):-len(END)]);assert not fields[0].strip() | |
| chunk_ids=[] | |
| for text in fields[1:]: | |
| text=text.rstrip();assert text.endswith('"') and text[:-1] in lookup | |
| chunk_ids.append(lookup[text[:-1]]) | |
| candidates=[] | |
| for cid in chunk_ids: | |
| c=pre[cid] | |
| for span in articles[c['article_source_id']]['source_unit_spans']: | |
| uid=span['source_unit_id'];u=units[uid] | |
| body=span['start_byte']+len(f"SourceID:{uid}\nTitle: {u['title']}\nPassage: ".encode()) | |
| if min(c['end_byte'],span['end_byte'])>max(c['start_byte'],body) and uid not in candidates:candidates.append(uid) | |
| rank[ident,method]=sorted(candidates,key=lambda k:priority.get(k,len(priority)+candidates.index(k)))[:8] | |
| graph_candidates.append({'id':ident,'method':method,'graph_chunk_ids':chunk_ids,'candidate_source_ids':candidates}) | |
| # Non-oracle selections are frozen BEFORE opening the candidate target/quote file. | |
| nonoracle_path=DEST/f'nonoracle_rankings{n*(len(METHODS)-1)}_before_gold_local.jsonl' | |
| freeze(nonoracle_path,''.join(json.dumps({'id':i,'method':m,'source_ids':rank[i,m],'gold_used_in_selection':False})+'\n' for i,m in rank)) | |
| freeze(DEST/f'graph_candidates{len(graph_candidates)}_before_gold_local.jsonl',''.join(json.dumps(r)+'\n' for r in graph_candidates)) | |
| items={r['id']:r for r in read(DEST/('reader_items8_local_only.jsonl' if args.validation_source18 else 'source_reporting_selected7_local_only.jsonl'))} | |
| for q in queries: | |
| item=items[q['id']];ids=[] | |
| for ev in item['evidence']: | |
| matches=sorted(k for k,u in units.items() if u['paper_id']==item['pmid'] and ev['quote'] in u['text']) | |
| if not matches:raise ValueError('Oracle quotation cannot map exactly to source unit: '+q['id']) | |
| if matches[0] not in ids:ids.append(matches[0]) | |
| rank[q['id'],METHODS[-1]]=ids | |
| encoder=tiktoken.encoding_for_model('gpt-4o') | |
| old=read(OUT/'study_bound_numeric_binding_development_v2/common42_hybrid_plain_reader_development_v2/requests68_local_only.jsonl') | |
| prompt=old[0]['messages'][0]['content'];assert all(r['messages'][0]['content']==prompt for r in old) | |
| def render(ids):return '\n\n'.join(f"[E{n}] SourceID:{k} {units[k]['title']}\n{units[k]['text']}" for n,k in enumerate(ids,1)) | |
| grids={name:[] for name in ['primary','matched_length']};coverage=[] | |
| for q in queries: | |
| ident=q['id'];raw={m:render(rank[ident,m]) for m in METHODS};lengths={m:len(encoder.encode(t)) for m,t in raw.items()} | |
| cap=min([6000]+[lengths[m] for m in METHODS[1:-1] if lengths[m]]) | |
| for _ in range(20): | |
| sizes={len(encoder.encode(encoder.decode(encoder.encode(raw[m])[:cap],errors='ignore'))) for m in METHODS[1:-1] if lengths[m]} | |
| if sizes=={cap}:break | |
| cap=min(sizes) | |
| else:raise ValueError('Unstable matched evidence token cap') | |
| for grid in grids: | |
| for method in METHODS: | |
| limit=cap if grid=='matched_length' and method in METHODS[1:-1] else 6000 | |
| evidence=encoder.decode(encoder.encode(raw[method])[:limit],errors='ignore') | |
| payload={'study':q['study'],'question':q['question'],'evidence':evidence} | |
| row={'id':ident,'method':method,'track':'prospective_source_reporting_'+grid,'option_letters':[], | |
| 'context_sha256':sha(evidence.encode()),'context_tokens_unified':len(encoder.encode(evidence)), | |
| 'response_protocol':'identified_numeric_prompt_only_plain_v2', | |
| 'messages':[{'role':'system','content':prompt},{'role':'user','content':json.dumps(payload,ensure_ascii=False)}]} | |
| grids[grid].append(row) | |
| coverage.append({'id':ident,'grid':grid,'method':method,'actual_evidence_tokens':row['context_tokens_unified'], | |
| 'source_ids':rank[ident,method],'annotated_quotes':len(items[ident]['evidence']), | |
| 'complete_annotated_quotes_visible':sum(e['quote'] in evidence for e in items[ident]['evidence']), | |
| 'all_annotated_quotes_visible':all(e['quote'] in evidence for e in items[ident]['evidence'])}) | |
| for name,rows in grids.items(): | |
| folder=DEST/('reader_'+name+'_v1');folder.mkdir(exist_ok=True) | |
| requestpath=folder/f'requests{n*len(METHODS)}_local_only.jsonl' | |
| freeze(requestpath,''.join(json.dumps(r)+'\n' for r in rows)) | |
| freeze(folder/'protocol.json',json.dumps({'scope':'Prospective source18automatic silver validation:6source-reporting positives/4families+2same-sourcecohortcontrols; NOT expert clinical validation.' if args.validation_source18 else 'Prospective automatic silver source-reporting confirmation, seven questions/sixfamilies; NOT expert clinical validation.', | |
| 'questions':n,'methods':METHODS,'requests_sha256':digest(requestpath), | |
| 'source_selection_sha256':digest(DEST/('selection_frozen_before_readers.json' if args.validation_source18 else 'source_scope_selection_frozen_before_readers_v1.json')), | |
| 'corpus_sha256':digest(corpus_path),'nonoracle_rankings_sha256':digest(nonoracle_path), | |
| 'grid':name,'max_evidence_tokens':6000,'max_source_units':8,'oracle_is_label_informed_upper_bound':True, | |
| 'same_messages_and_evidence_bytes_for_all_models':True,'max_completion_tokens_or_local_max_tokens':1000, | |
| 'luna_reasoning_effort':'low','luna_temperature':'provider_default','local_temperature':0, | |
| 'response_schema_enforced_by_API':False,'source_only_graph_query_new_API_calls':0, | |
| 'expert_reviews':0,'new_main_benchmark_accepted_questions':0},indent=2)+'\n') | |
| freeze(DEST/f'source_reporting_context_coverage{2*n*len(METHODS)}_before_readers.jsonl',''.join(json.dumps(r)+'\n' for r in coverage)) | |
| print('Frozen',n*len(METHODS),'primary+',n*len(METHODS),'matched-length requests, no reader calls') | |
| if __name__=='__main__':main() | |