Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,25 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import gc
|
|
|
|
|
|
|
| 4 |
import cv2
|
| 5 |
import torch
|
| 6 |
import numpy as np
|
|
|
|
|
|
|
| 7 |
import gradio as gr
|
|
|
|
|
|
|
| 8 |
import subprocess
|
| 9 |
import requests
|
| 10 |
from urllib.parse import urlparse
|
|
|
|
|
|
|
|
|
|
| 11 |
from huggingface_hub import hf_hub_download
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
from transformers import BlipProcessor, BlipForConditionalGeneration
|
|
|
|
|
|
|
| 15 |
from PIL import Image
|
|
|
|
| 16 |
|
| 17 |
# --- Environment setup ---
|
|
|
|
| 18 |
os.environ["HF_HOME"] = "/tmp/huggingface"
|
| 19 |
os.environ["TRANSFORMERS_CACHE"] = "/tmp/huggingface/transformers"
|
| 20 |
os.environ["MPLCONFIGDIR"] = "/tmp/matplotlib"
|
|
|
|
| 21 |
|
| 22 |
# --- Patch Gradio schema bug ---
|
|
|
|
| 23 |
def patch_gradio_utils():
|
| 24 |
"""Fix Gradio schema type checking bug"""
|
| 25 |
try:
|
|
@@ -34,16 +113,23 @@ def patch_gradio_utils():
|
|
| 34 |
return original_get_type(schema)
|
| 35 |
|
| 36 |
utils.get_type = patched_get_type
|
| 37 |
-
|
| 38 |
except Exception as e:
|
| 39 |
-
|
| 40 |
|
| 41 |
patch_gradio_utils()
|
| 42 |
|
| 43 |
# --- Load BLIP model ---
|
|
|
|
|
|
|
|
|
|
| 44 |
print("Loading BLIP model...")
|
| 45 |
blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
|
|
|
|
|
|
|
|
|
| 46 |
blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to("cpu")
|
|
|
|
| 47 |
|
| 48 |
def get_first_frame_for_blip(video_path, target_size=480):
|
| 49 |
"""Effizient: Lädt nur das erste Frame für BLIP (nicht alle Frames!)"""
|
|
@@ -353,19 +439,36 @@ def embed_thumbnail_in_video(video_path, thumbnail_array, base_name):
|
|
| 353 |
return False
|
| 354 |
|
| 355 |
# --- Load depth model ---
|
|
|
|
|
|
|
|
|
|
| 356 |
print("Loading Video Depth Anything model...")
|
| 357 |
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
|
|
|
|
|
|
|
| 358 |
encoder = 'vitl'
|
| 359 |
model_name = 'Large'
|
| 360 |
model_configs = {
|
| 361 |
'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},
|
| 362 |
}
|
|
|
|
|
|
|
| 363 |
video_depth_anything = VideoDepthAnything(**model_configs[encoder])
|
|
|
|
|
|
|
|
|
|
| 364 |
ckpt_path = hf_hub_download(repo_id=f"depth-anything/Video-Depth-Anything-{model_name}",
|
| 365 |
filename=f"video_depth_anything_{encoder}.pth",
|
| 366 |
cache_dir="/tmp/huggingface")
|
|
|
|
|
|
|
|
|
|
| 367 |
video_depth_anything.load_state_dict(torch.load(ckpt_path, map_location='cpu'))
|
|
|
|
|
|
|
|
|
|
| 368 |
video_depth_anything = video_depth_anything.to(DEVICE).eval()
|
|
|
|
| 369 |
|
| 370 |
# --- URL validation and download ---
|
| 371 |
def validate_url(url):
|
|
@@ -421,7 +524,6 @@ def download_video_with_ytdlp(url):
|
|
| 421 |
raise RuntimeError("yt-dlp Python module not installed. Install with: pip install yt-dlp")
|
| 422 |
except Exception as e:
|
| 423 |
raise RuntimeError(f"Failed to download with yt-dlp: {e}")
|
| 424 |
-
|
| 425 |
def detect_video_source(url):
|
| 426 |
"""Detect video source and determine download method"""
|
| 427 |
# Known platforms with special handling (priority check first)
|
|
|
|
| 1 |
+
# ==========================================
|
| 2 |
+
# 🔍 DEBUGGING SYSTEM FÜR HF SPACES
|
| 3 |
+
# ==========================================
|
| 4 |
+
import time
|
| 5 |
+
import psutil
|
| 6 |
+
import datetime
|
| 7 |
+
|
| 8 |
+
class SimpleDebugger:
|
| 9 |
+
def __init__(self):
|
| 10 |
+
self.start_time = time.time()
|
| 11 |
+
print("=" * 60)
|
| 12 |
+
print("🔍 HF SPACES DEBUGGING SYSTEM GESTARTET")
|
| 13 |
+
print(f"🕐 Start Zeit: {datetime.datetime.now().strftime('%H:%M:%S')}")
|
| 14 |
+
print("=" * 60)
|
| 15 |
+
|
| 16 |
+
# System Info
|
| 17 |
+
memory = psutil.virtual_memory()
|
| 18 |
+
print(f"💾 RAM Total: {memory.total / 1024**3:.1f}GB")
|
| 19 |
+
print(f"💾 RAM Free: {memory.available / 1024**3:.1f}GB")
|
| 20 |
+
print("=" * 60)
|
| 21 |
+
|
| 22 |
+
def log(self, message, details=None):
|
| 23 |
+
"""Checkpoint mit Timing und Memory Info"""
|
| 24 |
+
elapsed = time.time() - self.start_time
|
| 25 |
+
timestamp = datetime.datetime.now().strftime('%H:%M:%S')
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
memory = psutil.virtual_memory()
|
| 29 |
+
memory_pct = memory.percent
|
| 30 |
+
memory_free = memory.available / 1024**3
|
| 31 |
+
except:
|
| 32 |
+
memory_pct = 0
|
| 33 |
+
memory_free = 0
|
| 34 |
+
|
| 35 |
+
print(f"\n🕐 [{timestamp}] {message}")
|
| 36 |
+
print(f" ⏱️ Nach {elapsed:.1f}s | 💾 RAM: {memory_pct:.1f}% ({memory_free:.1f}GB frei)")
|
| 37 |
+
|
| 38 |
+
if details:
|
| 39 |
+
print(f" 📋 {details}")
|
| 40 |
+
|
| 41 |
+
# Warnung bei langsamen Operationen
|
| 42 |
+
if elapsed > 60:
|
| 43 |
+
print(f" ⚠️ WARNUNG: Schon {elapsed:.1f}s vergangen!")
|
| 44 |
+
elif elapsed > 300: # 5 Minuten
|
| 45 |
+
print(f" 🚨 SEHR LANGSAM: {elapsed:.1f}s - Das ist ungewöhnlich lang!")
|
| 46 |
+
|
| 47 |
+
# Debugger initialisieren
|
| 48 |
+
debug = SimpleDebugger()
|
| 49 |
+
|
| 50 |
+
# ==========================================
|
| 51 |
+
# IHR BESTEHENDER CODE MIT DEBUG-LOGS
|
| 52 |
+
# ==========================================
|
| 53 |
+
|
| 54 |
+
debug.log("Starte Python Imports...")
|
| 55 |
+
|
| 56 |
import os
|
| 57 |
import sys
|
| 58 |
import gc
|
| 59 |
+
debug.log("Basic Python imports fertig")
|
| 60 |
+
|
| 61 |
import cv2
|
| 62 |
import torch
|
| 63 |
import numpy as np
|
| 64 |
+
debug.log("OpenCV, PyTorch, NumPy imports fertig")
|
| 65 |
+
|
| 66 |
import gradio as gr
|
| 67 |
+
debug.log("Gradio importiert")
|
| 68 |
+
|
| 69 |
import subprocess
|
| 70 |
import requests
|
| 71 |
from urllib.parse import urlparse
|
| 72 |
+
debug.log("Network-Module importiert")
|
| 73 |
+
|
| 74 |
+
debug.log("Starte HuggingFace Hub Import...")
|
| 75 |
from huggingface_hub import hf_hub_download
|
| 76 |
+
debug.log("HuggingFace Hub importiert")
|
| 77 |
+
|
| 78 |
+
debug.log("Starte Video Depth Anything Import (kann hängen wenn Module fehlen)...")
|
| 79 |
+
try:
|
| 80 |
+
from video_depth_anything.video_depth import VideoDepthAnything
|
| 81 |
+
from utils.dc_utils import read_video_frames, save_video
|
| 82 |
+
debug.log("✅ Video Depth Anything Module erfolgreich importiert")
|
| 83 |
+
except Exception as e:
|
| 84 |
+
debug.log("❌ Video Depth Anything Import FEHLER", str(e))
|
| 85 |
+
|
| 86 |
+
debug.log("Starte Transformers Import (erstes kritisches Modul)...")
|
| 87 |
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 88 |
+
debug.log("✅ Transformers erfolgreich importiert")
|
| 89 |
+
|
| 90 |
from PIL import Image
|
| 91 |
+
debug.log("Alle Imports abgeschlossen")
|
| 92 |
|
| 93 |
# --- Environment setup ---
|
| 94 |
+
debug.log("Environment Variablen werden gesetzt...")
|
| 95 |
os.environ["HF_HOME"] = "/tmp/huggingface"
|
| 96 |
os.environ["TRANSFORMERS_CACHE"] = "/tmp/huggingface/transformers"
|
| 97 |
os.environ["MPLCONFIGDIR"] = "/tmp/matplotlib"
|
| 98 |
+
debug.log("Environment setup fertig")
|
| 99 |
|
| 100 |
# --- Patch Gradio schema bug ---
|
| 101 |
+
debug.log("Gradio Utils werden gepatcht...")
|
| 102 |
def patch_gradio_utils():
|
| 103 |
"""Fix Gradio schema type checking bug"""
|
| 104 |
try:
|
|
|
|
| 113 |
return original_get_type(schema)
|
| 114 |
|
| 115 |
utils.get_type = patched_get_type
|
| 116 |
+
debug.log("✅ Gradio utils erfolgreich gepatcht")
|
| 117 |
except Exception as e:
|
| 118 |
+
debug.log("❌ Gradio utils patching FEHLER", str(e))
|
| 119 |
|
| 120 |
patch_gradio_utils()
|
| 121 |
|
| 122 |
# --- Load BLIP model ---
|
| 123 |
+
debug.log("🔥 KRITISCH: BLIP Model Loading startet - das ist oft der langsamste Teil!")
|
| 124 |
+
|
| 125 |
+
debug.log("BLIP Processor Download/Load startet...")
|
| 126 |
print("Loading BLIP model...")
|
| 127 |
blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 128 |
+
debug.log("✅ BLIP Processor geladen")
|
| 129 |
+
|
| 130 |
+
debug.log("BLIP Model Download/Load startet - das dauert oft sehr lange...")
|
| 131 |
blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to("cpu")
|
| 132 |
+
debug.log("✅ BLIP Model geladen und auf CPU verschoben")
|
| 133 |
|
| 134 |
def get_first_frame_for_blip(video_path, target_size=480):
|
| 135 |
"""Effizient: Lädt nur das erste Frame für BLIP (nicht alle Frames!)"""
|
|
|
|
| 439 |
return False
|
| 440 |
|
| 441 |
# --- Load depth model ---
|
| 442 |
+
debug.log("🔥 KRITISCH: Video Depth Anything Model Loading startet!")
|
| 443 |
+
debug.log("Device wird ermittelt...")
|
| 444 |
+
|
| 445 |
print("Loading Video Depth Anything model...")
|
| 446 |
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 447 |
+
debug.log(f"Device ausgewählt: {DEVICE}")
|
| 448 |
+
|
| 449 |
encoder = 'vitl'
|
| 450 |
model_name = 'Large'
|
| 451 |
model_configs = {
|
| 452 |
'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},
|
| 453 |
}
|
| 454 |
+
|
| 455 |
+
debug.log("VideoDepthAnything Instanz wird erstellt...")
|
| 456 |
video_depth_anything = VideoDepthAnything(**model_configs[encoder])
|
| 457 |
+
debug.log("✅ VideoDepthAnything Instanz erstellt")
|
| 458 |
+
|
| 459 |
+
debug.log("🔥 KRITISCH: Model Checkpoint Download startet - das kann sehr lange dauern!")
|
| 460 |
ckpt_path = hf_hub_download(repo_id=f"depth-anything/Video-Depth-Anything-{model_name}",
|
| 461 |
filename=f"video_depth_anything_{encoder}.pth",
|
| 462 |
cache_dir="/tmp/huggingface")
|
| 463 |
+
debug.log("✅ Model Checkpoint heruntergeladen", f"Pfad: {ckpt_path}")
|
| 464 |
+
|
| 465 |
+
debug.log("Model Weights werden geladen...")
|
| 466 |
video_depth_anything.load_state_dict(torch.load(ckpt_path, map_location='cpu'))
|
| 467 |
+
debug.log("✅ Model Weights geladen")
|
| 468 |
+
|
| 469 |
+
debug.log("Model wird auf Device verschoben und in Eval-Modus gesetzt...")
|
| 470 |
video_depth_anything = video_depth_anything.to(DEVICE).eval()
|
| 471 |
+
debug.log("✅ Video Depth Anything Model komplett bereit!")
|
| 472 |
|
| 473 |
# --- URL validation and download ---
|
| 474 |
def validate_url(url):
|
|
|
|
| 524 |
raise RuntimeError("yt-dlp Python module not installed. Install with: pip install yt-dlp")
|
| 525 |
except Exception as e:
|
| 526 |
raise RuntimeError(f"Failed to download with yt-dlp: {e}")
|
|
|
|
| 527 |
def detect_video_source(url):
|
| 528 |
"""Detect video source and determine download method"""
|
| 529 |
# Known platforms with special handling (priority check first)
|