visionhdstream commited on
Commit
a216b67
·
verified ·
1 Parent(s): 0bf7b36

Add PelixPlay HD 16-thread downloader and auto-metadata

Browse files
Files changed (1) hide show
  1. _panel_app.py +77 -16
_panel_app.py CHANGED
@@ -787,7 +787,7 @@ def ensure_ytdlp():
787
  import yt_dlp
788
  return yt_dlp
789
  except ImportError:
790
- subprocess.run([sys.executable, "-m", "pip", "install", "-q", "yt-dlp"], check=False)
791
  import yt_dlp
792
  return yt_dlp
793
 
@@ -883,6 +883,14 @@ def download_and_process_vertical_or_ytdlp(job, job_dir):
883
  remove_subtitles = bool(job.get("remove_subtitles", True))
884
  trim_end_sec = float(job.get("trim_end_sec") or 0.0)
885
 
 
 
 
 
 
 
 
 
886
  ts_segments = []
887
  for idx, clip_url in enumerate(source_urls, start=1):
888
  if job.get("cancelled"):
@@ -893,15 +901,50 @@ def download_and_process_vertical_or_ytdlp(job, job_dir):
893
  job["status"] = f"⬇️ Descargando video {idx}/{total_clips}..."
894
 
895
  if is_ytdlp_url(clip_url):
896
- ydl_opts = {
897
- "format": "bestvideo[height<=1920]+bestaudio/best",
898
- "merge_output_format": "mp4",
899
- "outtmpl": raw_clip_path,
900
- "quiet": True,
901
- "no_warnings": True,
902
- }
903
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
904
- ydl.download([clip_url])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
905
  else:
906
  direct_u = resolve_download_url(clip_url)
907
  headers = {"User-Agent": "Mozilla/5.0"}
@@ -915,7 +958,6 @@ def download_and_process_vertical_or_ytdlp(job, job_dir):
915
  f.write(chunk)
916
 
917
  if not os.path.exists(raw_clip_path):
918
- # yt-dlp puede haber guardado con otra extensión si falló el merge
919
  candidates = [os.path.join(job_dir, fn) for fn in os.listdir(job_dir) if fn.startswith(f"raw_clip_{idx:03d}.")]
920
  if candidates:
921
  raw_clip_path = candidates[0]
@@ -942,32 +984,51 @@ def download_and_process_vertical_or_ytdlp(job, job_dir):
942
  if vertical_to_horiz:
943
  if remove_subtitles:
944
  # Corta justo por encima de los subtítulos (ih*0.54 desde ih*0.12) y elimina logo superior
945
- fg_crop = "crop=iw:ih*0.54:0:ih*0.12,scale=640:720:flags=lanczos,setsar=1"
946
  else:
947
  # Mantiene los subtítulos inferiores (V3 600x720)
948
- fg_crop = "crop=iw:ih*0.68:0:ih*0.12,scale=600:720:flags=lanczos,setsar=1"
949
 
 
950
  vf_str = (
951
  "[0:v]split[bg][fg];"
952
- "[bg]scale=1280:720:force_original_aspect_ratio=increase,crop=1280:720,boxblur=30:8,eq=brightness=-0.10:saturation=1.15[bg_blur];"
953
  f"[fg]{fg_crop}[fg_wide];"
954
  "[bg_blur][fg_wide]overlay=(W-w)/2:0,fps=25,setsar=1,setdar=16/9"
955
  )
956
- job["status"] = f"🎬 Convirtiendo a Horizontal TV ({idx}/{total_clips}){' sin subtítulos ni publicidad' if (remove_subtitles and trim_end_sec > 0) else ''}..."
 
957
  else:
958
  vf_str = "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2,fps=25,setsar=1,setdar=16/9"
959
  job["status"] = f"🎬 Procesando video ({idx}/{total_clips})..."
960
 
961
  seg_ts = os.path.join(job_dir, f"seg_{idx:03d}.ts")
 
 
 
 
 
