areebsatin commited on
Commit
78a9770
Β·
1 Parent(s): 2323e40

Feature: Standardized audio energy analysis via WAV extraction

Browse files
Files changed (1) hide show
  1. server.py +70 -1
server.py CHANGED
@@ -12,8 +12,10 @@ import math
12
  import socket
13
  import struct
14
  import subprocess
 
15
  import time
16
  import uuid
 
17
  from concurrent.futures import ThreadPoolExecutor, as_completed
18
  from html import escape
19
  from pathlib import Path
@@ -27,7 +29,6 @@ import mediapipe as mp
27
 
28
  # ── Config ────────────────────────────────────────────────────────────────────
29
  import os
30
- import os
31
  PORT = int(os.getenv("PORT", 5000))
32
  COOKIES_FILE = os.getenv("COOKIES_FILE", "") # path to cookies.txt
33
  YTDLP_PROXY = os.getenv("YTDLP_PROXY", "") # e.g., http://user:pass@host:port
@@ -539,6 +540,74 @@ def extract_audio_energy(video_path: Path, duration: float):
539
  return result
540
 
541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542
  # ── Step 4: Find hook segments ────────────────────────────────────────────────
543
  def find_segments(energies, duration: float, n_clips: int = MAX_CLIPS):
544
  """
 
12
  import socket
13
  import struct
14
  import subprocess
15
+ import tempfile
16
  import time
17
  import uuid
18
+ import wave
19
  from concurrent.futures import ThreadPoolExecutor, as_completed
20
  from html import escape
21
  from pathlib import Path
 
29
 
30
  # ── Config ────────────────────────────────────────────────────────────────────
31
  import os
 
32
  PORT = int(os.getenv("PORT", 5000))
33
  COOKIES_FILE = os.getenv("COOKIES_FILE", "") # path to cookies.txt
34
  YTDLP_PROXY = os.getenv("YTDLP_PROXY", "") # e.g., http://user:pass@host:port
 
540
  return result
541
 
542
 
543
+ def analyze_audio_energy(video_path: Path):
544
+ """
545
+ Extract 16kHz mono WAV via FFmpeg and calculate per-second RMS energy.
546
+ Returns: [{start_time: float, end_time: float, energy: float}]
547
+ """
548
+ print(f"[>>] Analyzing audio energy for: {video_path.name}", flush=True)
549
+ temp_wav = Path(tempfile.gettempdir()) / f"{uuid.uuid4().hex}.wav"
550
+
551
+ try:
552
+ # Extract 16kHz mono WAV
553
+ cmd = [
554
+ "ffmpeg", "-i", str(video_path),
555
+ "-vn", "-acodec", "pcm_s16le", "-ar", "16000", "-ac", "1",
556
+ str(temp_wav), "-y", "-loglevel", "quiet"
557
+ ]
558
+ subprocess.run(cmd, check=True)
559
+
560
+ if not temp_wav.exists():
561
+ print("[!] Audio extraction failed.", flush=True)
562
+ return []
563
+
564
+ with wave.open(str(temp_wav), "rb") as w:
565
+ n_frames = w.getnframes()
566
+ sample_rate = w.getframerate()
567
+ frames = w.readframes(n_frames)
568
+
569
+ # samples are 16-bit signed ints (s16le)
570
+ samples = struct.unpack(f"<{n_frames}h", frames)
571
+
572
+ # 1 second chunks
573
+ chunk_size = sample_rate
574
+ energies = []
575
+
576
+ for i in range(0, n_frames, chunk_size):
577
+ chunk = samples[i : i + chunk_size]
578
+ if not chunk:
579
+ continue
580
+
581
+ # RMS = sqrt(mean(samples^2))
582
+ # Using float conversion to ensure precision during large sums
583
+ ms = sum(float(s) * float(s) for s in chunk) / len(chunk)
584
+ rms = math.sqrt(ms)
585
+
586
+ energies.append({
587
+ "start_time": round(i / sample_rate, 2),
588
+ "end_time": round((i + chunk_size) / sample_rate, 2),
589
+ "energy": rms
590
+ })
591
+
592
+ # Normalize to 0.0 - 1.0
593
+ max_e = max((e["energy"] for e in energies), default=1.0)
594
+ if max_e == 0: max_e = 1.0
595
+
596
+ for e in energies:
597
+ e["energy"] = round(e["energy"] / max_e, 4)
598
+
599
+ print(f"[OK] Audio energy analyzed ({len(energies)} seconds).", flush=True)
600
+ return energies
601
+
602
+ except Exception as e:
603
+ print(f"[!] Audio analysis error: {e}", flush=True)
604
+ return []
605
+ finally:
606
+ if temp_wav.exists():
607
+ try: temp_wav.unlink()
608
+ except: pass
609
+
610
+
611
  # ── Step 4: Find hook segments ────────────────────────────────────────────────
612
  def find_segments(energies, duration: float, n_clips: int = MAX_CLIPS):
613
  """