feat: quality gate, output-format selection, whisper small (PR #50)
- Quality gate: quality_probe.py probes the offered YouTube resolution before starting; /api/process returns needs_confirmation below QUALITY_GATE_MIN_HEIGHT (720p) and the UI shows a 'process anyway' modal that resends with force_low_quality. Fail-open on any probe error. URL sources only. - Output format: MediaInput picks 9:16 / 1:1 / 16:9; threaded through /api/process -> main.py --format. render_clip() routes vertical/square to the reframe (aspect_ratio param) and horizontal to a passthrough (keep landscape). - Whisper: main pipeline defaults to 'small' (better non-English) with vad_filter + no cross-segment conditioning; env-overridable.
This commit is contained in:
parent
9693543f2d
commit
861134f8fe
6 changed files with 311 additions and 26 deletions
10
.env.example
10
.env.example
|
|
@ -17,3 +17,13 @@ AWS_S3_PUBLIC_BUCKET=your-public-bucket-name
|
|||
# Local dev: show the full pipeline logs (yt-dlp/ffmpeg/debug) in the UI even
|
||||
# when running in paid mode (BILLING_ENABLED). Cloud/prod leaves this unset.
|
||||
# DEBUG_LOGS=true
|
||||
|
||||
# Pre-flight quality gate: warn before processing a YouTube source below this
|
||||
# height (720p default; 0 disables). Only applies to URL sources.
|
||||
# QUALITY_GATE_MIN_HEIGHT=720
|
||||
|
||||
# Whisper transcription model (main pipeline). "small" is better than "base" on
|
||||
# non-English audio; "base" is faster. device/compute for GPU tuning.
|
||||
# WHISPER_MODEL=small
|
||||
# WHISPER_DEVICE=cpu
|
||||
# WHISPER_COMPUTE=int8
|
||||
|
|
|
|||
54
app.py
54
app.py
|
|
@ -1,5 +1,6 @@
|
|||
import os
|
||||
import re
|
||||
import sys
|
||||
import uuid
|
||||
import subprocess
|
||||
import threading
|
||||
|
|
@ -17,7 +18,7 @@ from contextlib import asynccontextmanager
|
|||
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import HTMLResponse, FileResponse
|
||||
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
|
||||
from starlette.background import BackgroundTask
|
||||
from pydantic import BaseModel
|
||||
from s3_uploader import upload_job_artifacts, list_all_clips, upload_actor_to_s3, list_actor_gallery, upload_video_to_gallery, list_video_gallery
|
||||
|
|
@ -35,6 +36,10 @@ os.makedirs(OUTPUT_DIR, exist_ok=True)
|
|||
MAX_CONCURRENT_JOBS = int(os.environ.get("MAX_CONCURRENT_JOBS", "5"))
|
||||
MAX_FILE_SIZE_MB = 2048 # 2GB limit
|
||||
JOB_RETENTION_SECONDS = int(os.environ.get("JOB_RETENTION_SECONDS", "3600")) # job/file retention (issue #46)
|
||||
# Pre-flight quality gate: warn before processing a YouTube source below this
|
||||
# height (0 disables). Only applies to URLs; uploads are whatever the user gave.
|
||||
QUALITY_GATE_MIN_HEIGHT = int(os.environ.get("QUALITY_GATE_MIN_HEIGHT", "720"))
|
||||
QUALITY_PROBE_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_probe.py")
|
||||
DISABLE_YOUTUBE_URL = os.environ.get("DISABLE_YOUTUBE_URL", "false").lower() in ("1", "true", "yes")
|
||||
|
||||
# ---- Cloud billing (paid / managed-keys) integration --------------------------
|
||||
|
|
@ -694,18 +699,38 @@ async def get_config():
|
|||
"googleAuthEnabled": bool(BILLING_ENABLED and cloud.settings.google_auth_enabled),
|
||||
}
|
||||
|
||||
async def _probe_youtube_quality(url: str) -> dict:
|
||||
"""Run quality_probe.py in a worker thread; {} on any failure (fail-open)."""
|
||||
def _run():
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[sys.executable, QUALITY_PROBE_SCRIPT, "--url", url],
|
||||
capture_output=True, timeout=75,
|
||||
)
|
||||
return json.loads(proc.stdout.decode(errors="replace").strip() or "{}")
|
||||
except Exception as e:
|
||||
print(f"⚠️ Quality probe failed ({e}); starting job without gate.")
|
||||
return {}
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(None, _run)
|
||||
|
||||
|
||||
@app.post("/api/process")
|
||||
async def process_endpoint(
|
||||
request: Request,
|
||||
file: Optional[UploadFile] = File(None),
|
||||
url: Optional[str] = Form(None),
|
||||
acknowledged: Optional[str] = Form(None)
|
||||
acknowledged: Optional[str] = Form(None),
|
||||
output_format: Optional[str] = Form(None),
|
||||
force_low_quality: Optional[str] = Form(None)
|
||||
):
|
||||
api_key = await resolve_gemini(request)
|
||||
if not api_key:
|
||||
raise gemini_missing_error()
|
||||
|
||||
ack_flag = str(acknowledged).lower() in ("1", "true", "yes")
|
||||
force_low = str(force_low_quality).lower() in ("1", "true", "yes")
|
||||
|
||||
# Handle JSON body manually for URL payload
|
||||
content_type = request.headers.get("content-type", "")
|
||||
|
|
@ -713,6 +738,12 @@ async def process_endpoint(
|
|||
body = await request.json()
|
||||
url = body.get("url")
|
||||
ack_flag = bool(body.get("acknowledged"))
|
||||
force_low = bool(body.get("force_low_quality"))
|
||||
output_format = body.get("output_format")
|
||||
|
||||
# Normalize output format (auto = keep pipeline default).
|
||||
if output_format not in ("vertical", "horizontal", "square"):
|
||||
output_format = "auto"
|
||||
|
||||
if not url and not file:
|
||||
raise HTTPException(status_code=400, detail="Must provide URL or File")
|
||||
|
|
@ -723,6 +754,23 @@ async def process_endpoint(
|
|||
if url and DISABLE_YOUTUBE_URL:
|
||||
raise HTTPException(status_code=403, detail="YouTube URL ingest is disabled on this deployment. Please upload a file you own.")
|
||||
|
||||
# Pre-flight quality gate: probe the offered resolution BEFORE starting, so
|
||||
# the user can abort (refresh cookies / update yt-dlp) instead of burning
|
||||
# 20 min on a 360p-only source. Fail-open: any probe error starts normally.
|
||||
if url and not force_low and QUALITY_GATE_MIN_HEIGHT > 0:
|
||||
probe = await _probe_youtube_quality(url)
|
||||
max_height = int(probe.get("max_height") or 0)
|
||||
if 0 < max_height < QUALITY_GATE_MIN_HEIGHT:
|
||||
print(f"⚠️ Quality gate: only {max_height}p available for {url} — asking user first.")
|
||||
return JSONResponse({
|
||||
"needs_confirmation": True,
|
||||
"quality_check": {
|
||||
"max_height": max_height,
|
||||
"min_height": QUALITY_GATE_MIN_HEIGHT,
|
||||
"cookies_invalid": bool(probe.get("cookies_invalid")),
|
||||
},
|
||||
})
|
||||
|
||||
# Capture attestation context for legal record (IP + timestamp + UA)
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
fwd = request.headers.get("x-forwarded-for")
|
||||
|
|
@ -772,6 +820,8 @@ async def process_endpoint(
|
|||
cmd.extend(["-i", input_path])
|
||||
|
||||
cmd.extend(["-o", job_output_dir])
|
||||
if output_format and output_format != "auto":
|
||||
cmd.extend(["--format", output_format])
|
||||
|
||||
print(f"[attestation] job={job_id} ip={attestation['ip']} source={attestation['source']} ack=true")
|
||||
|
||||
|
|
|
|||
|
|
@ -185,6 +185,8 @@ function App() {
|
|||
// within a clip's subtitle modal via "apply to all").
|
||||
const [bulkSub, setBulkSub] = useState({ running: false, current: 0, total: 0, errors: 0 });
|
||||
const [downloadingAll, setDownloadingAll] = useState(false);
|
||||
// Pre-flight quality gate: { info: {max_height, min_height, cookies_invalid}, data }
|
||||
const [qualityGate, setQualityGate] = useState(null);
|
||||
const [logs, setLogs] = useState([]);
|
||||
const [logsVisible, setLogsVisible] = useState(true);
|
||||
const [processingMedia, setProcessingMedia] = useState(null);
|
||||
|
|
@ -481,7 +483,7 @@ function App() {
|
|||
}
|
||||
};
|
||||
|
||||
const handleProcess = async (data) => {
|
||||
const handleProcess = async (data, forceLowQuality = false) => {
|
||||
// Hosted: must be signed in AND on an active plan/trial. Self-host: BYOK keys.
|
||||
if (billingEnabled) {
|
||||
if (!isSignedIn) { setShowLogin(true); return; }
|
||||
|
|
@ -494,6 +496,7 @@ function App() {
|
|||
setLogs(["Starting process..."]);
|
||||
setResults(null);
|
||||
setProcessingMedia(data);
|
||||
setQualityGate(null);
|
||||
|
||||
try {
|
||||
let body;
|
||||
|
|
@ -503,11 +506,17 @@ function App() {
|
|||
|
||||
if (data.type === 'url') {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
body = JSON.stringify({ url: data.payload, acknowledged: !!data.acknowledged });
|
||||
body = JSON.stringify({
|
||||
url: data.payload,
|
||||
acknowledged: !!data.acknowledged,
|
||||
output_format: data.outputFormat || 'auto',
|
||||
force_low_quality: forceLowQuality,
|
||||
});
|
||||
} else {
|
||||
const formData = new FormData();
|
||||
formData.append('file', data.payload);
|
||||
formData.append('acknowledged', data.acknowledged ? 'true' : 'false');
|
||||
formData.append('output_format', data.outputFormat || 'auto');
|
||||
body = formData;
|
||||
}
|
||||
|
||||
|
|
@ -515,6 +524,15 @@ function App() {
|
|||
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
const resData = await res.json();
|
||||
|
||||
// Quality gate: the source is below the min resolution — ask before burning
|
||||
// 20 min on it. On confirm we resend with force_low_quality.
|
||||
if (resData.needs_confirmation) {
|
||||
setStatus('idle');
|
||||
setQualityGate({ info: resData.quality_check, data });
|
||||
return;
|
||||
}
|
||||
|
||||
setJobId(resData.job_id);
|
||||
|
||||
} catch (e) {
|
||||
|
|
@ -1389,6 +1407,32 @@ function App() {
|
|||
isManaged={isManaged}
|
||||
/>
|
||||
|
||||
{/* Pre-flight quality gate */}
|
||||
{qualityGate && (
|
||||
<Modal isOpen={true} onClose={() => setQualityGate(null)} size="md" eyebrow="HEADS UP" title="low source quality">
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-ink2">
|
||||
YouTube only offers <span className="text-brass font-semibold">{qualityGate.info.max_height}p</span> for this video
|
||||
(below the {qualityGate.info.min_height}p we recommend). Processing anyway will produce lower-quality clips.
|
||||
</p>
|
||||
{qualityGate.info.cookies_invalid && (
|
||||
<p className="text-xs text-muted">
|
||||
Your YouTube cookies look expired — refreshing them (export again from an incognito window) often unlocks HD.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-2 justify-end pt-2">
|
||||
<button onClick={() => setQualityGate(null)} className="btn-ghost">cancel</button>
|
||||
<button
|
||||
onClick={() => { const d = qualityGate.data; setQualityGate(null); handleProcess(d, true); }}
|
||||
className="btn-primary"
|
||||
>
|
||||
process anyway
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
|
||||
{showLogin && <LoginModal onClose={() => setShowLogin(false)} />}
|
||||
{showTopUp && (
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
const [url, setUrl] = useState('');
|
||||
const [file, setFile] = useState(null);
|
||||
const [acknowledged, setAcknowledged] = useState(false);
|
||||
const [outputFormat, setOutputFormat] = useState('vertical'); // vertical | horizontal | square
|
||||
const [showInfo, setShowInfo] = useState(false);
|
||||
const infoRef = useRef(null);
|
||||
|
||||
|
|
@ -43,9 +44,9 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
e.preventDefault();
|
||||
if (!acknowledged) return;
|
||||
if (mode === 'url' && url) {
|
||||
onProcess({ type: 'url', payload: url, acknowledged: true });
|
||||
onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat });
|
||||
} else if (mode === 'file' && file) {
|
||||
onProcess({ type: 'file', payload: file, acknowledged: true });
|
||||
onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat });
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -158,6 +159,29 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
</div>
|
||||
)}
|
||||
|
||||
{/* Output format selector */}
|
||||
<div className="mt-5">
|
||||
<p className="eyebrow mb-2">Output format</p>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{[
|
||||
{ value: 'vertical', label: '9:16', hint: 'Shorts / Reels / TikTok' },
|
||||
{ value: 'square', label: '1:1', hint: 'Feed posts' },
|
||||
{ value: 'horizontal', label: '16:9', hint: 'Keep landscape' },
|
||||
].map((f) => (
|
||||
<button
|
||||
key={f.value}
|
||||
type="button"
|
||||
onClick={() => setOutputFormat(f.value)}
|
||||
title={f.hint}
|
||||
className={`py-2 rounded-input border text-center transition-colors
|
||||
${outputFormat === f.value ? 'border-[color:var(--color-accent)] text-ink' : 'border-rule2 text-muted hover:border-[color:var(--color-accent)]'}`}
|
||||
>
|
||||
<span className="block font-mono text-sm">{f.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="flex items-start gap-2 mt-5 text-xs text-muted cursor-pointer select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
|
|
|
|||
90
main.py
90
main.py
|
|
@ -83,22 +83,23 @@ class SmoothedCameraman:
|
|||
Only moves if the subject leaves the center safe zone.
|
||||
Moves slowly and linearly.
|
||||
"""
|
||||
def __init__(self, output_width, output_height, video_width, video_height):
|
||||
def __init__(self, output_width, output_height, video_width, video_height, aspect_ratio=ASPECT_RATIO):
|
||||
self.output_width = output_width
|
||||
self.output_height = output_height
|
||||
self.video_width = video_width
|
||||
self.video_height = video_height
|
||||
|
||||
self.aspect_ratio = aspect_ratio
|
||||
|
||||
# Initial State
|
||||
self.current_center_x = video_width / 2
|
||||
self.target_center_x = video_width / 2
|
||||
|
||||
|
||||
# Calculate crop dimensions once
|
||||
self.crop_height = video_height
|
||||
self.crop_width = int(self.crop_height * ASPECT_RATIO)
|
||||
self.crop_width = int(self.crop_height * aspect_ratio)
|
||||
if self.crop_width > video_width:
|
||||
self.crop_width = video_width
|
||||
self.crop_height = int(self.crop_width / ASPECT_RATIO)
|
||||
self.crop_height = int(self.crop_width / aspect_ratio)
|
||||
|
||||
# Safe Zone: 20% of the video width
|
||||
# As long as the target is within this zone relative to current center, DO NOT MOVE.
|
||||
|
|
@ -584,17 +585,45 @@ Technical Details: {str(last_err)}
|
|||
print(f"✅ Video downloaded in {time.time() - step_start_time:.2f}s: {downloaded_file}")
|
||||
return downloaded_file, sanitized_title
|
||||
|
||||
def process_video_to_vertical(input_video, final_output_video):
|
||||
def finalize_clip_passthrough(input_video, final_output_video):
|
||||
"""Keep the clip's native framing (for horizontal/16:9 output): just
|
||||
re-encode with faststart, no reframing/cropping."""
|
||||
if os.path.exists(final_output_video):
|
||||
os.remove(final_output_video)
|
||||
print(f"🎬 Passthrough (native framing): {input_video}")
|
||||
cmd = [
|
||||
'ffmpeg', '-y', '-i', input_video,
|
||||
'-c:v', 'libx264', '-preset', 'medium', '-crf', '18',
|
||||
'-c:a', 'aac', '-movflags', '+faststart',
|
||||
final_output_video,
|
||||
]
|
||||
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1800)
|
||||
print(f"✅ Clip saved to {final_output_video}")
|
||||
return True
|
||||
|
||||
|
||||
def render_clip(input_video, final_output_video, output_format="auto"):
|
||||
"""Route a cut clip through the right renderer for the chosen output format.
|
||||
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep."""
|
||||
if output_format == "horizontal":
|
||||
return finalize_clip_passthrough(input_video, final_output_video)
|
||||
aspect = 1.0 if output_format == "square" else ASPECT_RATIO
|
||||
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect)
|
||||
|
||||
|
||||
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO):
|
||||
"""
|
||||
Core logic to convert horizontal video to vertical using scene detection and Active Speaker Tracking (MediaPipe).
|
||||
Core logic to reframe a horizontal video to a target aspect ratio using
|
||||
scene detection and Active Speaker Tracking (MediaPipe).
|
||||
aspect_ratio: width/height of the output (9/16 vertical, 1.0 square).
|
||||
"""
|
||||
script_start_time = time.time()
|
||||
|
||||
|
||||
# Define temporary file paths based on the output name
|
||||
base_name = os.path.splitext(final_output_video)[0]
|
||||
temp_video_output = f"{base_name}_temp_video.mp4"
|
||||
temp_audio_output = f"{base_name}_temp_audio.aac"
|
||||
|
||||
|
||||
# Clean up previous temp files if they exist
|
||||
if os.path.exists(temp_video_output): os.remove(temp_video_output)
|
||||
if os.path.exists(temp_audio_output): os.remove(temp_audio_output)
|
||||
|
|
@ -619,12 +648,18 @@ def process_video_to_vertical(input_video, final_output_video):
|
|||
original_width, original_height = get_video_resolution(input_video)
|
||||
|
||||
OUTPUT_HEIGHT = original_height
|
||||
OUTPUT_WIDTH = int(OUTPUT_HEIGHT * ASPECT_RATIO)
|
||||
OUTPUT_WIDTH = int(OUTPUT_HEIGHT * aspect_ratio)
|
||||
# Never ask for a crop wider than the source; shrink height to fit instead.
|
||||
if OUTPUT_WIDTH > original_width:
|
||||
OUTPUT_WIDTH = original_width
|
||||
OUTPUT_HEIGHT = int(OUTPUT_WIDTH / aspect_ratio)
|
||||
if OUTPUT_WIDTH % 2 != 0:
|
||||
OUTPUT_WIDTH += 1
|
||||
if OUTPUT_HEIGHT % 2 != 0:
|
||||
OUTPUT_HEIGHT += 1
|
||||
|
||||
# Initialize Cameraman
|
||||
cameraman = SmoothedCameraman(OUTPUT_WIDTH, OUTPUT_HEIGHT, original_width, original_height)
|
||||
cameraman = SmoothedCameraman(OUTPUT_WIDTH, OUTPUT_HEIGHT, original_width, original_height, aspect_ratio=aspect_ratio)
|
||||
|
||||
# --- New Strategy: Per-Scene Analysis ---
|
||||
print("\n 🤖 Step 3: Analyzing Scenes for Strategy (Single vs Group)...")
|
||||
|
|
@ -759,11 +794,23 @@ def process_video_to_vertical(input_video, final_output_video):
|
|||
def transcribe_video(video_path):
|
||||
print("🎙️ Transcribing video with Faster-Whisper (CPU Optimized)...")
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
# Run on CPU with INT8 quantization for speed
|
||||
model = WhisperModel("base", device="cpu", compute_type="int8")
|
||||
|
||||
segments, info = model.transcribe(video_path, word_timestamps=True)
|
||||
|
||||
# "small" is noticeably better than "base" on non-English audio (e.g. German
|
||||
# compound words) at a modest speed cost. Overridable via env for tuning.
|
||||
model_size = os.environ.get("WHISPER_MODEL", "small")
|
||||
device = os.environ.get("WHISPER_DEVICE", "cpu")
|
||||
compute = os.environ.get("WHISPER_COMPUTE", "int8")
|
||||
model = WhisperModel(model_size, device=device, compute_type=compute)
|
||||
|
||||
# vad_filter drops silence; condition_on_previous_text off avoids repetition
|
||||
# loops / hallucinations across segments.
|
||||
segments, info = model.transcribe(
|
||||
video_path,
|
||||
word_timestamps=True,
|
||||
beam_size=5,
|
||||
vad_filter=True,
|
||||
condition_on_previous_text=False,
|
||||
)
|
||||
|
||||
print(f" Detected language '{info.language}' with probability {info.language_probability:.2f}")
|
||||
|
||||
|
|
@ -952,8 +999,11 @@ if __name__ == '__main__':
|
|||
parser.add_argument('-o', '--output', type=str, help="Output directory or file (if processing whole video).")
|
||||
parser.add_argument('--keep-original', action='store_true', help="Keep the downloaded YouTube video.")
|
||||
parser.add_argument('--skip-analysis', action='store_true', help="Skip AI analysis and convert the whole video.")
|
||||
|
||||
parser.add_argument('--format', type=str, default="auto", choices=["auto", "vertical", "horizontal", "square"],
|
||||
help="Output aspect: vertical/auto (9:16), horizontal (keep 16:9), square (1:1).")
|
||||
|
||||
args = parser.parse_args()
|
||||
output_format = args.format
|
||||
|
||||
script_start_time = time.time()
|
||||
|
||||
|
|
@ -1003,7 +1053,7 @@ if __name__ == '__main__':
|
|||
if args.skip_analysis:
|
||||
print("⏩ Skipping analysis, processing entire video...")
|
||||
output_file = args.output if args.output else os.path.join(output_dir, f"{video_title}_vertical.mp4")
|
||||
process_video_to_vertical(input_video, output_file)
|
||||
render_clip(input_video, output_file, output_format)
|
||||
else:
|
||||
# 3. Transcribe
|
||||
transcript = transcribe_video(input_video)
|
||||
|
|
@ -1021,7 +1071,7 @@ if __name__ == '__main__':
|
|||
if not clips_data or 'shorts' not in clips_data:
|
||||
print("❌ Failed to identify clips. Converting whole video as fallback.")
|
||||
output_file = os.path.join(output_dir, f"{video_title}_vertical.mp4")
|
||||
process_video_to_vertical(input_video, output_file)
|
||||
render_clip(input_video, output_file, output_format)
|
||||
else:
|
||||
print(f"🔥 Found {len(clips_data['shorts'])} viral clips!")
|
||||
|
||||
|
|
@ -1058,7 +1108,7 @@ if __name__ == '__main__':
|
|||
subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
||||
|
||||
# Process vertical
|
||||
success = process_video_to_vertical(clip_temp_path, clip_final_path)
|
||||
success = render_clip(clip_temp_path, clip_final_path, output_format)
|
||||
|
||||
if success:
|
||||
print(f" ✅ Clip {i+1} ready: {clip_final_path}")
|
||||
|
|
|
|||
107
quality_probe.py
Normal file
107
quality_probe.py
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
"""
|
||||
Fast pre-flight probe: what maximum resolution does YouTube offer for a URL?
|
||||
|
||||
Run as a short subprocess by app.py BEFORE a job starts, so the user can decide
|
||||
to abort (and e.g. refresh cookies) instead of burning 20+ minutes of
|
||||
transcription and rendering on a 360p-only source.
|
||||
|
||||
Prints JSON to stdout: {"max_height": int, "mode": str, "cookies_invalid": bool}
|
||||
Always exits 0 — the caller treats probe failures as "unknown" and starts the
|
||||
job anyway (fail-open), where the in-job warning still applies.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
def _find_cookies_path():
|
||||
# Mirrors main.py's cookie discovery.
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
for candidate in [
|
||||
os.path.join(script_dir, 'www.youtube.com_cookies.txt'),
|
||||
os.path.join(script_dir, 'cookies.txt'),
|
||||
'/app/cookies.txt',
|
||||
]:
|
||||
if os.path.exists(candidate):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Probe available YouTube quality for a URL.")
|
||||
parser.add_argument("--url", required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
result = {"max_height": 0, "mode": None, "cookies_invalid": False}
|
||||
try:
|
||||
import yt_dlp
|
||||
|
||||
warnings = []
|
||||
|
||||
class _CollectLogger:
|
||||
def debug(self, msg):
|
||||
pass
|
||||
|
||||
def info(self, msg):
|
||||
pass
|
||||
|
||||
def warning(self, msg):
|
||||
warnings.append(str(msg))
|
||||
|
||||
def error(self, msg):
|
||||
warnings.append(str(msg))
|
||||
|
||||
cookies_path = _find_cookies_path()
|
||||
base_opts = {
|
||||
'quiet': True,
|
||||
'no_warnings': False,
|
||||
'logger': _CollectLogger(),
|
||||
'socket_timeout': 20,
|
||||
'retries': 2,
|
||||
'nocheckcertificate': True,
|
||||
'cachedir': False,
|
||||
}
|
||||
# yt-dlp's default player clients (tv_downgraded/web_safari with
|
||||
# cookies, android_vr/web_safari anonymous) are the ones that still
|
||||
# serve HD without PO tokens — never override them here.
|
||||
attempts = []
|
||||
if cookies_path:
|
||||
attempts.append(("cookie-auth", {**base_opts, 'cookiefile': cookies_path}))
|
||||
attempts.append(("anonymous", {**base_opts, 'cookiefile': None}))
|
||||
|
||||
for mode, opts in attempts:
|
||||
try:
|
||||
with yt_dlp.YoutubeDL(opts) as ydl:
|
||||
info = ydl.extract_info(args.url, download=False)
|
||||
formats = info.get('formats') or []
|
||||
heights = [
|
||||
f.get('height') or 0
|
||||
for f in formats
|
||||
if f.get('vcodec', 'none') != 'none'
|
||||
and f.get('protocol') != 'mhtml'
|
||||
and f.get('ext') != 'mhtml'
|
||||
]
|
||||
max_height = max(heights, default=0)
|
||||
if max_height > result["max_height"]:
|
||||
result["max_height"] = max_height
|
||||
result["mode"] = mode
|
||||
if result["max_height"] >= 1080:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
result["cookies_invalid"] = any("no longer valid" in w for w in warnings)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(json.dumps(result))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Loading…
Reference in a new issue