apexnano commited on
Commit
5c06d9a
·
verified ·
1 Parent(s): 104212a

Upload aplicaci_n_hugging_face_space.py

Browse files
Files changed (1) hide show
  1. aplicaci_n_hugging_face_space.py +160 -0
aplicaci_n_hugging_face_space.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import imageio
4
+ import numpy as np
5
+ import gradio as gr
6
+ from diffusers import LTXPipeline
7
+
8
+ # ---------------------------------------------------------------------------
9
+ # 1. Configuración del modelo optimizado para Hugging Face Spaces (CPU / GPU)
10
+ # ---------------------------------------------------------------------------
11
+ MODEL_ID = "Lightricks/LTX-Video"
12
+
13
+ device = "cuda" if torch.cuda.is_available() else "cpu"
14
+ dtype = torch.bfloat16 if (torch.cuda.is_available() and torch.cuda.is_bf16_supported()) else torch.float32
15
+
16
+ print(f"Cargando modelo en dispositivo: {device}...")
17
+
18
+ try:
19
+ pipe = LTXPipeline.from_pretrained(MODEL_ID, torch_dtype=dtype)
20
+ if device == "cuda":
21
+ pipe.enable_sequential_cpu_offload()
22
+ if hasattr(pipe, "vae"):
23
+ pipe.vae.enable_slicing()
24
+ pipe.vae.enable_tiling()
25
+ else:
26
+ pipe.to("cpu")
27
+ print("Modelo cargado correctamente.")
28
+ except Exception as e:
29
+ print(f"Aviso de carga: {e}. Se utilizará modo simulación si no hay hardware CUDA.")
30
+ pipe = None
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # 2. Función principal de generación de vídeo
34
+ # ---------------------------------------------------------------------------
35
+ def generar_video(prompt, aspect_ratio_str, res_str, duration_sec):
36
+ if not prompt or prompt.strip() == "":
37
+ raise gr.Error("Por favor, introduce una descripción para tu vídeo.")
38
+
39
+ is_720 = "720p" in res_str
40
+
41
+ # Definición de resoluciones según aspecto
42
+ if "9:16" in aspect_ratio_str:
43
+ width, height = (720, 1280) if is_720 else (432, 768)
44
+ elif "1:1" in aspect_ratio_str:
45
+ width, height = (720, 720) if is_720 else (480, 480)
46
+ else:
47
+ width, height = (1280, 720) if is_720 else (768, 432)
48
+
49
+ fps = 24
50
+ num_frames = int(duration_sec * fps)
51
+ output_path = "video_generado.mp4"
52
+
53
+ if pipe is not None and torch.cuda.is_available():
54
+ with torch.inference_mode():
55
+ video_frames = pipe(
56
+ prompt=prompt,
57
+ width=width,
58
+ height=height,
59
+ num_frames=num_frames,
60
+ num_inference_steps=20,
61
+ guidance_scale=3.0,
62
+ output_type="pil"
63
+ ).frames[0]
64
+
65
+ writer = imageio.get_writer(output_path, fps=fps, codec='libx264')
66
+ for frame in video_frames:
67
+ writer.append_data(np.array(frame))
68
+ writer.close()
69
+ torch.cuda.empty_cache()
70
+ else:
71
+ # Fallback de prueba si se ejecuta en un Space de CPU gratuita sin GPU
72
+ frames = []
73
+ for i in range(num_frames):
74
+ color = int((i / num_frames) * 255)
75
+ frame = np.full((height, width, 3), [color, 100, 200 - color], dtype=np.uint8)
76
+ frames.append(frame)
77
+ imageio.mimsave(output_path, frames, fps=fps)
78
+
79
+ return output_path
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # 3. Interfaz de usuario HTML/CSS incrustada en Gradio
83
+ # ---------------------------------------------------------------------------
84
+ css = """
85
+ body, .gradio-container {
86
+ background-color: #0b0b0e !important;
87
+ color: #ffffff !important;
88
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
89
+ }
90
+ .header-bar {
91
+ display: flex;
92
+ justify-content: space-between;
93
+ align-items: center;
94
+ padding: 12px 20px;
95
+ background: #121216;
96
+ border-bottom: 1px solid #222;
97
+ border-radius: 8px;
98
+ margin-bottom: 15px;
99
+ }
100
+ .control-panel {
101
+ background: #16161c !important;
102
+ border: 1px solid rgba(255, 255, 255, 0.1) !important;
103
+ border-radius: 14px !important;
104
+ padding: 15px !important;
105
+ }
106
+ """
107
+
108
+ with gr.Blocks(css=css, title="Sora 2 Studio - HF Space") as demo:
109
+ gr.HTML("""
110
+ <div class="header-bar">
111
+ <span style="font-weight: 600; font-size: 16px;">Sora 2 Style Generator</span>
112
+ <span style="font-size: 12px; color: #a1a1aa;">Hugging Face Space Compatible</span>
113
+ </div>
114
+ """)
115
+
116
+ with gr.Row():
117
+ with gr.Column():
118
+ video_output = gr.Video(label="Vídeo Generado", interactive=False)
119
+
120
+ with gr.Row(elem_classes="control-panel"):
121
+ with gr.Column(scale=4):
122
+ prompt_input = gr.Textbox(
123
+ placeholder="Describe el vídeo que deseas generar...",
124
+ show_label=False,
125
+ container=False,
126
+ lines=2
127
+ )
128
+ with gr.Column(scale=3):
129
+ with gr.Row():
130
+ aspect_ratio = gr.Dropdown(
131
+ choices=["16:9 (Horizontal)", "9:16 (Vertical)", "1:1 (Cuadrado)"],
132
+ value="16:9 (Horizontal)",
133
+ label="Aspecto",
134
+ container=False
135
+ )
136
+ resolution = gr.Dropdown(
137
+ choices=["420p", "720p"],
138
+ value="420p",
139
+ label="Resolución",
140
+ container=False
141
+ )
142
+ with gr.Row():
143
+ duration = gr.Slider(
144
+ minimum=1,
145
+ maximum=5,
146
+ step=1,
147
+ value=5,
148
+ label="Duración (s)",
149
+ container=False
150
+ )
151
+ btn_generar = gr.Button("Generar Vídeo", variant="primary")
152
+
153
+ btn_generar.click(
154
+ fn=generar_video,
155
+ inputs=[prompt_input, aspect_ratio, resolution, duration],
156
+ outputs=video_output
157
+ )
158
+
159
+ if __name__ == "__main__":
160
+ demo.launch()