"""SOURCE render logic for TI-I-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_I_02(reg: dict) -> dict: """Long-Tail Demand Share - share of DI in head/torso/tail.""" chart_id = "TI-I-02" 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 title_metrics_daily WHERE demand_score IS NOT NULL AND geo_code='US') SELECT demand_score::numeric AS demand, file_date FROM title_metrics_daily JOIN latest USING (file_date) WHERE demand_score IS NOT NULL AND geo_code='US' ORDER BY demand_score DESC; """) q_sec = time.time() - t0 conn.close() if df.empty: lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], reg["pc_id"], "No demand data") write_shim(output_dir, chart_id); return {"status": "needs_spec_review"} freshness = str(df["file_date"].iloc[0]) di = df["demand"].astype(float).sort_values(ascending=False).reset_index(drop=True) # universe = titles with measurable demand that day (zeros dropped) - the SAME universe rule as # companion TI-DP-04, so the two charts' N and top-1% figures agree di = di[di > 0].reset_index(drop=True) n = len(di) cum_dem = di.cumsum() / di.sum() # cumulative share of demand cum_titles = (pd.Series(range(1, n + 1)) / n) # cumulative share of titles # share of demand captured by the top X% of titles def cap(p): return float(cum_dem.iloc[max(0, int(n * p) - 1)]) top1, top5, top20 = cap(0.01), cap(0.05), cap(0.20) # downsample to ~400 points for a smooth, light curve idx = sorted(set([0] + list(range(0, n, max(1, n // 400))) + [n - 1])) fig = go.Figure() # equality reference (if every title drew equal demand) fig.add_trace(go.Scatter(x=[0, 100], y=[0, 100], mode="lines", showlegend=False, hoverinfo="skip", line=dict(color=lib.MUTED, width=1, dash="dash"))) fig.add_trace(go.Scatter(x=(cum_titles.iloc[idx] * 100), y=(cum_dem.iloc[idx] * 100), mode="lines", fill="tozeroy", fillcolor="rgba(35,62,105,0.10)", line=dict(color=lib.NAVY, width=3), showlegend=False, hovertemplate="Top %{x:.0f}% of titles
= %{y:.0f}% of all the attention")) # markers at top 1% / 5% / 20% - white-backed, arrowed callouts so the labels never merge with the curve/fill for p, lab in [(1, top1), (5, top5), (20, top20)]: fig.add_trace(go.Scatter(x=[p], y=[lab * 100], mode="markers", showlegend=False, hoverinfo="skip", marker=dict(size=9, color=lib.NAVY, line=dict(width=1, color="white")))) fig.add_annotation(x=p, y=lab * 100, text=f"top {p}% → {lab:.0%} of the attention", showarrow=True, arrowhead=0, arrowwidth=1, arrowcolor=lib.MUTED, ax=22, ay=16, xanchor="left", yanchor="top", font=dict(size=11, color=lib.INK), bgcolor="rgba(255,255,255,0.85)", borderpad=2) # label the equality diagonal in-plot, OFFSET BELOW the line (at the old x=70/y=66 the dashes # ran through the label's tail) and angled to the line's RENDERED slope (~22deg on this canvas, # not the 45deg data slope) fig.add_annotation(x=70, y=60, text="if attention were spread evenly", textangle=-22, showarrow=False, font=dict(size=10, color=lib.MUTED)) title_lesson = (f"Viewer attention is brutally top-heavy: in a single day, the top 1% of titles capture {top1:.0%} of it, " f"and the top 20% capture {top20:.0%}") what = ("Of all the attention US viewers gave streaming titles on the latest tracked day, the curve shows how much went to the most-watched few - " "pick any share of titles along the bottom and read off their slice. The dashed line is what perfectly even attention would look like; " "the gap between the curve and that line is the imbalance.") why = ("This is the long tail. A tiny head drives the platform's headline numbers, but the vast tail is where niche loyalty, " "discovery and catalog depth live - and where a good recommendation engine earns its keep by matching the right viewer to it.") fig.update_layout(**lib.layout_v2(title_lesson, what, width=1080, height=680), xaxis=lib.standard_xaxis("Share of titles (most-watched first)", ticksuffix="%"), yaxis=lib.standard_yaxis("Share of all the attention they capture", ticksuffix="%")) fig.update_xaxes(range=[0, 100]); fig.update_yaxes(range=[0, 101]) # extra split into two short segments and trimmed so the whole Sources line fits the wrap # budget at this width (the long single segment wrapped a lone '· ref PC-I-02' onto line 3) lib.add_why_and_footer(fig, why, lib.assemble_footer("PC-I-02", ["CL-006 viewer panel (distinct viewers), not census"], freshness, ["title_metrics_daily"], f"N = {n:,} US-tracked titles with a measurable Demand Score that day · expert companion: power-law curve, ref PC-DP-06")) # csv ships PERCENT units (0-100): as 0-1 fractions the library rounder capped both columns at # 2dp (their max is 1.0), collapsing the whole head into rows printing '0.01' - the callouts # were not reconstructable from the printed x values lib.save_csv(pd.DataFrame({"cum_titles_pct": cum_titles * 100, "cum_demand_score_pct": cum_dem * 100}), output_dir) lib.export_chart(fig, output_dir, width=1080, height=680) 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-02", intended_lesson_from_spec="Long-tail demand concentration (Lorenz curve)", rendered_lesson={"reader_title": title_lesson, "reader_subtitle": what, "claim_strength": "strong", "rules_applied": "cumulative demand curve"}, row_count=n, freshness_date=freshness, query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec) return {"status": "ok", "rows": n}