"""SOURCE render logic for TI-I-05 (REFERENCE ONLY). This is the exact function from our pipeline. It is DB-coupled — you cannot run it without our database. The query result it produces is materialized for you in data.csv, and the rendered output is figure.json (load that to display the chart). This file is provided so you can understand / re-theme the logic. """ def render_TI_I_05(reg: dict) -> dict: """Decade Demand Distribution - DI rollup by decade of release.""" chart_id = "TI-I-05" output_dir = THIS_DIR / chart_id / ROLE conn = lib.connect_readonly() t0 = time.time() df = lib.run_query(conn, """ WITH latest AS (SELECT MAX(file_date) AS file_date FROM title_metrics_daily), rel AS (SELECT imdb_id, release_date FROM categorization_release_dates_all WHERE release_date IS NOT NULL) SELECT FLOOR(EXTRACT(YEAR FROM r.release_date)/10)*10 AS decade, SUM(t.demand_score::numeric) AS total_demand, COUNT(DISTINCT t.imdb_id) AS titles, (SELECT file_date FROM latest) AS file_date FROM title_metrics_daily t JOIN latest l USING (file_date) JOIN rel r USING (imdb_id) WHERE t.demand_score IS NOT NULL AND t.geo_code='US' GROUP BY FLOOR(EXTRACT(YEAR FROM r.release_date)/10)*10 HAVING SUM(t.demand_score::numeric) > 0 ORDER BY decade; """) q_sec = time.time() - t0 conn.close() if df.empty: lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], reg["pc_id"], "No decade data") write_shim(output_dir, chart_id); return {"status": "needs_spec_review"} df["total_demand"] = df["total_demand"].astype(float); df["decade"] = df["decade"].astype(int) df = df[df["decade"] >= 1900].reset_index(drop=True) freshness = str(df["file_date"].iloc[0]) df["pct"] = df["total_demand"] / df["total_demand"].sum() pct_lbl = [f"{p:.0%}" if p >= 0.005 else "<1%" for p in df["pct"]] fig = go.Figure() fig.add_trace(go.Bar(x=df["decade"].astype(str) + "s", y=df["total_demand"], marker=dict(color=lib.BLUE), text=[f"{v:,.0f}
{p}" for v, p in zip(df["total_demand"], pct_lbl)], textposition="outside", textfont=dict(size=10), cliponaxis=False, showlegend=False, customdata=df[["pct"]], hovertemplate="%{x}
Total Demand Score %{y:,.0f} (%{customdata[0]:.1%} of all demand)")) df_sorted = df.sort_values("total_demand", ascending=False) top_decade = df_sorted.iloc[0] top_pct = float(top_decade["pct"]) first_decade = int(df["decade"].iloc[0]) pre1970 = float(df[df["decade"] < 1970]["pct"].sum()) # make the long tail's reality visible instead of asserting it if (df["decade"] < 1970).any(): mid_idx = max(0, int((df["decade"] < 1970).sum() / 2) - 1) fig.add_annotation(x=str(int(df["decade"].iloc[mid_idx])) + "s", y=float(df["total_demand"].max()) * 0.22, text=f"pre-1970 combined: {pre1970:.1%} of all current demand - small, but real", showarrow=False, xanchor="left", font=dict(size=10.5, color=lib.MUTED), bgcolor="rgba(255,255,255,0.9)") title_lesson = (f"Today's attention pools in recent releases - the {int(top_decade['decade'])}s hold {top_pct:.0%} of all current demand - " f"but every decade back to the {first_decade}s still registers") what = ("Total current US demand summed by the decade a title was originally released, with each decade's share of that total " "labelled. Recent decades lead (more titles, plus recency), yet attention still flows to classics from every decade.") why = ("It maps how today's viewing splits between new and catalog content - the strategic balance between chasing fresh hits and " "mining a back library that, decade for decade, still commands real demand.") fig.update_layout(**lib.layout_v2(title_lesson, what, width=1200, height=560), xaxis=lib.standard_xaxis("Decade of original release"), yaxis=lib.standard_yaxis("Total Demand Score today", tickformat=",d")) lib.add_why_and_footer(fig, why, lib.assemble_footer("PC-I-05", ["CL-006 viewer panel (distinct viewers), not census"], freshness, ["title_metrics_daily", "categorization_release_dates_all"], "recent decades partly reflect catalog size + recency, not only taste")) lib.save_csv(df, output_dir); lib.export_chart(fig, output_dir, width=1200, height=560) lib.write_lesson_design(output_dir, chart_id, f"# {chart_id}\n\n{title_lesson}\n\n{what}\n") write_shim(output_dir, chart_id) lib.write_manifest(output_dir, chart_id, "ok", reg["spec_file"], pc_id="PC-I-05", intended_lesson_from_spec="Demand by release decade", rendered_lesson={"reader_title": title_lesson, "reader_subtitle": what, "claim_strength": "strong", "rules_applied": "decade rollup; share-of-total labels"}, row_count=len(df), freshness_date=freshness, query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec) return {"status": "ok", "rows": len(df)}