"""SOURCE render logic for TI-A-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_A_01(reg: dict) -> dict: """Most-watched titles in the US right now - weekly Demand Score ladder (official audience-size basis).""" chart_id = "TI-A-01" output_dir = THIS_DIR / chart_id / ROLE conn = lib.connect_readonly() t0 = time.time() # Basis = demand_score_7d from the official weekly demand rankings (audience-size basis, 7-day window). # The momentum-weighted di series is reserved for explicitly momentum-framed stories (see TI-A-02). df = lib.run_query(conn, """ WITH latest AS (SELECT MAX(file_date) AS file_date FROM metrics_demand_rank_history) SELECT r.imdb_id, r.demand_score_7d::numeric AS demand, r.title_type, ROW_NUMBER() OVER (ORDER BY r.demand_score_7d DESC, r.imdb_id) AS rank, l.file_date AS freshness_date FROM metrics_demand_rank_history r JOIN latest l USING (file_date) WHERE r.demand_score_7d IS NOT NULL AND r.geo_code = 'US' ORDER BY r.demand_score_7d DESC, r.imdb_id LIMIT 50; """) med_all = lib.run_query(conn, """ SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY demand_score_7d::numeric) AS m FROM metrics_demand_rank_history WHERE file_date = (SELECT MAX(file_date) FROM metrics_demand_rank_history) AND geo_code = 'US'; """) q_sec = time.time() - t0 if df.empty: lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], reg["pc_id"], "Empty weekly demand universe") conn.close() return {"status": "needs_spec_review"} df = lib.drop_demand_orphans(df, conn) # hide in-theaters / not-yet-streaming demand-orphans df["rank"] = range(1, len(df) + 1) titles = lib.resolve_titles(conn, df["imdb_id"].tolist()) conn.close() df = df.merge(titles[["imdb_id", "display_title", "start_year"]], on="imdb_id", how="left") df["display_title"] = df["display_title"].fillna(df["imdb_id"]) freshness = str(df["freshness_date"].iloc[0]) typical = float(med_all["m"].iloc[0]) if not med_all.empty and pd.notna(med_all["m"].iloc[0]) else None # Stats (official audience-size basis) d_arr = df["demand"].astype(float) stats = { "top_title": df.iloc[0]["display_title"], "gap_1_to_2": float(d_arr.iloc[0] / d_arr.iloc[1]), "gap_2_to_3": float(d_arr.iloc[1] / d_arr.iloc[2]), "gap_1_to_10": float(d_arr.iloc[0] / d_arr.iloc[9]), "top3_share": float(d_arr.head(3).sum() / d_arr.sum()), "top10_share": float(d_arr.head(10).sum() / d_arr.sum()), } lesson = lib.compute_lesson_concentration(stats, len(df)) top_title = df.iloc[0]["display_title"] gap12 = stats["gap_1_to_2"]; gap110 = stats["gap_1_to_10"]; top3_share = stats["top3_share"] N = 14 top = df.head(N).sort_values("rank", ascending=False) top["label"] = top.apply(lib.title_label, axis=1) colors = [lib.NAVY if r == 1 else (lib.BLUE if r <= 3 else lib.PALE_BLUE) for r in top["rank"]] bar_text = [f" {v:,.0f}" for v in top["demand"].astype(float)] fig = go.Figure() fig.add_trace(go.Bar( x=top["demand"].astype(float), y=top["label"], orientation="h", marker=dict(color=colors, line=dict(width=0)), text=bar_text, textposition="outside", textfont=dict(size=11, color=lib.MUTED), cliponaxis=False, showlegend=False, hovertemplate="%{y}
weekly Demand Score %{x:,.0f}", )) fig.update_xaxes(range=lib.pad_range(top["demand"].astype(float), labels=bar_text, fig_width=1180)) if lib.near_tie(d_arr.head(2), fmt=lambda v: f"{v:,.0f}"): second = df.iloc[1]["display_title"] takeaway = (f"“{top_title}” and “{second}” are neck and neck as America's most-watched title this week " f"({d_arr.iloc[0]:,.0f} weekly Demand Score apiece)") else: takeaway = f"“{top_title}” is the most-watched title in America right now - {gap12:.1f}x the audience of #2" what = ("Each bar = one title's weekly Demand Score, our measure of how many viewers it is drawing right now " "(7-day window, shows and movies together). Longest bar = the country's biggest title today.") why = (f"This is the fastest read on what to feature and what's breaking out. The field is winner-take-most: the top 3 titles " f"pull {top3_share:.0%} of all top-50 demand, and #1 runs {gap110:.0f}x ahead of #10.") scale_note = f"scale: a typical title on the top-500 boards ≈ {typical:,.0f}" if typical else "" footer = lib.assemble_footer( pc_id="PC-DP-01", caution_labels=["CL-006 viewer panel (distinct viewers), not total plays", "CL-013 latest weekly snapshot"], freshness_date=freshness, sources=["metrics_demand_rank_history"], extra=("weekly Demand Score (7-day audience-size basis, see the metric key); shows and movies ranked together" + (f"; {scale_note}" if scale_note else ""))) fig.update_layout(**lib.layout_v2(takeaway, what, width=1180, height=720), xaxis=lib.standard_xaxis("Weekly Demand Score", tickformat=",d"), yaxis=lib.standard_yaxis(showgrid=False)) lib.add_why_and_footer(fig, why, footer) lib.save_csv(df, output_dir) lib.export_chart(fig, output_dir, width=1180, height=720) lib.write_lesson_design(output_dir, chart_id, f"""# Lesson Design - {chart_id} ## Human lesson {takeaway} ## Rules applied {lesson['rules_applied']} ## Misread guard Weekly Demand Score = audience size (not watch count, not momentum) + CL-006 PANEL NOT CENSUS in footer. """) write_shim(output_dir, chart_id) lib.write_manifest( output_dir, chart_id, "ok", reg["spec_file"], pc_id="PC-DP-01", intended_lesson_from_spec="Top titles by weekly Demand Score (official audience-size basis)", rendered_lesson={"reader_title": takeaway, "reader_subtitle": what, "claim_strength": lesson["claim_strength"], "rules_applied": lesson["rules_applied"]}, row_count=len(df), freshness_date=freshness, query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec, ) return {"status": "ok", "rows": len(df)} A02_DS7_FLOOR = 300 # weekly Demand Score floor: keeps the momentum board to titles with a real current audience