douyinWEB/backend/app/clip_quality.py
2026-08-15 04:50:28 -05:00

141 lines
4.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""Clip quality gate — reject black/silent/too-short clips before upload queue."""
from __future__ import annotations
import json
import subprocess
from pathlib import Path
from typing import Any
def probe_clip(path: str | Path) -> dict[str, Any]:
p = Path(path)
if not p.is_file():
return {"ok": False, "reason": "成片文件不存在", "size": 0}
size = p.stat().st_size
if size < 80_000:
return {"ok": False, "reason": "成片过小,可能录制失败", "size": size}
cmd = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration,size:stream=codec_type,codec_name,width,height,bit_rate,avg_frame_rate",
"-of",
"json",
str(p),
]
try:
raw = subprocess.check_output(cmd, stderr=subprocess.STDOUT, timeout=25)
data = json.loads(raw.decode("utf-8", "replace") or "{}")
except Exception as exc:
# ffprobe missing — fall back to size-only gate
return {
"ok": size >= 200_000,
"reason": "" if size >= 200_000 else f"成片偏小且无法探测({exc})",
"size": size,
"duration": 0,
"has_video": True,
"has_audio": True,
"soft": True,
}
fmt = data.get("format") if isinstance(data.get("format"), dict) else {}
streams = data.get("streams") if isinstance(data.get("streams"), list) else []
duration = float(fmt.get("duration") or 0)
has_video = any(str(s.get("codec_type") or "") == "video" for s in streams if isinstance(s, dict))
has_audio = any(str(s.get("codec_type") or "") == "audio" for s in streams if isinstance(s, dict))
width = 0
height = 0
for s in streams:
if not isinstance(s, dict) or str(s.get("codec_type") or "") != "video":
continue
width = int(s.get("width") or 0)
height = int(s.get("height") or 0)
break
if duration > 0 and duration < 3.0:
return {"ok": False, "reason": "成片时长过短", "size": size, "duration": duration}
if not has_video:
return {"ok": False, "reason": "成片无视频轨", "size": size, "duration": duration}
if width and height and (width < 240 or height < 240):
return {"ok": False, "reason": "分辨率过低", "size": size, "duration": duration, "width": width, "height": height}
# crude black-frame / silence sample via ffmpeg volumedetect + blackdetect (best-effort)
black_ratio, silence = _sample_black_silence(p)
if black_ratio is not None and black_ratio >= 0.85:
return {
"ok": False,
"reason": "成片疑似黑屏",
"size": size,
"duration": duration,
"black_ratio": black_ratio,
}
if silence is True and has_audio:
return {
"ok": False,
"reason": "成片疑似静音",
"size": size,
"duration": duration,
"silent": True,
}
return {
"ok": True,
"reason": "",
"size": size,
"duration": duration,
"has_video": has_video,
"has_audio": has_audio,
"width": width,
"height": height,
"black_ratio": black_ratio,
}
def _sample_black_silence(path: Path) -> tuple[float | None, bool | None]:
"""Return (black_ratio, is_silent). None means probe skipped/failed."""
try:
# analyze first ~8s
cmd = [
"ffmpeg",
"-hide_banner",
"-nostats",
"-t",
"8",
"-i",
str(path),
"-vf",
"blackdetect=d=0.5:pix_th=0.10",
"-af",
"volumedetect",
"-f",
"null",
"-",
]
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=40)
err = (proc.stderr or "") + (proc.stdout or "")
black_ratio = None
if "black_start" in err:
# rough: if multiple black segments, treat as mostly black
black_ratio = 0.9 if err.count("black_start") >= 2 else 0.5
mean = None
for line in err.splitlines():
if "mean_volume:" in line:
try:
mean = float(line.split("mean_volume:")[1].split("dB")[0].strip())
except Exception:
mean = None
silent = mean is not None and mean <= -45.0
return black_ratio, silent
except Exception:
return None, None
def assert_clip_quality(path: str | Path) -> dict[str, Any]:
"""Raise ValueError if clip fails gate; otherwise return probe dict."""
info = probe_clip(path)
if not info.get("ok"):
raise ValueError(str(info.get("reason") or "成片质量不合格"))
return info