ihhereanth commited on
Commit
3f0cd1b
·
verified ·
1 Parent(s): caf410e

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +869 -255
src/streamlit_app.py CHANGED
@@ -3,19 +3,229 @@ import pandas as pd
3
  import plotly.express as px
4
  import plotly.graph_objects as go
5
  from plotly.subplots import make_subplots
 
6
 
 
 
 
7
  st.set_page_config(
8
- page_title="Netflix Content Dashboard",
9
  page_icon="🎬",
10
  layout="wide",
 
11
  )
12
 
13
- st.title("🎬 Netflix Content Dashboard")
14
- st.caption("ข้อมูลจาก TMDB API · อัปเดตผ่าน Airflow Pipeline")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- # ─────────────────────────────────────────────
17
- # โหลดข้อมูล — แยก 4 ตาราง
18
- # ─────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  BASE = "hf://datasets/ihhereanth/netflix_dataset/"
20
 
21
  @st.cache_data(ttl=3600)
@@ -25,297 +235,701 @@ def load_data():
25
  credits = pd.read_parquet(BASE + "credits.parquet")
26
  keywords = pd.read_parquet(BASE + "keywords.parquet")
27
 
28
- # แปลง numeric columns ทีเดียวทั้งหมด (ป้องกัน string dtype จาก PySpark)
29
- movie_numeric = [
30
- "vote_count", "vote_average", "runtime_min",
31
- "budget_usd", "revenue_usd", "popularity",
32
- "release_year", "release_month", "roi",
33
- ]
34
- tv_numeric = [
35
- "vote_count", "vote_average", "popularity",
36
- "number_of_seasons", "number_of_episodes",
37
- "first_air_year", "last_air_year",
38
- ]
39
- for col in movie_numeric:
40
- if col in movies.columns:
41
- movies[col] = pd.to_numeric(movies[col], errors="coerce")
42
- for col in tv_numeric:
43
- if col in tv.columns:
44
- tv[col] = pd.to_numeric(tv[col], errors="coerce")
45
 
46
  return movies, tv, credits, keywords
47
 
48
- with st.spinner("กำลังโหลดข้อมูลจาก Hugging Face..."):
 
49
  try:
50
  movies, tv, credits, keywords = load_data()
51
  except Exception as e:
52
  st.error(f"โหลดข้อมูลไม่สำเร็จ: {e}")
53
- st.info("ตรวจสอบว่า Dataset ใน Hugging Face มีข้อมูลแล้ว และ repo_id ถูกต้อง")
54
  st.stop()
55
 
56
- # ─────────────────────────────────────────────
57
- # SIDEBAR — Filters
58
- # ─────────────────────────────────────────────
 
59
  with st.sidebar:
60
- st.header("🔧 ตัวกรอง")
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  all_genres = sorted({
63
  g for genres in movies["genres"].dropna()
64
  for g in (genres if isinstance(genres, list) else [])
65
  })
66
- selected_genres = st.multiselect("Genre (Movies)", all_genres, default=[])
67
 
68
  year_min = int(movies["release_year"].min()) if "release_year" in movies.columns else 2000
69
  year_max = int(movies["release_year"].max()) if "release_year" in movies.columns else 2024
70
- year_range = st.slider("ปีที่ออกฉาย", year_min, year_max, (2010, year_max))
 
 
 
 
 
 
 
 
71
 
72
- min_votes = st.slider("Vote count ขั้นต่ำ", 0, 5000, 100, step=50)
73
 
74
- # ── Apply filters ────────────────────────────
75
  movies_f = movies.copy()
76
  if selected_genres:
77
- movies_f = movies_f[movies_f["genres"].apply(
78
- lambda g: bool(set(g or []) & set(selected_genres))
79
- )]
80
  if "release_year" in movies_f.columns:
81
  movies_f = movies_f[movies_f["release_year"].between(*year_range)]
82
  if "vote_count" in movies_f.columns:
83
  movies_f = movies_f[movies_f["vote_count"] >= min_votes]
84
 
85
- # ─────────────────────────────────────────────
86
- # ROW 1 — KPI Cards
87
- # ─────────────────────────────────────────────
88
- st.subheader("📊 ภาพรวม")
89
- c1, c2, c3, c4, c5 = st.columns(5)
90
- c1.metric("🎬 Movies", f"{len(movies_f):,}")
91
- c2.metric("📺 TV Shows", f"{len(tv):,}")
92
- c3.metric("⭐ Avg Rating", f"{pd.to_numeric(movies_f['vote_average'], errors='coerce').mean():.2f}"
93
- if "vote_average" in movies_f.columns else "N/A")
94
- c4.metric("⏱️ Avg Runtime", f"{pd.to_numeric(movies_f['runtime_min'], errors='coerce').mean():.0f} min"
95
- if "runtime_min" in movies_f.columns else "N/A")
96
- c5.metric("🔑 Unique Keywords", f"{keywords['keyword'].nunique():,}" if not keywords.empty else "N/A")
97
-
98
- st.divider()
99
-
100
- # ─────────────────────────────────────────────
101
- # ROW 2 — Top Rated + Rating Distribution
102
- # ─────────────────────────────────────────────
103
- st.subheader("🏆 Top 10 Movies ที่ได้คะแนนสูงสุด")
104
- col1, col2 = st.columns([3, 2])
105
-
106
- with col1:
107
- if "vote_average" in movies_f.columns and "title" in movies_f.columns:
108
- top_rated = (movies_f[movies_f["vote_count"] >= 500]
109
- .nlargest(10, "vote_average")
110
- [["title", "vote_average", "vote_count", "release_year"]])
111
- fig = px.bar(
112
- top_rated, x="vote_average", y="title",
113
- orientation="h", color="vote_average",
114
- color_continuous_scale="RdYlGn",
115
- text="vote_average",
116
- labels={"vote_average": "คะแนน", "title": ""},
117
- )
118
- fig.update_traces(texttemplate="%{text:.2f}", textposition="outside")
119
- fig.update_layout(yaxis={"categoryorder": "total ascending"}, showlegend=False,
120
- coloraxis_showscale=False, height=400)
121
- st.plotly_chart(fig, use_container_width=True)
122
-
123
- with col2:
124
- if "vote_average" in movies_f.columns:
125
- fig2 = px.histogram(
126
- movies_f, x="vote_average", nbins=40,
127
- color_discrete_sequence=["#E50914"],
128
- labels={"vote_average": "คะแนน", "count": "จำนวน"},
129
- title="การกระจายของ Rating",
130
- )
131
- fig2.update_layout(height=400, bargap=0.05)
132
- st.plotly_chart(fig2, use_container_width=True)
133
 