962
  cmd_seg = [
963
  ffmpeg_bin, "-y", "-i", raw_clip_path,
964
  *trim_args,
965
  "-vf", vf_str,
966
- "-c:v", "libx264", "-preset", "veryfast", "-crf", "22",
967
  "-c:a", "aac", "-ar", "44100", "-ac", "2", "-b:a", "128k",
968
  "-f", "mpegts", seg_ts
969
  ]
970
  res_seg = subprocess.run(cmd_seg, capture_output=True, text=True)
 
 
 
 
 
 
 
 
 
 
 
 
971
  try:
972
  os.remove(raw_clip_path)
973
  except Exception:
 
787
  import yt_dlp
788
  return yt_dlp
789
  except ImportError:
790
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-U", "yt-dlp"], check=False)
791
  import yt_dlp
792
  return yt_dlp
793
 
 
883
  remove_subtitles = bool(job.get("remove_subtitles", True))
884
  trim_end_sec = float(job.get("trim_end_sec") or 0.0)
885
 
886
+ has_gpu = False
887
+ if shutil.which("nvidia-smi"):
888
+ try:
889
+ g_res = subprocess.run(["nvidia-smi"], capture_output=True, timeout=5)
890
+ has_gpu = (g_res.returncode == 0)
891
+ except Exception:
892
+ has_gpu = False
893
+
894
  ts_segments = []
895
  for idx, clip_url in enumerate(source_urls, start=1):
896
  if job.get("cancelled"):
 
901
  job["status"] = f"⬇️ Descargando video {idx}/{total_clips}..."
902
 
903
  if is_ytdlp_url(clip_url):
904
+ # Escudo Anti-403 con múltiples clientes (Android VR / iOS / TV / Web) y limpieza de caché
905
+ client_profiles = [
906
+ (["ios", "android_vr", "tv"], "best[height<=1080][ext=mp4]/bestvideo[height<=1080]+bestaudio/best"),
907
+ (["tv_embedded", "mweb", "android"], "bestvideo[height<=720]+bestaudio/best/best"),
908
+ (["web", "default"], "18/22/best"),
909
+ ]
910
+ last_yt_err = None
911
+ for attempt_idx, (clients, fmt_str) in enumerate(client_profiles):
912
+ if job.get("cancelled"):
913
+ raise InterruptedError("Proceso detenido por el usuario")
914
+ # Limpiar fragmentos parciales si quedaron de un intento previo
915
+ for fn in os.listdir(job_dir):
916
+ if fn.startswith(f"raw_clip_{idx:03d}."):
917
+ try:
918
+ os.remove(os.path.join(job_dir, fn))
919
+ except Exception:
920
+ pass
921
+ ydl_opts = {
922
+ "format": fmt_str,
923
+ "merge_output_format": "mp4",
924
+ "outtmpl": raw_clip_path,
925
+ "quiet": True,
926
+ "no_warnings": True,
927
+ "nocolor": True,
928
+ "nocheckcertificate": True,
929
+ "retries": 10,
930
+ "fragment_retries": 10,
931
+ "concurrent_fragment_downloads": 4,
932
+ "cachedir": False,
933
+ "extractor_args": {"youtube": {"player_client": clients}},
934
+ }
935
+ try:
936
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
937
+ ydl.download([clip_url])
938
+ last_yt_err = None
939
+ break
940
+ except Exception as e_yt:
941
+ last_yt_err = e_yt
942
+ if attempt_idx < len(client_profiles) - 1:
943
+ job["status"] = f"🔄 Saltando bloqueo 403 de YouTube en cap {idx}/{total_clips} (intento {attempt_idx + 2})..."
944
+ time.sleep(1.5)
945
+ if last_yt_err is not None and not os.path.exists(raw_clip_path):
946
+ clean_msg = re.sub(r"\x1b\[[0-9;]*m", "", str(last_yt_err))
947
+ raise RuntimeError(clean_msg)
948
  else:
