"""Build, country-fill, and merge PATSTAT 2023-2026 collection with legacy Stage3 master.""" import csv, gzip, json, re from collections import Counter, defaultdict from pathlib import Path csv.field_size_limit(100_000_000) ROOT=Path('/Users/deep1003/data3/webofscience_ai_global_export/bibtex/ai_policy_organized_20260619/patstat') RAW=ROOT/'online_sql_exports/patstat_2026_spring_ai_expanded_v2_full_fields' OUT=ROOT/'final_master_20260712'; OUT.mkdir(parents=True,exist_ok=True) LEGACY=ROOT/'final_three_datasets_20260622/patstat_keyword_precise_ai_20260704_stage3_person_fields_joined_to_ai_full.csv.gz' YEARS=(2023,2024,2025,2026) BITS={'KR':1,'US':2,'CN':4}; HAS=8 VALID=re.compile(r'^[A-Z]{2}$') TERMS={'KR':['SAMSUNG','LG','HYUNDAI','SK HYNIX','KIA','POSCO','ETRI','KAIST'],'US':['IBM','GOOGLE','MICROSOFT','INTEL','QUALCOMM','APPLE','AMAZON','META PLATFORMS','NVIDIA','GENERAL ELECTRIC'],'CN':['HUAWEI','TENCENT','ALIBABA','BAIDU','ZTE','XIAOMI','BYD','STATE GRID','PING AN']} PATS={c:[re.compile(rf'(?0 except: on=False if on: for out,src in [('person_ids','person_id'),('names','psn_name'),('countries','person_ctry_code'),('addresses','person_address'),('sectors','psn_sector')]: uniq_add(agg[a],f'{pref}_{out}',r.get(src) or (r.get('person_name') if out=='names' else '')) specs={'ipc':[('all_ipc_codes','ipc_class_symbol')],'cpc':[('all_cpc_codes','cpc_class_symbol')],'publication':[('publication_ids','pat_publn_id'),('publication_numbers','publn_nr'),('publication_dates','publn_date')],'priority':[('priority_appln_ids','prior_appln_id')]} for g,maps in specs.items(): for p in files(y,g): with p.open(encoding='utf-8-sig',newline='') as f: for r in csv.DictReader(f,delimiter=';'): a=r.get('app_id'); if a in master: for o,s in maps: uniq_add(agg[a],o,r.get(s)) added=['applicant_person_ids','applicant_names','applicant_countries','applicant_addresses','applicant_sectors','inventor_person_ids','inventor_names','inventor_countries','inventor_addresses','inventor_sectors','all_ipc_codes','all_cpc_codes','publication_ids','publication_numbers','publication_dates','priority_appln_ids'] out=OUT/f'patstat_ai_integrated_{y}.csv.gz' with gzip.open(out,'wt',encoding='utf-8',newline='') as f: w=csv.DictWriter(f,fieldnames=fields+added); w.writeheader() for a in sorted(master,key=int): r=master[a] for k in added:r[k]='; '.join(agg[a].get(k,[])) w.writerow(r) print('integrated',y,len(master),flush=True); return out,len(master),fields+added def main(): integ=[]; collection={}; schemas=[] for y in YEARS: p,n,s=integrate_year(y); integ.append(p); schemas.append(s) with gzip.open(p,'rt',encoding='utf-8',newline='') as f: for r in csv.DictReader(f): collection[r['app_id']]=r # family maps from direct applicant, else inventor doc=defaultdict(int); inp=defaultdict(int) before_country=Counter(); before_office=defaultdict(Counter) for r in collection.values(): m=mask(r.get('applicant_countries')) or mask(r.get('inventor_countries')) for c,b in BITS.items(): before_country[c]+=bool(m&b); before_office[r.get('patent_office','')][c]+=bool(m&b) if m: for k,d in [('docdb_family_id',doc),('inpadoc_family_id',inp)]: fid=(r.get(k) or '').strip() if fid and fid not in {'0','0.0'}: d[fid]|=m methods=Counter(); after_country=Counter(); after_office=defaultdict(Counter) for r in collection.values(): m=mask(r.get('applicant_countries')); method='applicant' if m else '' if not m: m=mask(r.get('inventor_countries')); method='inventor' if m else '' if not m: fid=(r.get('docdb_family_id') or '').strip(); m=doc.get(fid,0) if fid not in {'','0','0.0'} else 0 if not m: fid=(r.get('inpadoc_family_id') or '').strip(); m=inp.get(fid,0) if fid not in {'','0','0.0'} else 0 if m: method='family' if not m: m=nmask(r.get('applicant_names')); method='name' if m else '' if not m and r.get('patent_office') in BITS: m=HAS|BITS[r['patent_office']]; method='office' if not m: method='none' r['country_kr']=str(int(bool(m&1))); r['country_us']=str(int(bool(m&2))); r['country_cn']=str(int(bool(m&4))); r['country_fill_method']=method; r['patstat_release']='PATSTAT Online 2026 Spring'; r['record_source']='new_collection_2023_2026' methods[method]+=1 for c,b in BITS.items(): after_country[c]+=bool(m&b); after_office[r.get('patent_office','')][c]+=bool(m&b) new_schema=[] for s in schemas: for c in s+['country_kr','country_us','country_cn','country_fill_method','patstat_release','record_source']: if c not in new_schema:new_schema.append(c) newout=OUT/'patstat_ai_new_collection_2023_2026_integrated_country_filled.csv.gz' with gzip.open(newout,'wt',encoding='utf-8',newline='') as f: w=csv.DictWriter(f,fieldnames=new_schema);w.writeheader();w.writerows(collection.values()) # legacy priority: legacy values win on shared columns; new-only columns are appended and populated on matches with gzip.open(LEGACY,'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]; final_schema=legacy_schema+append final=OUT/'patstat_ai_complete_master_legacy_priority_20260712.csv.gz'; legacy_ids=set(); legacy_n=matched=0 with gzip.open(LEGACY,'rt',encoding='utf-8-sig',newline='') as src,gzip.open(final,'wt',encoding='utf-8',newline='') as dst: rd=csv.DictReader(src);w=csv.DictWriter(dst,fieldnames=final_schema);w.writeheader() for r in rd: a=r['app_id'];legacy_ids.add(a);legacy_n+=1; nr=collection.get(a) if nr: matched+=1 for c in append:r[c]=nr.get(c,'') if nr else '' if 'record_source' in append:r['record_source']='legacy_priority_overlap' if nr else 'legacy_only' w.writerow(r) new_only=0 for a,nr in collection.items(): if a in legacy_ids:continue row={c:'' for c in final_schema} for c,v in nr.items(): if c in row:row[c]=v row['record_source']='new_only';w.writerow(row);new_only+=1 report={'collection_status':'complete','years':list(YEARS),'new_integrated_rows':len(collection),'new_duplicate_app_ids_removed':sum(x[1] for x in [(0,0)]),'country_before':dict(before_country),'country_after':dict(after_country),'country_change':{c:after_country[c]-before_country[c] for c in BITS},'fill_methods':dict(methods),'office_before':{o:dict(v) for o,v in before_office.items()},'office_after':{o:dict(v) for o,v in after_office.items()},'legacy_rows':legacy_n,'overlap_rows_legacy_wins':matched,'new_only_rows':new_only,'final_rows':legacy_n+new_only,'legacy_columns':len(legacy_schema),'new_columns_added':append,'final_columns':len(final_schema),'outputs':{'new_integrated':str(newout),'complete_master':str(final)}} (OUT/'integration_report.json').write_text(json.dumps(report,indent=2),encoding='utf-8') print(json.dumps(report,indent=2),flush=True) if __name__=='__main__':main()