134
- # ─────────────────────────────────────────────
135
- # ROW 3 — Genre Analysis
136
- # ─────────────────────────────────────────────
137
- st.subheader("🎭 Genre Analysis")
138
- col3, col4 = st.columns(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
- with col3:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  genre_counts = (
142
- movies_f.explode("genres")
143
- .groupby("genres")["title"]
144
- .count()
145
- .reset_index()
146
- .rename(columns={"title": "count", "genres": "genre"})
147
- .sort_values("count", ascending=False)
148
- .head(15)
149
  )
150
- fig3 = px.bar(
151
  genre_counts, x="count", y="genre", orientation="h",
152
- color="count", color_continuous_scale="Reds",
153
- title="จำนวน Movies แต่ละ Genre",
154
- labels={"count": "จำนวน", "genre": ""},
 
 
155
  )
156
- fig3.update_layout(yaxis={"categoryorder": "total ascending"},
157
- coloraxis_showscale=False, height=420)
158
- st.plotly_chart(fig3, use_container_width=True)
 
159
 
160
- with col4:
161
  genre_rating = (
162
- movies_f.explode("genres")
163
- .groupby("genres")["vote_average"]
164
- .mean()
165
- .reset_index()
166
- .rename(columns={"genres": "genre"})
167
- .sort_values("vote_average", ascending=False)
168
- .head(15)
169
  )
170
- fig4 = px.bar(
171
- genre_rating, x="vote_average", y="genre", orientation="h",
172
- color="vote_average", color_continuous_scale="RdYlGn",
173
- title="Rating เฉลี่ยแต่ละ Genre",
174
- labels={"vote_average": "Rating เฉลี่ย", "genre": ""},
 
 
175
  )
176
- fig4.update_layout(yaxis={"categoryorder": "total ascending"},
177
- coloraxis_showscale=False, height=420)
178
- st.plotly_chart(fig4, use_container_width=True)
179
-
180
- # ─────────────────────────────────────────────
181
- # ROW 4 — Content Over Time
182
- # ─────────────────────────────────────────────
183
- st.subheader("📅 Content ที่เพิ่มขึ้นตามปี")
184
- if "release_year" in movies_f.columns and "first_air_year" in tv.columns:
185
- col5, col6 = st.columns(2)
186
-
187
- with col5:
188
- by_year = movies_f.groupby("release_year").size().reset_index(name="count")
189
- fig5 = px.area(by_year, x="release_year", y="count",
190
- color_discrete_sequence=["#E50914"],
191
- title="จำนวน Movies ต่อปี",
192
- labels={"release_year": "ปี", "count": "จำนวน"})
193
- st.plotly_chart(fig5, use_container_width=True)
194
-
195
- with col6:
196
- tv_year = tv.groupby("first_air_year").size().reset_index(name="count")
197
- tv_year = tv_year[tv_year["first_air_year"] >= 1990]
198
- fig6 = px.area(tv_year, x="first_air_year", y="count",
199
- color_discrete_sequence=["#564d9f"],
200
- title="จำนวน TV Shows ต่อปี",
201
- labels={"first_air_year": "ปี", "count": "จำนวน"})
202
- st.plotly_chart(fig6, use_container_width=True)
203
-
204
- # ─────────────────────────────────────────────
205
- # ROW 5 — Budget vs Revenue Scatter (Movies)
206
- # ─────────────────────────────────────────────
207
- if all(c in movies_f.columns for c in ["budget_usd", "revenue_usd", "title"]):
208
- st.subheader("💰 Budget vs Revenue")
209
- scatter_df = movies_f[
210
- (movies_f["budget_usd"] > 1_000_000) &
211
- (movies_f["revenue_usd"] > 1_000_000)
212
- ].copy()
213
-
214
- if not scatter_df.empty:
215
- scatter_df["roi_label"] = scatter_df["roi"].apply(
216
- lambda x: f"{x:.1f}x" if pd.notna(x) else "N/A"
 
 
 
 
 
217
  )
218
- fig7 = px.scatter(
219
- scatter_df,
220
- x="budget_usd", y="revenue_usd",
221
- color="roi", size="vote_count",
222
- hover_name="title",
223
- hover_data={"budget_usd": ":,.0f", "revenue_usd": ":,.0f", "roi_label": True},
224
- color_continuous_scale="RdYlGn",
225
- log_x=True, log_y=True,
226
- title="Budget vs Revenue (log scale) — ขนาดฟอง = จำนวน votes",
227
- labels={"budget_usd": "Budget (USD)", "revenue_usd": "Revenue (USD)", "roi": "ROI"},
 
 
 
 
 
 
228
  )
229
- max_val = max(scatter_df["budget_usd"].max(), scatter_df["revenue_usd"].max())
230
- fig7.add_shape(type="line", x0=1e6, y0=1e6, x1=max_val, y1=max_val,
231
- line={"color": "gray", "dash": "dash", "width": 1})
232
- fig7.add_annotation(x=9, y=9, xref="x", yref="y",
233
- text="Break-even", showarrow=False,
234
- font={"color": "gray", "size": 11})
235
- st.plotly_chart(fig7, use_container_width=True)
236
-
237
- # ─────────────────────────────────────────────
238
- # ROW 6 — Credits Analysis
239
- # ─────────────────────────────────────────────
240
- st.subheader("🎭 Credits Analysis")
241
- col7, col8 = st.columns(2)
242
-
243
- with col7:
244
- top_cast = (credits[credits["role"] == "cast"]
245
- .groupby("name").size()
246
- .reset_index(name="appearances")
247
- .nlargest(15, "appearances"))
248
- fig8 = px.bar(top_cast, x="appearances", y="name", orientation="h",
249
- color="appearances", color_continuous_scale="Blues",
250
- title="นักแสดงที่ปรากฏใน Netflix มากที่สุด",
251
- labels={"appearances": "จำนวนเรื่อง", "name": ""})
252
- fig8.update_layout(yaxis={"categoryorder": "total ascending"},
253
- coloraxis_showscale=False, height=400)
254
- st.plotly_chart(fig8, use_container_width=True)
255
-
256
- with col8:
257
- gender_counts = (credits[credits["role"] == "cast"]
258
- .groupby("gender").size()
259
- .reset_index(name="count"))
260
- fig9 = px.pie(gender_counts, names="gender", values="count",
261
- color_discrete_sequence=["#E50914", "#564d9f", "#aaaaaa"],
262
- title="สัดส่วน Gender ของนักแสดง",
263
- hole=0.4)
264
- fig9.update_traces(textinfo="percent+label")
265
- st.plotly_chart(fig9, use_container_width=True)
266
-
267
- # ─────────────────────────────────────────────
268
- # ROW 7 — TV Show Status + Content Rating
269
- # ─────────────────────────────────────────────
270
- st.subheader("📺 TV Show Overview")
271
- col9, col10 = st.columns(2)
272
-
273
- with col9:
274
  if "status" in tv.columns:
275
  status_counts = tv["status"].value_counts().reset_index()
276
  status_counts.columns = ["status", "count"]
277
- fig10 = px.pie(status_counts, names="status", values="count",
278
- title="สถานะ TV Shows",
279
- color_discrete_sequence=px.colors.qualitative.Set2,
280
- hole=0.35)
281
- st.plotly_chart(fig10, use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
 
283
- with col10:
 
 
 
 
 
 
 
 
 
284
  if "us_content_rating" in tv.columns:
285
- rating_counts = (tv["us_content_rating"].dropna()
286
- .value_counts().reset_index())
287
- rating_counts.columns = ["rating", "count"]
288
- fig11 = px.bar(rating_counts, x="rating", y="count",
289
- color="rating",
290
- title="US Content Rating ของ TV Shows",
291
- labels={"rating": "Rating", "count": "จำนวน"})
292
- fig11.update_layout(showlegend=False)
293
- st.plotly_chart(fig11, use_container_width=True)
294
-
295
- # ─────────────────────────────────────────────
296
- # ROW 8 Top Keywords
297
- # ─────────────────────────────────────────────
298
- st.subheader("🔑 Keywords ที่พบบ่อยที่สุด")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  if not keywords.empty:
300
- top_kw = (keywords.groupby("keyword").size()
301
- .reset_index(name="count")
302
- .nlargest(20, "count"))
303
- fig12 = px.treemap(top_kw, path=["keyword"], values="count",
304
- color="count", color_continuous_scale="Reds",
305
- title="Top 20 Keywords ใน Netflix Content")
306
- fig12.update_layout(height=400)
307
- st.plotly_chart(fig12, use_container_width=True)
308
-
309
- # ─────────────────────────────────────────────
310
- # ROW 9 — Raw Data Explorer
311
- # ─────────────────────────────────────────────
312
- with st.expander("🗃️ ดูข้อมูลดิบ"):
313
- tab1, tab2, tab3, tab4 = st.tabs(["Movies", "TV Shows", "Credits", "Keywords"])
314
- with tab1:
315
- st.dataframe(movies_f.head(100), use_container_width=True)
316
- with tab2:
317
- st.dataframe(tv.head(100), use_container_width=True)
318
- with tab3:
319
- st.dataframe(credits.head(100), use_container_width=True)
320
- with tab4:
321
- st.dataframe(keywords.head(100), use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import plotly.express as px
4
  import plotly.graph_objects as go
5
  from plotly.subplots import make_subplots
6
+ import numpy as np
7
 
8
+ # ─────────────────────────────────────────────────────────────────────────────
9
+ # PAGE CONFIG
10
+ # ─────────────────────────────────────────────────────────────────────────────
11
  st.set_page_config(
12
+ page_title="Netflix Analytics",
13
  page_icon="🎬",
14
  layout="wide",
15
+ initial_sidebar_state="expanded",
16
  )
17
 
18
+ # ─────────────────────────────────────────────────────────────────────────────
19
+ # GLOBAL THEME CSS
20
+ # ─────────────────────────────────────────────────────────────────────────────
21
+ NETFLIX_RED = "#E50914"
22
+ NETFLIX_DARK = "#141414"
23
+ NETFLIX_CARD = "#1f1f1f"
24
+ NETFLIX_GRAY = "#2a2a2a"
25
+ ACCENT_PURPLE = "#6C5CE7"
26
+ ACCENT_TEAL = "#00B4D8"
27
+ TEXT_PRIMARY = "#FFFFFF"
28
+ TEXT_MUTED = "#9e9e9e"
29
+
30
+ PLOTLY_TEMPLATE = dict(
31
+ layout=go.Layout(
32
+ paper_bgcolor="rgba(0,0,0,0)",
33
+ plot_bgcolor="rgba(0,0,0,0)",
34
+ font=dict(family="DM Sans, sans-serif", color=TEXT_PRIMARY, size=12),
35
+ xaxis=dict(gridcolor="#2a2a2a", linecolor="#2a2a2a", tickcolor="#9e9e9e"),
36
+ yaxis=dict(gridcolor="#2a2a2a", linecolor="#2a2a2a", tickcolor="#9e9e9e"),
37
+ colorway=[NETFLIX_RED, ACCENT_PURPLE, ACCENT_TEAL, "#F39C12", "#27AE60"],
38
+ legend=dict(bgcolor="rgba(0,0,0,0)", font=dict(color=TEXT_PRIMARY)),
39
+ margin=dict(l=10, r=10, t=40, b=10),
40
+ title=dict(font=dict(size=14, color=TEXT_PRIMARY)),
41
+ )
42
+ )
43
+
44
+ st.markdown(f"""
45
+ <style>
46
+ @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600;700&family=Bebas+Neue&display=swap');
47
+
48
+ /* ── Reset & Base ── */
49
+ html, body, [data-testid="stAppViewContainer"] {{
50
+ background-color: {NETFLIX_DARK};
51
+ color: {TEXT_PRIMARY};
52
+ font-family: 'DM Sans', sans-serif;
53
+ }}
54
+ [data-testid="stAppViewContainer"] {{
55
+ background: radial-gradient(ellipse at top left, #1a0a0a 0%, {NETFLIX_DARK} 50%);
56
+ }}
57
+ [data-testid="stSidebar"] {{
58
+ background-color: #0d0d0d !important;
59
+ border-right: 1px solid #2a2a2a;
60
+ }}
61
+ [data-testid="stSidebar"] * {{ color: {TEXT_PRIMARY} !important; }}
62
+ [data-testid="stMetricLabel"] {{ color: {TEXT_MUTED} !important; font-size: 11px !important; }}
63
+ [data-testid="stMetricValue"] {{ color: {TEXT_PRIMARY} !important; font-size: 22px !important; font-weight: 700; }}
64
+
65
+ /* ── Divider ── */
66
+ hr {{ border-color: #2a2a2a !important; margin: 1.5rem 0; }}
67
+
68
+ /* ── Plotly Charts ── */
69
+ .js-plotly-plot .plotly {{ border-radius: 12px; }}
70
+
71
+ /* ── Section Header ── */
72
+ .section-header {{
73
+ font-family: 'Bebas Neue', sans-serif;
74
+ font-size: 26px;
75
+ letter-spacing: 2px;
76
+ color: {TEXT_PRIMARY};
77
+ margin: 0.5rem 0 1rem 0;
78
+ padding-bottom: 6px;
79
+ border-bottom: 2px solid {NETFLIX_RED};
80
+ display: inline-block;
81
+ }}
82
+
83
+ /* ── KPI Card ── */
84
+ .kpi-card {{
85
+ background: linear-gradient(135deg, {NETFLIX_CARD} 0%, #252525 100%);
86
+ border: 1px solid #2f2f2f;
87
+ border-radius: 12px;
88
+ padding: 20px 18px;
89
+ text-align: center;
90
+ transition: transform 0.2s, border-color 0.2s;
91
+ position: relative;
92
+ overflow: hidden;
93
+ }}
94
+ .kpi-card::before {{
95
+ content: '';
96
+ position: absolute;
97
+ top: 0; left: 0; right: 0;
98
+ height: 3px;
99
+ background: linear-gradient(90deg, {NETFLIX_RED}, {ACCENT_PURPLE});
100
+ }}
101
+ .kpi-card:hover {{ transform: translateY(-3px); border-color: {NETFLIX_RED}; }}
102
+ .kpi-card .kpi-icon {{ font-size: 28px; margin-bottom: 6px; }}
103
+ .kpi-card .kpi-value {{
104
+ font-size: 28px; font-weight: 700;
105
+ color: {TEXT_PRIMARY}; line-height: 1;
106
+ }}
107
+ .kpi-card .kpi-label {{
108
+ font-size: 11px; font-weight: 500;
109
+ color: {TEXT_MUTED}; letter-spacing: 1px;
110
+ text-transform: uppercase; margin-top: 4px;
111
+ }}
112
+ .kpi-card .kpi-delta {{
113
+ font-size: 12px; margin-top: 8px;
114
+ padding: 2px 8px; border-radius: 20px;
115
+ display: inline-block;
116
+ }}
117
+ .kpi-delta-pos {{ background: rgba(39,174,96,0.2); color: #27AE60; }}
118
+ .kpi-delta-neg {{ background: rgba(229,9,20,0.2); color: {NETFLIX_RED}; }}
119
+ .kpi-delta-neu {{ background: rgba(158,158,158,0.15); color: {TEXT_MUTED}; }}
120
+
121
+ /* ── Insight Card ── */
122
+ .insight-card {{
123
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
124
+ border: 1px solid {ACCENT_PURPLE}33;
125
+ border-left: 3px solid {ACCENT_PURPLE};
126
+ border-radius: 10px;
127
+ padding: 14px 16px;
128
+ margin-bottom: 10px;
129
+ }}
130
+ .insight-card.red {{ border-left-color: {NETFLIX_RED}; background: linear-gradient(135deg, #1a0808 0%, #1f0f0f 100%); }}
131
+ .insight-card.teal {{ border-left-color: {ACCENT_TEAL}; background: linear-gradient(135deg, #051a1f 0%, #0a1f25 100%); }}
132
+ .insight-icon {{ font-size: 18px; margin-right: 8px; }}
133
+ .insight-text {{ font-size: 13px; color: {TEXT_MUTED}; line-height: 1.5; }}
134
+ .insight-text strong {{ color: {TEXT_PRIMARY}; }}
135
+
136
+ /* ── Comparison Badge ── */
137
+ .compare-badge {{
138
+ display: inline-flex; align-items: center; gap: 6px;
139
+ padding: 4px 12px; border-radius: 20px;
140
+ font-size: 12px; font-weight: 600;
141
+ }}
142
+ .badge-movie {{ background: rgba(229,9,20,0.15); color: {NETFLIX_RED}; border: 1px solid {NETFLIX_RED}44; }}
143
+ .badge-tv {{ background: rgba(108,92,231,0.15); color: {ACCENT_PURPLE}; border: 1px solid {ACCENT_PURPLE}44; }}
144
+
145
+ /* ── Dashboard Hero ── */
146
+ .hero-title {{
147
+ font-family: 'Bebas Neue', sans-serif;
148
+ font-size: 52px;
149
+ letter-spacing: 4px;
150
+ color: {TEXT_PRIMARY};
151
+ line-height: 1;
152
+ margin: 0;
153
+ }}
154
+ .hero-title span {{ color: {NETFLIX_RED}; }}
155
+ .hero-subtitle {{
156
+ font-size: 13px;
157
+ color: {TEXT_MUTED};
158
+ letter-spacing: 2px;
159
+ text-transform: uppercase;
160
+ margin-top: 4px;
161
+ }}
162
+
163
+ /* ── Tab styling ── */
164
+ [data-testid="stTabs"] [role="tab"] {{
165
+ color: {TEXT_MUTED};
166
+ font-weight: 500;
167
+ border-bottom: 2px solid transparent;
168
+ }}
169
+ [data-testid="stTabs"] [role="tab"][aria-selected="true"] {{
170
+ color: {TEXT_PRIMARY};
171
+ border-bottom: 2px solid {NETFLIX_RED};
172
+ }}
173
+
174
+ /* Expander */
175
+ [data-testid="stExpander"] {{
176
+ background: {NETFLIX_CARD};
177
+ border: 1px solid #2f2f2f;
178
+ border-radius: 10px;
179
+ }}
180
+
181
+ /* Multiselect */
182
+ [data-testid="stMultiSelect"] > div > div {{ background: {NETFLIX_GRAY}; border-color: #3a3a3a; }}
183
+ </style>
184
+ """, unsafe_allow_html=True)
185
+
186
+
187
+ # ─────────────────────────────────────────────────────────────────────────────
188
+ # HELPER — reusable chart style
189
+ # ─────────────────────────────────────────────────────────────────────────────
190
+ def apply_theme(fig, height=380):
191
+ fig.update_layout(
192
+ **PLOTLY_TEMPLATE["layout"].to_plotly_json(),
193
+ height=height,
194
+ )
195
+ return fig
196
+
197
+
198
+ def section(label):
199
+ st.markdown(f'<div class="section-header">{label}</div>', unsafe_allow_html=True)
200
 
201
+
202
+ def insight(text, style="purple"):
203
+ cls = "red" if style == "red" else ("teal" if style == "teal" else "")
204
+ icons = {"red": "🔴", "teal": "🔵", "": "💡"}
205
+ icon = icons.get(cls, "💡")
206
+ st.markdown(f"""
207
+ <div class="insight-card {cls}">
208
+ <span class="insight-icon">{icon}</span>
209
+ <span class="insight-text">{text}</span>
210
+ </div>""", unsafe_allow_html=True)
211
+
212
+
213
+ def kpi(icon, value, label, delta=None, delta_type="neu"):
214
+ delta_html = ""
215
+ if delta:
216
+ delta_html = f'<div class="kpi-delta kpi-delta-{delta_type}">{delta}</div>'
217
+ st.markdown(f"""
218
+ <div class="kpi-card">
219
+ <div class="kpi-icon">{icon}</div>
220
+ <div class="kpi-value">{value}</div>
221
+ <div class="kpi-label">{label}</div>
222
+ {delta_html}
223
+ </div>""", unsafe_allow_html=True)
224
+
225
+
226
+ # ─────────────────────────────────────────────────────────────────────────────
227
+ # DATA LOADING
228
+ # ─────────────────────────────────────────────────────────────────────────────
229
  BASE = "hf://datasets/ihhereanth/netflix_dataset/"
230
 
231
  @st.cache_data(ttl=3600)
 
235
  credits = pd.read_parquet(BASE + "credits.parquet")
236
  keywords = pd.read_parquet(BASE + "keywords.parquet")
237
 
238
+ movie_num = ["vote_count","vote_average","runtime_min","budget_usd","revenue_usd","popularity","release_year","release_month","roi"]
239
+ tv_num = ["vote_count","vote_average","popularity","number_of_seasons","number_of_episodes","first_air_year","last_air_year"]
240
+ for c in movie_num:
241
+ if c in movies.columns: movies[c] = pd.to_numeric(movies[c], errors="coerce")
242
+ for c in tv_num:
243
+ if c in tv.columns: tv[c] = pd.to_numeric(tv[c], errors="coerce")
244
+
245
+ # Derived columns
246
+ if "budget_usd" in movies.columns and "revenue_usd" in movies.columns:
247
+ movies["profit_usd"] = movies["revenue_usd"] - movies["budget_usd"]
248
+ if "release_year" in movies.columns:
249
+ movies["decade"] = (movies["release_year"] // 10 * 10).astype("Int64").astype(str) + "s"
250
+ if "first_air_year" in tv.columns:
251
+ tv["decade"] = (tv["first_air_year"] // 10 * 10).astype("Int64").astype(str) + "s"
252
+ if "gender" in credits.columns:
253
+ credits["gender"] = credits["gender"].map({0:"Unknown",1:"Female",2:"Male"}).fillna("Unknown")
 
254
 
255
  return movies, tv, credits, keywords
256
 
257
+
258
+ with st.spinner(""):
259
  try:
260
  movies, tv, credits, keywords = load_data()
261
  except Exception as e:
262
  st.error(f"โหลดข้อมูลไม่สำเร็จ: {e}")
 
263
  st.stop()
264
 
265
+
266
+ # ─────────────────────────────────────────────────────────────────────────────
267
+ # SIDEBAR FILTERS
268
+ # ─────────────────────────────────────────────────────────────────────────────
269
  with st.sidebar:
270
+ st.markdown("""
271
+ <div style="text-align:center; padding: 12px 0 20px 0;">
272
+ <div style="font-family:'Bebas Neue',sans-serif; font-size:28px; letter-spacing:3px; color:#E50914;">
273
+ NETFLIX
274
+ </div>
275
+ <div style="font-size:10px; letter-spacing:2px; color:#9e9e9e; text-transform:uppercase;">
276
+ Analytics Dashboard
277
+ </div>
278
+ </div>
279
+ """, unsafe_allow_html=True)
280
+
281
+ st.markdown("### 🔧 Filters")
282
 
283
  all_genres = sorted({
284
  g for genres in movies["genres"].dropna()
285
  for g in (genres if isinstance(genres, list) else [])
286
  })
287
+ selected_genres = st.multiselect("🎭 Genre", all_genres, default=[])
288
 
289
  year_min = int(movies["release_year"].min()) if "release_year" in movies.columns else 2000
290
  year_max = int(movies["release_year"].max()) if "release_year" in movies.columns else 2024
291
+ year_range = st.slider("📅 Release Year", year_min, year_max, (2010, year_max))
292
+
293
+ min_votes = st.slider("🗳️ Min Vote Count", 0, 5000, 100, step=50)
294
+
295
+ st.markdown("---")
296
+ st.markdown(f"""
297
+ <div style="font-size:11px; color:#555; text-align:center;">
298
+ Data via TMDB · Airflow Pipeline<br>Updated weekly
299
+ </div>""", unsafe_allow_html=True)
300
 
 
301
 
302
+ # ── Apply Filters ────────────────────────────────────────────────────────────
303
  movies_f = movies.copy()
304
  if selected_genres:
305
+ movies_f = movies_f[movies_f["genres"].apply(lambda g: bool(set(g or []) & set(selected_genres)))]
 
 
306
  if "release_year" in movies_f.columns:
307
  movies_f = movies_f[movies_f["release_year"].between(*year_range)]
308
  if "vote_count" in movies_f.columns:
309
  movies_f = movies_f[movies_f["vote_count"] >= min_votes]
310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
 
312
+ # ─────────────────────────────────────────────────────────────────────────────
313
+ # HERO HEADER
314
+ # ─────────────────────────────────────────────────────────────────────────────
315
+ st.markdown("""
316
+ <div style="padding: 20px 0 10px 0;">
317
+ <div class="hero-title">NETFLIX <span>ANALYTICS</span></div>
318
+ <div class="hero-subtitle">Content Intelligence Dashboard · TMDB Dataset</div>
319
+ </div>
320
+ """, unsafe_allow_html=True)
321
+
322
+ st.markdown("---")
323
+
324
+
325
+ # ─────────────────────────────────────────────────────────────────────────────
326
+ # SECTION 1 — KPI Overview
327
+ # ─────────────────────────────────────────────────────────────────────────────
328
+ section("📊 OVERVIEW")
329
+
330
+ avg_rating_m = movies_f["vote_average"].mean() if "vote_average" in movies_f else 0
331
+ avg_rating_tv = tv["vote_average"].mean() if "vote_average" in tv.columns else 0
332
+ avg_rt = movies_f["runtime_min"].mean() if "runtime_min" in movies_f else 0
333
+ total_rev = movies_f["revenue_usd"].sum() if "revenue_usd" in movies_f.columns else 0
334
+ total_budget = movies_f["budget_usd"].sum() if "budget_usd" in movies_f.columns else 0
335
+ unique_kw = keywords["keyword"].nunique() if not keywords.empty else 0
336
+
337
+ c1, c2, c3, c4, c5, c6 = st.columns(6)
338
+ with c1: kpi("🎬", f"{len(movies_f):,}", "Movies")
339
+ with c2: kpi("📺", f"{len(tv):,}", "TV Shows")
340
+ with c3: kpi("⭐", f"{avg_rating_m:.2f}", "Avg Movie Rating",
341
+ delta=f"TV: {avg_rating_tv:.2f}",
342
+ delta_type="pos" if avg_rating_m >= avg_rating_tv else "neg")
343
+ with c4: kpi("⏱️", f"{avg_rt:.0f} min", "Avg Runtime")
344
+ with c5: kpi("💰", f"${total_rev/1e9:.1f}B", "Total Revenue")
345
+ with c6: kpi("🔑", f"{unique_kw:,}", "Keywords")
346
+
347
+ st.markdown("---")
348
+
349
+
350
+ # ─────────────────────────────────────────────────────────────────────────────
351
+ # SECTION 2 — Movie vs TV Comparison
352
+ # ─────────────────────────────────────────────────────────────────────────────
353
+ section("⚔️ MOVIES vs TV SHOWS")
354
+
355
+ col_l, col_r = st.columns([1, 1], gap="large")
356
+
357
+ # ── 2A: Rating Distribution Side-by-Side ──
358
+ with col_l:
359
+ st.markdown('<span class="compare-badge badge-movie">🎬 Movies</span>&nbsp;<span class="compare-badge badge-tv">📺 TV Shows</span>', unsafe_allow_html=True)
360
+ st.markdown("**Rating Distribution**")
361
+
362
+ fig_cmp1 = go.Figure()
363
+ fig_cmp1.add_trace(go.Histogram(
364
+ x=movies_f["vote_average"].dropna(), name="Movies",
365
+ nbinsx=30, marker_color=NETFLIX_RED, opacity=0.75,
366
+ histnorm="percent",
367
+ ))
368
+ fig_cmp1.add_trace(go.Histogram(
369
+ x=tv["vote_average"].dropna(), name="TV Shows",
370
+ nbinsx=30, marker_color=ACCENT_PURPLE, opacity=0.75,
371
+ histnorm="percent",
372
+ ))
373
+ fig_cmp1.update_layout(barmode="overlay", xaxis_title="Rating", yaxis_title="% of Titles")
374
+ apply_theme(fig_cmp1, height=320)
375
+ fig_cmp1.add_vline(x=movies_f["vote_average"].median(), line_dash="dash",
376
+ line_color=NETFLIX_RED, annotation_text=f"Movie median", annotation_font_size=10)
377
+ fig_cmp1.add_vline(x=tv["vote_average"].median(), line_dash="dash",
378
+ line_color=ACCENT_PURPLE, annotation_text=f"TV median", annotation_font_size=10)
379
+ st.plotly_chart(fig_cmp1, use_container_width=True)
380
+
381
+ # ── 2B: Radar — Avg Metrics ──
382
+ with col_r:
383
+ st.markdown("**Content Profile Radar**")
384
+
385
+ def safe_norm(val, ref_max): return min(val / ref_max, 1.0) if ref_max else 0
386
+
387
+ m_rating = movies_f["vote_average"].mean() or 0
388
+ tv_rating = tv["vote_average"].mean() or 0
389
+ m_pop = movies_f["popularity"].mean() or 0
390
+ tv_pop = tv["popularity"].mean() or 0
391
+ m_votes = movies_f["vote_count"].mean() or 0
392
+ tv_votes = tv["vote_count"].mean() or 0
393
+ m_seasons = 1
394
+ tv_seasons= tv["number_of_seasons"].mean() or 1
395
+
396
+ cats = ["Rating", "Popularity", "Engagement\n(Votes)", "Longevity\n(Seasons)", "Diversity\n(Genres)"]
397
+ max_vals = [10, max(m_pop, tv_pop) or 1, max(m_votes, tv_votes) or 1, max(m_seasons, tv_seasons) or 1, 1]
398
+ m_vals = [m_rating, m_pop, m_votes, m_seasons, min(len(selected_genres)/20 if selected_genres else 0.5, 1)]
399
+ tv_vals = [tv_rating, tv_pop, tv_votes, tv_seasons, 0.7]
400
+
401
+ m_norm = [safe_norm(v, mx) * 10 for v, mx in zip(m_vals, max_vals)]
402
+ tv_norm = [safe_norm(v, mx) * 10 for v, mx in zip(tv_vals, max_vals)]
403
+
404
+ fig_radar = go.Figure()
405
+ for name, vals, color in [("Movies", m_norm, NETFLIX_RED), ("TV Shows", tv_norm, ACCENT_PURPLE)]:
406
+ fig_radar.add_trace(go.Scatterpolar(
407
+ r=vals + [vals[0]], theta=cats + [cats[0]],
408
+ fill="toself", name=name,
409
+ line=dict(color=color, width=2),
410
+ fillcolor=color + "22",
411
+ ))
412
+ fig_radar.update_layout(polar=dict(
413
+ bgcolor="rgba(0,0,0,0)",
414
+ radialaxis=dict(visible=True, range=[0, 10], gridcolor="#2a2a2a", color="#555"),
415
+ angularaxis=dict(gridcolor="#2a2a2a", color=TEXT_MUTED),
416
+ ))
417
+ apply_theme(fig_radar, height=320)
418
+ st.plotly_chart(fig_radar, use_container_width=True)
419
+
420
+ # ── 2C: Popularity by Year — Area Comparison ──
421
+ st.markdown("**Content Volume Over Time**")
422
 
423
+ if "release_year" in movies_f.columns and "first_air_year" in tv.columns:
424
+ by_year_m = movies_f.groupby("release_year").size().reset_index(name="count")
425
+ by_year_tv = tv[tv["first_air_year"] >= 1990].groupby("first_air_year").size().reset_index(name="count")
426
+ by_year_tv = by_year_tv.rename(columns={"first_air_year": "year"})
427
+ by_year_m = by_year_m.rename(columns={"release_year": "year"})
428
+
429
+ fig_timeline = go.Figure()
430
+ fig_timeline.add_trace(go.Scatter(
431
+ x=by_year_m["year"], y=by_year_m["count"],
432
+ name="Movies", mode="lines", fill="tozeroy",
433
+ line=dict(color=NETFLIX_RED, width=2),
434
+ fillcolor=NETFLIX_RED + "22",
435
+ ))
436
+ fig_timeline.add_trace(go.Scatter(
437
+ x=by_year_tv["year"], y=by_year_tv["count"],
438
+ name="TV Shows", mode="lines", fill="tozeroy",
439
+ line=dict(color=ACCENT_PURPLE, width=2),
440
+ fillcolor=ACCENT_PURPLE + "22",
441
+ ))
442
+ fig_timeline.update_layout(xaxis_title="Year", yaxis_title="Titles Added")
443
+ apply_theme(fig_timeline, height=260)
444
+ st.plotly_chart(fig_timeline, use_container_width=True)
445
+
446
+ # ── Comparison Insight Box ──
447
+ col_i1, col_i2, col_i3 = st.columns(3)
448
+ with col_i1:
449
+ diff = abs(avg_rating_m - avg_rating_tv)
450
+ winner = "TV Shows" if avg_rating_tv > avg_rating_m else "Movies"
451
+ insight(f"<strong>{winner}</strong> ได้คะแนน Rating สูงกว่าอีกฝ่ายถึง <strong>{diff:.2f} คะแนน</strong>", "red")
452
+ with col_i2:
453
+ m_count = len(movies_f); tv_count = len(tv)
454
+ ratio = m_count / (tv_count or 1)
455
+ insight(f"Netflix มี Movies มากกว่า TV Shows <strong>{ratio:.1f}x</strong> ({m_count:,} vs {tv_count:,} รายการ)", "teal")
456
+ with col_i3:
457
+ if "vote_count" in movies_f.columns and "vote_count" in tv.columns:
458
+ m_eng = movies_f["vote_count"].median(); tv_eng = tv["vote_count"].median()
459
+ eng_winner = "Movies" if m_eng > tv_eng else "TV Shows"
460
+ insight(f"<strong>{eng_winner}</strong> ได้รับ Community Engagement (votes) สูงกว่า — median <strong>{max(m_eng,tv_eng):.0f}</strong> votes")
461
+
462
+ st.markdown("---")
463
+
464
+
465
+ # ─────────────────────────────────────────────────────────────────────────────
466
+ # SECTION 3 — Top Performers
467
+ # ─────────────────────────────────────────────────────────────────────────────
468
+ section("🏆 TOP PERFORMERS")
469
+
470
+ tab1, tab2, tab3 = st.tabs(["🎬 Top Movies", "📺 Top TV Shows", "💰 Box Office"])
471
+
472
+ with tab1:
473
+ col_a, col_b = st.columns([3, 2], gap="large")
474
+ with col_a:
475
+ if "vote_average" in movies_f.columns:
476
+ top_rated = (movies_f[movies_f["vote_count"] >= 500]
477
+ .nlargest(12, "vote_average")
478
+ [["title", "vote_average", "vote_count", "release_year"]]
479
+ .reset_index(drop=True))
480
+ fig_top = px.bar(
481
+ top_rated, x="vote_average", y="title", orientation="h",
482
+ color="vote_average", color_continuous_scale=["#6C1F1F", NETFLIX_RED, "#FF6B6B"],
483
+ text="vote_average",
484
+ custom_data=["vote_count", "release_year"],
485
+ )
486
+ fig_top.update_traces(
487
+ texttemplate="%{text:.2f}",
488
+ textposition="outside",
489
+ hovertemplate="<b>%{y}</b><br>Rating: %{x:.2f}<br>Votes: %{customdata[0]:,}<br>Year: %{customdata[1]}<extra></extra>",
490
+ )
491
+ fig_top.update_layout(
492
+ yaxis={"categoryorder": "total ascending"},
493
+ coloraxis_showscale=False, showlegend=False,
494
+ )
495
+ apply_theme(fig_top, 420)
496
+ st.plotly_chart(fig_top, use_container_width=True)
497
+
498
+ with col_b:
499
+ st.markdown("#### 📌 Key Insights")
500
+ if "vote_average" in movies_f.columns:
501
+ best = movies_f[movies_f["vote_count"] >= 500].nlargest(1, "vote_average").iloc[0]
502
+ insight(f"🥇 Top-rated: <strong>{best['title']}</strong> ({best['vote_average']:.1f}/10)", "red")
503
+ avg_top10 = movies_f[movies_f["vote_count"] >= 500].nlargest(10, "vote_average")["vote_average"].mean()
504
+ insight(f"Top 10 Movies มีคะแนนเฉลี่ย <strong>{avg_top10:.2f}/10</strong> — สูงกว่าค่าเฉลี่ยทั้งหมด {avg_top10 - avg_rating_m:.2f} คะแนน")
505
+ if "release_year" in movies_f.columns:
506
+ top10_yr = movies_f[movies_f["vote_count"] >= 500].nlargest(10, "vote_average")["release_year"].mean()
507
+ insight(f"Top 10 ส่วนใหญ่ออกฉายในช่วง <strong>ปี {top10_yr:.0f}</strong> เฉลี่ย", "teal")
508
+
509
+ with tab2:
510
+ col_a, col_b = st.columns([3, 2], gap="large")
511
+ with col_a:
512
+ if "vote_average" in tv.columns and "name" in tv.columns:
513
+ top_tv = (tv[tv["vote_count"] >= 200]
514
+ .nlargest(12, "vote_average")
515
+ [["name", "vote_average", "vote_count", "number_of_seasons"]]
516
+ .reset_index(drop=True))
517
+ fig_tv = px.bar(
518
+ top_tv, x="vote_average", y="name", orientation="h",
519
+ color="vote_average", color_continuous_scale=["#1a1040", ACCENT_PURPLE, "#A29BFE"],
520
+ text="vote_average",
521
+ custom_data=["vote_count", "number_of_seasons"],
522
+ )
523
+ fig_tv.update_traces(
524
+ texttemplate="%{text:.2f}",
525
+ textposition="outside",
526
+ hovertemplate="<b>%{y}</b><br>Rating: %{x:.2f}<br>Votes: %{customdata[0]:,}<br>Seasons: %{customdata[1]}<extra></extra>",
527
+ )
528
+ fig_tv.update_layout(yaxis={"categoryorder": "total ascending"}, coloraxis_showscale=False, showlegend=False)
529
+ apply_theme(fig_tv, 420)
530
+ st.plotly_chart(fig_tv, use_container_width=True)
531
+
532
+ with col_b:
533
+ st.markdown("#### 📌 Key Insights")
534
+ if "vote_average" in tv.columns:
535
+ best_tv = tv[tv["vote_count"] >= 200].nlargest(1, "vote_average").iloc[0]
536
+ insight(f"🥇 Top-rated TV: <strong>{best_tv['name']}</strong> ({best_tv['vote_average']:.1f}/10)", "red")
537
+ if "number_of_seasons" in tv.columns:
538
+ avg_seasons = tv["number_of_seasons"].mean()
539
+ long_running = tv[tv["number_of_seasons"] >= 5]
540
+ insight(f"TV Shows มีเฉลี่ย <strong>{avg_seasons:.1f} seasons</strong> — {len(long_running)} เรื่องมี 5+ seasons")
541
+ if "status" in tv.columns:
542
+ ongoing = (tv["status"] == "Returning Series").sum()
543
+ insight(f"<strong>{ongoing} รายการ</strong> ยังคง Active อยู่ใน Netflix ปัจจุบัน", "teal")
544
+
545
+ with tab3:
546
+ if all(c in movies_f.columns for c in ["budget_usd", "revenue_usd", "title"]):
547
+ scatter_df = movies_f[
548
+ (movies_f["budget_usd"] > 1_000_000) & (movies_f["revenue_usd"] > 1_000_000)
549
+ ].copy()
550
+ if not scatter_df.empty:
551
+ scatter_df["roi_display"] = scatter_df["roi"].apply(lambda x: f"{x:.1f}x" if pd.notna(x) else "N/A")
552
+
553
+ col_a, col_b = st.columns([3, 1], gap="large")
554
+ with col_a:
555
+ fig_sc = px.scatter(
556
+ scatter_df,
557
+ x="budget_usd", y="revenue_usd",
558
+ color="roi",
559
+ size="vote_count",
560
+ hover_name="title",
561
+ hover_data={"budget_usd": ":,.0f", "revenue_usd": ":,.0f", "roi_display": True, "vote_count": False},
562
+ color_continuous_scale=["#6C1F1F", "#E50914", "#F39C12", "#27AE60"],
563
+ log_x=True, log_y=True,
564
+ labels={"budget_usd": "Budget (USD)", "revenue_usd": "Revenue (USD)", "roi": "ROI"},
565
+ )
566
+ max_val = max(scatter_df["budget_usd"].max(), scatter_df["revenue_usd"].max())
567
+ fig_sc.add_shape(type="line", x0=1e6, y0=1e6, x1=max_val, y1=max_val,
568
+ line=dict(color="#444", dash="dash", width=1))
569
+ fig_sc.add_annotation(x=np.log10(max_val*0.5), y=np.log10(max_val*0.5),
570
+ text="Break-even", showarrow=False, font=dict(color="#555", size=10))
571
+ apply_theme(fig_sc, 420)
572
+ st.plotly_chart(fig_sc, use_container_width=True)
573
+
574
+ with col_b:
575
+ st.markdown("#### 📌 Box Office")
576
+ top_rev = scatter_df.nlargest(1, "revenue_usd").iloc[0]
577
+ insight(f"💎 Highest Revenue: <strong>{top_rev['title']}</strong><br>${top_rev['revenue_usd']/1e9:.1f}B", "red")
578
+ profitable = (scatter_df["roi"] > 1).sum() if "roi" in scatter_df else 0
579
+ total_sc = len(scatter_df)
580
+ insight(f"<strong>{profitable}/{total_sc}</strong> movies ({profitable/total_sc*100:.0f}%) ทำกำไรได้เกินทุน")
581
+ if "roi" in scatter_df.columns:
582
+ top_roi = scatter_df.nlargest(1, "roi").iloc[0]
583
+ insight(f"🚀 Best ROI: <strong>{top_roi['title']}</strong> — {top_roi['roi']:.1f}x คืนทุน", "teal")
584
+
585
+ st.markdown("---")
586
+
587
+
588
+ # ─────────────────────────────────────────────────────────────────────────────
589
+ # SECTION 4 — Genre Deep-Dive
590
+ # ─────────────────────────────────────────────────────────────────────────────
591
+ section("🎭 GENRE ANALYSIS")
592
+
593
+ col_g1, col_g2, col_g3 = st.columns([2, 2, 1], gap="large")
594
+
595
+ with col_g1:
596
  genre_counts = (
597
+ movies_f.explode("genres").groupby("genres")["title"]
598
+ .count().reset_index().rename(columns={"title": "count", "genres": "genre"})
599
+ .sort_values("count", ascending=False).head(15)
 
 
 
 
600
  )
601
+ fig_gc = px.bar(
602
  genre_counts, x="count", y="genre", orientation="h",
603
+ color="count",
604
+ color_continuous_scale=["#3D0000", NETFLIX_RED],
605
+ text="count",
606
+ labels={"count": "Titles", "genre": ""},
607
+ title="Volume by Genre",
608
  )
609
+ fig_gc.update_traces(texttemplate="%{text:,}", textposition="outside")
610
+ fig_gc.update_layout(yaxis={"categoryorder": "total ascending"}, coloraxis_showscale=False)
611
+ apply_theme(fig_gc, 420)
612
+ st.plotly_chart(fig_gc, use_container_width=True)
613
 
614
+ with col_g2:
615
  genre_rating = (
616
+ movies_f.explode("genres").groupby("genres")["vote_average"]
617
+ .agg(["mean", "count"]).reset_index()
618
+ .rename(columns={"genres": "genre", "mean": "avg_rating"})
619
+ .query("count >= 10")
620
+ .sort_values("avg_rating", ascending=False).head(15)
 
 
621
  )
622
+ fig_gr = px.bar(
623
+ genre_rating, x="avg_rating", y="genre", orientation="h",
624
+ color="avg_rating",
625
+ color_continuous_scale=["#ff4b4b", "#ffaa00", "#00cc88"],
626
+ text="avg_rating",
627
+ labels={"avg_rating": "Avg Rating", "genre": ""},
628
+ title="Quality by Genre (Avg Rating)",
629
  )
630
+ fig_gr.update_traces(texttemplate="%{text:.2f}", textposition="outside")
631
+ fig_gr.update_layout(yaxis={"categoryorder": "total ascending"}, coloraxis_showscale=False)
632
+ apply_theme(fig_gr, 420)
633
+ st.plotly_chart(fig_gr, use_container_width=True)
634
+
635
+ with col_g3:
636
+ st.markdown("#### 📌 Genre Insights")
637
+ if not genre_counts.empty:
638
+ top_genre = genre_counts.iloc[0]
639
+ insight(f"<strong>{top_genre['genre']}</strong> คือ Genre ที่มีเนื้อหามากสุด: <strong>{top_genre['count']:,} เรื่อง</strong>", "red")
640
+ if not genre_rating.empty:
641
+ best_genre = genre_rating.iloc[0]
642
+ insight(f"<strong>{best_genre['genre']}</strong> มีคะแนนเฉลี่ยสูงสุด: <strong>{best_genre['avg_rating']:.2f}</strong>")
643
+ # Underrated = high rating but low volume
644
+ merged_g = genre_counts.merge(genre_rating[["genre", "avg_rating"]], on="genre")
645
+ if not merged_g.empty:
646
+ merged_g["score"] = merged_g["avg_rating"] - merged_g["count"] / merged_g["count"].max() * 2
647
+ underrated = merged_g.nlargest(1, "score").iloc[0]
648
+ insight(f"💎 Hidden Gem: <strong>{underrated['genre']}</strong> — Rating ดีแต่ยังไม่ค่อยมีเนื้อหา", "teal")
649
+
650
+ st.markdown("---")
651
+
652
+
653
+ # ─────────────────────────────────────────────────────────────────────────────
654
+ # SECTION 5 — Language & Geography
655
+ # ─────────────────────────────────────────────────────────────────────────────
656
+ section("🌍 LANGUAGE & ORIGIN")
657
+
658
+ col_l1, col_l2 = st.columns(2, gap="large")
659
+
660
+ with col_l1:
661
+ if "original_language" in movies_f.columns:
662
+ lang_counts = (movies_f["original_language"].value_counts().head(15).reset_index())
663
+ lang_counts.columns = ["language", "count"]
664
+ lang_map = {"en":"English","ja":"Japanese","ko":"Korean","fr":"French","es":"Spanish",
665
+ "de":"German","it":"Italian","pt":"Portuguese","zh":"Chinese","hi":"Hindi",
666
+ "ru":"Russian","th":"Thai","ar":"Arabic","nl":"Dutch","sv":"Swedish"}
667
+ lang_counts["language_name"] = lang_counts["language"].map(lang_map).fillna(lang_counts["language"])
668
+
669
+ fig_lang = px.bar(
670
+ lang_counts, x="count", y="language_name", orientation="h",
671
+ color="count",
672
+ color_continuous_scale=["#001a33", ACCENT_TEAL],
673
+ text="count",
674
+ title="Movies by Original Language",
675
+ labels={"count": "Movies", "language_name": ""},
676
  )
677
+ fig_lang.update_traces(texttemplate="%{text:,}", textposition="outside")
678
+ fig_lang.update_layout(yaxis={"categoryorder": "total ascending"}, coloraxis_showscale=False)
679
+ apply_theme(fig_lang, 380)
680
+ st.plotly_chart(fig_lang, use_container_width=True)
681
+
682
+ with col_l2:
683
+ if "original_language" in tv.columns:
684
+ tv_lang = (tv["original_language"].value_counts().head(10).reset_index())
685
+ tv_lang.columns = ["language", "count"]
686
+ tv_lang["language_name"] = tv_lang["language"].map(lang_map).fillna(tv_lang["language"])
687
+
688
+ fig_tv_lang = px.pie(
689
+ tv_lang, names="language_name", values="count",
690
+ hole=0.5,
691
+ color_discrete_sequence=[ACCENT_PURPLE, NETFLIX_RED, ACCENT_TEAL, "#F39C12","#27AE60","#E17055","#74B9FF","#A29BFE","#FD79A8","#55EFC4"],
692
+ title="TV Shows by Language",
693
  )
694
+ fig_tv_lang.update_traces(
695
+ textinfo="percent+label",
696
+ textfont_size=11,
697
+ hovertemplate="<b>%{label}</b><br>%{value:,} shows (%{percent})<extra></extra>",
698
+ )
699
+ apply_theme(fig_tv_lang, 380)
700
+ st.plotly_chart(fig_tv_lang, use_container_width=True)
701
+
702
+ # Language insights
703
+ col_li1, col_li2 = st.columns(2)
704
+ with col_li1:
705
+ if "original_language" in movies_f.columns:
706
+ non_en = (movies_f["original_language"] != "en").sum()
707
+ pct = non_en / len(movies_f) * 100
708
+ insight(f"<strong>{pct:.0f}%</strong> ของ Movies บน Netflix มาจากภาษาอื่น (ไม่ใช่ English) — แสดงให้เห็นความหลากหลายสากล", "teal")
709
+ with col_li2:
710
+ if "original_language" in movies_f.columns:
711
+ ko_count = (movies_f["original_language"] == "ko").sum()
712
+ ja_count = (movies_f["original_language"] == "ja").sum()
713
+ insight(f"Asian Content เติบโตแรง: <strong>Korean {ko_count} เรื่อง</strong>, <strong>Japanese {ja_count} เรื่อง</strong> — K-Drama effect ชัดเจน", "red")
714
+
715
+ st.markdown("---")
716
+
717
+
718
+ # ─────────────────────────────────────────────────────────────────────────────
719
+ # SECTION 6 — TV Show Deep-Dive
720
+ # ─────────────────────────────────────────────────────────────────────────────
721
+ section("📺 TV SHOW DEEP-DIVE")
722
+
723
+ col_t1, col_t2, col_t3 = st.columns([2, 2, 1], gap="large")
724
+
725
+ with col_t1:
 
 
 
 
 
 
 
 
 
 
 
 
 
726
  if "status" in tv.columns:
727
  status_counts = tv["status"].value_counts().reset_index()
728
  status_counts.columns = ["status", "count"]
729
+ status_colors = {
730
+ "Returning Series": "#27AE60",
731
+ "Ended": NETFLIX_RED,
732
+ "Canceled": "#E17055",
733
+ "In Production": ACCENT_TEAL,
734
+ "Planned": ACCENT_PURPLE,
735
+ }
736
+ fig_status = px.pie(
737
+ status_counts, names="status", values="count",
738
+ hole=0.55, title="TV Show Status",
739
+ color="status",
740
+ color_discrete_map=status_colors,
741
+ )
742
+ fig_status.update_traces(textinfo="percent+label", textfont_size=11)
743
+ apply_theme(fig_status, 360)
744
+ st.plotly_chart(fig_status, use_container_width=True)
745
+
746
+ with col_t2:
747
+ if "number_of_seasons" in tv.columns:
748
+ season_dist = (tv["number_of_seasons"].dropna()
749
+ .astype(int).value_counts().sort_index()
750
+ .reset_index())
751
+ season_dist.columns = ["seasons", "count"]
752
+ season_dist = season_dist[season_dist["seasons"] <= 20]
753
+
754
+ fig_seasons = px.bar(
755
+ season_dist, x="seasons", y="count",
756
+ color="count", color_continuous_scale=["#1a0040", ACCENT_PURPLE],
757
+ text="count",
758
+ title="Distribution of Seasons",
759
+ labels={"seasons": "Number of Seasons", "count": "Shows"},
760
+ )
761
+ fig_seasons.update_traces(texttemplate="%{text}", textposition="outside")
762
+ fig_seasons.update_layout(coloraxis_showscale=False, bargap=0.3)
763
+ apply_theme(fig_seasons, 360)
764
+ st.plotly_chart(fig_seasons, use_container_width=True)
765
 
766
+ with col_t3:
767
+ st.markdown("#### 📌 TV Insights")
768
+ if "status" in tv.columns:
769
+ returning = (tv["status"] == "Returning Series").sum()
770
+ ended = (tv["status"] == "Ended").sum()
771
+ insight(f"<strong>{returning}</strong> รายการยังออกอากาศอยู่ vs <strong>{ended}</strong> รายการจบแล้ว", "red")
772
+ if "number_of_seasons" in tv.columns:
773
+ one_season = (tv["number_of_seasons"] == 1).sum()
774
+ pct_one = one_season / len(tv) * 100
775
+ insight(f"<strong>{pct_one:.0f}%</strong> ของ TV Shows มีแค่ 1 season — หลายเรื่องอาจถูก cancel เร็ว")
776
  if "us_content_rating" in tv.columns:
777
+ most_rating = tv["us_content_rating"].mode().iloc[0] if not tv["us_content_rating"].dropna().empty else "N/A"
778
+ insight(f"Content Rating ที่พบมากสุดคือ <strong>{most_rating}</strong>", "teal")
779
+
780
+ st.markdown("---")
781
+
782
+
783
+ # ─────────────────────────────────────────────────────────────────────────────
784
+ # SECTION 7 — Credits & Talent
785
+ # ─────────────────────────────────────────────────────────────────────────────
786
+ section("🌟 TALENT & CREDITS")
787
+
788
+ col_c1, col_c2, col_c3 = st.columns([2, 1, 2], gap="large")
789
+
790
+ with col_c1:
791
+ top_cast = (credits[credits["role"] == "cast"]
792
+ .groupby("name").size().reset_index(name="appearances")
793
+ .nlargest(15, "appearances"))
794
+ fig_cast = px.bar(
795
+ top_cast, x="appearances", y="name", orientation="h",
796
+ color="appearances", color_continuous_scale=["#001433", ACCENT_TEAL],
797
+ text="appearances",
798
+ title="Most Appearing Cast",
799
+ labels={"appearances": "Appearances", "name": ""},
800
+ )
801
+ fig_cast.update_traces(texttemplate="%{text}", textposition="outside")
802
+ fig_cast.update_layout(yaxis={"categoryorder": "total ascending"}, coloraxis_showscale=False)
803
+ apply_theme(fig_cast, 420)
804
+ st.plotly_chart(fig_cast, use_container_width=True)
805
+
806
+ with col_c2:
807
+ if "gender" in credits.columns:
808
+ cast_only = credits[credits["role"] == "cast"]
809
+ gender_dist = cast_only["gender"].value_counts().reset_index()
810
+ gender_dist.columns = ["gender", "count"]
811
+ fig_gender = px.pie(
812
+ gender_dist, names="gender", values="count",
813
+ hole=0.55, title="Gender Distribution",
814
+ color="gender",
815
+ color_discrete_map={"Female": ACCENT_TEAL, "Male": ACCENT_PURPLE, "Unknown": "#444"},
816
+ )
817
+ fig_gender.update_traces(textinfo="percent+label", textfont_size=11)
818
+ apply_theme(fig_gender, 280)
819
+ st.plotly_chart(fig_gender, use_container_width=True)
820
+
821
+ # Insight
822
+ female_pct = gender_dist[gender_dist["gender"] == "Female"]["count"].sum() / len(cast_only) * 100
823
+ insight(f"นักแสดงหญิง <strong>{female_pct:.0f}%</strong> ของทั้งหมด — {'ยังมีช่องว่าง gender gap' if female_pct < 40 else 'สัดส่วนดีขึ้น'}", "red")
824
+
825
+ with col_c3:
826
+ top_directors = (credits[credits["character"].isin(["Director","Producer","Creator"])]
827
+ .groupby("name").size().reset_index(name="count")
828
+ .nlargest(12, "count"))
829
+ fig_dir = px.bar(
830
+ top_directors, x="count", y="name", orientation="h",
831
+ color="count", color_continuous_scale=["#1a0a20", ACCENT_PURPLE],
832
+ text="count",
833
+ title="Top Directors / Producers",
834
+ labels={"count": "Projects", "name": ""},
835
+ )
836
+ fig_dir.update_traces(texttemplate="%{text}", textposition="outside")
837
+ fig_dir.update_layout(yaxis={"categoryorder": "total ascending"}, coloraxis_showscale=False)
838
+ apply_theme(fig_dir, 420)
839
+ st.plotly_chart(fig_dir, use_container_width=True)
840
+
841
+ st.markdown("---")
842
+
843
+
844
+ # ─────────────────────────────────────────────────────────────────────────────
845
+ # SECTION 8 — Keywords & Themes
846
+ # ───────────────────────────────────���─────────────────────────────────────────
847
+ section("🔑 TRENDING THEMES")
848
+
849
  if not keywords.empty:
850
+ col_k1, col_k2 = st.columns([3, 1], gap="large")
851
+
852
+ with col_k1:
853
+ top_kw = (keywords.groupby("keyword").size().reset_index(name="count").nlargest(25, "count"))
854
+ fig_kw = px.treemap(
855
+ top_kw, path=["keyword"], values="count",
856
+ color="count", color_continuous_scale=["#200000", "#6C1F1F", NETFLIX_RED],
857
+ title="Top 25 Content Themes (Keywords)",
858
+ )
859
+ fig_kw.update_traces(
860
+ textfont=dict(size=13, family="DM Sans"),
861
+ hovertemplate="<b>%{label}</b><br>%{value:,} titles<extra></extra>",
862
+ )
863
+ apply_theme(fig_kw, 380)
864
+ st.plotly_chart(fig_kw, use_container_width=True)
865
+
866
+ with col_k2:
867
+ st.markdown("#### 📌 Theme Insights")
868
+ top1 = top_kw.iloc[0]
869
+ insight(f"<strong>'{top1['keyword']}'</strong> คือ Theme ที่ปรากฏมากสุด: <strong>{top1['count']:,} เรื่อง</strong>", "red")
870
+
871
+ # Keywords unique per media type
872
+ kw_movie = keywords[keywords["media_type"] == "movie"]["keyword"].nunique()
873
+ kw_tv = keywords[keywords["media_type"] == "tv"]["keyword"].nunique()
874
+ insight(f"Movies มี <strong>{kw_movie:,}</strong> unique themes vs TV Shows <strong>{kw_tv:,}</strong>")
875
+
876
+ # Check for "based on" type keywords
877
+ based_on = keywords[keywords["keyword"].str.contains("based on|novel|book|comic", case=False, na=False)]
878
+ insight(f"<strong>{len(based_on):,}</strong> เรื่องมี keyword เกี่ยวกับ adaptation (จากหนังสือ/comic)", "teal")
879
+
880
+ st.markdown("---")
881
+
882
+
883
+ # ─────────────────────────────────────────────────────────────────────────────
884
+ # SECTION 9 — Summary Insights Panel
885
+ # ─────────────────────────────────────────────────────────────────────────────
886
+ section("💡 EXECUTIVE SUMMARY")
887
+
888
+ ins_cols = st.columns(3)
889
+ summary_insights = [
890
+ ("red", "📊 Content Scale",
891
+ f"Netflix มีเนื้อหารวม <strong>{len(movies_f)+len(tv):,} รายการ</strong> — แบ่งเป็น Movies {len(movies_f):,} เรื่อง และ TV Shows {len(tv):,} รายการ"),
892
+ ("teal", "⭐ Quality Benchmark",
893
+ f"คะแนนเฉลี่ยทั้ง catalog อยู่ที่ <strong>{avg_rating_m:.1f}/10</strong> (Movies) และ <strong>{avg_rating_tv:.1f}/10</strong> (TV) — Netflix เน้นคุณภาพมากกว่าปริมาณ"),
894
+ ("", "🌏 Global Reach",
895
+ f"Content ไม่ใช่ภาษาอังกฤษคิดเป็น <strong>{(movies_f['original_language'] != 'en').sum()/len(movies_f)*100:.0f}%</strong> — K-Content และ European productions เติบโตต่อเนื่อง" if "original_language" in movies_f.columns else "Netflix มีเนื้อหาจากหลายภาษาทั่วโลก"),
896
+ ("red", "💰 Financial Power",
897
+ f"รายได้รวมของ Movies ในฐานข้อมูลสูงถึง <strong>${total_rev/1e9:.0f}B</strong> — ทุน ${total_budget/1e9:.0f}B → ROI เฉลี่ย {total_rev/max(total_budget,1):.1f}x" if total_rev > 0 else "ข้อมูล Box Office ครอบคลุมกว้างขวาง"),
898
+ ("teal", "📺 Binge Culture",
899
+ f"TV Shows เฉลี่ย <strong>{tv['number_of_seasons'].mean():.1f} seasons</strong> — ซีรีส์ยาวหลายฤดูกาลเป็นสูตรสำเร็จของ Netflix" if "number_of_seasons" in tv.columns else "TV Shows มีความยาวหลากหลาย"),
900
+ ("", "🎭 Genre Diversity",
901
+ f"มีมากกว่า <strong>{len(all_genres)} genres</strong> — Drama และ Comedy ครองตลาดหลัก แต่ Documentary และ Animation เติบโตเร็ว"),
902
+ ]
903
+
904
+ for idx, (style, title, text) in enumerate(summary_insights):
905
+ with ins_cols[idx % 3]:
906
+ st.markdown(f"**{title}**")
907
+ insight(text, style)
908
+
909
+ st.markdown("---")
910
+
911
+
912
+ # ─────────────────────────────────────────────────────────────────────────────
913
+ # SECTION 10 — Raw Data Explorer
914
+ # ─────────────────────────────────────────────────────────────────────────────
915
+ with st.expander("🗃️ Raw Data Explorer", expanded=False):
916
+ tab_m, tab_tv, tab_cr, tab_kw = st.tabs(["🎬 Movies", "📺 TV Shows", "🎭 Credits", "🔑 Keywords"])
917
+ with tab_m:
918
+ st.caption(f"{len(movies_f):,} records (filtered)")
919
+ st.dataframe(movies_f.head(200), use_container_width=True, height=350)
920
+ with tab_tv:
921
+ st.caption(f"{len(tv):,} records")
922
+ st.dataframe(tv.head(200), use_container_width=True, height=350)
923
+ with tab_cr:
924
+ st.caption(f"{len(credits):,} records")
925
+ st.dataframe(credits.head(200), use_container_width=True, height=350)
926
+ with tab_kw:
927
+ st.caption(f"{len(keywords):,} records")
928
+ st.dataframe(keywords.head(200), use_container_width=True, height=350)
929
+
930
+ # Footer
931
+ st.markdown(f"""
932
+ <div style="text-align:center; padding: 30px 0 10px 0; color: #444; font-size: 11px; letter-spacing: 1px;">
933
+ NETFLIX ANALYTICS DASHBOARD · DATA: TMDB API · PIPELINE: APACHE AIRFLOW → PYSPARK → HUGGING FACE
934
+ </div>
935
+ """, unsafe_allow_html=True)