"""Reproduce the charts in ALENZA CODES' December 2026 analysis pieces.

Usage:  python alenza-analysis-2026-12.py DATA_DIR OUT_DIR
Python 3.11+, pandas, numpy, openpyxl.

Inputs to place in DATA_DIR (all public):
  fedreg2026.json          Federal Register API, documents matching "artificial intelligence",
                           published 2026-01-01 to 2026-12-03 (https://www.federalregister.gov/developers/documentation/api/v1)
  fedreg2025_counts.json   Monthly 2025 counts from the same query, {"1": n, ..., "12": n}
  fda-ai-devices.xlsx      FDA "Artificial Intelligence-Enabled Medical Devices" list
  canadabuys-open-tenders.csv   CanadaBuys open tender notices (Open Government Licence - Canada)
  kaggle/<owner>_<dataset>/...  The Kaggle datasets named in each post, unzipped

This script produces the Federal Register, FDA, CanadaBuys, Arena, salary, synthetic-data audit,
job-vacancy, wage and education charts. The Toronto language and OpenAlex charts were computed
separately from the sources named on those pages; their CSVs are published beside each chart.
Licence: CC BY 4.0, ALENZA CODES.
"""
import sys, os
DATA_DIR = sys.argv[1] if len(sys.argv) > 1 else "data"
OUT_DIR = sys.argv[2] if len(sys.argv) > 2 else "out"
os.makedirs(OUT_DIR, exist_ok=True)
import json, re, collections, pandas as pd, numpy as np, os, calendar
OUT=os.path.join(OUT_DIR,"charts.json")
CSV=OUT_DIR+"/"
C={}; F={}  # charts, facts
def save(cid, spec, df):
    df.to_csv(CSV+cid+".csv", index=False); spec["csv"]=f"/assets/blog/data/{cid}.csv"; C[cid]=spec
MON=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
K=os.path.join(DATA_DIR,"kaggle")+"/"
# ---- Federal Register
docs=json.load(open(os.path.join(DATA_DIR,"fedreg2026.json"))); c25=json.load(open(os.path.join(DATA_DIR,"fedreg2025_counts.json")))
for d in docs: d["m"]=int(d["publication_date"][5:7])
m26=collections.Counter(d["m"] for d in docs)
df=pd.DataFrame({"month":MON,"2025":[c25[str(i)] for i in range(1,13)],"2026":[m26.get(i,0) for i in range(1,13)]})
save("fr_monthly",{"type":"bar","title":"US Federal Register documents mentioning \"artificial intelligence\", by month","x":MON,"series":[{"name":"2025","values":df["2025"].tolist()},{"name":"2026 (Dec to date)","values":df["2026"].tolist()}],"y":"Documents","source":"Federal Register API, retrieved 3 Dec 2026"},df)
F["fr_total26"]=len(docs); F["fr_total25"]=sum(c25.values())
ag=collections.Counter(a.get("name") or a.get("raw_name") for d in docs for a in d["agencies"])
top=ag.most_common(12); dfa=pd.DataFrame(top,columns=["agency","documents"])
save("fr_agency",{"type":"hbar","title":"Which US agencies published most about AI in 2026","x":[a for a,_ in top],"series":[{"name":"Documents","values":[n for _,n in top]}],"y":"Documents (2026 to date)","source":"Federal Register API, retrieved 3 Dec 2026; a document can list more than one agency"},dfa)
ty=collections.Counter(d["type"] for d in docs); dft=pd.DataFrame(ty.most_common(),columns=["type","documents"])
save("fr_type",{"type":"hbar","title":"2026 AI documents by type","x":dft.type.tolist(),"series":[{"name":"Documents","values":dft.documents.tolist()}],"y":"Documents","source":"Federal Register API, retrieved 3 Dec 2026"},dft)
F["fr_type"]=dict(ty)
for i in range(1,13):
    agm=collections.Counter(a.get("name") or a.get("raw_name") for d in docs if d["m"]==i for a in d["agencies"]).most_common(6)
    titles=[(d["title"],d["html_url"],d["type"]) for d in docs if d["m"]==i]
    F[f"fr_m{i}"]={"n":m26.get(i,0),"n25":c25[str(i)],"agencies":agm,"titles":titles[:40]}
    if agm:
        dm=pd.DataFrame(agm,columns=["agency","documents"])
        save(f"fr_m{i}",{"type":"hbar","title":f"{calendar.month_name[i]} 2026: agencies publishing on AI","x":dm.agency.tolist(),"series":[{"name":"Documents","values":dm.documents.tolist()}],"y":"Documents","source":"Federal Register API, retrieved 3 Dec 2026"},dm)
