File size: 12,118 Bytes
fbb4be5 212a1c0 fbb4be5 b487155 fbb4be5 8e09f07 fbb4be5 4e713ce fbb4be5 4e713ce a333b8b 9799dec a333b8b fbb4be5 4e713ce fbb4be5 4e713ce fbb4be5 4e713ce fbb4be5 4e713ce fbb4be5 212a1c0 fbb4be5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 | import os
import time
from typing import Any, Dict, Optional
import requests
import pandas as pd
import streamlit as st
import altair as alt
import matplotlib.pyplot as plt
import os
print("BOOT OK. BACKEND_URL env:", os.getenv("BACKEND_URL"))
# =========================
# Config
# =========================
st.set_page_config(
page_title="Multimodal Video Sentiment Dashboard",
page_icon="π¬",
layout="wide",
)
DEFAULT_POLL_INTERVAL_S = 2
DEFAULT_TIMEOUT_S = 10 * 60 # 10 menit
# =========================
# Helpers
# =========================
def get_backend_url() -> str:
# HF Spaces Docker: secrets = environment variables
url = os.getenv("BACKEND_URL", "")
return (url or "").strip().rstrip("/")
def safe_request_json(method: str, url: str, **kwargs) -> Dict[str, Any]:
"""
Wrapper requests dengan error message yang user-friendly.
"""
try:
resp = requests.request(method, url, timeout=kwargs.pop("timeout", 60), **kwargs)
except requests.exceptions.RequestException as e:
raise RuntimeError(f"Gagal menghubungi backend. Detail: {e}")
if not (200 <= resp.status_code < 300):
# coba ambil json error, kalau gagal ambil text
try:
payload = resp.json()
detail = payload.get("detail") or payload.get("error") or payload
except Exception:
detail = resp.text[:500]
raise RuntimeError(f"Backend error (HTTP {resp.status_code}): {detail}")
try:
return resp.json()
except Exception:
raise RuntimeError("Response backend bukan JSON yang valid.")
def check_health(backend_url: str) -> bool:
data = safe_request_json("GET", f"{backend_url}/health", timeout=20)
return bool(data.get("ok", False))
def upload_video(backend_url: str, file_bytes: bytes, filename: str) -> str:
files = {"file": (filename, file_bytes)}
data = safe_request_json("POST", f"{backend_url}/jobs/upload", files=files, timeout=120)
job_id = data.get("job_id")
if not job_id:
raise RuntimeError("Upload sukses, tapi backend tidak mengembalikan job_id.")
return job_id
def get_job(backend_url: str, job_id: str) -> Dict[str, Any]:
return safe_request_json("GET", f"{backend_url}/jobs/{job_id}", timeout=30)
def label_badge(label_text: str) -> str:
# simple visual cue
if label_text.upper() == "POSITIVE":
return "β
POSITIVE"
if label_text.upper() == "NEGATIVE":
return "β NEGATIVE"
return label_text
def render_dashboard(result: Dict[str, Any]) -> None:
summary = result.get("summary", {}) or {}
charts = result.get("charts", {}) or {}
clips = result.get("clips", []) or []
video_level = result.get("video_level", {}) or {}
meta = result.get("meta", {}) or {}
# ===== counts POS/NEG (prioritas dari summary, fallback hitung dari clips) =====
pos_clips = summary.get("positive_clips", None)
neg_clips = summary.get("negative_clips", None)
if pos_clips is None or neg_clips is None:
if isinstance(clips, list) and len(clips) > 0:
pos_clips = sum(1 for c in clips if c.get("label") == 1)
neg_clips = sum(1 for c in clips if c.get("label") == 0)
else:
pos_clips, neg_clips = 0, 0
total_clips = summary.get("total_clips", None)
if total_clips is None:
total_clips = int(pos_clips) + int(neg_clips)
# ===== majority label by clip counts =====
if pos_clips > neg_clips:
majority_label_text = "POSITIVE"
elif neg_clips > pos_clips:
majority_label_text = "NEGATIVE"
else:
majority_label_text = "TIE"
# tie-breaker: kalau seimbang, fallback ke video_level.label (mean prob)
if majority_label_text == "TIE":
if video_level.get("label") == 1:
label_text = "POSITIVE"
elif video_level.get("label") == 0:
label_text = "NEGATIVE"
else:
label_text = "TIE"
tie_note = "Jumlah klip seimbang; label ditentukan dari rata-rata probabilitas (mean)."
else:
label_text = majority_label_text
tie_note = None
# =======================
# HEADER BOX HASIL
# =======================
st.markdown("## Hasil")
with st.container(border=True):
# label warna
if label_text == "POSITIVE":
color = "#16a34a" # hijau
elif label_text == "NEGATIVE":
color = "#dc2626" # merah
else:
color = "#6b7280" # abu (tie)
st.markdown(
f"""
<div style="text-align:center; padding: 10px 0;">
<div style="font-size: 38px; font-weight: 800; color: {color};">
{label_text}
</div>
</div>
""",
unsafe_allow_html=True
)
# metrics ringkas di bawah label
m1, m2, m3 = st.columns(3)
m1.metric("Positive Clips", value=str(pos_clips))
m2.metric("Negative Clips", value=str(neg_clips))
m3.metric("Total Clips", value=str(total_clips))
st.divider()
# ===== Charts =====
left, right = st.columns([2, 1])
with left:
st.markdown("### Probabilitas per menit")
by_minute = charts.get("by_minute", []) or []
if len(by_minute) == 0:
st.info("Tidak ada data charts.by_minute.")
else:
dfm = pd.DataFrame(by_minute)
for col in ["minute", "range", "prob_mean", "n_clips"]:
if col not in dfm.columns:
dfm[col] = None
bar = (
alt.Chart(dfm)
.mark_bar()
.encode(
x=alt.X("minute:O", title="Menit"),
y=alt.Y("prob_mean:Q", title="Rata-rata prob_pos", scale=alt.Scale(domain=[0, 1])),
tooltip=[
alt.Tooltip("range:N", title="Range menit"),
alt.Tooltip("prob_mean:Q", title="prob_mean", format=".3f"),
alt.Tooltip("n_clips:Q", title="n_clips"),
],
)
.properties(height=320)
)
st.altair_chart(bar, use_container_width=True)
with st.expander("Lihat data by_minute"):
st.dataframe(dfm, use_container_width=True)
with right:
st.markdown("### Distribusi label clip")
pie = charts.get("pie", {}) or {}
pos = int(pie.get("positive", pos_clips) or 0)
neg = int(pie.get("negative", neg_clips) or 0)
if (pos + neg) == 0:
st.info("Tidak ada data charts.pie.")
else:
fig, ax = plt.subplots()
ax.pie([pos, neg], labels=["Positive", "Negative"], autopct="%1.1f%%", startangle=90)
ax.axis("equal")
st.pyplot(fig, clear_figure=True)
st.caption(f"Positive: **{pos}** | Negative: **{neg}**")
st.divider()
# ===== Clip table =====
st.markdown("### Detail per clip")
if len(clips) == 0:
st.warning("Tidak ada data clips.")
return
dfc = pd.DataFrame(clips)
desired_cols = ["idx", "start_s", "end_s", "prob_pos", "label", "logit"]
for col in desired_cols:
if col not in dfc.columns:
dfc[col] = None
if "label" in dfc.columns:
dfc["label_text"] = dfc["label"].apply(lambda x: "POSITIVE" if x == 1 else ("NEGATIVE" if x == 0 else None))
if "mask_stats" in dfc.columns:
def pick_mask(d, k):
if isinstance(d, dict):
return d.get(k)
return None
dfc["text_valid"] = dfc["mask_stats"].apply(lambda d: pick_mask(d, "text_valid"))
dfc["audio_valid"] = dfc["mask_stats"].apply(lambda d: pick_mask(d, "audio_valid"))
dfc["visual_valid"] = dfc["mask_stats"].apply(lambda d: pick_mask(d, "visual_valid"))
show_cols = ["idx", "start_s", "end_s", "prob_pos", "label_text", "text_valid", "audio_valid", "visual_valid", "asr_text"]
show_cols = [c for c in show_cols if c in dfc.columns]
for col in ["start_s", "end_s", "prob_pos", "logit"]:
if col in dfc.columns:
dfc[col] = pd.to_numeric(dfc[col], errors="coerce")
st.dataframe(dfc[show_cols].sort_values("idx"), use_container_width=True, height=420)
st.download_button(
label="β¬οΈ Download result JSON",
data=pd.Series(result).to_json(indent=2, force_ascii=False),
file_name="result.json",
mime="application/json",
)
# =========================
# UI
# =========================
st.title("π¬ Multimodal Sentiment Analysis Video")
backend_url = get_backend_url()
with st.sidebar:
st.header("βοΈ Konfigurasi")
st.write("Backend URL diambil dari **HF Secret** `BACKEND_URL`.")
st.code(backend_url if backend_url else "(BACKEND_URL belum di-set)", language="text")
poll_interval = st.number_input("Polling interval (detik)", min_value=1, max_value=10, value=DEFAULT_POLL_INTERVAL_S)
timeout_s = st.number_input("Timeout (detik)", min_value=30, max_value=3600, value=DEFAULT_TIMEOUT_S, step=30)
st.divider()
st.subheader("Cek koneksi backend")
if st.button("π Health check"):
if not backend_url:
st.error("BACKEND_URL belum di-set di Secrets.")
else:
try:
ok = check_health(backend_url)
if ok:
st.success("Backend OK β
")
else:
st.error("Backend merespons tapi ok=false.")
except Exception as e:
st.error(str(e))
if not backend_url:
st.error("BACKEND_URL belum di-set. Tambahkan di HF Space β Settings β Repository secrets β BACKEND_URL.")
st.stop()
st.markdown("### Upload Video")
uploaded = st.file_uploader("Pilih file video", type=["mp4", "mov", "mkv", "webm"])
if uploaded is not None:
st.video(uploaded)
analyze = st.button("π Analisis", type="primary", disabled=(uploaded is None))
if analyze:
# 1) health check singkat dulu biar cepat ketahuan kalau backend mati
try:
_ = check_health(backend_url)
except Exception as e:
st.error(f"Backend tidak reachable: {e}")
st.stop()
# 2) upload -> job_id
try:
with st.spinner("Mengupload video ke backend..."):
file_bytes = uploaded.getvalue()
job_id = upload_video(backend_url, file_bytes, uploaded.name)
st.success(f"Upload sukses. job_id = {job_id}")
except Exception as e:
st.error(f"Upload gagal: {e}")
st.stop()
# 3) polling status
status_box = st.empty()
progress = st.progress(0)
t0 = time.time()
last_status: Optional[str] = None
payload: Optional[Dict[str, Any]] = None
while True:
elapsed = time.time() - t0
if elapsed > float(timeout_s):
st.error(f"Timeout: job belum selesai setelah {int(timeout_s)} detik.")
st.stop()
try:
payload = get_job(backend_url, job_id)
except Exception as e:
st.error(f"Gagal polling job: {e}")
st.stop()
status = payload.get("status")
if status != last_status:
status_box.info(f"Status job: **{status}**")
last_status = status
# progress bar kasar (berdasar waktu)
progress_value = min(0.95, elapsed / float(timeout_s))
progress.progress(progress_value)
if status == "done":
progress.progress(1.0)
st.success("Selesai β
")
result = payload.get("result")
if not isinstance(result, dict):
st.error("Job done tapi result kosong / format tidak valid.")
st.stop()
render_dashboard(result)
break
if status == "failed":
progress.progress(1.0)
err = payload.get("error") or "Unknown error"
st.error(f"Job failed β\n\n{err}")
st.stop()
# queued / running
time.sleep(float(poll_interval))
|