Spaces:
Runtime error
Runtime error
File size: 21,121 Bytes
492a8d3 |
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 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
import gradio as gr
import time
import json
from typing import Dict, List, Tuple
import random
class ChromecastController:
def __init__(self):
self.tv_states = {
1: {"name": "TV - Sala Principal", "device": "Chromecast Ultra", "connected": True, "playing": False, "volume": 50, "content": "Esperando..."},
2: {"name": "TV - Barra", "device": "Chromecast 4K", "connected": True, "playing": False, "volume": 50, "content": "Esperando..."},
3: {"name": "TV - Terraza", "device": "Chromecast with Google TV", "connected": True, "playing": False, "volume": 50, "content": "Esperando..."}
}
self.current_video = None
self.is_playing = False
self.progress = 0
self.playlist = [
{"title": "Video Promocional", "source": "YouTube", "url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "duration": "3:45"},
{"title": "Video Corporativo", "source": "Vimeo", "url": "https://vimeo.com/123456789", "duration": "2:30"},
{"title": "Video Evento", "source": "Directo", "url": "https://example.com/video.mp4", "duration": "5:15"}
]
def get_tv_status(self, tv_id: int) -> Dict:
"""Get status of a specific TV"""
return self.tv_states.get(tv_id, {})
def get_all_tvs_status(self) -> List[Dict]:
"""Get status of all TVs"""
return [self.tv_states[i] for i in range(1, 4)]
def load_video(self, url: str) -> Tuple[str, str, str]:
"""Load a video URL to all TVs"""
if not url:
return "❌ Error", "Por favor, introduce una URL válida", "error"
self.current_video = url
video_name = self._extract_video_name(url)
for i in range(1, 4):
self.tv_states[i]["content"] = video_name
self.progress = 0
return "✅ Éxito", f"Video '{video_name}' cargado en todas las TVs", "success"
def _extract_video_name(self, url: str) -> str:
"""Extract video name from URL"""
if "youtube" in url.lower():
return "Video de YouTube"
elif "vimeo" in url.lower():
return "Video de Vimeo"
elif ".mp4" in url.lower():
return "Video Directo"
else:
return "Video Online"
def control_tv(self, tv_id: int, action: str) -> Tuple[str, str, str]:
"""Control individual TV"""
if tv_id not in self.tv_states:
return "❌ Error", f"TV {tv_id} no encontrada", "error"
tv = self.tv_states[tv_id]
if action == "play":
if not self.current_video:
return "❌ Error", "No hay video cargado", "error"
tv["playing"] = True
self.is_playing = True
return "✅ Reproduciendo", f"TV {tv_id} está reproduciendo", "success"
elif action == "pause":
tv["playing"] = False
return "⏸️ Pausado", f"TV {tv_id} pausado", "info"
elif action == "stop":
tv["playing"] = False
tv["content"] = "Esperando..."
return "⏹️ Detenido", f"TV {tv_id} detenido", "info"
elif action == "mute":
tv["volume"] = 0 if tv["volume"] > 0 else 50
status = "silenciado" if tv["volume"] == 0 else "activado"
return "🔇 Volumen", f"TV {tv_id} {status}", "info"
return "❌ Error", "Acción no reconocida", "error"
def control_all_tvs(self, action: str) -> Tuple[str, str, str]:
"""Control all TVs simultaneously"""
if action == "play":
if not self.current_video:
return "❌ Error", "Por favor, carga un video primero", "error"
for i in range(1, 4):
self.tv_states[i]["playing"] = True
self.is_playing = True
return "✅ Reproduciendo", "Reproduciendo en todas las TVs", "success"
elif action == "pause":
for i in range(1, 4):
self.tv_states[i]["playing"] = False
self.is_playing = False
return "⏸️ Pausado", "Pausado en todas las TVs", "info"
elif action == "stop":
for i in range(1, 4):
self.tv_states[i]["playing"] = False
self.tv_states[i]["content"] = "Esperando..."
self.is_playing = False
self.current_video = None
self.progress = 0
return "⏹️ Detenido", "Transmisión detenida", "info"
elif action == "mute":
for i in range(1, 4):
self.tv_states[i]["volume"] = 0 if self.tv_states[i]["volume"] > 0 else 50
return "🔇 Volumen", "Silencio toggled en todas las TVs", "info"
return "❌ Error", "Acción no reconocida", "error"
def change_volume(self, volume: int) -> Tuple[str, str, str]:
"""Change volume for all TVs"""
volume = max(0, min(100, volume))
for i in range(1, 4):
self.tv_states[i]["volume"] = volume
return "🔊 Volumen", f"Volumen ajustado a {volume}%", "info"
def update_progress(self) -> Tuple[float, str, str]:
"""Update playback progress"""
if self.is_playing and self.progress < 100:
self.progress += 0.5
current_seconds = int(self.progress * 2.25)
current_time = f"{current_seconds // 60:02d}:{current_seconds % 60:02d}"
duration = "03:45"
return self.progress, current_time, duration
def get_playlist(self) -> List[Dict]:
"""Get current playlist"""
return self.playlist
def add_to_playlist(self, url: str, title: str = "") -> Tuple[str, str, str]:
"""Add video to playlist"""
if not url:
return "❌ Error", "Introduce una URL primero", "error"
if not title:
title = self._extract_video_name(url)
self.playlist.append({
"title": title,
"source": "Custom",
"url": url,
"duration": "--:--"
})
return "✅ Éxito", "Video agregado a la playlist", "success"
def play_from_playlist(self, index: int) -> Tuple[str, str, str]:
"""Play video from playlist"""
if 0 <= index < len(self.playlist):
video = self.playlist[index]
return self.load_video(video["url"])
return "❌ Error", "Video no encontrado en playlist", "error"
# Initialize controller
controller = ChromecastController()
def update_tvs_display():
"""Update the TVs status display"""
statuses = controller.get_all_tvs_status()
html = ""
for i, tv in enumerate(statuses, 1):
status_class = "connected" if tv["connected"] else "disconnected"
if tv["playing"]:
status_class = "playing"
status_text = "Conectado" if status_class == "connected" else "Desconectado"
if status_class == "playing":
status_text = "Reproduciendo"
status_color = {
"connected": "#16a34a",
"playing": "#d97706",
"disconnected": "#dc2626"
}[status_class]
html += f"""
<div style="background: white; border-radius: 12px; padding: 16px; margin: 8px 0; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
<h3 style="margin: 0; display: flex; align-items: center; gap: 8px;">
📺 {tv['name']}
</h3>
<span style="background: {status_color}20; color: {status_color}; padding: 4px 12px; border-radius: 8px; font-size: 12px; font-weight: 600;">
{status_text}
</span>
</div>
<div style="display: grid; gap: 8px; margin-bottom: 12px;">
<div style="display: flex; justify-content: space-between; padding: 8px; background: #f3f4f6; border-radius: 8px;">
<span style="font-weight: 600; color: #6b7280;">Dispositivo:</span>
<span>{tv['device']}</span>
</div>
<div style="display: flex; justify-content: space-between; padding: 8px; background: #f3f4f6; border-radius: 8px;">
<span style="font-weight: 600; color: #6b7280;">Reproduciendo:</span>
<span id="tv{i}-content">{tv['content']}</span>
</div>
<div style="display: flex; justify-content: space-between; padding: 8px; background: #f3f4f6; border-radius: 8px;">
<span style="font-weight: 600; color: #6b7280;">Volumen:</span>
<span id="tv{i}-volume">{tv['volume']}%</span>
</div>
</div>
</div>
"""
return html
def update_playlist_display():
"""Update the playlist display"""
playlist = controller.get_playlist()
html = ""
for i, video in enumerate(playlist):
html += f"""
<div style="background: #f3f4f6; border-radius: 8px; padding: 12px; margin: 4px 0; cursor: pointer; transition: all 0.3s;"
onmouseover="this.style.background='#e5e7eb'" onmouseout="this.style.background='#f3f4f6'">
<div style="display: flex; justify-content: space-between; align-items: center;">
<div style="display: flex; align-items: center; gap: 12px;">
<img src="https://picsum.photos/seed/video{i}/60/40" alt="Thumbnail" style="width: 60px; height: 40px; border-radius: 4px; object-fit: cover;">
<div>
<h4 style="margin: 0; font-size: 14px;">{video['title']}</h4>
<p style="margin: 0; font-size: 12px; color: #6b7280;">{video['source']} • {video['duration']}</p>
</div>
</div>
<div style="display: flex; gap: 4px;">
<button onclick="play_playlist_item({i})" style="background: #10b981; color: white; border: none; padding: 6px 12px; border-radius: 6px; cursor: pointer;">▶️</button>
</div>
</div>
</div>
"""
return html
def load_video_url(url):
"""Load video from URL"""
title, message, status = controller.load_video(url)
return title, message, update_tvs_display(), url
def control_individual_tv(tv_id, action):
"""Control individual TV"""
title, message, status = controller.control_tv(tv_id, action)
return title, message, update_tvs_display()
def control_all_tvs_action(action):
"""Control all TVs"""
title, message, status = controller.control_all_tvs(action)
return title, message, update_tvs_display(), "" if action == "stop" else gr.update()
def change_volume_all(volume):
"""Change volume for all TVs"""
title, message, status = controller.change_volume(volume)
return title, message, update_tvs_display(), f"{volume}%"
def update_playback_progress():
"""Update playback progress"""
progress, current_time, duration = controller.update_progress()
return progress, current_time, duration
def add_video_to_playlist(url, title):
"""Add video to playlist"""
result_title, message, status = controller.add_to_playlist(url, title)
return result_title, message, update_playlist_display()
def play_playlist_item(index):
"""Play item from playlist"""
title, message, status = controller.play_from_playlist(index)
return title, message, update_tvs_display()
def load_sample_video(sample_type):
"""Load sample video"""
samples = {
"youtube": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"vimeo": "https://vimeo.com/123456789",
"direct": "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
}
url = samples.get(sample_type, "")
return load_video_url(url)
# Create Gradio interface
with gr.Blocks(title="Control Multimedia Chromecast", theme=gr.themes.Soft()) as demo:
gr.HTML("""
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 12px; margin-bottom: 20px;">
<h1 style="margin: 0; display: flex; align-items: center; gap: 10px;">
📺 Control Multimedia Chromecast - Hostelería
</h1>
<p style="margin: 8px 0 0 0; opacity: 0.9;">Sistema de control para múltiples dispositivos Chromecast</p>
</div>
""")
with gr.Row():
with gr.Column(scale=2):
# Quick Actions
gr.HTML("<h2>⚡ Acciones Rápidas</h2>")
with gr.Row():
play_all_btn = gr.Button("▶️ Reproducir", variant="primary", size="sm")
pause_all_btn = gr.Button("⏸️ Pausar", variant="secondary", size="sm")
stop_all_btn = gr.Button("⏹️ Detener", variant="stop", size="sm")
mute_all_btn = gr.Button("🔇 Silenciar", variant="secondary", size="sm")
# TV Status Display
gr.HTML("<h2>📺 Estado de los Dispositivos</h2>")
tvs_display = gr.HTML(update_tvs_display())
# Video Input Section
gr.HTML("<h2>🎬 Control de Reproducción</h2>")
with gr.Row():
video_url = gr.Textbox(label="URL del Video", placeholder="Introduce URL (YouTube, Vimeo, directa)")
load_btn = gr.Button("📥 Cargar Video", variant="primary")
with gr.Row():
youtube_btn = gr.Button("📺 YouTube Sample", size="sm")
vimeo_btn = gr.Button("🎥 Vimeo Sample", size="sm")
direct_btn = gr.Button("🔗 URL Directa", size="sm")
# Progress Bar
gr.HTML("<h3>📊 Progreso de Reproducción</h3>")
progress = gr.Slider(0, 100, value=0, label="Progreso", interactive=True)
with gr.Row():
current_time = gr.Textbox("00:00", label="Tiempo Actual", interactive=False)
duration_time = gr.Textbox("03:45", label="Duración", interactive=False)
# Media Controls
gr.HTML("<h3>🎮 Controles de Multimedia</h3>")
with gr.Row():
rewind_btn = gr.Button("⏪ Rebobinar", size="sm")
play_btn = gr.Button("▶️ Reproducir", variant="primary", size="sm")
pause_btn = gr.Button("⏸️ Pausar", variant="secondary", size="sm")
stop_btn = gr.Button("⏹️ Detener", variant="stop", size="sm")
forward_btn = gr.Button("⏩ Adelantar", size="sm")
# Volume Control
gr.HTML("<h3>🔊 Control de Volumen</h3>")
with gr.Row():
volume_slider = gr.Slider(0, 100, value=50, label="Volumen Maestro")
volume_percentage = gr.Textbox("50%", label="Porcentaje", interactive=False)
with gr.Column(scale=1):
# Individual TV Controls
gr.HTML("<h2>🎛️ Controles Individuales</h2>")
with gr.Group():
gr.HTML("<h4>TV 1 - Sala Principal</h4>")
with gr.Row():
tv1_play = gr.Button("▶️", size="sm", variant="primary")
tv1_pause = gr.Button("⏸️", size="sm")
tv1_stop = gr.Button("⏹️", size="sm", variant="stop")
tv1_mute = gr.Button("🔇", size="sm")
gr.HTML("<h4>TV 2 - Barra</h4>")
with gr.Row():
tv2_play = gr.Button("▶️", size="sm", variant="primary")
tv2_pause = gr.Button("⏸️", size="sm")
tv2_stop = gr.Button("⏹️", size="sm", variant="stop")
tv2_mute = gr.Button("🔇", size="sm")
gr.HTML("<h4>TV 3 - Terraza</h4>")
with gr.Row():
tv3_play = gr.Button("▶️", size="sm", variant="primary")
tv3_pause = gr.Button("⏸️", size="sm")
tv3_stop = gr.Button("⏹️", size="sm", variant="stop")
tv3_mute = gr.Button("🔇", size="sm")
# Playlist Section
gr.HTML("<h2>📋 Playlist de Videos</h2>")
playlist_display = gr.HTML(update_playlist_display())
with gr.Group():
playlist_url = gr.Textbox(label="URL para Playlist", placeholder="Agrega video a playlist")
playlist_title = gr.Textbox(label="Título (opcional)")
add_playlist_btn = gr.Button("➕ Agregar a Playlist", variant="primary")
# Status Display
with gr.Row():
status_title = gr.Textbox("✅ Sistema Listo", label="Estado", interactive=False)
status_message = gr.Textbox("Todos los dispositivos conectados", label="Mensaje", interactive=False)
# Event Handlers
load_btn.click(load_video_url, inputs=[video_url], outputs=[status_title, status_message, tvs_display, video_url])
# Sample videos
youtube_btn.click(fn=lambda: load_sample_video("youtube"), outputs=[status_title, status_message, tvs_display, video_url])
vimeo_btn.click(fn=lambda: load_sample_video("vimeo"), outputs=[status_title, status_message, tvs_display, video_url])
direct_btn.click(fn=lambda: load_sample_video("direct"), outputs=[status_title, status_message, tvs_display, video_url])
# Quick actions
play_all_btn.click(fn=lambda: control_all_tvs_action("play"), outputs=[status_title, status_message, tvs_display, video_url])
pause_all_btn.click(fn=lambda: control_all_tvs_action("pause"), outputs=[status_title, status_message, tvs_display, video_url])
stop_all_btn.click(fn=lambda: control_all_tvs_action("stop"), outputs=[status_title, status_message, tvs_display, video_url])
mute_all_btn.click(fn=lambda: control_all_tvs_action("mute"), outputs=[status_title, status_message, tvs_display, video_url])
# Media controls
play_btn.click(fn=lambda: control_all_tvs_action("play"), outputs=[status_title, status_message, tvs_display, video_url])
pause_btn.click(fn=lambda: control_all_tvs_action("pause"), outputs=[status_title, status_message, tvs_display, video_url])
stop_btn.click(fn=lambda: control_all_tvs_action("stop"), outputs=[status_title, status_message, tvs_display, video_url])
# Volume control
volume_slider.change(change_volume_all, inputs=[volume_slider], outputs=[status_title, status_message, tvs_display, volume_percentage])
# Individual TV controls
tv1_play.click(fn=lambda: control_individual_tv(1, "play"), outputs=[status_title, status_message, tvs_display])
tv1_pause.click(fn=lambda: control_individual_tv(1, "pause"), outputs=[status_title, status_message, tvs_display])
tv1_stop.click(fn=lambda: control_individual_tv(1, "stop"), outputs=[status_title, status_message, tvs_display])
tv1_mute.click(fn=lambda: control_individual_tv(1, "mute"), outputs=[status_title, status_message, tvs_display])
tv2_play.click(fn=lambda: control_individual_tv(2, "play"), outputs=[status_title, status_message, tvs_display])
tv2_pause.click(fn=lambda: control_individual_tv(2, "pause"), outputs=[status_title, status_message, tvs_display])
tv2_stop.click(fn=lambda: control_individual_tv(2, "stop"), outputs=[status_title, status_message, tvs_display])
tv2_mute.click(fn=lambda: control_individual_tv(2, "mute"), outputs=[status_title, status_message, tvs_display])
tv3_play.click(fn=lambda: control_individual_tv(3, "play"), outputs=[status_title, status_message, tvs_display])
tv3_pause.click(fn=lambda: control_individual_tv(3, "pause"), outputs=[status_title, status_message, tvs_display])
tv3_stop.click(fn=lambda: control_individual_tv(3, "stop"), outputs=[status_title, status_message, tvs_display])
tv3_mute.click(fn=lambda: control_individual_tv(3, "mute"), outputs=[status_title, status_message, tvs_display])
# Playlist controls
add_playlist_btn.click(add_video_to_playlist, inputs=[playlist_url, playlist_title], outputs=[status_title, status_message, playlist_display])
# Timer for progress update
timer = gr.Timer(1.0)
timer.tick(update_playback_progress, outputs=[progress, current_time, duration_time])
# Footer
gr.HTML("""
<div style="text-align: center; margin-top: 30px; padding: 20px; border-top: 1px solid #e5e7eb;">
<a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #3b82f6; text-decoration: none; font-weight: 600;">
Built with anycoder
</a>
</div>
""")
if __name__ == "__main__":
demo.launch() |