visionhdstream commited on
Commit
433b70f
·
verified ·
1 Parent(s): 4277b7f

Add PelixPlay HD 16-thread downloader and auto-metadata

Browse files
Files changed (1) hide show
  1. _panel_app.py +126 -6
_panel_app.py CHANGED
@@ -453,7 +453,11 @@ def download_pelixplay_to_mp4(job, p_info, job_dir):
453
  seg_lock = threading.Lock()
454
 
455
  def fetch_seg(idx, s_url):
 
 
456
  for attempt in range(4):
 
 
457
  try:
458
  resp = requests.get(s_url, headers={"User-Agent": headers["User-Agent"]}, timeout=20)
459
  if resp.status_code == 200 and resp.content:
@@ -462,6 +466,8 @@ def download_pelixplay_to_mp4(job, p_info, job_dir):
462
  with open(seg_file, "wb") as fs:
463
  fs.write(clean_ts)
464
  return len(clean_ts)
 
 
465
  except Exception:
466
  time.sleep(0.5 * (attempt + 1))
467
  raise RuntimeError(f"Fallo descargando segmento {idx}/{total_segs}")
@@ -469,6 +475,10 @@ def download_pelixplay_to_mp4(job, p_info, job_dir):
469
  with ThreadPoolExecutor(max_workers=16) as pool:
470
  futures = {pool.submit(fetch_seg, i, u): i for i, u in enumerate(seg_urls)}
471
  for fut in as_completed(futures):
 
 
 
 
472
  sz = fut.result()
473
  with seg_lock:
474
  completed_segs += 1
@@ -486,6 +496,9 @@ def download_pelixplay_to_mp4(job, p_info, job_dir):
486
  f"a {speed_mb:.1f} MB/s — {format_eta(eta_s)}"
487
  )
488
 
 
 
 
489
  # Unir todos los segmentos TS en orden y pasar a MP4 con ffmpeg (-c copy, instantáneo)
490
  job["status"] = "🎬 Empaquetando video en formato .MP4 limpio (sin recodificar)..."
491
  job["progress"] = 71
@@ -610,6 +623,8 @@ def process_job(job):
610
  last_update = time.time()
611
  with open(download_path, "wb") as f:
612
  for chunk in r.iter_content(chunk_size=1024 * 1024):
 
 
613
  if chunk:
614
  f.write(chunk)
615
  downloaded += len(chunk)
@@ -691,6 +706,9 @@ def process_job(job):
691
  else:
692
  target_video_path = download_path
693
 
 
 
 
694
  video_size = os.path.getsize(target_video_path)
695
  size_str = format_size(video_size)
696
 
@@ -705,6 +723,9 @@ def process_job(job):
705
  else:
706
  camouflaged_name = f"v_{idx:04d}.mp4"
707
 
 
 
 
708
  job["camouflaged_name"] = camouflaged_name
709
  job["video_size_bytes"] = video_size
710
  job["upload_start_ts"] = time.time()
@@ -790,6 +811,11 @@ def process_job(job):
790
  job["status"] = f"✅ ¡Completado! Subido a Hugging Face como {camouflaged_name} ({size_str})"
791
  job["state"] = "done"
792
 
 
 
 
 
 
793
  except Exception as e:
794
  ACTIVE_UPLOAD_JOB = None
795
  job["state"] = "error"
@@ -805,6 +831,8 @@ def background_worker():
805
  next_job = None
806
  with STATE_LOCK:
807
  for j in JOBS:
 
 
808
  if j["state"] == "queued":
809
  j["state"] = "running"
810
  next_job = j
@@ -966,6 +994,44 @@ def api_item_delete():
966
  return jsonify({"success": True})
967
 
968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
969
  HTML_TEMPLATE = r"""<!DOCTYPE html>
970
  <html lang="es">
971
  <head>
@@ -1412,6 +1478,14 @@ HTML_TEMPLATE = r"""<!DOCTYPE html>
1412
  <div class="card" id="jobsCard" style="display:none;">
1413
  <div class="card-header" style="margin-bottom:12px;">
1414
  <div class="card-title"><i class="fa-solid fa-bolt" style="color:#facc15;"></i> Procesos en Segundo Plano</div>
 
 
 
 
 
 
 
 
1415
  </div>
1416
  <div id="jobsContainer"></div>
1417
  </div>
@@ -1736,6 +1810,33 @@ HTML_TEMPLATE = r"""<!DOCTYPE html>
1736
  }
1737
  }
1738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1739
  async function refreshState() {
1740
  try {
1741
  const res = await fetch('/api/state');
@@ -1747,17 +1848,36 @@ HTML_TEMPLATE = r"""<!DOCTYPE html>
1747
  const jobsContainer = document.getElementById('jobsContainer');
