Update app.py
Browse files
app.py
CHANGED
|
@@ -10,21 +10,20 @@ import langdetect
|
|
| 10 |
import uuid
|
| 11 |
import time
|
| 12 |
import random
|
| 13 |
-
import
|
| 14 |
-
|
| 15 |
|
| 16 |
# --- CONFIGURACIΓN INICIAL ---
|
| 17 |
-
print("Starting the
|
| 18 |
-
print("Checking dependencies...")
|
| 19 |
|
| 20 |
# Verificar si curl-cffi estΓ‘ disponible
|
| 21 |
try:
|
| 22 |
import curl_cffi
|
| 23 |
CURL_CFFI_AVAILABLE = True
|
| 24 |
-
print("β
curl-cffi is available
|
| 25 |
except ImportError:
|
| 26 |
CURL_CFFI_AVAILABLE = False
|
| 27 |
-
print("β οΈ curl-cffi not available
|
| 28 |
|
| 29 |
# Carga del modelo en CPU
|
| 30 |
model_path = "Qwen/Qwen2.5-7B-Instruct"
|
|
@@ -34,152 +33,48 @@ model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch.float
|
|
| 34 |
model = model.eval()
|
| 35 |
print("β
Model successfully loaded.")
|
| 36 |
|
| 37 |
-
# ---
|
| 38 |
-
def
|
| 39 |
-
"""
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
r'player\.vimeo\.com/video/(\d+)',
|
| 44 |
-
r'vimeo\.com/.*/(\d+)',
|
| 45 |
-
]
|
| 46 |
-
|
| 47 |
-
for pattern in patterns:
|
| 48 |
-
match = re.search(pattern, vimeo_url)
|
| 49 |
-
if match:
|
| 50 |
-
video_id = match.group(1)
|
| 51 |
-
return f"https://player.vimeo.com/video/{video_id}"
|
| 52 |
-
|
| 53 |
-
return vimeo_url
|
| 54 |
-
|
| 55 |
-
def get_primary_ydl_opts(output_path):
|
| 56 |
-
"""ConfiguraciΓ³n principal con curl-cffi si estΓ‘ disponible"""
|
| 57 |
opts = {
|
| 58 |
'format': 'bestaudio/best',
|
| 59 |
-
'postprocessors': [{
|
| 60 |
-
'key': 'FFmpegExtractAudio',
|
| 61 |
-
'preferredcodec': 'wav',
|
| 62 |
-
}],
|
| 63 |
'outtmpl': output_path,
|
| 64 |
-
'keepvideo': False,
|
| 65 |
-
|
| 66 |
-
# Configuraciones bΓ‘sicas de red
|
| 67 |
-
'socket_timeout': 60,
|
| 68 |
-
'retries': 3,
|
| 69 |
-
'fragment_retries': 5,
|
| 70 |
-
|
| 71 |
-
# Headers realistas
|
| 72 |
-
'http_headers': {
|
| 73 |
-
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
| 74 |
-
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
|
| 75 |
-
'Accept-Language': 'en-US,en;q=0.9',
|
| 76 |
-
'Accept-Encoding': 'gzip, deflate, br',
|
| 77 |
-
'DNT': '1',
|
| 78 |
-
'Connection': 'keep-alive',
|
| 79 |
-
'Sec-Fetch-Dest': 'document',
|
| 80 |
-
'Sec-Fetch-Mode': 'navigate',
|
| 81 |
-
'Sec-Fetch-Site': 'none',
|
| 82 |
-
'Sec-Fetch-User': '?1',
|
| 83 |
-
'Upgrade-Insecure-Requests': '1',
|
| 84 |
-
},
|
| 85 |
-
|
| 86 |
-
# Rate limiting
|
| 87 |
-
'sleep_interval': random.uniform(3, 6),
|
| 88 |
-
'max_sleep_interval': 10,
|
| 89 |
-
'sleep_interval_requests': random.uniform(1, 2),
|
| 90 |
-
|
| 91 |
-
# Configuraciones especΓficas para Vimeo
|
| 92 |
-
'extractor_args': {
|
| 93 |
-
'vimeo': {
|
| 94 |
-
'client': 'web',
|
| 95 |
-
'original_format_policy': 'never', # Evitar requests extra que pueden causar bloqueos
|
| 96 |
-
}
|
| 97 |
-
},
|
| 98 |
-
|
| 99 |
-
# Bypass geo
|
| 100 |
-
'geo_bypass': True,
|
| 101 |
-
'geo_bypass_country': 'US',
|
| 102 |
-
|
| 103 |
-
# Configuraciones adicionales
|
| 104 |
-
'no_warnings': False,
|
| 105 |
-
'ignoreerrors': False,
|
| 106 |
-
'abort_on_unavailable_fragments': False,
|
| 107 |
-
}
|
| 108 |
-
|
| 109 |
-
# AΓ±adir impersonaciΓ³n solo si curl-cffi estΓ‘ disponible
|
| 110 |
-
if CURL_CFFI_AVAILABLE:
|
| 111 |
-
opts['impersonate'] = 'chrome'
|
| 112 |
-
print("π Using Chrome impersonation")
|
| 113 |
-
else:
|
| 114 |
-
print("β οΈ Using basic user agent (curl-cffi not available)")
|
| 115 |
-
|
| 116 |
-
return opts
|
| 117 |
-
|
| 118 |
-
def get_fallback_ydl_opts(output_path, method="player"):
|
| 119 |
-
"""Configuraciones alternativas cuando el mΓ©todo principal falla"""
|
| 120 |
-
opts = {
|
| 121 |
-
'format': 'bestaudio/best',
|
| 122 |
'postprocessors': [{
|
| 123 |
'key': 'FFmpegExtractAudio',
|
| 124 |
-
'preferredcodec': 'wav',
|
|
|
|
| 125 |
}],
|
| 126 |
-
'
|
| 127 |
-
'
|
| 128 |
-
|
| 129 |
-
# Configuraciones mΓ‘s conservadoras
|
| 130 |
-
'socket_timeout': 120,
|
| 131 |
'retries': 2,
|
| 132 |
-
'
|
| 133 |
-
|
| 134 |
-
# Rate limiting mΓ‘s agresivo
|
| 135 |
-
'sleep_interval': random.uniform(5, 10),
|
| 136 |
-
'max_sleep_interval': 15,
|
| 137 |
-
'sleep_interval_requests': random.uniform(2, 4),
|
| 138 |
-
|
| 139 |
-
# Headers simplificados
|
| 140 |
-
'http_headers': {
|
| 141 |
-
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
| 142 |
-
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
| 143 |
-
'Accept-Language': 'en-US,en;q=0.5',
|
| 144 |
-
'Accept-Encoding': 'gzip, deflate',
|
| 145 |
-
'DNT': '1',
|
| 146 |
-
},
|
| 147 |
|
| 148 |
-
#
|
| 149 |
-
'
|
| 150 |
-
'vimeo': {
|
| 151 |
-
'client': 'android' if method == "android" else 'web',
|
| 152 |
-
'original_format_policy': 'never',
|
| 153 |
-
}
|
| 154 |
-
},
|
| 155 |
-
|
| 156 |
-
# Configuraciones adicionales para estabilidad
|
| 157 |
-
'no_warnings': True,
|
| 158 |
-
'ignoreerrors': True,
|
| 159 |
-
'abort_on_unavailable_fragments': True,
|
| 160 |
}
|
| 161 |
|
| 162 |
return opts
|
| 163 |
|
| 164 |
-
def
|
| 165 |
-
"""
|
|
|
|
|
|
|
| 166 |
return {
|
| 167 |
'format': 'bestaudio/best',
|
|
|
|
| 168 |
'postprocessors': [{
|
| 169 |
'key': 'FFmpegExtractAudio',
|
| 170 |
'preferredcodec': 'wav',
|
| 171 |
}],
|
| 172 |
-
'
|
| 173 |
-
'keepvideo': False,
|
| 174 |
-
'socket_timeout': 180,
|
| 175 |
-
'retries': 1,
|
| 176 |
-
'http_headers': {
|
| 177 |
-
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 178 |
-
},
|
| 179 |
-
'sleep_interval': 10,
|
| 180 |
'no_warnings': True,
|
| 181 |
-
'
|
| 182 |
-
'
|
|
|
|
| 183 |
}
|
| 184 |
|
| 185 |
# --- FUNCIONES AUXILIARES ---
|
|
@@ -195,161 +90,116 @@ def cleanup_files(*files):
|
|
| 195 |
except OSError as e:
|
| 196 |
print(f"β Error removing file {file}: {e}")
|
| 197 |
|
| 198 |
-
def
|
| 199 |
-
"""
|
| 200 |
-
|
| 201 |
-
print(f"β³ Waiting {delay:.1f} seconds...")
|
| 202 |
-
time.sleep(delay)
|
| 203 |
|
| 204 |
def is_vimeo_url(url):
|
| 205 |
"""Detecta si una URL es de Vimeo"""
|
| 206 |
return 'vimeo.com' in url.lower()
|
| 207 |
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
patterns = [
|
| 211 |
-
r'vimeo\.com/(\d+)',
|
| 212 |
-
r'player\.vimeo\.com/video/(\d+)',
|
| 213 |
-
r'vimeo\.com/.*/(\d+)',
|
| 214 |
-
]
|
| 215 |
-
|
| 216 |
-
for pattern in patterns:
|
| 217 |
-
match = re.search(pattern, url)
|
| 218 |
-
if match:
|
| 219 |
-
return match.group(1)
|
| 220 |
-
return None
|
| 221 |
-
|
| 222 |
-
# --- LΓGICA PRINCIPAL MEJORADA CON MΓLTIPLES FALLBACKS ---
|
| 223 |
-
def download_video_audio_multi_fallback(url):
|
| 224 |
"""
|
| 225 |
-
|
| 226 |
"""
|
| 227 |
-
print(f"π― Processing URL: {url}")
|
| 228 |
-
temp_filename = generate_unique_filename("")
|
| 229 |
-
output_path = f"{temp_filename}.wav"
|
| 230 |
-
|
| 231 |
-
# Delay inicial
|
| 232 |
-
human_like_delay(1, 3)
|
| 233 |
|
| 234 |
-
#
|
| 235 |
-
|
| 236 |
-
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
# MΓ©todos a intentar en orden de preferencia
|
| 251 |
-
methods = [
|
| 252 |
-
("primary", "π Primary method (with impersonation)", get_primary_ydl_opts),
|
| 253 |
-
("player", "π Player URL method", get_fallback_ydl_opts),
|
| 254 |
-
("android", "π± Android client method", lambda p: get_fallback_ydl_opts(p, "android")),
|
| 255 |
-
("generic", "π οΈ Generic fallback method", get_generic_ydl_opts),
|
| 256 |
-
]
|
| 257 |
-
|
| 258 |
-
total_attempts = 0
|
| 259 |
-
max_total_attempts = 12 # 3 URLs Γ 4 mΓ©todos
|
| 260 |
-
|
| 261 |
-
for current_url in urls_to_try:
|
| 262 |
-
print(f"\nπ Trying URL: {current_url}")
|
| 263 |
-
|
| 264 |
-
for method_name, method_desc, get_opts_func in methods:
|
| 265 |
-
total_attempts += 1
|
| 266 |
-
print(f"\nπ Attempt {total_attempts}/{max_total_attempts}")
|
| 267 |
-
print(f"π‘οΈ Using: {method_desc}")
|
| 268 |
-
|
| 269 |
-
try:
|
| 270 |
-
# Configurar opciones segΓΊn el mΓ©todo
|
| 271 |
-
ydl_opts = get_opts_func(temp_filename)
|
| 272 |
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
delay_time = min(2 ** (total_attempts // 3), 15) # Backoff exponencial limitado
|
| 276 |
-
human_like_delay(delay_time, delay_time + 2)
|
| 277 |
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
-
#
|
| 291 |
-
|
|
|
|
| 292 |
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
ydl.download([current_url])
|
| 296 |
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
|
|
|
|
|
|
| 300 |
|
| 301 |
-
|
| 302 |
-
if os.path.exists(output_path):
|
| 303 |
-
file_size = os.path.getsize(output_path)
|
| 304 |
-
print(f"β
Download successful! File size: {file_size} bytes")
|
| 305 |
-
|
| 306 |
-
if file_size > 1000: # Al menos 1KB
|
| 307 |
-
return output_path
|
| 308 |
-
else:
|
| 309 |
-
raise Exception("Downloaded file is too small (possible error)")
|
| 310 |
-
else:
|
| 311 |
-
raise FileNotFoundError(f"Expected file {output_path} was not found")
|
| 312 |
-
|
| 313 |
-
except Exception as e:
|
| 314 |
-
error_msg = str(e).lower()
|
| 315 |
-
print(f"β Method '{method_name}' failed: {str(e)}")
|
| 316 |
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
human_like_delay(10, 15) # Delay extra para rate limiting
|
| 325 |
-
elif "tls fingerprint" in error_msg:
|
| 326 |
-
print("π‘οΈ TLS fingerprinting detected")
|
| 327 |
-
elif "oauth token" in error_msg:
|
| 328 |
-
print("π OAuth token issue")
|
| 329 |
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
# Γltimo intento fallΓ³
|
| 340 |
-
break
|
| 341 |
-
|
| 342 |
-
# Todos los mΓ©todos fallaron
|
| 343 |
-
raise Exception(f"All {total_attempts} download attempts failed. Vimeo may be blocking this IP or the video is not accessible.")
|
| 344 |
-
|
| 345 |
-
def transcribe_audio_enhanced(file_path):
|
| 346 |
-
"""FunciΓ³n mejorada de transcripciΓ³n con mejor manejo de errores"""
|
| 347 |
-
print(f"π€ Starting transcription of file: {file_path}")
|
| 348 |
-
temp_audio = None
|
| 349 |
-
original_file_to_clean = file_path
|
| 350 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
try:
|
| 352 |
-
# Verificar
|
| 353 |
if not os.path.exists(file_path):
|
| 354 |
raise FileNotFoundError(f"Audio file not found: {file_path}")
|
| 355 |
|
|
@@ -357,23 +207,11 @@ def transcribe_audio_enhanced(file_path):
|
|
| 357 |
print(f"π Audio file size: {file_size} bytes")
|
| 358 |
|
| 359 |
if file_size < 1000:
|
| 360 |
-
raise Exception("Audio file
|
| 361 |
-
|
| 362 |
-
# Convertir a WAV si es necesario
|
| 363 |
-
if not file_path.endswith('.wav'):
|
| 364 |
-
print("π Converting to WAV format...")
|
| 365 |
-
video = mp.VideoFileClip(file_path)
|
| 366 |
-
if not video.audio:
|
| 367 |
-
raise Exception("No audio track found in video file")
|
| 368 |
-
|
| 369 |
-
temp_audio = generate_unique_filename(".wav")
|
| 370 |
-
video.audio.write_audiofile(temp_audio, verbose=False, logger=None)
|
| 371 |
-
video.close()
|
| 372 |
-
file_path = temp_audio
|
| 373 |
|
|
|
|
| 374 |
output_file = generate_unique_filename(".json")
|
| 375 |
|
| 376 |
-
# Comando de Whisper con configuraciones robustas
|
| 377 |
command = [
|
| 378 |
"insanely-fast-whisper",
|
| 379 |
"--file-name", file_path,
|
|
@@ -382,235 +220,149 @@ def transcribe_audio_enhanced(file_path):
|
|
| 382 |
"--task", "transcribe",
|
| 383 |
"--timestamp", "chunk",
|
| 384 |
"--transcript-path", output_file,
|
| 385 |
-
"--batch-size", "2",
|
| 386 |
-
"--hf-token", "dummy", # Token dummy para evitar warnings
|
| 387 |
]
|
| 388 |
|
| 389 |
-
print(
|
| 390 |
result = subprocess.run(
|
| 391 |
command,
|
| 392 |
check=True,
|
| 393 |
capture_output=True,
|
| 394 |
text=True,
|
| 395 |
-
timeout=
|
| 396 |
)
|
| 397 |
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
# Verificar que el archivo de salida existe
|
| 401 |
-
if not os.path.exists(output_file):
|
| 402 |
-
raise FileNotFoundError("Transcription output file not found")
|
| 403 |
-
|
| 404 |
-
# Leer y procesar resultado
|
| 405 |
with open(output_file, "r", encoding='utf-8') as f:
|
| 406 |
transcription_data = json.load(f)
|
| 407 |
|
| 408 |
result_text = transcription_data.get("text", "").strip()
|
| 409 |
|
| 410 |
-
# Fallback: concatenar chunks si no hay texto principal
|
| 411 |
if not result_text:
|
| 412 |
chunks = transcription_data.get("chunks", [])
|
| 413 |
-
|
| 414 |
-
result_text = " ".join([chunk.get("text", "").strip() for chunk in chunks])
|
| 415 |
-
|
| 416 |
-
# Validar resultado
|
| 417 |
-
if not result_text or len(result_text) < 10:
|
| 418 |
-
raise Exception("Transcription produced no meaningful text")
|
| 419 |
|
| 420 |
-
print(f"β
Transcription completed. Length: {len(result_text)} characters")
|
| 421 |
cleanup_files(output_file)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
return result_text
|
| 423 |
-
|
| 424 |
-
except subprocess.TimeoutExpired:
|
| 425 |
-
print("β° Transcription timed out")
|
| 426 |
-
raise Exception("Transcription process timed out (15 minutes)")
|
| 427 |
except Exception as e:
|
| 428 |
print(f"β Transcription error: {e}")
|
| 429 |
raise
|
| 430 |
-
finally:
|
| 431 |
-
# Limpieza
|
| 432 |
-
if temp_audio and os.path.exists(temp_audio):
|
| 433 |
-
cleanup_files(temp_audio)
|
| 434 |
-
if original_file_to_clean != file_path and os.path.exists(original_file_to_clean):
|
| 435 |
-
cleanup_files(original_file_to_clean)
|
| 436 |
|
| 437 |
-
def
|
| 438 |
-
"""FunciΓ³n
|
| 439 |
if not transcription or len(transcription.strip()) < 20:
|
| 440 |
-
return "β οΈ Transcription
|
| 441 |
|
| 442 |
-
print("π€ Generating AI summary...")
|
| 443 |
-
|
| 444 |
try:
|
| 445 |
detected_language = langdetect.detect(transcription)
|
| 446 |
-
print(f"π Detected language: {detected_language}")
|
| 447 |
except:
|
| 448 |
detected_language = "en"
|
| 449 |
-
print("π Language detection failed, defaulting to English")
|
| 450 |
|
| 451 |
-
#
|
| 452 |
-
max_chars =
|
| 453 |
-
|
| 454 |
if len(transcription) > max_chars:
|
| 455 |
-
|
| 456 |
-
print(f"π Transcription truncated to {max_chars} characters")
|
| 457 |
|
| 458 |
-
prompt = f"""
|
| 459 |
-
The summary should be 150-300 words and capture the main points, key ideas, and important details:
|
| 460 |
|
| 461 |
-
|
| 462 |
|
| 463 |
try:
|
| 464 |
response, _ = model.chat(tokenizer, prompt, history=[])
|
| 465 |
-
print("β
Summary generated successfully")
|
| 466 |
return response
|
| 467 |
except Exception as e:
|
| 468 |
-
|
| 469 |
-
return f"β οΈ Error generating summary: {str(e)}\n\nOriginal transcription:\n{transcription[:1000]}..."
|
| 470 |
|
| 471 |
-
# --- FUNCIONES DE INTERFAZ
|
| 472 |
-
def
|
| 473 |
-
"""FunciΓ³n
|
| 474 |
if not url or not url.strip():
|
| 475 |
return "β Please enter a valid video URL.", "β οΈ No URL provided"
|
| 476 |
|
| 477 |
url = url.strip()
|
| 478 |
print(f"\n{'='*50}")
|
| 479 |
-
print(f"π― PROCESSING
|
| 480 |
-
print(f"{'='*50}")
|
| 481 |
print(f"URL: {url}")
|
| 482 |
-
|
| 483 |
-
# Detectar plataforma
|
| 484 |
-
platform = "Unknown"
|
| 485 |
-
if "youtube.com" in url or "youtu.be" in url:
|
| 486 |
-
platform = "YouTube"
|
| 487 |
-
elif "vimeo.com" in url:
|
| 488 |
-
platform = "Vimeo"
|
| 489 |
-
|
| 490 |
-
print(f"Platform: {platform}")
|
| 491 |
print(f"curl-cffi available: {CURL_CFFI_AVAILABLE}")
|
|
|
|
| 492 |
|
| 493 |
audio_file = None
|
| 494 |
try:
|
| 495 |
-
#
|
| 496 |
-
|
| 497 |
-
|
| 498 |
|
| 499 |
-
|
| 500 |
-
transcription = transcribe_audio_enhanced(audio_file)
|
| 501 |
-
|
| 502 |
-
if not transcription:
|
| 503 |
-
return "β No transcription could be generated from this video.", "β οΈ Transcription failed"
|
| 504 |
-
|
| 505 |
-
print(f"\nβ
Process completed successfully!")
|
| 506 |
-
success_msg = f"β
Successfully processed {platform} video ({len(transcription)} chars transcribed)"
|
| 507 |
return transcription, success_msg
|
| 508 |
|
| 509 |
except Exception as e:
|
| 510 |
error_msg = str(e)
|
| 511 |
-
print(f"
|
| 512 |
|
| 513 |
-
# AnΓ‘lisis de errores
|
| 514 |
-
if "
|
| 515 |
-
return
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
elif "
|
| 521 |
-
return
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
"Try again later or contact support."), "π‘οΈ Security Block"
|
| 527 |
-
elif "oauth token" in error_msg or "Bad Request" in error_msg:
|
| 528 |
-
return ("β API ERROR: Vimeo's API is experiencing issues or the video format is not supported. "
|
| 529 |
-
"Try with a different Vimeo video."), "π API Issue"
|
| 530 |
-
elif "not accessible" in error_msg.lower():
|
| 531 |
-
return ("β VIDEO NOT ACCESSIBLE: All download methods failed. The video might be: "
|
| 532 |
-
"1) Private/Password protected, 2) Geo-restricted, 3) Deleted, or 4) Not a valid video URL."), "π« Not Accessible"
|
| 533 |
-
elif "timeout" in error_msg.lower():
|
| 534 |
-
return ("β TIMEOUT: The process took too long. This might be due to: "
|
| 535 |
-
"1) Very long video, 2) Network issues, or 3) Server overload. Try with a shorter video."), "β° Timeout"
|
| 536 |
else:
|
| 537 |
-
return f"β
|
| 538 |
finally:
|
| 539 |
-
# Limpieza final
|
| 540 |
if audio_file and os.path.exists(audio_file):
|
| 541 |
cleanup_files(audio_file)
|
| 542 |
|
| 543 |
-
def
|
| 544 |
-
"""
|
| 545 |
if video_path is None:
|
| 546 |
-
return "β Please upload a video file
|
| 547 |
|
| 548 |
-
print(f"\n{'='*50}")
|
| 549 |
-
print(f"π€ PROCESSING UPLOADED VIDEO")
|
| 550 |
-
print(f"{'='*50}")
|
| 551 |
-
print(f"File path: {video_path}")
|
| 552 |
-
|
| 553 |
try:
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
return "β Uploaded file not found.", "β File not found"
|
| 557 |
-
|
| 558 |
-
file_size = os.path.getsize(video_path)
|
| 559 |
-
print(f"File size: {file_size} bytes")
|
| 560 |
-
|
| 561 |
-
if file_size < 1000:
|
| 562 |
-
return "β Uploaded file is too small or corrupted.", "β Invalid file"
|
| 563 |
-
|
| 564 |
-
print(f"π€ Starting transcription...")
|
| 565 |
-
transcription = transcribe_audio_enhanced(video_path)
|
| 566 |
-
|
| 567 |
-
if not transcription:
|
| 568 |
-
return "β No transcription could be generated from this video.", "β οΈ Transcription failed"
|
| 569 |
-
|
| 570 |
-
print(f"β
Process completed successfully!")
|
| 571 |
-
success_msg = f"β
Successfully processed uploaded video ({len(transcription)} chars transcribed)"
|
| 572 |
-
return transcription, success_msg
|
| 573 |
-
|
| 574 |
except Exception as e:
|
| 575 |
-
|
| 576 |
-
print(f"β ERROR: {error_msg}")
|
| 577 |
-
|
| 578 |
-
if "No audio track" in error_msg:
|
| 579 |
-
return "β NO AUDIO: The uploaded video doesn't contain an audio track.", "π No Audio"
|
| 580 |
-
elif "timeout" in error_msg.lower():
|
| 581 |
-
return "β TIMEOUT: Video processing took too long. Try with a shorter video.", "β° Timeout"
|
| 582 |
-
else:
|
| 583 |
-
return f"β ERROR: {error_msg}", "β Processing Error"
|
| 584 |
|
| 585 |
-
# ---
|
| 586 |
-
print("π¨
|
| 587 |
|
| 588 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="π₯
|
| 589 |
-
gr.Markdown("# π₯
|
| 590 |
gr.Markdown(f"""
|
| 591 |
-
|
| 592 |
|
| 593 |
-
|
| 594 |
-
- curl-cffi
|
| 595 |
-
-
|
| 596 |
-
-
|
| 597 |
-
-
|
| 598 |
""")
|
| 599 |
|
| 600 |
with gr.Tabs():
|
| 601 |
-
with gr.TabItem("π Video URL
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
url_button = gr.Button("π Process URL", variant="primary", scale=1)
|
| 609 |
|
| 610 |
-
with gr.TabItem("π€ Upload Video
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
video_button = gr.Button("π Process Video", variant="primary", scale=1)
|
| 614 |
|
| 615 |
with gr.Row():
|
| 616 |
with gr.Column():
|
|
@@ -624,84 +376,64 @@ with gr.Blocks(theme=gr.themes.Soft(), title="π₯ Anti-Block Video Transcriptio
|
|
| 624 |
summary_output = gr.Textbox(
|
| 625 |
label="π AI Summary",
|
| 626 |
lines=15,
|
| 627 |
-
placeholder="
|
| 628 |
)
|
| 629 |
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
)
|
| 637 |
-
summary_button = gr.Button("π Generate Summary", variant="secondary")
|
| 638 |
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
-
|
| 661 |
-
- Wait 10-15 minutes and try again
|
| 662 |
-
|
| 663 |
-
**"Rate Limited" or "HTTP 429"**
|
| 664 |
-
- Too many requests sent
|
| 665 |
-
- Wait 5-10 minutes before retrying
|
| 666 |
-
|
| 667 |
-
**"TLS Fingerprint Blocked"**
|
| 668 |
-
- Advanced anti-bot protection detected
|
| 669 |
-
- System will try multiple fallback methods automatically
|
| 670 |
-
|
| 671 |
-
**"All download attempts failed"**
|
| 672 |
-
- Video may be geo-restricted or deleted
|
| 673 |
-
- Try a different video to test if service is working
|
| 674 |
-
|
| 675 |
-
## π Support
|
| 676 |
-
If problems persist, check if the video plays normally in your browser and try with a different public video.
|
| 677 |
""")
|
| 678 |
|
| 679 |
-
#
|
| 680 |
url_button.click(
|
| 681 |
-
fn=
|
| 682 |
inputs=[url_input],
|
| 683 |
outputs=[transcription_output, status_output]
|
| 684 |
)
|
| 685 |
|
| 686 |
video_button.click(
|
| 687 |
-
fn=
|
| 688 |
inputs=[video_input],
|
| 689 |
outputs=[transcription_output, status_output]
|
| 690 |
)
|
| 691 |
|
| 692 |
summary_button.click(
|
| 693 |
-
fn=
|
| 694 |
inputs=[transcription_output],
|
| 695 |
outputs=[summary_output]
|
| 696 |
)
|
| 697 |
|
| 698 |
-
print("
|
| 699 |
-
print(f"π§ curl-cffi status: {'Available' if CURL_CFFI_AVAILABLE else 'Not available'}")
|
| 700 |
print("π Launching application...")
|
| 701 |
|
| 702 |
demo.launch(
|
| 703 |
server_name="0.0.0.0",
|
| 704 |
server_port=7860,
|
| 705 |
-
show_error=True
|
| 706 |
-
share=False
|
| 707 |
)
|
|
|
|
| 10 |
import uuid
|
| 11 |
import time
|
| 12 |
import random
|
| 13 |
+
import tempfile
|
| 14 |
+
import shutil
|
| 15 |
|
| 16 |
# --- CONFIGURACIΓN INICIAL ---
|
| 17 |
+
print("Starting the working program based on successful Streamlit version...")
|
|
|
|
| 18 |
|
| 19 |
# Verificar si curl-cffi estΓ‘ disponible
|
| 20 |
try:
|
| 21 |
import curl_cffi
|
| 22 |
CURL_CFFI_AVAILABLE = True
|
| 23 |
+
print("β
curl-cffi is available")
|
| 24 |
except ImportError:
|
| 25 |
CURL_CFFI_AVAILABLE = False
|
| 26 |
+
print("β οΈ curl-cffi not available")
|
| 27 |
|
| 28 |
# Carga del modelo en CPU
|
| 29 |
model_path = "Qwen/Qwen2.5-7B-Instruct"
|
|
|
|
| 33 |
model = model.eval()
|
| 34 |
print("β
Model successfully loaded.")
|
| 35 |
|
| 36 |
+
# --- CONFIGURACIΓN EXITOSA BASADA EN TU CΓDIGO ---
|
| 37 |
+
def get_working_ydl_opts(output_path):
|
| 38 |
+
"""
|
| 39 |
+
ConfiguraciΓ³n que FUNCIONA basada en el cΓ³digo de Streamlit exitoso
|
| 40 |
+
"""
|
| 41 |
+
# Limpiar la URL de parΓ‘metros innecesarios (como en tu cΓ³digo)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
opts = {
|
| 43 |
'format': 'bestaudio/best',
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
'outtmpl': output_path,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
'postprocessors': [{
|
| 46 |
'key': 'FFmpegExtractAudio',
|
| 47 |
+
'preferredcodec': 'wav', # Cambiado a wav para consistencia
|
| 48 |
+
'preferredquality': '64'
|
| 49 |
}],
|
| 50 |
+
'quiet': True,
|
| 51 |
+
'no_warnings': True,
|
|
|
|
|
|
|
|
|
|
| 52 |
'retries': 2,
|
| 53 |
+
'socket_timeout': 30, # Exactamente como tu configuraciΓ³n
|
| 54 |
+
'postprocessor_args': ['-ar', '16000', '-ac', '1'], # Igual que tu cΓ³digo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
# Β‘LA LΓNEA CLAVE DE TU CΓDIGO QUE FUNCIONA!
|
| 57 |
+
'impersonate': 'chrome120', # EspecΓficamente chrome120 como en tu cΓ³digo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
}
|
| 59 |
|
| 60 |
return opts
|
| 61 |
|
| 62 |
+
def get_fallback_ydl_opts(output_path):
|
| 63 |
+
"""
|
| 64 |
+
ConfiguraciΓ³n de fallback simplificada
|
| 65 |
+
"""
|
| 66 |
return {
|
| 67 |
'format': 'bestaudio/best',
|
| 68 |
+
'outtmpl': output_path,
|
| 69 |
'postprocessors': [{
|
| 70 |
'key': 'FFmpegExtractAudio',
|
| 71 |
'preferredcodec': 'wav',
|
| 72 |
}],
|
| 73 |
+
'quiet': True,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
'no_warnings': True,
|
| 75 |
+
'retries': 1,
|
| 76 |
+
'socket_timeout': 45,
|
| 77 |
+
# Sin impersonaciΓ³n para fallback
|
| 78 |
}
|
| 79 |
|
| 80 |
# --- FUNCIONES AUXILIARES ---
|
|
|
|
| 90 |
except OSError as e:
|
| 91 |
print(f"β Error removing file {file}: {e}")
|
| 92 |
|
| 93 |
+
def clean_url(url):
|
| 94 |
+
"""Limpiar URL como en tu cΓ³digo exitoso"""
|
| 95 |
+
return url.split('?')[0] if '?' in url else url
|
|
|
|
|
|
|
| 96 |
|
| 97 |
def is_vimeo_url(url):
|
| 98 |
"""Detecta si una URL es de Vimeo"""
|
| 99 |
return 'vimeo.com' in url.lower()
|
| 100 |
|
| 101 |
+
# --- FUNCIΓN PRINCIPAL BASADA EN TU CΓDIGO EXITOSO ---
|
| 102 |
+
def download_video_audio_working_method(url):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
"""
|
| 104 |
+
MΓ©todo basado en tu cΓ³digo de Streamlit que SΓ funciona con Vimeo
|
| 105 |
"""
|
| 106 |
+
print(f"π― Processing URL with working method: {url}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
# Limpiar URL como en tu cΓ³digo
|
| 109 |
+
clean_url_value = clean_url(url)
|
| 110 |
+
print(f"π§Ή Cleaned URL: {clean_url_value}")
|
| 111 |
|
| 112 |
+
# Crear directorio temporal
|
| 113 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 114 |
+
temp_filename = generate_unique_filename("")
|
| 115 |
+
|
| 116 |
+
# MΓ©todo 1: Tu configuraciΓ³n exacta que funciona
|
| 117 |
+
print("π Trying working method (chrome120 impersonation)...")
|
| 118 |
+
try:
|
| 119 |
+
ydl_opts = get_working_ydl_opts(os.path.join(temp_dir, f'{temp_filename}.%(ext)s'))
|
| 120 |
|
| 121 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 122 |
+
print("π Extracting video information...")
|
| 123 |
+
info_dict = ydl.extract_info(clean_url_value, download=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
+
if not info_dict:
|
| 126 |
+
raise Exception("Could not extract video information")
|
|
|
|
|
|
|
| 127 |
|
| 128 |
+
video_title = info_dict.get('title', 'Unknown')
|
| 129 |
+
duration = info_dict.get('duration')
|
| 130 |
+
|
| 131 |
+
print(f"β
Video found: {video_title}")
|
| 132 |
+
if duration:
|
| 133 |
+
print(f"β±οΈ Duration: {duration} seconds")
|
| 134 |
+
|
| 135 |
+
# Verificar duraciΓ³n (como en tu cΓ³digo)
|
| 136 |
+
MAX_DURATION_SECONDS = 1800 # 30 minutos como en tu cΓ³digo
|
| 137 |
+
if duration and duration > MAX_DURATION_SECONDS:
|
| 138 |
+
raise Exception(f"Video too long: {duration}s > {MAX_DURATION_SECONDS}s")
|
| 139 |
+
|
| 140 |
+
print("β¬οΈ Downloading audio...")
|
| 141 |
+
ydl.download([clean_url_value])
|
| 142 |
+
|
| 143 |
+
# Buscar archivo descargado
|
| 144 |
+
for filename in os.listdir(temp_dir):
|
| 145 |
+
if filename.endswith(('.wav', '.mp3', '.m4a')):
|
| 146 |
+
source_path = os.path.join(temp_dir, filename)
|
| 147 |
|
| 148 |
+
# Verificar tamaΓ±o del archivo
|
| 149 |
+
file_size = os.path.getsize(source_path)
|
| 150 |
+
print(f"π Downloaded file size: {file_size} bytes")
|
| 151 |
|
| 152 |
+
if file_size < 1024: # Menor que 1KB
|
| 153 |
+
raise Exception("Downloaded file too small")
|
|
|
|
| 154 |
|
| 155 |
+
# Copiar a ubicaciΓ³n final
|
| 156 |
+
final_path = generate_unique_filename(".wav")
|
| 157 |
+
shutil.copy2(source_path, final_path)
|
| 158 |
+
print(f"β
Audio saved to: {final_path}")
|
| 159 |
+
return final_path
|
| 160 |
|
| 161 |
+
raise FileNotFoundError("No audio file found after download")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
+
except Exception as e:
|
| 164 |
+
print(f"β Working method failed: {str(e)}")
|
| 165 |
+
|
| 166 |
+
# MΓ©todo 2: Fallback sin impersonaciΓ³n
|
| 167 |
+
print("π Trying fallback method...")
|
| 168 |
+
try:
|
| 169 |
+
ydl_opts = get_fallback_ydl_opts(os.path.join(temp_dir, f'{temp_filename}_fallback.%(ext)s'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 172 |
+
print("π Extracting with fallback...")
|
| 173 |
+
info_dict = ydl.extract_info(clean_url_value, download=False)
|
| 174 |
+
|
| 175 |
+
if info_dict:
|
| 176 |
+
print("β¬οΈ Downloading with fallback...")
|
| 177 |
+
ydl.download([clean_url_value])
|
| 178 |
+
|
| 179 |
+
# Buscar archivo descargado
|
| 180 |
+
for filename in os.listdir(temp_dir):
|
| 181 |
+
if filename.endswith(('.wav', '.mp3', '.m4a')) and 'fallback' in filename:
|
| 182 |
+
source_path = os.path.join(temp_dir, filename)
|
| 183 |
+
file_size = os.path.getsize(source_path)
|
| 184 |
+
|
| 185 |
+
if file_size >= 1024:
|
| 186 |
+
final_path = generate_unique_filename(".wav")
|
| 187 |
+
shutil.copy2(source_path, final_path)
|
| 188 |
+
print(f"β
Fallback successful: {final_path}")
|
| 189 |
+
return final_path
|
| 190 |
|
| 191 |
+
except Exception as fallback_error:
|
| 192 |
+
print(f"β Fallback also failed: {str(fallback_error)}")
|
| 193 |
+
|
| 194 |
+
# Si todo falla
|
| 195 |
+
raise Exception(f"All methods failed. Primary error: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
+
def transcribe_audio_simple(file_path):
|
| 198 |
+
"""FunciΓ³n simplificada de transcripciΓ³n"""
|
| 199 |
+
print(f"π€ Starting transcription: {file_path}")
|
| 200 |
+
|
| 201 |
try:
|
| 202 |
+
# Verificar archivo
|
| 203 |
if not os.path.exists(file_path):
|
| 204 |
raise FileNotFoundError(f"Audio file not found: {file_path}")
|
| 205 |
|
|
|
|
| 207 |
print(f"π Audio file size: {file_size} bytes")
|
| 208 |
|
| 209 |
if file_size < 1000:
|
| 210 |
+
raise Exception("Audio file too small")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
+
# Usar Whisper con configuraciΓ³n robusta
|
| 213 |
output_file = generate_unique_filename(".json")
|
| 214 |
|
|
|
|
| 215 |
command = [
|
| 216 |
"insanely-fast-whisper",
|
| 217 |
"--file-name", file_path,
|
|
|
|
| 220 |
"--task", "transcribe",
|
| 221 |
"--timestamp", "chunk",
|
| 222 |
"--transcript-path", output_file,
|
| 223 |
+
"--batch-size", "2",
|
|
|
|
| 224 |
]
|
| 225 |
|
| 226 |
+
print("π€ Running transcription...")
|
| 227 |
result = subprocess.run(
|
| 228 |
command,
|
| 229 |
check=True,
|
| 230 |
capture_output=True,
|
| 231 |
text=True,
|
| 232 |
+
timeout=600 # 10 minutos
|
| 233 |
)
|
| 234 |
|
| 235 |
+
# Leer resultado
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
with open(output_file, "r", encoding='utf-8') as f:
|
| 237 |
transcription_data = json.load(f)
|
| 238 |
|
| 239 |
result_text = transcription_data.get("text", "").strip()
|
| 240 |
|
|
|
|
| 241 |
if not result_text:
|
| 242 |
chunks = transcription_data.get("chunks", [])
|
| 243 |
+
result_text = " ".join([chunk.get("text", "").strip() for chunk in chunks])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
|
|
|
| 245 |
cleanup_files(output_file)
|
| 246 |
+
|
| 247 |
+
if len(result_text) < 10:
|
| 248 |
+
raise Exception("Transcription too short")
|
| 249 |
+
|
| 250 |
+
print(f"β
Transcription completed: {len(result_text)} characters")
|
| 251 |
return result_text
|
| 252 |
+
|
|
|
|
|
|
|
|
|
|
| 253 |
except Exception as e:
|
| 254 |
print(f"β Transcription error: {e}")
|
| 255 |
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
+
def generate_summary_simple(transcription):
|
| 258 |
+
"""FunciΓ³n simple de resumen"""
|
| 259 |
if not transcription or len(transcription.strip()) < 20:
|
| 260 |
+
return "β οΈ Transcription too short to summarize."
|
| 261 |
|
|
|
|
|
|
|
| 262 |
try:
|
| 263 |
detected_language = langdetect.detect(transcription)
|
|
|
|
| 264 |
except:
|
| 265 |
detected_language = "en"
|
|
|
|
| 266 |
|
| 267 |
+
# Limitar texto
|
| 268 |
+
max_chars = 10000
|
| 269 |
+
text = transcription[:max_chars]
|
| 270 |
if len(transcription) > max_chars:
|
| 271 |
+
text += "..."
|
|
|
|
| 272 |
|
| 273 |
+
prompt = f"""Create a summary in {detected_language} of this video transcription (150-250 words):
|
|
|
|
| 274 |
|
| 275 |
+
{text}"""
|
| 276 |
|
| 277 |
try:
|
| 278 |
response, _ = model.chat(tokenizer, prompt, history=[])
|
|
|
|
| 279 |
return response
|
| 280 |
except Exception as e:
|
| 281 |
+
return f"Summary error: {str(e)}"
|
|
|
|
| 282 |
|
| 283 |
+
# --- FUNCIONES DE INTERFAZ ---
|
| 284 |
+
def process_video_url_working(url):
|
| 285 |
+
"""FunciΓ³n principal usando el mΓ©todo que funciona"""
|
| 286 |
if not url or not url.strip():
|
| 287 |
return "β Please enter a valid video URL.", "β οΈ No URL provided"
|
| 288 |
|
| 289 |
url = url.strip()
|
| 290 |
print(f"\n{'='*50}")
|
| 291 |
+
print(f"π― PROCESSING WITH WORKING METHOD")
|
|
|
|
| 292 |
print(f"URL: {url}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
print(f"curl-cffi available: {CURL_CFFI_AVAILABLE}")
|
| 294 |
+
print(f"{'='*50}")
|
| 295 |
|
| 296 |
audio_file = None
|
| 297 |
try:
|
| 298 |
+
# MΓ©todo basado en tu cΓ³digo exitoso
|
| 299 |
+
audio_file = download_video_audio_working_method(url)
|
| 300 |
+
transcription = transcribe_audio_simple(audio_file)
|
| 301 |
|
| 302 |
+
success_msg = f"β
Successfully processed! ({len(transcription)} chars)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
return transcription, success_msg
|
| 304 |
|
| 305 |
except Exception as e:
|
| 306 |
error_msg = str(e)
|
| 307 |
+
print(f"β ERROR: {error_msg}")
|
| 308 |
|
| 309 |
+
# AnΓ‘lisis especΓfico de errores
|
| 310 |
+
if "too long" in error_msg.lower():
|
| 311 |
+
return "β VIDEO TOO LONG: Video exceeds 30-minute limit.", "β±οΈ Duration Limit"
|
| 312 |
+
elif "http error 401" in error_msg.lower():
|
| 313 |
+
return "β ACCESS DENIED: Video is private or requires authentication.", "π Private Video"
|
| 314 |
+
elif "http error 403" in error_msg.lower():
|
| 315 |
+
return "β BLOCKED: IP temporarily blocked. Wait 10-15 minutes.", "π« IP Blocked"
|
| 316 |
+
elif "http error 429" in error_msg.lower():
|
| 317 |
+
return "β RATE LIMITED: Too many requests. Wait 5-10 minutes.", "β° Rate Limited"
|
| 318 |
+
elif "file too small" in error_msg.lower():
|
| 319 |
+
return "β DOWNLOAD FAILED: Audio file is corrupted or empty.", "π File Error"
|
| 320 |
+
elif "not found" in error_msg.lower():
|
| 321 |
+
return "β VIDEO NOT FOUND: URL may be invalid or video deleted.", "π Not Found"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
else:
|
| 323 |
+
return f"β PROCESSING ERROR: {error_msg}", "β Unknown Error"
|
| 324 |
finally:
|
|
|
|
| 325 |
if audio_file and os.path.exists(audio_file):
|
| 326 |
cleanup_files(audio_file)
|
| 327 |
|
| 328 |
+
def process_uploaded_video_simple(video_path):
|
| 329 |
+
"""Procesar video subido"""
|
| 330 |
if video_path is None:
|
| 331 |
+
return "β Please upload a video file.", "β οΈ No file"
|
| 332 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
try:
|
| 334 |
+
transcription = transcribe_audio_simple(video_path)
|
| 335 |
+
return transcription, f"β
Processed upload ({len(transcription)} chars)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
except Exception as e:
|
| 337 |
+
return f"β Upload error: {str(e)}", "β Error"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
|
| 339 |
+
# --- INTERFAZ GRADIO ---
|
| 340 |
+
print("π¨ Creating Gradio interface...")
|
| 341 |
|
| 342 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="π₯ Working Vimeo Transcriptor") as demo:
|
| 343 |
+
gr.Markdown("# π₯ Working Vimeo Transcriptor")
|
| 344 |
gr.Markdown(f"""
|
| 345 |
+
**Based on proven Streamlit code that works with Vimeo!**
|
| 346 |
|
| 347 |
+
π‘οΈ **Status:**
|
| 348 |
+
- curl-cffi: {'β
Available' if CURL_CFFI_AVAILABLE else 'β Not Available'}
|
| 349 |
+
- Chrome120 Impersonation: β
Enabled
|
| 350 |
+
- Working Method: β
Active
|
| 351 |
+
- Max Duration: β±οΈ 30 minutes
|
| 352 |
""")
|
| 353 |
|
| 354 |
with gr.Tabs():
|
| 355 |
+
with gr.TabItem("π Video URL"):
|
| 356 |
+
url_input = gr.Textbox(
|
| 357 |
+
label="Vimeo URL",
|
| 358 |
+
placeholder="https://vimeo.com/123456789",
|
| 359 |
+
info="Paste your Vimeo URL here"
|
| 360 |
+
)
|
| 361 |
+
url_button = gr.Button("π Process with Working Method", variant="primary")
|
|
|
|
| 362 |
|
| 363 |
+
with gr.TabItem("π€ Upload Video"):
|
| 364 |
+
video_input = gr.Video(label="Upload Video File")
|
| 365 |
+
video_button = gr.Button("π Process Upload", variant="primary")
|
|
|
|
| 366 |
|
| 367 |
with gr.Row():
|
| 368 |
with gr.Column():
|
|
|
|
| 376 |
summary_output = gr.Textbox(
|
| 377 |
label="π AI Summary",
|
| 378 |
lines=15,
|
| 379 |
+
placeholder="Summary will appear here..."
|
| 380 |
)
|
| 381 |
|
| 382 |
+
status_output = gr.Textbox(
|
| 383 |
+
label="π Status",
|
| 384 |
+
interactive=False,
|
| 385 |
+
placeholder="Ready to process...",
|
| 386 |
+
lines=1
|
| 387 |
+
)
|
|
|
|
|
|
|
| 388 |
|
| 389 |
+
summary_button = gr.Button("π Generate Summary", variant="secondary")
|
| 390 |
+
|
| 391 |
+
with gr.Accordion("βΉοΈ Working Method Info", open=False):
|
| 392 |
+
gr.Markdown("""
|
| 393 |
+
## π― This Version Uses Your Proven Method
|
| 394 |
+
|
| 395 |
+
**Key Differences:**
|
| 396 |
+
- β
Uses `impersonate: 'chrome120'` (your working config)
|
| 397 |
+
- β
URL cleaning: removes query parameters
|
| 398 |
+
- β
30-minute duration limit (like your Streamlit)
|
| 399 |
+
- β
Simplified error handling
|
| 400 |
+
- β
File size validation (minimum 1KB)
|
| 401 |
+
|
| 402 |
+
**Success Rate Expected:**
|
| 403 |
+
- Public Vimeo videos: ~85%
|
| 404 |
+
- Private videos: Limited (depends on access)
|
| 405 |
+
- Videos > 30 min: Blocked (by design)
|
| 406 |
+
|
| 407 |
+
**Troubleshooting:**
|
| 408 |
+
- If blocked: Wait 10-15 minutes
|
| 409 |
+
- Try different public videos first
|
| 410 |
+
- Ensure video plays in browser
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
""")
|
| 412 |
|
| 413 |
+
# Event handlers
|
| 414 |
url_button.click(
|
| 415 |
+
fn=process_video_url_working,
|
| 416 |
inputs=[url_input],
|
| 417 |
outputs=[transcription_output, status_output]
|
| 418 |
)
|
| 419 |
|
| 420 |
video_button.click(
|
| 421 |
+
fn=process_uploaded_video_simple,
|
| 422 |
inputs=[video_input],
|
| 423 |
outputs=[transcription_output, status_output]
|
| 424 |
)
|
| 425 |
|
| 426 |
summary_button.click(
|
| 427 |
+
fn=generate_summary_simple,
|
| 428 |
inputs=[transcription_output],
|
| 429 |
outputs=[summary_output]
|
| 430 |
)
|
| 431 |
|
| 432 |
+
print("β
Gradio interface ready with working method!")
|
|
|
|
| 433 |
print("π Launching application...")
|
| 434 |
|
| 435 |
demo.launch(
|
| 436 |
server_name="0.0.0.0",
|
| 437 |
server_port=7860,
|
| 438 |
+
show_error=True
|
|
|
|
| 439 |
)
|