"""SOURCE render logic for TI-E-02 (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_02(reg: dict) -> dict: """Director Demand Leaderboard.""" chart_id = "TI-E-02" output_dir = THIS_DIR / chart_id / ROLE conn = lib.connect_readonly() t0 = time.time() # BASIS (locked metric semantics): audience-size leaderboard → demand_score, never di (di = momentum only; # the momentum basis is exactly what put a pre-release biopic spike at #1 of a "right now" board). 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 ), dirs AS ( SELECT DISTINCT d.imdb_id, d.nconst FROM categorization_imdb_directors d JOIN top_titles tt USING (imdb_id) WHERE d.nconst IS NOT NULL ), counts AS (SELECT imdb_id, COUNT(*) AS pc FROM dirs GROUP BY imdb_id) SELECT d.nconst, n.primary_name, SUM(tt.demand / NULLIF(c.pc, 0)) AS credit_demand, COUNT(DISTINCT d.imdb_id) AS title_count, (ARRAY_AGG(d.imdb_id ORDER BY tt.demand DESC))[1] AS top_title_id, (SELECT file_date FROM latest) AS freshness_date FROM dirs d JOIN counts c USING (imdb_id) JOIN top_titles tt USING (imdb_id) LEFT JOIN categorization_imdb_name_basics n USING (nconst) GROUP BY d.nconst, n.primary_name HAVING COUNT(DISTINCT d.imdb_id) >= 2 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 director 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 (one series' episode directors can't flood the board) 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"])) type_map = dict(zip(tt["imdb_id"], tt["title_type"])) df["top_title"] = df["top_title_id"].map(tmap).fillna("") df = df.sort_values("credit_demand", ascending=True) # each bar prints its VALUE (quotable; separates the near-equal mid-board) + the FULL carrying # title (48-char word-boundary budget - 'The Lord of the Rings: The…' was ambiguous across 3 films) 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)) top_d = df.iloc[-1] # a one-word carrying title (e.g. the biopic "Michael") reads as a person's name - gloss it with its type GLOSS = {"movie": "the film", "tvMovie": "the film", "tvSeries": "the series", "tvMiniSeries": "the series"} gloss = GLOSS.get(str(type_map.get(top_d["top_title_id"], "")), "") carried = (f"{gloss} \"{top_d['top_title']}\"" if gloss and len(str(top_d["top_title"]).split()) <= 2 else f"\"{top_d['top_title']}\"") df_desc = df.sort_values("credit_demand", ascending=False) a1, a2 = df_desc.iloc[0], df_desc.iloc[1] if a2["credit_demand"] >= 0.97 * a1["credit_demand"]: title_lesson = f"{a1['display']} and {a2['display']} are neck-and-neck for the most in-demand director right now" else: title_lesson = f"{top_d['display']} is the most in-demand director right now - driven by {carried}" what = ("Top directors ranked by the demand their titles are pulling right now (each title's audience split across credited directors, " "then summed per person; max two names per title). The title doing the heavy lifting is named after each bar.") why = ("A read on which filmmakers' names move audiences this moment - useful for greenlighting and deal-making - with the carrying " "title shown so a name isn't credited for one breakout it merely touched.") fig.update_layout(**lib.layout_v2(title_lesson, what, width=1200, height=800), xaxis=lib.standard_xaxis("US Demand Score credited to the director"), yaxis=lib.standard_yaxis(showgrid=False)) lib.add_why_and_footer(fig, why, lib.assemble_footer("PC-E-02", ["CL-006 viewer panel (distinct viewers), not census"], freshness, ["title_metrics_daily", "IMDb director credits", "IMDb name catalog"], "US demand basis · top-3000 title universe; credit-shared Demand Score; max 2 names per carrying title; " "a series' Demand Score splits across its episode directors")) 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-02", intended_lesson_from_spec="Director 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)}