"""SOURCE render logic for TI-I-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_I_01(reg: dict) -> dict: """Evergreen Rank Ladder - top 30 by rank.""" chart_id = "TI-I-01" 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 metrics_evergreen_population_daily) SELECT imdb_id, evergreen_score::numeric AS eg, rank, age_factor::numeric AS age_f, eshare_pctl::numeric AS eshare_p, quality_pctl::numeric AS quality_p, (SELECT file_date FROM latest) AS file_date FROM metrics_evergreen_population_daily JOIN latest USING (file_date) WHERE rank <= 30 ORDER BY rank; """) pop = lib.run_query(conn, """ SELECT COUNT(*) AS n FROM metrics_evergreen_population_daily WHERE file_date = (SELECT MAX(file_date) FROM metrics_evergreen_population_daily); """) q_sec = time.time() - t0 if df.empty: lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], reg["pc_id"], "No evergreen rank") conn.close(); write_shim(output_dir, chart_id); return {"status": "needs_spec_review"} titles = lib.resolve_titles(conn, df["imdb_id"].tolist()) conn.close() df = df.merge(titles[["imdb_id", "display_title"]], on="imdb_id", how="left") df["display_title"] = df["display_title"].fillna(df["imdb_id"]) df["eg"] = df["eg"].astype(float) freshness = str(df["file_date"].iloc[0]) n_pop = int(pop["n"].iloc[0]) if not pop.empty else 0 df_s = df.sort_values("eg", ascending=True) eg_max = float(df_s["eg"].max()) # Dot plot on a declared, range-framed axis: a zero-based bar wall makes 30 scores within ~15 points # visually identical; the truncation is declared in the footer. fig = go.Figure() fig.add_trace(go.Scatter(x=df_s["eg"], y=[short_title(t, 42) for t in df_s["display_title"]], mode="markers+text", marker=dict(size=10, color=lib.NAVY, line=dict(width=1, color="white")), text=[f" {v:.0f}" for v in df_s["eg"]], textposition="middle right", textfont=dict(size=10, color=lib.MUTED), cliponaxis=False, showlegend=False, hovertemplate="%{y}
timelessness score %{x:.0f}")) top1 = df_s.iloc[-1] if lib.near_tie(df_s["eg"].iloc[-2:], fmt=lambda v: f"{v:.0f}"): t2 = df_s.iloc[-2]["display_title"] title_lesson = (f"{short_title(top1['display_title'], 30)} and {short_title(t2, 30)} are tied as the catalog's most timeless titles - " "both keep drawing audiences decade after decade") else: title_lesson = f"The catalog's most timeless title is {short_title(top1['display_title'], 34)} - it keeps drawing an audience decade after decade" what = (f"Each dot = a title's evergreen score, a ‘timelessness’ index that tops out ≈ {eg_max:.0f} today (higher = more " f"steadily watched year after year); a model score, not a viewer count. Top 30 of {n_pop:,} scored titles.") why = ("Evergreen titles are a catalog's annuities - they earn attention with no marketing push, year after year. " "They're the safest licensing bets and the backbone of a deep, durable library.") fig.update_layout(**lib.layout_v2(title_lesson, what, width=1200, height=900), xaxis=lib.standard_xaxis("Evergreen score (timelessness index)"), yaxis=lib.standard_yaxis(showgrid=False)) fig.update_xaxes(range=[105, eg_max + 2.5]) # axis hugs the leader (no dead band past the top dot) lib.add_why_and_footer(fig, why, lib.assemble_footer("PC-I-01", ["CL-006 viewer panel (distinct viewers), not census"], freshness, ["metrics_evergreen_population_daily"], f"M046 V4.1: age × (baseline + engagement + quality percentiles), decline/crash-penalized; " f"axis spans 105-{eg_max + 2.5:.0f} to spread a tightly packed top 30 (scores ~111-{eg_max:.0f})")) lib.save_csv(df, output_dir); lib.export_chart(fig, output_dir, width=1200, height=900) 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-01", intended_lesson_from_spec="Evergreen ladder (timelessness index defined)", rendered_lesson={"reader_title": title_lesson, "reader_subtitle": what, "claim_strength": "strong", "rules_applied": f"rank<=30; dot plot, declared 105-{eg_max + 2.5:.0f} range frame"}, row_count=len(df), freshness_date=freshness, query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec) return {"status": "ok", "rows": len(df)}