# ---- FDA
fda=pd.read_excel(os.path.join(DATA_DIR,"fda-ai-devices.xlsx")); fda["date"]=pd.to_datetime(fda["Date of Final Decision"]); fda["year"]=fda.date.dt.year
by=fda.groupby("year").size().reset_index(name="devices"); by=by[by.year>=1995]
save("fda_year",{"type":"bar","title":"FDA-authorised AI-enabled medical devices, by year of decision","x":[str(y) for y in by.year],"series":[{"name":"Devices","values":by.devices.tolist()}],"y":"Devices","source":"FDA AI-Enabled Medical Devices list (through decisions dated "+fda.date.max().strftime("%-d %b %Y")+")","note":"2026 is a partial year."},by)
p=fda["Panel (Lead)"].value_counts().head(10); dp=p.reset_index(); dp.columns=["panel","devices"]
save("fda_panel",{"type":"hbar","title":"AI-enabled devices by review panel (all years)","x":dp.panel.tolist(),"series":[{"name":"Devices","values":dp.devices.tolist()}],"y":"Devices","source":"FDA AI-Enabled Medical Devices list"},dp)
co=fda["Company"].value_counts().head(10); dc=co.reset_index(); dc.columns=["company","devices"]
save("fda_company",{"type":"hbar","title":"Companies with the most AI-enabled device authorisations","x":dc.company.tolist(),"series":[{"name":"Devices","values":dc.devices.tolist()}],"y":"Devices","source":"FDA AI-Enabled Medical Devices list"},dc)
F["fda_total"]=len(fda); F["fda_max"]=fda.date.max().strftime("%-d %B %Y"); F["fda_rad_share"]=round(100*(fda["Panel (Lead)"]=="Radiology").mean(),1)
F["fda_by_year"]=dict(zip(by.year.astype(str),by.devices)); F["fda_2026"]=int((fda.year==2026).sum())
sub=fda["Submission Number"].str[:1].value_counts(); F["fda_k_share"]=round(100*sub.get("K",0)/len(fda),1)
# ---- CanadaBuys
t=pd.read_csv(os.path.join(DATA_DIR,"canadabuys-open-tenders.csv"),encoding="utf-8-sig",low_memory=False)
pat=re.compile(r"\b((?i:artificial intelligence|machine learning|generative ai|large language model|chatbot|automated decision)|LLM|AI)\b")
txt=(t["title-titre-eng"].fillna("")+" "+t["tenderDescription-descriptionAppelOffres-eng"].fillna(""))
ai=t[txt.map(lambda s: bool(pat.search(s)))].copy()
ai["close"]=ai["tenderClosingDate-appelOffresDateCloture"].fillna("").str[:10]
ai=ai[(ai.close=="")|(ai.close>="2026-12-03")]
b=ai["contractingEntityName-nomEntitContractante-eng"].fillna("Unknown").str.strip().value_counts().head(12); db=b.reset_index(); db.columns=["buyer","open_notices"]
save("cb_buyer",{"type":"hbar","title":"Open CanadaBuys notices mentioning AI, by buyer","x":db.buyer.tolist(),"series":[{"name":"Open notices","values":db.open_notices.tolist()}],"y":"Open notices","source":"CanadaBuys open tender notices, retrieved 3 Dec 2026 (Open Government Licence – Canada); keyword match"},db)
nt=ai["noticeType-avisType-eng"].fillna("Unknown").value_counts(); dn=nt.reset_index(); dn.columns=["notice_type","open_notices"]
save("cb_type",{"type":"hbar","title":"Open AI-related notices by type","x":dn.notice_type.tolist(),"series":[{"name":"Open notices","values":dn.open_notices.tolist()}],"y":"Open notices","source":"CanadaBuys, retrieved 3 Dec 2026"},dn)
F["cb_total_open"]=len(t); F["cb_ai"]=len(ai)
F["cb_titles"]=ai[["title-titre-eng","contractingEntityName-nomEntitContractante-eng","close"]].head(40).values.tolist()
# ---- Arena
a=pd.read_csv(K+"riyagarg0314_ai-model-arena-rankings-2023-2026/ai_model_arena_rankings.csv.csv")
a=a[(a.subset=="text")&(a.category=="overall")].copy(); a["d"]=pd.to_datetime(a.leaderboard_publish_date)
a["open"]=~a.license.fillna("Proprietary").str.contains("Proprietary")
g=a.groupby("d").apply(lambda x: pd.Series({"top_any":x.rating.max(),"top_open":x[x.open].rating.max(),"top_prop":x[~x.open].rating.max(),"leader":x.loc[x.rating.idxmax(),"model_name"],"leader_org":x.loc[x.rating.idxmax(),"organization"]})).reset_index()
g["month"]=g.d.dt.to_period("M").astype(str); gm=g.groupby("month").last().reset_index()
save("arena_gap",{"type":"line","title":"Top Arena rating: best proprietary vs best open-licence model (text)","x":gm.month.tolist(),"series":[{"name":"Best proprietary","values":[round(v,0) if v==v else None for v in gm.top_prop]},{"name":"Best open licence","values":[round(v,0) if v==v else None for v in gm.top_open]}],"y":"Arena rating","source":"AI Model Arena Rankings 2023–2026 by riyagarg0314 on Kaggle (CC BY-SA 4.0), compiled from the public Arena leaderboard","note":"Ratings are relative within each leaderboard snapshot; compare shapes and gaps, not absolute levels across years."},gm[["month","top_prop","top_open","leader","leader_org"]])
lead=g.drop_duplicates(subset=["leader"])[["d","leader","leader_org"]]; F["arena_leaders"]=[(r.d.strftime("%b %Y"),r.leader,r.leader_org) for r in lead.itertuples()]
orgs=g.leader_org.value_counts(); do=orgs.reset_index(); do.columns=["organization","snapshots_at_number_1"]
save("arena_orgs",{"type":"hbar","title":"Whose model held the #1 spot, by number of leaderboard snapshots","x":do.organization.tolist(),"series":[{"name":"Snapshots at #1","values":do.snapshots_at_number_1.tolist()}],"y":"Leaderboard snapshots","source":"AI Model Arena Rankings 2023–2026 (CC BY-SA 4.0)"},do)
F["arena_snaps"]=len(g); F["arena_gap_first"]=(gm.top_prop.iloc[0]-gm.top_open.iloc[0]) if gm.top_open.iloc[0]==gm.top_open.iloc[0] else None
gm2=gm.dropna(); F["arena_gap_last"]=float(gm2.top_prop.iloc[-1]-gm2.top_open.iloc[-1]); F["arena_gap_series"]=list(zip(gm2.month,(gm2.top_prop-gm2.top_open).round(0)))
# ---- Salaries
s=pd.read_csv(K+"saurabhbadole_latest-data-science-job-salaries-2024/DataScience_salaries_2025.csv")
F["sal_rows"]=len(s); F["sal_years"]=s.work_year.value_counts().sort_index().to_dict()
ex={"EN":"Entry","MI":"Mid","SE":"Senior","EX":"Executive"}
sy=s[s.work_year>=2021].groupby(["work_year","experience_level"]).salary_in_usd.median().unstack()
save("sal_exp",{"type":"line","title":"Median salary (USD) by experience level, data and AI roles","x":[str(y) for y in sy.index],"series":[{"name":ex[k],"values":[int(v) for v in sy[k]]} for k in ["EN","MI","SE","EX"] if k in sy],"y":"Median salary (USD)","source":"Data Science Job Salaries 2020–2025 by saurabhbadole on Kaggle (CC0), data from ai-jobs.net"},sy.reset_index())
titles=["Machine Learning Engineer","AI Engineer","Research Scientist","Data Scientist","Data Engineer","Data Analyst","Applied Scientist","AI Researcher"]
s25=s[s.work_year==2025]; jt=s25[s25.job_title.isin(titles)].groupby("job_title").salary_in_usd.agg(["median","count"]).sort_values("median")
jt=jt[jt["count"]>=30]
save("sal_titles",{"type":"hbar","title":"2025 median salary by job title (USD, titles with 30+ responses)","x":jt.index.tolist(),"series":[{"name":"Median salary","values":[int(v) for v in jt["median"]]}],"y":"USD","source":"Data Science Job Salaries 2020–2025 (CC0), ai-jobs.net"},jt.reset_index())
cn=s25.groupby("company_location").salary_in_usd.agg(["median","count"]); cn=cn[cn["count"]>=40].sort_values("median").tail(10)
save("sal_country",{"type":"hbar","title":"2025 median salary by company location (USD, 40+ responses)","x":cn.index.tolist(),"series":[{"name":"Median salary","values":[int(v) for v in cn["median"]]}],"y":"USD","source":"Data Science Job Salaries 2020–2025 (CC0), ai-jobs.net; ISO country codes"},cn.reset_index())
rr=s[s.work_year>=2021].groupby("work_year").remote_ratio.apply(lambda x: round(100*(x==100).mean(),1))
save("sal_remote",{"type":"line","title":"Share of fully remote roles","x":[str(y) for y in rr.index],"series":[{"name":"% fully remote","values":rr.tolist()}],"y":"% of responses","source":"Data Science Job Salaries 2020–2025 (CC0), ai-jobs.net"},rr.reset_index())
F["sal_ca"]=s25[s25.company_location=="CA"].salary_in_usd.median(); F["sal_us"]=s25[s25.company_location=="US"].salary_in_usd.median(); F["sal_ca_n"]=int((s25.company_location=="CA").sum())
F["sal_remote"]=rr.to_dict()
# ---- Synthetic audit
def audit(name,path,desc_flag,num_cols=None):
    d=pd.read_csv(path,low_memory=False); nums=d.select_dtypes("number")
    nums=nums[[c for c in nums.columns if not re.search(r"id$|_id|ID",c)]]
    corr=nums.corr().abs().values; off=corr[~np.eye(len(corr),dtype=bool)] if len(corr)>1 else np.array([0])
    near0=round(100*(off<0.05).mean(),0)
    cats=d.select_dtypes(exclude="number"); bal=[]
    for c in cats.columns:
        vc=d[c].value_counts(normalize=True)
        if 2<=len(vc)<=12: bal.append(vc.max()-vc.min())
    flat=round(100*np.mean([x<0.05 for x in bal]),0) if bal else None
    return dict(dataset=name,rows=len(d),cols=d.shape[1],says_synthetic=desc_flag,pct_pairs_near_zero_corr=near0,pct_categories_evenly_split=flat)
