"""SOURCE render logic for METH-03 (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_METH_03(reg): """The numbers, decoded v2 (rebuilt 2026-06-12, pinned first on the site) - the SEVEN on-chart concepts, each as one layman sentence plus one precise expert clause, anchored by a LIVE scale ladder (typical / top-10 entry / #1 weekly Demand Score, queried at render). Copy basis: METH03_COPY_SPEC.md v4.1 (reach-era scale). EShare REMOVED 2026-06-16 (founder panel-quality-disclosure rule: no public surface admits the panel contains bots/low-trust traffic; EShare is internal-only now, so it is no longer a public concept). data.csv feeds the site glossary, so the metric/definition columns must survive any redesign.""" chart_id = "METH-03"; output_dir = THIS_DIR / chart_id / ROLE conn = lib.connect_readonly(); t0 = time.time() # Live scale anchors - rule-based (queried nightly, never hardcoded), orphan-dropped to match the # published boards, movie rows gated on di_rank (the PVOD side-lane never anchors the ladder). board = lib.run_query(conn, """ SELECT r.imdb_id, r.demand_score_7d::numeric AS ds, r.file_date AS freshness_date FROM metrics_demand_rank_history r WHERE r.file_date = (SELECT MAX(file_date) FROM metrics_demand_rank_history) AND r.geo_code = 'US' AND r.demand_score_7d IS NOT NULL AND (r.title_type <> 'movie' OR r.di_rank IS NOT NULL) ORDER BY r.demand_score_7d DESC, r.imdb_id; """) eg = lib.run_query(conn, """ SELECT b.primary_title, e.evergreen_score::numeric AS s FROM metrics_evergreen_population_daily e JOIN categorization_imdb_title_basics b USING (imdb_id) WHERE e.file_date = (SELECT MAX(file_date) FROM metrics_evergreen_population_daily) ORDER BY e.evergreen_score DESC NULLS LAST LIMIT 1; """) if board.empty: conn.close() lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], "PC-METH-03", "Empty weekly board universe - no live scale anchors") write_shim(output_dir, chart_id); return {"status": "needs_spec_review"} board = lib.drop_demand_orphans(board, conn) lead_t = lib.resolve_titles(conn, [str(board.iloc[0]["imdb_id"])]) conn.close(); q_sec = time.time() - t0 board["ds"] = board["ds"].astype(float) fresh = str(board["freshness_date"].iloc[0]) ds_med = float(board["ds"].median()) ds_cut = float(board["ds"].iloc[9]) if len(board) >= 10 else float(board["ds"].min()) ds_max = float(board["ds"].iloc[0]) lead_name = lib.ellipsize(str(lead_t["display_title"].iloc[0]), 26) if len(lead_t) else "this week's #1" eg_top = float(eg["s"].iloc[0]) if (len(eg) and pd.notna(eg["s"].iloc[0])) else None eg_name = lib.ellipsize(str(eg["primary_title"].iloc[0]), 22) if len(eg) else "" eg_clause = (f"today it tops out near {eg_top:,.0f} ({eg_name})" if eg_top is not None else "the most timeless titles sit near the index ceiling") # Eight concepts in the exact vocabulary printed on the other charts. Layman sentence first # (repeatable out loud), then the precise clause an expert can hold us to. cards = [ ("Demand Score", "Our measure of weekly at-home audience: how many people a title is actually pulling right now.", "The 7-day average of distinct daily viewers in our US panel, adjusted by two published credibility " "factors: outside corroboration and panel composition. A level, not a running total."), ("Viewers (panel)", "The raw headcount behind every score: distinct viewers in our US panel who watched a title that day.", "Unadjusted daily reach. It stays visible in chart hovers and side notes, and it reads on a panel " "scale, never as a national total."), ("Baseline demand", "A title's normal everyday level: what it draws in a quiet week with no news and no new season.", "The trailing 28-day basis of a title's daily audience, the yardstick that rising, fading and " "spike claims are measured against."), ("Momentum", "Whether a title is heating up or cooling off compared with its own recent past.", "This week's level vs the title's own baseline demand, computed on share of panel so a small " "panel day cannot fake a move."), ("Evergreen", "How well a title keeps drawing viewers years after release, instead of fading away.", f"An index blending a title's age with how steadily it still earns attention; {eg_clause}."), ("Hit-dependence", "How much of a platform's audience hangs on just a few big titles.", "The share of a platform's total weekly Demand Score held by its top titles. Higher means more " "fragile, one big ending away from a slump."), ("Taste fingerprint", "The signature mix of genres a country or platform watches more of than everyone else.", # basis matches the shipped fingerprint charts exactly (they index vs the TYPICAL peer # shown - the average across the chart's countries/platforms - not a panel-wide average) "Genre shares compared with the typical country or platform on the same chart (the average " "across the peers shown), as over- or under-index ratios, where 1.0 means perfectly typical taste."), ] W, H = 1240, 980 fig = go.Figure() fig.update_xaxes(visible=False, range=[0, 1]); fig.update_yaxes(visible=False, range=[0, 1]) # --- concept cards: 2 cols x 4 rows, layman-first. Uniform NEUTRAL accent (grey) - card identity # is not a verdict, so no semantic hues (color contract: navy/green/red/amber stay reserved). xL = [0.0, 0.525]; ys = [1.0, 0.795, 0.59, 0.385] for i, (name, lay, precise) in enumerate(cards): cx = xL[i % 2]; cy = ys[i // 2] lay_w, _ = lib._wrap(lay, width=72) pre_w, _ = lib._wrap(precise, width=86) fig.add_shape(type="rect", xref="paper", yref="paper", x0=cx, x1=cx + 0.006, y0=cy - 0.032, y1=cy, fillcolor="#8D94A1", line=dict(width=0)) fig.add_annotation(xref="paper", yref="paper", x=cx + 0.016, y=cy, xanchor="left", yanchor="top", showarrow=False, align="left", font=dict(size=12.5, color=lib.INK), text=(f"{name}
" f"{lay_w}
" f"{pre_w}")) # --- the scale ladder: place any number you meet on the other charts (live anchors, linear 0..#1). LX0, LX1, LY = 0.015, 0.985, 0.075 pos = lambda v: LX0 + (LX1 - LX0) * (v / ds_max if ds_max > 0 else 0.0) fig.add_annotation(xref="paper", yref="paper", x=0.0, y=0.205, xanchor="left", yanchor="top", showarrow=False, align="left", font=dict(size=12.5, color=lib.INK), text=(f"The scale, live this week  " f"where weekly Demand Scores land " f"on the US boards: #1 runs about {ds_max / max(ds_med, 0.01):,.0f}x a typical " f"charted title")) fig.add_shape(type="line", xref="paper", yref="paper", x0=LX0, x1=LX1, y0=LY, y1=LY, line=dict(color=lib.GRID, width=3)) anchors = [(ds_med, "a typical charted title", lib.BLUE, "above"), (ds_cut, "top-10 entry", lib.BLUE, "below"), (ds_max, f"#1 this week ({lead_name})", lib.NAVY, "above")] for v, label, col, side in anchors: x = pos(v) fig.add_shape(type="line", xref="paper", yref="paper", x0=x, x1=x, y0=LY - 0.013, y1=LY + 0.013, line=dict(color=col, width=3)) xa = "left" if x < 0.12 else ("right" if x > 0.88 else "center") ya, yy = ("bottom", LY + 0.020) if side == "above" else ("top", LY - 0.020) fig.add_annotation(xref="paper", yref="paper", x=x, y=yy, xanchor=xa, yanchor=ya, showarrow=False, align={"left": "left", "right": "right", "center": "center"}[xa], font=dict(size=10.5, color=lib.INK), text=f"{label}
{v:,.0f}") fig.add_annotation(xref="paper", yref="paper", x=LX0, y=LY - 0.020, xanchor="center", yanchor="top", showarrow=False, font=dict(size=9.5, color=lib.MUTED), text="0") title_lesson = "The numbers, decoded: the seven ideas every chart here is built on" what = ("Each idea in plain words first, then the precise version in smaller type for experts. " "The live scale at the bottom shows where weekly Demand Scores land right now, " "so you can place any number you meet.") why = ("Every chart on this site speaks this vocabulary. A reader who knows that Demand Score is a " "level, not a running total, and who can place a number on the scale above, can read any " "chart here without being misled.") fig.update_layout(**lib.layout_v2(title_lesson, what, width=W, height=H)) # Expert pointer demoted to ONE short clause on the provenance line; no internal abbreviations # (the old ES/BL/'cred and comp' shorthand read as jargon, and M055 overstated the documented # M008-M052 catalog). expert_line = "experts: our technical docs cover these under metric codes M008-M052" # every remaining card reads on the US panel (EShare, the lone worldwide card, was removed # 2026-06-16), so the blanket US-panel scope line is now exactly correct with no exception footer = scope_footer(lib.assemble_footer("PC-METH-03", ["scale anchors queried live at render; scores use a 7-day basis"], fresh, ["metrics_demand_rank_history", "metrics_evergreen_daily"], expert_line), "US viewer panel (distinct viewers), not a census") lib.add_why_and_footer(fig, why, footer) lib.save_csv(pd.DataFrame([(c[0], c[1], c[2]) for c in cards], columns=["metric", "definition", "expert_clause"]), output_dir) lib.export_chart(fig, output_dir, width=W, height=H) 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-METH-03", intended_lesson_from_spec="v2 metric decoder: 8 on-chart concepts (layman + expert) + live scale ladder", rendered_lesson={"reader_title": title_lesson, "reader_subtitle": what, "claim_strength": "strong", "rules_applied": "8 concepts per METH03_COPY_SPEC v4.1; ladder anchors live (median / top-10 entry / max, orphan-dropped)"}, row_count=len(cards), freshness_date=fresh, # evergreen ceiling backed here so the card's one live number is reproducible from run artifacts extra={"scale_ladder": {"typical_median": round(ds_med, 2), "top10_entry": round(ds_cut, 2), "number_one": round(ds_max, 2), "number_one_title": lead_name}, "evergreen_ceiling": ({"score": round(eg_top, 2), "title": eg_name} if eg_top is not None else None)}, query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec) return {"status": "ok", "rows": len(cards)}