1748
  if (data.jobs && data.jobs.length > 0) {
1749
  jobsCard.style.display = 'block';
1750
- jobsContainer.innerHTML = data.jobs.map(j => `
 
 
 
 
 
1751
  <div class="job-item">
1752
  <div class="job-top">
1753
- <span>${j.display_label}</span>
1754
- <span style="color:${j.state === 'error' ? '#f87171' : (j.state === 'done' ? '#34d399' : '#38bdf8')}">${j.status}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
1755
  </div>
1756
- <div class="progress-track">
1757
- <div class="progress-fill" style="width:${j.progress || 0}%"></div>
1758
  </div>
1759
  </div>
1760
- `).join('');
 
1761
  } else {
1762
  jobsCard.style.display = 'none';
1763
  }
 
453
  seg_lock = threading.Lock()
454
 
455
  def fetch_seg(idx, s_url):
456
+ if job.get("cancelled"):
457
+ raise InterruptedError("Cancelado por el usuario")
458
  for attempt in range(4):
459
+ if job.get("cancelled"):
460
+ raise InterruptedError("Cancelado por el usuario")
461
  try:
462
  resp = requests.get(s_url, headers={"User-Agent": headers["User-Agent"]}, timeout=20)
463
  if resp.status_code == 200 and resp.content:
 
466
  with open(seg_file, "wb") as fs:
467
  fs.write(clean_ts)
468
  return len(clean_ts)
469
+ except InterruptedError:
470
+ raise
471
  except Exception:
472
  time.sleep(0.5 * (attempt + 1))
473
  raise RuntimeError(f"Fallo descargando segmento {idx}/{total_segs}")
 
475
  with ThreadPoolExecutor(max_workers=16) as pool:
476
  futures = {pool.submit(fetch_seg, i, u): i for i, u in enumerate(seg_urls)}
477
  for fut in as_completed(futures):
478
+ if job.get("cancelled"):
479
+ for f_rem in futures:
480
+ f_rem.cancel()
481
+ raise InterruptedError("Cancelado por el usuario")
482
  sz = fut.result()
483
  with seg_lock:
484
  completed_segs += 1
 
496
  f"a {speed_mb:.1f} MB/s — {format_eta(eta_s)}"
497
  )
498
 
499
+ if job.get("cancelled"):
500
+ raise InterruptedError("Cancelado por el usuario")
501
+
502
  # Unir todos los segmentos TS en orden y pasar a MP4 con ffmpeg (-c copy, instantáneo)
503
  job["status"] = "🎬 Empaquetando video en formato .MP4 limpio (sin recodificar)..."
504
  job["progress"] = 71
 
623
  last_update = time.time()
624
  with open(download_path, "wb") as f:
625
  for chunk in r.iter_content(chunk_size=1024 * 1024):
626
+ if job.get("cancelled"):
627
+ raise InterruptedError("Descarga detenida por el usuario")
628
  if chunk:
629
  f.write(chunk)
630
  downloaded += len(chunk)
 
706
  else:
707
  target_video_path = download_path
708
 
709
+ if job.get("cancelled"):
710
+ raise InterruptedError("Cancelado por el usuario")
711
+
712
  video_size = os.path.getsize(target_video_path)
713
  size_str = format_size(video_size)
714
 
 
723
  else:
724
  camouflaged_name = f"v_{idx:04d}.mp4"
725
 
726
+ if job.get("cancelled"):
727
+ raise InterruptedError("Cancelado por el usuario")
728
+
729
  job["camouflaged_name"] = camouflaged_name
730
  job["video_size_bytes"] = video_size
731
  job["upload_start_ts"] = time.time()
 
811
  job["status"] = f"✅ ¡Completado! Subido a Hugging Face como {camouflaged_name} ({size_str})"
812
  job["state"] = "done"
813
 
814
+ except InterruptedError:
815
+ ACTIVE_UPLOAD_JOB = None
816
+ job["state"] = "error"
817
+ job["status"] = "🛑 Proceso detenido por el usuario."
818
+ job["progress"] = 0
819
  except Exception as e:
820
  ACTIVE_UPLOAD_JOB = None
821
  job["state"] = "error"
 
831
  next_job = None
832
  with STATE_LOCK:
833
  for j in JOBS:
834
+ if j.get("cancelled"):
835
+ continue
836
  if j["state"] == "queued":
837
  j["state"] = "running"
838
  next_job = j
 
994
  return jsonify({"success": True})
995
 
996
 
