"""SOURCE render logic for TI-E-01 (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_E_01(reg: dict) -> dict: """Actor Demand Leaderboard - top actors by sum-of-credit-normalized DI.""" chart_id = "TI-E-01" output_dir = THIS_DIR / chart_id / ROLE conn = lib.connect_readonly() t0 = time.time() # BASIS (locked metric semantics): a "most in-demand talent" leaderboard is an audience-SIZE story → # demand_score, never di (di is momentum-weighted, reserved for momentum stories). df = lib.run_query(conn, """ WITH latest AS (SELECT MAX(file_date) AS file_date FROM title_metrics_daily), top_titles AS ( SELECT t.imdb_id, t.demand_score::numeric AS demand FROM title_metrics_daily t JOIN latest l USING (file_date) WHERE t.demand_score IS NOT NULL AND t.geo_code='US' AND t.imdb_id NOT IN (SELECT imdb_id FROM metrics_avail_match_daily WHERE file_date = (SELECT MAX(file_date) FROM metrics_avail_match_daily) AND country_code='US' AND flag='ORPHAN' AND imdb_id IS NOT NULL) ORDER BY t.demand_score DESC LIMIT 3000 ), principals AS ( SELECT DISTINCT p.imdb_id, p.nconst FROM categorization_imdb_principals p JOIN top_titles tt USING (imdb_id) WHERE p.category IN ('actor', 'actress') ), counts AS (SELECT imdb_id, COUNT(*) AS pc FROM principals GROUP BY imdb_id) SELECT p.nconst, n.primary_name, SUM(tt.demand / NULLIF(c.pc, 0)) AS credit_demand, COUNT(DISTINCT p.imdb_id) AS title_count, (ARRAY_AGG(p.imdb_id ORDER BY tt.demand DESC))[1] AS top_title_id, (SELECT file_date FROM latest) AS freshness_date FROM principals p JOIN counts c USING (imdb_id) JOIN top_titles tt USING (imdb_id) LEFT JOIN categorization_imdb_name_basics n USING (nconst) GROUP BY p.nconst, n.primary_name HAVING COUNT(DISTINCT p.imdb_id) >= 3 ORDER BY credit_demand DESC LIMIT 80; """) q_sec = time.time() - t0 if df.empty: lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], reg["pc_id"], "No actor data") conn.close(); write_shim(output_dir, chart_id); return {"status": "needs_spec_review"} freshness = str(df["freshness_date"].iloc[0]) df = df.drop(columns=["freshness_date"]) df["credit_demand"] = df["credit_demand"].astype(float) df["display"] = df["primary_name"].fillna(df["nconst"]) # BOARD CAP: max 2 names per carrying title, so one hot ensemble can't flood the leaderboard df = df.sort_values("credit_demand", ascending=False) df = df[df.groupby("top_title_id", dropna=False).cumcount() < 2].head(22) tt = lib.resolve_titles(conn, df["top_title_id"].dropna().tolist()); conn.close() tmap = dict(zip(tt["imdb_id"], tt["display_title"])) df["top_title"] = df["top_title_id"].map(tmap).fillna("") df = df.sort_values("credit_demand", ascending=True) # each bar prints its VALUE (quotable) + the full carrying title (no clipped words) bar_texts = [(f" {v:,.0f} · mainly via {lib.ellipsize(h, 60)}" if h else f" {v:,.0f}") for v, h in zip(df["credit_demand"], df["top_title"])] fig = go.Figure() fig.add_trace(go.Bar(x=df["credit_demand"], y=df["display"], orientation="h", marker=dict(color=lib.BLUE), text=bar_texts, textposition="outside", textfont=dict(size=10, color=lib.MUTED), cliponaxis=False, showlegend=False, hovertemplate="%{y}
Demand Score %{x:,.0f} · top title: %{customdata}", customdata=df["top_title"])) fig.update_xaxes(range=lib.pad_range(df["credit_demand"], labels=bar_texts, font_px=10, fig_width=1200)) df_desc = df.sort_values("credit_demand", ascending=False) a1, a2 = df_desc.iloc[0], df_desc.iloc[1] is_tie = a2["credit_demand"] >= 0.97 * a1["credit_demand"] # top two within 3% = a credit-split near-tie, not a meaningful #1 same_show = bool(a1["top_title"]) and a1["top_title"] == a2["top_title"] if is_tie and same_show: title_lesson = (f"{a1['top_title']} cast dominate on-screen demand right now - " f"{a1['display']} and {a2['display']} are neck-and-neck at the top") elif is_tie: title_lesson = f"{a1['display']} and {a2['display']} are neck-and-neck for the most in-demand talent right now" else: title_lesson = f"{a1['display']} is the most in-demand on-screen talent right now - carried mainly by {a1['top_title']}" what = ("Top actors ranked by the demand their titles are pulling right now (each title's audience split across its credited cast, " "voice roles included, then summed per person; max two names per show). The title doing the heavy lifting is named after each bar.") why = ("Talent demand is a casting and marketing signal: who's hot this moment, and - crucially - why (one breakout role can lift " "a name overnight). The 'mainly via' tag keeps it honest about what's actually carrying each name.") fig.update_layout(**lib.layout_v2(title_lesson, what, width=1200, height=800), xaxis=lib.standard_xaxis("US Demand Score credited to the actor"), yaxis=lib.standard_yaxis(showgrid=False)) lib.add_why_and_footer(fig, why, lib.assemble_footer("PC-E-01", ["CL-006 viewer panel (distinct viewers), not census"], freshness, ["title_metrics_daily", "IMDb cast credits", "IMDb name catalog"], "US demand basis · top-3000 title universe; credit-shared Demand Score; max 2 names per carrying title")) lib.save_csv(df, output_dir); lib.export_chart(fig, output_dir, width=1200, height=800) 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-E-01", intended_lesson_from_spec="Actor demand leaderboard + carrying title", rendered_lesson={"reader_title": title_lesson, "reader_subtitle": what, "claim_strength": "strong", "rules_applied": "credit-shared demand_score (audience-size basis) + top title; max 2 names per carrying title"}, row_count=len(df), freshness_date=freshness, query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec) return {"status": "ok", "rows": len(df)}