"""SOURCE render logic for TI-D-10 (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_D_10(reg: dict) -> dict: """Hit-driven vs broad markets - share of each major country's viewing from its top 10 titles.""" chart_id = "TI-D-10" 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_country_share_90d) SELECT country_code AS geo_code, imdb_id, n_unique_viewers::numeric AS viewers, (SELECT file_date FROM latest) AS freshness_date FROM metrics_country_share_90d JOIN latest USING (file_date) WHERE n_unique_viewers IS NOT NULL; """) 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 country viewing data") 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["viewers"] = df["viewers"].astype(float) MAJOR = ['US','GB','CA','AU','DE','FR','ES','IT','JP','KR','BR','MX','IN','NL','SE','PL','TR','PH'] rows = [] for c, sub in df[df["geo_code"].isin(MAJOR)].groupby("geo_code"): total = sub["viewers"].sum() if total <= 0 or len(sub) < 20: continue top10 = sub.nlargest(10, "viewers")["viewers"].sum() rows.append({"geo_code": c, "top10_share": top10 / total, "n_titles": len(sub)}) out = pd.DataFrame(rows).sort_values("top10_share", ascending=True) if out.empty: lib.needs_spec_review(output_dir, chart_id, reg["spec_file"], reg["pc_id"], "No major markets with scale") write_shim(output_dir, chart_id); return {"status": "needs_spec_review"} out["geo_code"] = out["geo_code"].map(cn) # full country names for the layman hit = out.iloc[-1]; broad = out.iloc[0] # single hue (the old navy/blue split encoded an unlabeled, arbitrary above-median cut); # the leader's label carries the scale context that dramatizes the number texts = [f"{s:.0%}" for s in out["top10_share"]] texts[-1] = f"{hit['top10_share']:.0%} (top 10 of {int(hit['n_titles']):,} titles watched there)" fig = go.Figure() # navy = the leader (the most hit-dependent market, the headline subject) ONLY; pale field fig.add_trace(go.Bar(x=out["top10_share"], y=out["geo_code"], orientation="h", marker=dict(color=lib.leader_colors(out["top10_share"])), text=texts, textposition="outside", textfont=dict(size=11, color=lib.INK), cliponaxis=False, showlegend=False, hovertemplate="%{y}
top 10 titles = %{x:.0%} of viewing")) fig.update_xaxes(range=lib.pad_range(out["top10_share"], labels=texts, fig_width=1200)) if lib.near_tie(out["top10_share"], fmt=lambda v: f"{v:.0%}"): second = out.iloc[-2] title_lesson = (f"Hit-dependence by country: {hit['geo_code']} and {second['geo_code']} lean hardest on their hits - the top 10 titles are " f"{hit['top10_share']:.0%} of all viewing; {broad['geo_code']} is the broadest ({broad['top10_share']:.0%})") else: title_lesson = (f"Hit-dependence by country: {hit['geo_code']} leans hardest on its hits - its top 10 titles alone are {hit['top10_share']:.0%} " f"of all viewing; {broad['geo_code']} is the broadest ({broad['top10_share']:.0%})") what = ("Hit-dependence is how much of a market's total viewing rides on its few biggest titles - here, the share of all a country's " "viewing that goes to just its top 10 titles. High = a 'monoculture' where a few hits dominate; low = a broad market where attention is spread across many titles.") why = ("It changes how you win a market. In a hit-driven country, you need one of the few blockbusters to matter; in a broad market, a " "deep, varied catalog pays off. The same global title can land very differently depending on the market's shape.") fig.update_layout(**lib.layout_v2(title_lesson, what, width=1200, height=680), xaxis=lib.standard_xaxis("Share of the market's viewing from its top 10 titles", tickformat=".0%"), yaxis=lib.standard_yaxis(showgrid=False)) lib.add_why_and_footer(fig, why, scope_footer(lib.assemble_footer("PC-D-10", ["CL-006 viewer panel (distinct viewers), not census"], freshness, ["PeerLogix country-viewing share (90-day)"], f"major markets (n={len(out)})"))) lib.save_csv(out, output_dir); lib.export_chart(fig, output_dir, width=1200, 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-D-10", intended_lesson_from_spec="Hit-driven vs broad markets (redesigned from volatility)", rendered_lesson={"reader_title": title_lesson, "reader_subtitle": what, "claim_strength": "strong", "rules_applied": "top-10 viewing share per market"}, row_count=len(out), freshness_date=freshness, query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec) return {"status": "ok", "rows": len(out)}