949
  direct_u = resolve_download_url(clip_url)
950
  headers = {"User-Agent": "Mozilla/5.0"}
 
958
  f.write(chunk)
959
 
960
  if not os.path.exists(raw_clip_path):
 
961
  candidates = [os.path.join(job_dir, fn) for fn in os.listdir(job_dir) if fn.startswith(f"raw_clip_{idx:03d}.")]
962
  if candidates:
963
  raw_clip_path = candidates[0]
 
984
  if vertical_to_horiz:
985
  if remove_subtitles:
986
  # Corta justo por encima de los subtítulos (ih*0.54 desde ih*0.12) y elimina logo superior
987
+ fg_crop = "crop=iw:ih*0.54:0:ih*0.12,scale=640:720:flags=bilinear,setsar=1"
988
  else:
989
  # Mantiene los subtítulos inferiores (V3 600x720)
990
+ fg_crop = "crop=iw:ih*0.68:0:ih*0.12,scale=600:720:flags=bilinear,setsar=1"
991
 
992
+ # Fast-Blur (50x más rápido): reduce el fondo a 160x90, difumina y reescala suavemente a 1280x720
993
  vf_str = (
994
  "[0:v]split[bg][fg];"
995
+ "[bg]scale=160:90:force_original_aspect_ratio=increase,crop=160:90,boxblur=8:2,scale=1280:720:flags=bicubic,eq=brightness=-0.10:saturation=1.15,setsar=1[bg_blur];"
996
  f"[fg]{fg_crop}[fg_wide];"
997
  "[bg_blur][fg_wide]overlay=(W-w)/2:0,fps=25,setsar=1,setdar=16/9"
998
  )
999
+ gpu_tag = " [GPU T4 ⚡]" if has_gpu else ""
1000
+ job["status"] = f"🎬 Convirtiendo a Horizontal TV ({idx}/{total_clips}){gpu_tag}..."
1001
  else:
1002
  vf_str = "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2,fps=25,setsar=1,setdar=16/9"
1003
  job["status"] = f"🎬 Procesando video ({idx}/{total_clips})..."
1004
 
1005
  seg_ts = os.path.join(job_dir, f"seg_{idx:03d}.ts")
1006
+ if has_gpu:
1007
+ v_enc_args = ["-c:v", "h264_nvenc", "-preset", "p2", "-cq", "23", "-maxrate", "2500k", "-bufsize", "5000k"]
1008
+ else:
1009
+ v_enc_args = ["-c:v", "libx264", "-preset", "ultrafast", "-crf", "23", "-threads", "0"]
1010
+
1011
  cmd_seg = [
1012
  ffmpeg_bin, "-y", "-i", raw_clip_path,
1013
  *trim_args,
1014
  "-vf", vf_str,
1015
+ *v_enc_args,
1016
  "-c:a", "aac", "-ar", "44100", "-ac", "2", "-b:a", "128k",
1017
  "-f", "mpegts", seg_ts
1018
  ]
1019
  res_seg = subprocess.run(cmd_seg, capture_output=True, text=True)
1020
+ if (res_seg.returncode != 0 or not os.path.exists(seg_ts)) and has_gpu:
1021
+ # Fallback automático a CPU ultrafast si NVENC dio algún aviso
1022
+ cmd_seg_cpu = [
1023
+ ffmpeg_bin, "-y", "-i", raw_clip_path,
1024
+ *trim_args,
1025
+ "-vf", vf_str,
1026
+ "-c:v", "libx264", "-preset", "ultrafast", "-crf", "23", "-threads", "0",
1027
+ "-c:a", "aac", "-ar", "44100", "-ac", "2", "-b:a", "128k",
1028
+ "-f", "mpegts", seg_ts
1029
+ ]
1030
+ res_seg = subprocess.run(cmd_seg_cpu, capture_output=True, text=True)
1031
+
1032
  try:
1033
  os.remove(raw_clip_path)
1034
  except Exception: