-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
362 lines (323 loc) · 17 KB
/
Copy pathapp.py
File metadata and controls
362 lines (323 loc) · 17 KB
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
"""
Frontend Streamlit para el sistema de detección de logos de videojuegos.
Uso:
streamlit run app.py
"""
import streamlit as st
import requests
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# ──────────────────────────────────────────────
# Configuración de página
# ──────────────────────────────────────────────
st.set_page_config(
page_title="|Logo Detector|",
page_icon="🎮",
layout="wide",
initial_sidebar_state="expanded"
)
API_URL_LOCAL = "http://127.0.0.1:8000"
API_URL_HF = "https://michh14-logo-detector.hf.space"
# ──────────────────────────────────────────────
# Estilos CSS
# ──────────────────────────────────────────────
st.markdown("""
<style>
.stApp { background-color: #0d0d1a; }
[data-testid="stSidebar"] { background-color: #12122b; border-right: 1px solid #2a2a5a; }
.main-title {
font-size: 2.8rem;
font-weight: 800;
background: linear-gradient(135deg, #7b2ff7, #00d4ff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-align: center;
margin-bottom: 0.2rem;
}
.main-subtitle {
text-align: center;
color: #8888bb;
font-size: 1rem;
margin-bottom: 2rem;
}
.frame-label {
font-size: 0.8rem;
color: #8888bb;
text-align: center;
margin-top: 4px;
}
[data-testid="stMetricValue"] {
color: #00d4ff !important;
font-size: 1.6rem !important;
font-weight: 700 !important;
}
[data-testid="stMetricLabel"] { color: #8888bb !important; }
.stTextInput input {
background-color: #1a1a3e !important;
color: white !important;
border: 1px solid #3a3a7a !important;
border-radius: 8px !important;
}
.stButton > button {
background: linear-gradient(135deg, #7b2ff7, #00d4ff) !important;
color: white !important;
font-weight: 700 !important;
border: none !important;
border-radius: 8px !important;
padding: 0.6rem 2rem !important;
font-size: 1rem !important;
width: 100% !important;
}
.stButton > button:hover { opacity: 0.85 !important; }
hr { border-color: #2a2a5a !important; }
p, li, span { color: #ccccee !important; }
h1, h2, h3 { color: #ffffff !important; }
</style>
""", unsafe_allow_html=True)
# ──────────────────────────────────────────────
# Helper
# ──────────────────────────────────────────────
def check_api(url: str) -> bool:
try:
return requests.get(f"{url}/", timeout=3).status_code == 200
except Exception:
return False
# ──────────────────────────────────────────────
# Sidebar
# ──────────────────────────────────────────────
with st.sidebar:
st.markdown("## ⚙️ Configuración")
st.divider()
conf_threshold = st.slider(
"Umbral de confianza",
min_value=0.20, max_value=0.90,
value=0.50, step=0.05,
help="Sube el umbral para reducir falsos positivos."
)
st.divider()
st.markdown("**Estado de la API**")
st.markdown("🖥️ Local")
if check_api(API_URL_LOCAL):
st.success("✅ Conectada")
else:
st.error("❌ Sin conexión")
st.caption("Ejecuta:\n`uvicorn main:app --reload`")
st.markdown("☁️ HuggingFace")
if check_api(API_URL_HF):
st.success("✅ Conectada")
try:
info = requests.get(f"{API_URL_HF}/", timeout=3).json()
with st.expander("Clases disponibles"):
for clase in info.get("clases", []):
st.markdown(f"• `{clase}`")
except Exception:
pass
else:
st.error("❌ Sin conexión")
st.divider()
st.markdown("### 📂 Historial")
historial_api = st.radio("Ver historial de:", ["Local", "HuggingFace"], horizontal=True)
if st.button("🔄 Cargar historial"):
api_hist = API_URL_LOCAL if historial_api == "Local" else API_URL_HF
try:
videos = requests.get(f"{api_hist}/videos", timeout=5).json()
if videos:
for v in videos[:5]:
st.markdown(f"**{v['nombre']}**")
st.caption(f"ID: {v['id']} | {v['duracion_s']:.0f}s | {v['fecha_analisis'][:10]}")
else:
st.info("No hay vídeos analizados aún.")
except Exception:
st.error("No se pudo conectar con la API.")
# ──────────────────────────────────────────────
# Contenido principal
# ──────────────────────────────────────────────
st.markdown('<div class="main-title">🎮 Logo Detector</div>', unsafe_allow_html=True)
st.markdown('<div class="main-subtitle">Detección de logos de videojuegos en vídeos con YOLOv8</div>', unsafe_allow_html=True)
st.divider()
# ── Selector de modo ───────────────────────────────────────────────────────
modo = st.radio(
"Modo de análisis",
["🔗 URL de YouTube (local)", "📁 Subir vídeo (HuggingFace)"],
horizontal=True
)
st.divider()
if modo == "🔗 URL de YouTube (local)":
col_input, col_btn = st.columns([4, 1])
with col_input:
url = st.text_input(
"URL", placeholder="https://www.youtube.com/watch?v=...",
label_visibility="collapsed"
)
with col_btn:
analizar = st.button("🔍 Analizar", use_container_width=True)
uploaded_file = None
else:
uploaded_file = st.file_uploader(
"Sube tu vídeo",
type=["mp4", "avi", "mkv", "mov"],
label_visibility="collapsed"
)
analizar = st.button("🔍 Analizar", use_container_width=True)
url = None
st.divider()
# ──────────────────────────────────────────────
# Análisis
# ──────────────────────────────────────────────
if analizar:
if modo == "🔗 URL de YouTube (local)" and not url:
st.warning("⚠️ Introduce una URL de YouTube primero.")
elif modo == "📁 Subir vídeo (HuggingFace)" and not uploaded_file:
st.warning("⚠️ Sube un vídeo primero.")
else:
api = API_URL_LOCAL if modo == "🔗 URL de YouTube (local)" else API_URL_HF
if not check_api(api):
st.error(f"❌ No hay conexión con la API ({'local' if api == API_URL_LOCAL else 'HuggingFace'}). "
f"{'Ejecuta `uvicorn main:app --reload`' if api == API_URL_LOCAL else 'Comprueba el Space en HuggingFace'}")
else:
with st.spinner("⬇️ Analizando el vídeo... puede tardar unos minutos"):
try:
if modo == "🔗 URL de YouTube (local)":
resp = requests.post(
f"{api}/analizar",
json={"url": url, "conf": conf_threshold},
timeout=600
)
else:
resp = requests.post(
f"{api}/analizar",
files={"file": (uploaded_file.name, uploaded_file.getvalue(), "video/mp4")},
params={"conf": conf_threshold},
timeout=600
)
data = resp.json()
if "detail" in data:
st.error(f"❌ {data['detail']}")
else:
st.success("✅ Análisis completado")
# ── Métricas generales ─────────────────────────────
st.markdown("### 📊 Resumen general")
m1, m2, m3, m4 = st.columns(4)
m1.metric("⏱️ Duración", f"{data['duracion_s']}s")
m2.metric("🎞️ Total frames", data['total_frames'])
m3.metric("📺 FPS", data['fps'])
m4.metric("🏷️ Marcas detectadas", len(data['marcas']))
st.divider()
if not data["marcas"]:
st.info("No se detectaron logos. Prueba bajando el umbral de confianza.")
else:
marcas_sorted = sorted(
data["marcas"].items(),
key=lambda x: -x[1]["porcentaje"]
)
# ── Frames representativos ─────────────────────
st.markdown("### 🖼️ Detecciones visuales")
st.caption("Mejor frame detectado por cada marca con su bounding box")
cols_per_row = 3
marcas_list = list(marcas_sorted)
for i in range(0, len(marcas_list), cols_per_row):
row_marcas = marcas_list[i:i + cols_per_row]
cols = st.columns(cols_per_row)
for col, (marca, info) in zip(cols, row_marcas):
with col:
frame_url = info.get("frame_url")
if frame_url:
try:
img_resp = requests.get(
f"{api}{frame_url}", timeout=10
)
if img_resp.status_code == 200:
st.image(img_resp.content, use_container_width=True)
except Exception:
st.info("Frame no disponible")
st.markdown(
f"<div class='frame-label'>"
f"<b>{marca.upper()}</b> · "
f"{info['confianza_maxima']}% confianza máx."
f"</div>",
unsafe_allow_html=True
)
st.divider()
# ── Estadísticas por marca ─────────────────────
st.markdown("### 🏷️ Estadísticas por marca")
for marca, info in marcas_sorted:
c1, c2, c3, c4 = st.columns([2, 1, 1, 1])
c1.markdown(f"**{marca.upper()}**")
c2.metric("⏱️ Tiempo", f"{info['tiempo_pantalla_s']}s")
c3.metric("📊 % vídeo", f"{info['porcentaje']}%")
c4.metric("🎯 Confianza", f"{info['confianza_media']}%")
st.progress(min(info["porcentaje"] / 100, 1.0))
st.divider()
# ── Gráficas ───────────────────────────────────
st.markdown("### 📈 Comparativa visual")
col_c1, col_c2 = st.columns(2)
nombres = [m for m, _ in marcas_sorted]
porcentajes = [i["porcentaje"] for _, i in marcas_sorted]
confianzas = [i["confianza_media"] for _, i in marcas_sorted]
colors = plt.cm.plasma([i / max(len(nombres), 1) for i in range(len(nombres))])
with col_c1:
fig1, ax1 = plt.subplots(figsize=(5, 3), facecolor="#0d0d1a")
ax1.set_facecolor("#1a1a3e")
ax1.barh(nombres, porcentajes, color=colors, edgecolor="none")
ax1.set_xlabel("% aparición", color="#8888bb", fontsize=9)
ax1.set_title("% aparición por marca", color="white", fontsize=10)
ax1.tick_params(colors="white", labelsize=8)
ax1.spines[:].set_color("#2a2a5a")
st.pyplot(fig1)
plt.close(fig1)
with col_c2:
fig2, ax2 = plt.subplots(figsize=(5, 3), facecolor="#0d0d1a")
ax2.set_facecolor("#1a1a3e")
ax2.bar(nombres, confianzas, color=colors, edgecolor="none")
ax2.set_ylabel("Confianza (%)", color="#8888bb", fontsize=9)
ax2.set_title("Confianza media por marca", color="white", fontsize=10)
ax2.tick_params(colors="white", labelsize=8)
ax2.spines[:].set_color("#2a2a5a")
plt.setp(ax2.get_xticklabels(), rotation=20, ha="right", fontsize=8)
st.pyplot(fig2)
plt.close(fig2)
# ── Tabla descargable ──────────────────────────
st.markdown("### 📋 Tabla de resultados")
df = pd.DataFrame([
{
"Marca": marca.upper(),
"Tiempo (s)": info["tiempo_pantalla_s"],
"% del vídeo": info["porcentaje"],
"Confianza media %": info["confianza_media"],
"Confianza máx %": info["confianza_maxima"],
"Frames detectados": info["frames_detectados"],
}
for marca, info in marcas_sorted
])
st.dataframe(df, use_container_width=True, hide_index=True)
st.download_button(
"⬇️ Descargar CSV",
data=df.to_csv(index=False),
file_name="resultados_logos.csv",
mime="text/csv"
)
# ── Informe PNG ────────────────────────────────
if data.get("informe_url"):
st.markdown("### 🖼️ Informe visual completo")
try:
img_resp = requests.get(
f"{api}{data['informe_url']}", timeout=10
)
if img_resp.status_code == 200:
st.image(img_resp.content, use_container_width=True)
except Exception:
st.info("El informe visual se guardó en outputs/")
except requests.exceptions.Timeout:
st.error("⏱️ Tiempo agotado. Prueba con un vídeo más corto.")
except Exception as e:
st.error(f"❌ Error inesperado: {e}")
# ── Footer ─────────────────────────────────────────────────────────────────
st.divider()
st.markdown(
"<p style='text-align:center; color:#444477; font-size:0.8rem;'>"
"v3 · Detección de logos · YOLOv8 + FastAPI + Streamlit"
"</p>",
unsafe_allow_html=True
)