Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -151,33 +151,51 @@ class WatermarkRemover:
|
|
| 151 |
|
| 152 |
cap = cv2.VideoCapture(video_path)
|
| 153 |
if not cap.isOpened():
|
| 154 |
-
return None, "Error: No se pudo abrir el video"
|
| 155 |
|
| 156 |
# Propiedades del video
|
| 157 |
fps = int(cap.get(cv2.CAP_PROP_FPS))
|
|
|
|
|
|
|
|
|
|
| 158 |
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 159 |
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 160 |
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
progress(0.05, desc="Analizando marca de agua...")
|
| 163 |
|
| 164 |
-
# Leer muestra de frames
|
| 165 |
sample_frames = []
|
| 166 |
-
sample_size = min(
|
|
|
|
| 167 |
for i in range(sample_size):
|
| 168 |
frame_idx = int(i * total_frames / sample_size)
|
| 169 |
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
|
| 170 |
ret, frame = cap.read()
|
| 171 |
if ret:
|
|
|
|
|
|
|
| 172 |
sample_frames.append(frame)
|
| 173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
# Detectar máscara base de marca de agua
|
| 175 |
base_watermark_mask = self.detect_moving_watermark(sample_frames)
|
| 176 |
|
| 177 |
-
# Encontrar puntos característicos
|
| 178 |
mask_points = cv2.goodFeaturesToTrack(
|
| 179 |
base_watermark_mask,
|
| 180 |
-
maxCorners=
|
| 181 |
qualityLevel=0.01,
|
| 182 |
minDistance=10
|
| 183 |
)
|
|
@@ -191,22 +209,31 @@ class WatermarkRemover:
|
|
| 191 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 192 |
output_path = self.temp_dir / f"cleaned_{timestamp}.mp4"
|
| 193 |
|
| 194 |
-
# Usar
|
| 195 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 196 |
out = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
|
| 197 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
prev_gray = None
|
| 199 |
tracked_points = mask_points
|
| 200 |
frame_count = 0
|
|
|
|
| 201 |
|
| 202 |
while True:
|
| 203 |
ret, frame = cap.read()
|
| 204 |
if not ret:
|
| 205 |
break
|
| 206 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
curr_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 208 |
|
| 209 |
-
# Actualizar tracking
|
| 210 |
if prev_gray is not None and tracked_points is not None:
|
| 211 |
tracked_points = self.track_watermark_position(
|
| 212 |
prev_gray, curr_gray, tracked_points
|
|
@@ -226,45 +253,27 @@ class WatermarkRemover:
|
|
| 226 |
prev_gray = curr_gray
|
| 227 |
frame_count += 1
|
| 228 |
|
| 229 |
-
# Re-detectar puntos cada 30 frames
|
| 230 |
-
if frame_count % 30 == 0:
|
| 231 |
-
tracked_points =
|
| 232 |
-
base_watermark_mask,
|
| 233 |
-
maxCorners=50,
|
| 234 |
-
qualityLevel=0.01,
|
| 235 |
-
minDistance=10
|
| 236 |
-
)
|
| 237 |
|
| 238 |
-
|
|
|
|
| 239 |
progress_val = 0.1 + (0.85 * frame_count / total_frames)
|
| 240 |
-
progress(progress_val, desc=f"
|
| 241 |
|
| 242 |
cap.release()
|
| 243 |
out.release()
|
| 244 |
|
| 245 |
-
progress(0.95, desc="Optimizando video...")
|
| 246 |
-
|
| 247 |
-
# Recodificar con ffmpeg si está disponible
|
| 248 |
-
final_output = self.temp_dir / f"final_{timestamp}.mp4"
|
| 249 |
-
try:
|
| 250 |
-
subprocess.run([
|
| 251 |
-
'ffmpeg', '-i', str(output_path),
|
| 252 |
-
'-c:v', 'libx264', '-crf', '23',
|
| 253 |
-
'-preset', 'medium', '-c:a', 'copy',
|
| 254 |
-
'-y', str(final_output)
|
| 255 |
-
], check=True, capture_output=True, timeout=300)
|
| 256 |
-
|
| 257 |
-
output_path.unlink() # Eliminar temporal
|
| 258 |
-
output_path = final_output
|
| 259 |
-
except:
|
| 260 |
-
pass # Si ffmpeg falla, usar el video original
|
| 261 |
-
|
| 262 |
progress(1.0, desc="¡Completado!")
|
| 263 |
|
| 264 |
-
return str(output_path), f"✅ Video procesado: {frame_count} frames\n🎯
|
| 265 |
|
| 266 |
except Exception as e:
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
| 268 |
|
| 269 |
# Crear instancia del removedor
|
| 270 |
remover = WatermarkRemover()
|
|
@@ -290,12 +299,16 @@ with gr.Blocks(title="Eliminador de Marcas de Agua - REAL", theme=gr.themes.Soft
|
|
| 290 |
- 🧹 Limpieza automática de archivos (cada 2 horas)
|
| 291 |
|
| 292 |
---
|
|
|
|
| 293 |
""")
|
| 294 |
|
| 295 |
with gr.Row():
|
| 296 |
with gr.Column(scale=1):
|
| 297 |
gr.Markdown("### 📥 Entrada")
|
| 298 |
-
video_input = gr.Video(
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
sensitivity = gr.Slider(
|
| 301 |
minimum=10,
|
|
@@ -310,9 +323,10 @@ with gr.Blocks(title="Eliminador de Marcas de Agua - REAL", theme=gr.themes.Soft
|
|
| 310 |
|
| 311 |
gr.Markdown("""
|
| 312 |
### 💡 Tips:
|
| 313 |
-
-
|
| 314 |
-
-
|
| 315 |
-
-
|
|
|
|
| 316 |
""")
|
| 317 |
|
| 318 |
with gr.Column(scale=1):
|
|
@@ -342,4 +356,7 @@ with gr.Blocks(title="Eliminador de Marcas de Agua - REAL", theme=gr.themes.Soft
|
|
| 342 |
""")
|
| 343 |
|
| 344 |
if __name__ == "__main__":
|
| 345 |
-
demo.launch(
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
cap = cv2.VideoCapture(video_path)
|
| 153 |
if not cap.isOpened():
|
| 154 |
+
return None, "❌ Error: No se pudo abrir el video"
|
| 155 |
|
| 156 |
# Propiedades del video
|
| 157 |
fps = int(cap.get(cv2.CAP_PROP_FPS))
|
| 158 |
+
if fps == 0:
|
| 159 |
+
fps = 30 # fallback
|
| 160 |
+
|
| 161 |
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 162 |
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 163 |
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 164 |
|
| 165 |
+
# Limitar tamaño para evitar timeouts en HuggingFace
|
| 166 |
+
max_resolution = 1280
|
| 167 |
+
scale = 1.0
|
| 168 |
+
if width > max_resolution or height > max_resolution:
|
| 169 |
+
scale = max_resolution / max(width, height)
|
| 170 |
+
width = int(width * scale)
|
| 171 |
+
height = int(height * scale)
|
| 172 |
+
|
| 173 |
progress(0.05, desc="Analizando marca de agua...")
|
| 174 |
|
| 175 |
+
# Leer muestra reducida de frames
|
| 176 |
sample_frames = []
|
| 177 |
+
sample_size = min(20, total_frames) # Reducido para más velocidad
|
| 178 |
+
|
| 179 |
for i in range(sample_size):
|
| 180 |
frame_idx = int(i * total_frames / sample_size)
|
| 181 |
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
|
| 182 |
ret, frame = cap.read()
|
| 183 |
if ret:
|
| 184 |
+
if scale != 1.0:
|
| 185 |
+
frame = cv2.resize(frame, (width, height))
|
| 186 |
sample_frames.append(frame)
|
| 187 |
|
| 188 |
+
if len(sample_frames) == 0:
|
| 189 |
+
cap.release()
|
| 190 |
+
return None, "❌ No se pudieron leer frames del video"
|
| 191 |
+
|
| 192 |
# Detectar máscara base de marca de agua
|
| 193 |
base_watermark_mask = self.detect_moving_watermark(sample_frames)
|
| 194 |
|
| 195 |
+
# Encontrar puntos característicos
|
| 196 |
mask_points = cv2.goodFeaturesToTrack(
|
| 197 |
base_watermark_mask,
|
| 198 |
+
maxCorners=30, # Reducido para rendimiento
|
| 199 |
qualityLevel=0.01,
|
| 200 |
minDistance=10
|
| 201 |
)
|
|
|
|
| 209 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 210 |
output_path = self.temp_dir / f"cleaned_{timestamp}.mp4"
|
| 211 |
|
| 212 |
+
# Usar MP4V codec (más compatible)
|
| 213 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 214 |
out = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
|
| 215 |
|
| 216 |
+
if not out.isOpened():
|
| 217 |
+
cap.release()
|
| 218 |
+
return None, "❌ Error al crear archivo de salida"
|
| 219 |
+
|
| 220 |
prev_gray = None
|
| 221 |
tracked_points = mask_points
|
| 222 |
frame_count = 0
|
| 223 |
+
update_interval = max(1, total_frames // 50) # Actualizar progreso cada 2%
|
| 224 |
|
| 225 |
while True:
|
| 226 |
ret, frame = cap.read()
|
| 227 |
if not ret:
|
| 228 |
break
|
| 229 |
|
| 230 |
+
# Redimensionar si es necesario
|
| 231 |
+
if scale != 1.0:
|
| 232 |
+
frame = cv2.resize(frame, (width, height))
|
| 233 |
+
|
| 234 |
curr_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 235 |
|
| 236 |
+
# Actualizar tracking
|
| 237 |
if prev_gray is not None and tracked_points is not None:
|
| 238 |
tracked_points = self.track_watermark_position(
|
| 239 |
prev_gray, curr_gray, tracked_points
|
|
|
|
| 253 |
prev_gray = curr_gray
|
| 254 |
frame_count += 1
|
| 255 |
|
| 256 |
+
# Re-detectar puntos cada 30 frames
|
| 257 |
+
if frame_count % 30 == 0 and mask_points is not None:
|
| 258 |
+
tracked_points = mask_points.copy()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
+
# Actualizar progreso menos frecuentemente
|
| 261 |
+
if frame_count % update_interval == 0:
|
| 262 |
progress_val = 0.1 + (0.85 * frame_count / total_frames)
|
| 263 |
+
progress(progress_val, desc=f"Procesando: {frame_count}/{total_frames}")
|
| 264 |
|
| 265 |
cap.release()
|
| 266 |
out.release()
|
| 267 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
progress(1.0, desc="¡Completado!")
|
| 269 |
|
| 270 |
+
return str(output_path), f"✅ Video procesado: {frame_count} frames\n🎯 Resolución: {width}x{height}\n⏱️ FPS: {fps}"
|
| 271 |
|
| 272 |
except Exception as e:
|
| 273 |
+
import traceback
|
| 274 |
+
error_msg = f"❌ Error: {str(e)}\n{traceback.format_exc()}"
|
| 275 |
+
print(error_msg)
|
| 276 |
+
return None, error_msg
|
| 277 |
|
| 278 |
# Crear instancia del removedor
|
| 279 |
remover = WatermarkRemover()
|
|
|
|
| 299 |
- 🧹 Limpieza automática de archivos (cada 2 horas)
|
| 300 |
|
| 301 |
---
|
| 302 |
+
⚠️ **Límites en HuggingFace Spaces:** Videos > 1280p se redimensionan automáticamente
|
| 303 |
""")
|
| 304 |
|
| 305 |
with gr.Row():
|
| 306 |
with gr.Column(scale=1):
|
| 307 |
gr.Markdown("### 📥 Entrada")
|
| 308 |
+
video_input = gr.Video(
|
| 309 |
+
label="Video con Marca de Agua",
|
| 310 |
+
format="mp4"
|
| 311 |
+
)
|
| 312 |
|
| 313 |
sensitivity = gr.Slider(
|
| 314 |
minimum=10,
|
|
|
|
| 323 |
|
| 324 |
gr.Markdown("""
|
| 325 |
### 💡 Tips:
|
| 326 |
+
- Videos cortos (< 3 min) procesan más rápido
|
| 327 |
+
- Formatos: MP4, AVI, MOV, MKV
|
| 328 |
+
- Si falla la carga, comprime el video primero
|
| 329 |
+
- Aumenta sensibilidad si no detecta la marca
|
| 330 |
""")
|
| 331 |
|
| 332 |
with gr.Column(scale=1):
|
|
|
|
| 356 |
""")
|
| 357 |
|
| 358 |
if __name__ == "__main__":
|
| 359 |
+
demo.queue(max_size=5).launch(
|
| 360 |
+
server_name="0.0.0.0",
|
| 361 |
+
server_port=7860
|
| 362 |
+
)
|