import csv,gzip,json,os from collections import Counter,defaultdict from pathlib import Path csv.field_size_limit(100_000_000) OUT=Path('/Users/deep1003/data3/webofscience_ai_global_export/bibtex/ai_policy_organized_20260619/patstat/final_master_20260712') LEG=Path('/Users/deep1003/data3/webofscience_ai_global_export/bibtex/ai_policy_organized_20260619/patstat/final_three_datasets_20260622/patstat_keyword_precise_ai_20260704_stage3_person_fields_joined_to_ai_full.csv.gz') FLAGS=Path('/Users/deep1003/data3/ai_stpi_presentation_202607/dispersion_analysis_20260712/data/patent_appid_country_flags.csv') NEW=OUT/'patstat_ai_new_collection_2023_2026_integrated_country_filled.csv.gz' FINAL=OUT/'patstat_ai_complete_master_legacy_priority_20260712.csv.gz'; TMP=OUT/'_complete_master.tmp.csv.gz' REP=OUT/'integration_report.json' new={} with gzip.open(NEW,'rt',encoding='utf-8',newline='') as f: r=csv.DictReader(f); new_schema=r.fieldnames for x in r:new[x['app_id']]=x with gzip.open(LEG,'rt',encoding='utf-8-sig',newline='') as f: legacy_schema=next(csv.reader(f)) append=[c for c in new_schema if c not in legacy_schema]; schema=legacy_schema+append seen=set(); total=matched=0; countries=Counter(); offices=defaultdict(Counter); methods=Counter() with gzip.open(LEG,'rt',encoding='utf-8-sig',newline='') as lf, open(FLAGS,encoding='utf-8',newline='') as ff, gzip.open(TMP,'wt',encoding='utf-8',newline='') as of: lr=csv.DictReader(lf); fr=csv.DictReader(ff); w=csv.DictWriter(of,fieldnames=schema);w.writeheader() for row,flag in zip(lr,fr): assert row['app_id']==flag['app_id']; a=row['app_id'];seen.add(a);total+=1;nr=new.get(a) if nr:matched+=1 for c in append:row[c]=nr.get(c,'') if nr else '' row['country_kr']=flag['kr'];row['country_us']=flag['us'];row['country_cn']=flag['cn'];row['country_fill_method']=flag['fill_method'];row['patstat_release']='PATSTAT Online 2026 Spring';row['record_source']='legacy_priority_overlap' if nr else 'legacy_only' methods[row['country_fill_method']]+=1 for c,k in [('KR','country_kr'),('US','country_us'),('CN','country_cn')]:countries[c]+=int(row[k]);offices[row.get('patent_office','')][c]+=int(row[k]) w.writerow(row) new_only=0 for a,row in new.items(): if a in seen:continue out={c:'' for c in schema} for c,v in row.items(): if c in out:out[c]=v out['record_source']='new_only';w.writerow(out);new_only+=1;methods[out['country_fill_method']]+=1 for c,k in [('KR','country_kr'),('US','country_us'),('CN','country_cn')]:countries[c]+=int(out[k]);offices[out.get('patent_office','')][c]+=int(out[k]) os.replace(TMP,FINAL) rep=json.load(open(REP));rep.update({'final_rows':total+new_only,'overlap_rows_legacy_wins':matched,'new_only_rows':new_only,'final_country_totals':dict(countries),'final_fill_method_counts':dict(methods),'final_office_country_totals':{o:dict(v) for o,v in offices.items()},'final_country_flags_note':'Legacy rows use legacy-derived country flags; new-only rows use new-collection-derived flags. Existing rows win on overlap.'}) REP.write_text(json.dumps(rep,indent=2),encoding='utf-8') print(json.dumps({k:rep[k] for k in ['final_rows','overlap_rows_legacy_wins','new_only_rows','final_country_totals','final_fill_method_counts']},indent=2))