rows=[audit("Impact of AI on Students (laveshjadon)",K+"laveshjadon_ai-impact-on-students/ai_student_impact_dataset (1).csv","No statement"),
audit("AI Usage & Student Academic Performance (ranaghulamnabi)",K+"ranaghulamnabi_ai-usage-and-student-academic-performance-analysis/ai_student_impact_dataset (1).csv","No statement; file identical to the one above"),
audit("Global AI Job Market & Salary Trends 2025 (bismasajjad)",K+"bismasajjad_global-ai-job-market-and-salary-trends-2025/ai_job_dataset.csv","Yes: 'algorithmically generated'"),
audit("AI Impact on Jobs 2030 (khushikyad001)",K+"khushikyad001_ai-impact-on-jobs-2030/AI_Impact_on_Jobs_2030.csv","No statement"),
audit("AI Workforce Displacement 2020–2026 (alitaqishah)",K+"alitaqishah_ai-workforce-displacement-20202026/ai_workforce_displacement_global_2020_2026.csv","Yes: 'research-calibrated synthetic data'"),
audit("Data Science Job Salaries 2020–2025 (saurabhbadole)",K+"saurabhbadole_latest-data-science-job-salaries-2024/DataScience_salaries_2025.csv","Source named: ai-jobs.net")]
da=pd.DataFrame(rows); da.to_csv(CSV+"synthetic_audit.csv",index=False); F["audit"]=rows
C["synthetic_audit"]={"type":"hbar","title":"Share of numeric column pairs with near-zero correlation (|r| < 0.05)","x":[r["dataset"] for r in rows],"series":[{"name":"% of pairs","values":[r["pct_pairs_near_zero_corr"] for r in rows]}],"y":"%","source":"ALENZA CODES analysis of public Kaggle datasets, 3 Dec 2026","csv":"/assets/blog/data/synthetic_audit.csv","note":"Real-world variables are usually correlated with each other to some degree. A very high share of near-zero correlations is one warning sign of independently generated columns. It is a signal to investigate, not proof."}
dl=pd.read_csv(K+"laveshjadon_ai-impact-on-students/ai_student_impact_dataset (1).csv")
F["stu_corr_hours_gpa"]=round(dl.Weekly_GenAI_Hours.corr(dl.Post_Semester_GPA),3)
h=np.histogram(dl.Weekly_GenAI_Hours,bins=10); F["stu_hist"]=h[0].tolist()
save("students_hist",{"type":"bar","title":"Weekly generative-AI hours in the 'AI Impact on Students' dataset (50,000 rows)","x":[f"{h[1][i]:.0f}–{h[1][i+1]:.0f}" for i in range(10)],"series":[{"name":"Students","values":h[0].tolist()}],"y":"Students","source":"Impact of AI on Students by laveshjadon on Kaggle (CC0)","note":"A near-flat histogram across the whole range is unusual for real survey answers about time use, which usually cluster at low values."},pd.DataFrame({"bin":[f"{h[1][i]:.1f}-{h[1][i+1]:.1f}" for i in range(10)],"students":h[0]}))
# ---- Job vacancies
v=pd.read_csv(K+"johnnykhan1_canada-job-vacancies-monthly/job_vacancies_canada_by_industry.csv",low_memory=False)
v=v[v.statistic=="Job vacancy rate"]; v["ref_date"]=v.ref_date.str[:7]
vp=v.pivot_table(index="ref_date",columns="naics",values="value").reset_index()
keep=["Total, all industries","Professional, scientific and technical services [54]","Information and cultural industries [51]"]
vp=vp[["ref_date"]+keep].dropna()
save("vac_rate",{"type":"line","title":"Job vacancy rate in Canada (%), seasonally adjusted","x":vp.ref_date.tolist(),"series":[{"name":"All industries","values":vp[keep[0]].round(2).tolist()},{"name":"Professional, scientific & technical","values":vp[keep[1]].round(2).tolist()},{"name":"Information & cultural","values":vp[keep[2]].round(2).tolist()}],"y":"Vacancy rate (%)","source":"Canada job vacancies by industry by johnnykhan1 on Kaggle, from Statistics Canada table 14-10-0406-01 (Statistics Canada Open Licence)"},vp)
F["vac_last"]=vp.iloc[-1].to_dict(); F["vac_peak"]={k:(vp.loc[vp[k].idxmax(),"ref_date"],float(vp[k].max())) for k in keep}
# ---- Wages
w=pd.read_csv(K+"johnnykhan1_canada-employee-wages-by-industry/employee_wages_by_industry_long.csv",low_memory=False,usecols=["ref_date","geo","wage_measure","type_of_work","naics","gender","age_group","value"])
w=w[(w.geo=="Canada")&(w.wage_measure=="Average weekly wage rate")&(w.type_of_work=="Both full- and part-time employees")&(w.gender=="Total - Gender")&(w.age_group=="15 years and over")]
wn=["Total employees, all industries","Professional, scientific and technical services [54]"]
wp=w[w.naics.isin(wn)].pivot_table(index="ref_date",columns="naics",values="value").reset_index(); wp["year"]=wp.ref_date.str[:4]
wp["premium_pct"]=(100*(wp[wn[1]]/wp[wn[0]]-1)).round(1)
save("wages",{"type":"line","title":"Average weekly wage, Canada (current dollars)","x":wp.year.tolist(),"series":[{"name":"All industries","values":wp[wn[0]].round(0).tolist()},{"name":"Professional, scientific & technical","values":wp[wn[1]].round(0).tolist()}],"y":"$ per week","source":"Canada employee wages by industry by johnnykhan1 on Kaggle, from Statistics Canada table 14-10-0064-01"},wp[["year"]+wn+["premium_pct"]])
F["wage_first"]=wp.iloc[0][["year"]+wn+["premium_pct"]].to_dict(); F["wage_last"]=wp.iloc[-1][["year"]+wn+["premium_pct"]].to_dict()
# ---- Education income
e=pd.read_csv(K+"johnnykhan1_canada-education-employment-income/education_employment_income_long.csv")
e=e[(e.age_group=="25 to 64 years")]
lv=["High (secondary) school diploma or equivalency certificate","College, CEGEP or other non-university certificate or diploma","Bachelor's degree","Master's degree","Earned doctorate"]
short={"High (secondary) school diploma or equivalency certificate":"High school","College, CEGEP or other non-university certificate or diploma":"College / CEGEP","Bachelor's degree":"Bachelor's","Master's degree":"Master's","Earned doctorate":"Doctorate"}
ce=e[(e.geo=="Canada")&e.education_level.isin(lv)].set_index("education_level").loc[lv]
cities=["Toronto (CMA), Ont.","Montréal (CMA), Que.","Vancouver (CMA), B.C.","Ottawa - Gatineau (CMA), Ont./Que.","Calgary (CMA), Alta."]
ser=[{"name":"Canada","values":[int(x) for x in ce.median_employment_income]}]
rows=[]
for cty in cities:
    x=e[(e.geo==cty)&e.education_level.isin(lv)].set_index("education_level")
    if len(x)==5: ser.append({"name":cty.split(" (")[0],"values":[int(x.loc[l,"median_employment_income"]) for l in lv]})
for sname in ser:
    rows.append([sname["name"]]+sname["values"])
dfe=pd.DataFrame(rows,columns=["geo"]+[short[l] for l in lv])
save("edu_income",{"type":"bar","title":"Median employment income (2020) by highest qualification, ages 25–64","x":[short[l] for l in lv],"series":ser,"y":"$ (2020)","source":"Canada education and employment income by johnnykhan1 on Kaggle, from the 2021 Census of Population (Statistics Canada)"},dfe)
F["edu"]=dfe.to_dict("records")
# ---- Toronto languages
tp=pd.read_csv(K+"johnnykhan1_toronto-neighbourhood-profiles-2021/census_profile_2021_long.csv",low_memory=False)
cl=pd.read_csv(K+"johnnykhan1_toronto-neighbourhood-profiles-2021/characteristic_list.csv")
F["tor_lang_chars"]=[(r.characteristic_id,r.characteristic,r.indent_level) for r in cl[cl.characteristic.str.contains("language",case=False)].itertuples()][:20]
json.dump(C,open(OUT,"w"),ensure_ascii=False,default=str)
json.dump(F,open(os.path.join(OUT_DIR,"facts.json"),"w"),ensure_ascii=False,default=str,indent=1)
print("charts",len(C))
