"""Fill selected blank legacy fields from new PATSTAT source while preserving nonblank legacy values.""" import csv,gzip,json,os from collections import defaultdict,Counter from pathlib import Path csv.field_size_limit(100_000_000) BASE=Path('/Users/deep1003/data3/webofscience_ai_global_export/bibtex/ai_policy_organized_20260619/patstat') OUT=BASE/'final_master_20260712'; RAW=BASE/'online_sql_exports/patstat_2026_spring_ai_expanded_v2_full_fields' FINAL=OUT/'patstat_ai_complete_master_legacy_priority_20260712.csv.gz';TMP=OUT/'_coalesce.tmp.csv.gz' NEW=OUT/'patstat_ai_new_collection_2023_2026_integrated_country_filled.csv.gz' YEARS=(2023,2024,2025,2026) def add(d,k,v): v=(v or '').strip() if v and v not in d[k]:d[k].append(v) def code_count(v): return str(len({x.strip() for x in (v or '').split(';') if x.strip()})) if (v or '').strip() else '' new={} with gzip.open(NEW,'rt',encoding='utf-8',newline='') as f: for r in csv.DictReader(f):new[r['app_id']]={'all_ipc_codes':r.get('all_ipc_codes',''),'all_cpc_codes':r.get('all_cpc_codes','')} people=defaultdict(lambda:defaultdict(list)) for y in YEARS: for p in sorted(RAW.glob(f'patstat_ai_person_{y}_{y}_rows_*.csv')): with p.open(encoding='utf-8-sig',newline='') as f: for r in csv.DictReader(f,delimiter=';'): a=r.get('app_id') if a not in new:continue for pref,seq in [('applicant','applt_seq_nr'),('inventor','invt_seq_nr')]: try:on=int(r.get(seq) or 0)>0 except:on=False if not on:continue add(people[a],f'{pref}_std_ids',r.get('doc_std_name_id')) add(people[a],f'{pref}_countries',r.get('person_ctry_code')) add(people[a],f'{pref}_addresses',r.get('person_address')) name=r.get('doc_std_name') or r.get('psn_name') or r.get('person_name') or '' info='|'.join([r.get('person_id','').strip(),name.strip(),r.get('person_ctry_code','').strip(),r.get('person_address','').strip()]).rstrip('|') add(people[a],f'{pref}_info',info) for a,x in new.items(): p=people.get(a,{}) x.update({'applicant_info':'; '.join(p.get('applicant_info',[])),'applicant_std_name_ids':'; '.join(p.get('applicant_std_ids',[])),'applicant_ctry_codes':'; '.join(p.get('applicant_countries',[])),'inventor_info':'; '.join(p.get('inventor_info',[])),'inventor_ctry_codes':'; '.join(p.get('inventor_countries',[])),'inventor_addresses':'; '.join(p.get('inventor_addresses',[]))}) targets=['all_ipc_codes','ipc_count','all_cpc_codes','cpc_count','applicant_info','applicant_std_name_ids','applicant_ctry_codes','inventor_info','inventor_ctry_codes','inventor_addresses'] filled=Counter();before=Counter();after=Counter();rows=0 with gzip.open(FINAL,'rt',encoding='utf-8',newline='') as src,gzip.open(TMP,'wt',encoding='utf-8',newline='') as dst: rd=csv.DictReader(src);w=csv.DictWriter(dst,fieldnames=rd.fieldnames);w.writeheader() for r in rd: rows+=1;n=new.get(r['app_id'],{}) for c in targets:before[c]+=bool((r.get(c) or '').strip()) for c in ['all_ipc_codes','all_cpc_codes','applicant_info','applicant_std_name_ids','applicant_ctry_codes','inventor_info','inventor_ctry_codes','inventor_addresses']: if not (r.get(c) or '').strip() and (n.get(c) or '').strip():r[c]=n[c];filled[c]+=1 if not (r.get('ipc_count') or '').strip() and (r.get('all_ipc_codes') or '').strip():r['ipc_count']=code_count(r['all_ipc_codes']);filled['ipc_count']+=1 if not (r.get('cpc_count') or '').strip() and (r.get('all_cpc_codes') or '').strip():r['cpc_count']=code_count(r['all_cpc_codes']);filled['cpc_count']+=1 for c in targets:after[c]+=bool((r.get(c) or '').strip()) w.writerow(r) os.replace(TMP,FINAL) report={'rows':rows,'rule':'preserve existing nonblank; fill blank from new PATSTAT source; derive counts from final code lists','targets':targets,'before_nonempty':dict(before),'filled_rows':dict(filled),'after_nonempty':dict(after),'remaining_missing':{c:rows-after[c] for c in targets}} (OUT/'coalesced_fields_report.json').write_text(json.dumps(report,indent=2),encoding='utf-8') print(json.dumps(report,indent=2))