997
+ @app.route("/api/jobs/cancel", methods=["POST"])
998
+ def api_jobs_cancel():
999
+ data = request.get_json() or {}
1000
+ job_id = data.get("id")
1001
+ with STATE_LOCK:
1002
+ for j in JOBS:
1003
+ if j.get("id") == job_id:
1004
+ j["cancelled"] = True
1005
+ if j.get("state") == "queued":
1006
+ j["state"] = "error"
1007
+ j["status"] = "🛑 Cancelado antes de iniciar."
1008
+ elif j.get("state") == "running":
1009
+ j["status"] = "🛑 Cancelando y limpiando temporales..."
1010
+ break
1011
+ return jsonify({"success": True})
1012
+
1013
+
1014
+ @app.route("/api/jobs/cancel-all", methods=["POST"])
1015
+ def api_jobs_cancel_all():
1016
+ with STATE_LOCK:
1017
+ for j in JOBS:
1018
+ j["cancelled"] = True
1019
+ if j.get("state") == "queued":
1020
+ j["state"] = "error"
1021
+ j["status"] = "🛑 Cancelado."
1022
+ elif j.get("state") == "running":
1023
+ j["status"] = "🛑 Cancelando y deteniendo..."
1024
+ return jsonify({"success": True})
1025
+
1026
+
1027
+ @app.route("/api/jobs/clear", methods=["POST"])
1028
+ def api_jobs_clear():
1029
+ global JOBS
1030
+ with STATE_LOCK:
1031
+ JOBS[:] = [j for j in JOBS if j.get("state") == "running" and not j.get("cancelled")]
1032
+ return jsonify({"success": True})
1033
+
1034
+
1035
  HTML_TEMPLATE = r"""<!DOCTYPE html>
1036
  <html lang="es">
1037
  <head>
 
1478
  <div class="card" id="jobsCard" style="display:none;">
1479
  <div class="card-header" style="margin-bottom:12px;">
1480
  <div class="card-title"><i class="fa-solid fa-bolt" style="color:#facc15;"></i> Procesos en Segundo Plano</div>
1481
+ <div style="display:flex; gap:8px;">
1482
+ <button type="button" class="btn btn-sm" style="background:#dc2626;" onclick="cancelAllJobs()">
1483
+ <i class="fa-solid fa-circle-stop"></i> 🛑 Detener Todo
1484
+ </button>
1485
+ <button type="button" class="btn btn-sm" style="background:#475569;" onclick="clearCompletedJobs()">
1486
+ <i class="fa-solid fa-broom"></i> Limpiar Lista
1487
+ </button>
1488
+ </div>
1489
  </div>
1490
  <div id="jobsContainer"></div>
1491
  </div>
 
1810
  }
1811
  }
1812
 
1813
+ async function cancelJob(id) {
1814
+ if (!confirm('¿Deseas cancelar / quitar este proceso?')) return;
1815
+ await fetch('/api/jobs/cancel', {
1816
+ method: 'POST',
1817
+ headers: {'Content-Type': 'application/json'},
1818
+ body: JSON.stringify({id})
1819
+ });
1820
+ refreshState();
1821
+ }
1822
+
1823
+ async function cancelAllJobs() {
1824
+ if (!confirm('¿Seguro que deseas DETENER todas las descargas y procesos en cola?')) return;
1825
+ await fetch('/api/jobs/cancel-all', {
1826
+ method: 'POST',
1827
+ headers: {'Content-Type': 'application/json'}
1828
+ });
1829
+ refreshState();
1830
+ }
1831
+
1832
+ async function clearCompletedJobs() {
1833
+ await fetch('/api/jobs/clear', {
1834
+ method: 'POST',
1835
+ headers: {'Content-Type': 'application/json'}
1836
+ });
1837
+ refreshState();
1838
+ }
1839
+
1840
  async function refreshState() {
1841
  try {
1842
  const res = await fetch('/api/state');
 
1848
  const jobsContainer = document.getElementById('jobsContainer');
1849
  if (data.jobs && data.jobs.length > 0) {
1850
  jobsCard.style.display = 'block';
1851
+ jobsContainer.innerHTML = data.jobs.map(j => {
1852
+ const isDone = j.state === 'done';
1853
+ const isError = j.state === 'error';
1854
+ const isRunningOrQueued = !isDone && !isError;
1855
+ const statusColor = isError ? '#f87171' : (isDone ? '#34d399' : '#38bdf8');
1856
+ return `
1857
  <div class="job-item">
1858
  <div class="job-top">
1859
+ <div>
1860
+ <span style="font-weight:700;">${j.display_label}</span>
1861
+ <span style="color:${statusColor}; font-size:12px; margin-left:10px;">${j.status}</span>
1862
+ </div>
1863
+ <div>
1864
+ ${isRunningOrQueued ? `
1865
+ <button class="btn btn-sm" style="background:#ef4444; padding:4px 9px; font-size:11px;" onclick="cancelJob('${j.id}')">
1866
+ <i class="fa-solid fa-xmark"></i> Cancelar
1867
+ </button>
1868
+ ` : `
1869
+ <button class="btn btn-sm" style="background:#334155; padding:4px 9px; font-size:11px;" onclick="cancelJob('${j.id}')">
1870
+ <i class="fa-solid fa-trash"></i> Quitar
1871
+ </button>
1872
+ `}
1873
+ </div>
1874
  </div>
1875
+ <div class="progress-track" style="margin-top:6px;">
1876
+ <div class="progress-fill" style="width:${j.progress || 0}%; background:${isError ? '#ef4444' : (isDone ? '#10b981' : 'linear-gradient(90deg, #6366f1, #06b6d4)')};"></div>
1877
  </div>
1878
  </div>
1879
+ `;
1880
+ }).join('');
1881
  } else {
1882
  jobsCard.style.display = 'none';
1883
  }