Compare commits
No commits in common. "d9e6b6ce043166dd615ba631f95584f82a7f04f8" and "ea251a11283a19e28feab08aa02d7ed2c4e33811" have entirely different histories.
d9e6b6ce04
...
ea251a1128
41 changed files with 125 additions and 5453 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -30,7 +30,6 @@ output/
|
|||
# Cache dirs
|
||||
.cache/
|
||||
.config/
|
||||
.fontconfig/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
|
||||
|
|
|
|||
12
Dockerfile
12
Dockerfile
|
|
@ -71,18 +71,6 @@ COPY --from=builder /opt/venv /opt/venv
|
|||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
# Runtime caches must not land inside the bind-mounted source tree. Compose
|
||||
# mounts the host repo at /app, and the container's non-root appuser cannot
|
||||
# write there, so matplotlib/fontconfig logged permission errors and dropped a
|
||||
# stray .fontconfig (owned by the container's uid) into the repo. Point HOME
|
||||
# and the disposable caches at writable /tmp; keep the ASR model cache on the
|
||||
# named volume mounted at HF_HOME (see docker-compose.yml) so it survives
|
||||
# container recreates.
|
||||
ENV HOME=/tmp \
|
||||
MPLCONFIGDIR=/tmp/.cache/matplotlib \
|
||||
YOLO_CONFIG_DIR=/tmp/Ultralytics \
|
||||
HF_HOME=/app/.cache/huggingface
|
||||
|
||||
# GPU runtime wiring — harmless no-ops on CPU builds / hosts without the
|
||||
# NVIDIA runtime. LD_LIBRARY_PATH points at the pip-installed CUDA libs
|
||||
# (paths simply don't exist in CPU images); DRIVER_CAPABILITIES asks the
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import os
|
||||
from clipwright.pipeline import llm_backend, profiles
|
||||
from clipwright.pipeline import llm_backend
|
||||
import re
|
||||
import sys
|
||||
import uuid
|
||||
|
|
@ -29,7 +29,7 @@ import httpx
|
|||
from clipwright.media import recut
|
||||
from clipwright.layouts import layout_ranges
|
||||
from clipwright.api import media_auth
|
||||
from clipwright.integrations import postiz, youtube_data
|
||||
from clipwright.integrations import postiz
|
||||
from clipwright.core.paths import REPO_ROOT
|
||||
|
||||
load_dotenv()
|
||||
|
|
@ -1518,11 +1518,6 @@ def _safe_under(base_dir: str, user_rel_path: str) -> Optional[str]:
|
|||
|
||||
class ProcessRequest(BaseModel):
|
||||
url: str
|
||||
# Channel profile slug (channels/<slug>.json); OPTIONAL per PLAN #1 v0.
|
||||
channel: Optional[str] = None
|
||||
# Target long-form video for the Shorts->long-form bridge copy/checklist
|
||||
# (PLAN #6). OPTIONAL: without it the profile history is used.
|
||||
related_video_url: Optional[str] = None
|
||||
|
||||
# Masks user:password credentials embedded in any URL (e.g. the residential
|
||||
# proxy URL that yt-dlp echoes in its verbose debug output) before the line is
|
||||
|
|
@ -1757,18 +1752,6 @@ async def get_config():
|
|||
"localLlm": llm_backend.describe(),
|
||||
}
|
||||
|
||||
@app.get("/api/channels")
|
||||
async def list_channels():
|
||||
"""The channel profiles a job can be tagged with (PLAN #1).
|
||||
|
||||
Each entry is ``{"slug", "name"}`` for the dashboard's profile selector:
|
||||
``slug`` is the ``channels/<slug>.json`` filename stem and ``name`` is the
|
||||
profile's display name, falling back to the slug when the file omits it.
|
||||
Malformed profile files are skipped by the loader, so the selector always
|
||||
receives a usable list.
|
||||
"""
|
||||
return {"channels": profiles.list_profiles()}
|
||||
|
||||
async def _probe_youtube_quality(url: str) -> dict:
|
||||
"""Run quality_probe.py in a worker thread; {} on any failure (fail-open)."""
|
||||
def _run():
|
||||
|
|
@ -1868,7 +1851,6 @@ def _reject_short_source(duration: float):
|
|||
LAYOUT_ENV = {
|
||||
"split": "SPLIT_LAYOUT", # two speakers stacked
|
||||
"screencast": "SCREENCAST_LAYOUT", # slides/screen share over the speaker
|
||||
"code": "CODE_LAYOUT", # IDE / terminal text column
|
||||
"speaker_cut": "SPEAKER_CUT", # hard cuts to whoever is talking
|
||||
"punch_in": "PUNCH_IN", # small push on the clip's beats
|
||||
}
|
||||
|
|
@ -1901,27 +1883,17 @@ def _upload_url_base(request):
|
|||
|
||||
@app.post("/api/uploads")
|
||||
async def create_upload(request: Request):
|
||||
"""Reserve an upload slot. Body (JSON, optional): {"filename": "..."}.
|
||||
|
||||
``kind`` defaults to ``"video"`` (probed for a duration on PUT). A
|
||||
``"handoff"`` slot carries a ZIP bundle (cadence manifest + transcript) and
|
||||
is stored verbatim — see /api/process ``handoff_id``.
|
||||
"""
|
||||
"""Reserve an upload slot. Body (JSON, optional): {"filename": "..."}."""
|
||||
user_id = await _owner_id(request)
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
body = {}
|
||||
body = body or {}
|
||||
kind = str(body.get("kind") or "video").strip().lower()
|
||||
if kind not in ("video", "handoff"):
|
||||
raise HTTPException(status_code=400, detail="kind must be 'video' or 'handoff'")
|
||||
filename = os.path.basename(str(body.get("filename") or "video.mp4")) or "video.mp4"
|
||||
filename = os.path.basename(str((body or {}).get("filename") or "video.mp4")) or "video.mp4"
|
||||
upload_id = str(uuid.uuid4())
|
||||
pending_uploads[upload_id] = {
|
||||
"user_id": user_id,
|
||||
"filename": filename,
|
||||
"kind": kind,
|
||||
"path": os.path.join(UPLOAD_DIR, f"pending_{upload_id}_{filename}"),
|
||||
"created": time.time(),
|
||||
"bytes": 0,
|
||||
|
|
@ -1929,7 +1901,6 @@ async def create_upload(request: Request):
|
|||
}
|
||||
return {
|
||||
"upload_id": upload_id,
|
||||
"kind": kind,
|
||||
"upload_url": f"{_upload_url_base(request)}/api/uploads/{upload_id}",
|
||||
"method": "PUT",
|
||||
"max_mb": MAX_FILE_SIZE_MB,
|
||||
|
|
@ -1963,18 +1934,12 @@ async def put_upload(upload_id: str, request: Request):
|
|||
os.remove(slot["path"])
|
||||
raise HTTPException(status_code=400, detail="Empty body")
|
||||
slot.update({"bytes": size, "complete": True})
|
||||
if slot.get("kind") == "handoff":
|
||||
# A handoff slot holds a ZIP (manifest + transcript), not media: the
|
||||
# duration probe below would reject it as "not a readable video".
|
||||
return {"upload_id": upload_id, "kind": "handoff", "bytes": size,
|
||||
"hint": "Now call /api/process with handoff_id (and your master video)."}
|
||||
duration = await asyncio.get_event_loop().run_in_executor(None, _media_duration_seconds, slot["path"])
|
||||
if duration <= 0:
|
||||
os.remove(slot["path"])
|
||||
slot["complete"] = False
|
||||
raise HTTPException(status_code=400, detail="The body is not a readable video file")
|
||||
return {"upload_id": upload_id, "kind": "video", "bytes": size,
|
||||
"duration_seconds": round(duration, 1),
|
||||
return {"upload_id": upload_id, "bytes": size, "duration_seconds": round(duration, 1),
|
||||
"hint": "Now call /api/process with upload_id."}
|
||||
|
||||
|
||||
|
|
@ -2018,106 +1983,6 @@ def _take_pending_upload(upload_id, user_id):
|
|||
return slot
|
||||
|
||||
|
||||
_HANDOFF_SCHEMA = "clipwright.handoff/1"
|
||||
|
||||
|
||||
def _handoff_member_name(name):
|
||||
"""Basename of a ZIP member, normalized so no member can escape on extract."""
|
||||
return os.path.basename(name.replace("\\", "/").rstrip("/"))
|
||||
|
||||
|
||||
def _read_handoff_manifest(zf, members):
|
||||
"""(member_name, manifest_dict) for the bundle's manifest, or (None, None).
|
||||
|
||||
Prefers the documented ``*.handoff.json`` name, then falls back to any JSON
|
||||
member carrying the handoff schema marker.
|
||||
"""
|
||||
for name in members:
|
||||
if name.endswith(".handoff.json"):
|
||||
try:
|
||||
data = json.loads(zf.read(members[name].filename).decode("utf-8"))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
continue
|
||||
if isinstance(data, dict):
|
||||
return name, data
|
||||
for name, info in members.items():
|
||||
if not name.endswith(".json"):
|
||||
continue
|
||||
try:
|
||||
data = json.loads(zf.read(info.filename).decode("utf-8"))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
continue
|
||||
if isinstance(data, dict) and data.get("schema") == _HANDOFF_SCHEMA:
|
||||
return name, data
|
||||
return None, None
|
||||
|
||||
|
||||
def _stage_handoff_bundle(bundle_path, job_output_dir):
|
||||
"""Stage an uploaded cadence handoff ZIP into the job dir.
|
||||
|
||||
Writes the transcript to ``<job>/source_transcript.json`` and a manifest
|
||||
pointing at it to ``<job>/cadence_handoff.json``, then returns the latter's
|
||||
path (handed to the child as ``--handoff``). Only the manifest and the
|
||||
transcript it references are read; ``sources[].path`` is never opened (they
|
||||
are emitter-local), and member names are reduced to basenames so a hostile
|
||||
archive cannot read or write outside the job dir.
|
||||
"""
|
||||
if not zipfile.is_zipfile(bundle_path):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Handoff bundle must be a ZIP containing the manifest and transcript.json")
|
||||
limit_bytes = MAX_FILE_SIZE_MB * 1024 * 1024
|
||||
try:
|
||||
with zipfile.ZipFile(bundle_path) as zf:
|
||||
members = {}
|
||||
for info in zf.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
if limit_bytes and info.file_size > limit_bytes:
|
||||
raise HTTPException(status_code=413, detail="Handoff bundle entry too large")
|
||||
members[_handoff_member_name(info.filename)] = info
|
||||
manifest_name, manifest = _read_handoff_manifest(zf, members)
|
||||
if manifest_name is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Handoff bundle has no manifest (expected a *.handoff.json "
|
||||
f"with schema {_HANDOFF_SCHEMA!r})")
|
||||
ref = manifest.get("transcript")
|
||||
ref = ref.get("path") if isinstance(ref, dict) else None
|
||||
if not ref:
|
||||
raise HTTPException(status_code=400,
|
||||
detail="Handoff manifest has no transcript.path")
|
||||
transcript_name = _handoff_member_name(str(ref))
|
||||
info = members.get(transcript_name)
|
||||
if info is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Handoff transcript {ref!r} is not in the bundle")
|
||||
transcript_bytes = zf.read(info.filename)
|
||||
except HTTPException:
|
||||
raise
|
||||
except zipfile.BadZipFile as e:
|
||||
raise HTTPException(status_code=400, detail=f"Unreadable handoff bundle: {e}")
|
||||
|
||||
try:
|
||||
transcript = json.loads(transcript_bytes.decode("utf-8"))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
||||
raise HTTPException(status_code=400, detail=f"Malformed handoff transcript: {e}")
|
||||
if not isinstance(transcript, dict) or not transcript.get("segments"):
|
||||
raise HTTPException(status_code=400, detail="Handoff transcript has no segments")
|
||||
|
||||
transcript_path = os.path.join(job_output_dir, "source_transcript.json")
|
||||
with open(transcript_path, "wb") as out:
|
||||
out.write(transcript_bytes)
|
||||
manifest = dict(manifest)
|
||||
manifest["transcript"] = dict(manifest.get("transcript") or {})
|
||||
manifest["transcript"]["path"] = "source_transcript.json"
|
||||
manifest_path = os.path.join(job_output_dir, "cadence_handoff.json")
|
||||
with open(manifest_path, "w", encoding="utf-8") as f:
|
||||
json.dump(manifest, f, indent=2)
|
||||
return manifest_path
|
||||
|
||||
|
||||
def layout_env(requested):
|
||||
"""Env overrides for the layouts this job allows. Unknown names are ignored
|
||||
rather than rejected: a newer dashboard must not break an older API.
|
||||
|
|
@ -2167,9 +2032,6 @@ async def process_endpoint(
|
|||
captions: Optional[str] = Form(None),
|
||||
upload_id: Optional[str] = Form(None),
|
||||
max_minutes: Optional[str] = Form(None),
|
||||
channel: Optional[str] = Form(None),
|
||||
handoff_id: Optional[str] = Form(None),
|
||||
related_video_url: Optional[str] = Form(None),
|
||||
):
|
||||
api_key = await resolve_gemini(request)
|
||||
if not api_key and not llm_backend.active():
|
||||
|
|
@ -2202,9 +2064,6 @@ async def process_endpoint(
|
|||
captions = body.get("captions")
|
||||
upload_id = body.get("upload_id")
|
||||
max_minutes = body.get("max_minutes")
|
||||
channel = body.get("channel")
|
||||
handoff_id = body.get("handoff_id")
|
||||
related_video_url = body.get("related_video_url")
|
||||
|
||||
# Normalize output format (auto = keep pipeline default).
|
||||
if output_format not in ("vertical", "horizontal", "square"):
|
||||
|
|
@ -2295,31 +2154,6 @@ async def process_endpoint(
|
|||
# fails instead. setdefault, so an explicit PYTHONIOENCODING still wins.
|
||||
env.setdefault("PYTHONIOENCODING", "utf-8")
|
||||
|
||||
# Per-channel profile (PLAN #1 v0). Validate the slug now so a typo is a
|
||||
# clear 400 instead of a job that dies in the subprocess, then hand the
|
||||
# child just the slug -- generation behaviour is unchanged until later items.
|
||||
channel_slug = str(channel).strip() if channel else ""
|
||||
if channel_slug:
|
||||
from clipwright.pipeline.profiles import ProfileError, load_profile
|
||||
try:
|
||||
load_profile(channel_slug)
|
||||
except ProfileError as e:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid channel profile: {e}")
|
||||
env["CHANNEL_PROFILE"] = channel_slug
|
||||
print(f"[channel] job={job_id} profile={channel_slug}")
|
||||
|
||||
# Shorts -> long-form bridge target (PLAN #6). Explicit URL only; the
|
||||
# per-clip copy falls back to the profile's published_video_history when it
|
||||
# is absent. Passed as a CLI flag, so a value that looks like an option can
|
||||
# never be misread (argv list, no shell).
|
||||
bridge_target = str(related_video_url).strip() if related_video_url else ""
|
||||
if bridge_target:
|
||||
if not bridge_target.startswith(("http://", "https://")):
|
||||
raise HTTPException(status_code=400,
|
||||
detail="related_video_url must be an http(s) URL")
|
||||
cmd.extend(["--longform-url", bridge_target])
|
||||
print(f"[bridge] job={job_id} longform={bridge_target}")
|
||||
|
||||
# Optional layouts are per job. The renderer reads these at import time in
|
||||
# the subprocess, so they must be set before Popen.
|
||||
chosen = layout_env(layouts)
|
||||
|
|
@ -2447,20 +2281,6 @@ async def process_endpoint(
|
|||
|
||||
cmd.extend(["-i", input_path])
|
||||
|
||||
# Cadence handoff (PLAN #8): the bundle was uploaded to its own slot. Stage
|
||||
# the manifest + transcript in the job dir and point the child at it; the
|
||||
# slot is only consumed once staging succeeded. Never touches sources[].path.
|
||||
if handoff_id:
|
||||
slot = _take_pending_upload(handoff_id, await _owner_id(request))
|
||||
manifest_path = _stage_handoff_bundle(slot["path"], job_output_dir)
|
||||
pending_uploads.pop(handoff_id, None)
|
||||
try:
|
||||
os.remove(slot["path"])
|
||||
except OSError:
|
||||
pass
|
||||
cmd.extend(["--handoff", manifest_path])
|
||||
print(f"[handoff] job={job_id} manifest={os.path.basename(manifest_path)}")
|
||||
|
||||
cmd.extend(["-o", job_output_dir])
|
||||
if output_format and output_format != "auto":
|
||||
cmd.extend(["--format", output_format])
|
||||
|
|
@ -3154,140 +2974,6 @@ async def get_clip_edl(job_id: str, clip_index: int, request: Request):
|
|||
}
|
||||
|
||||
|
||||
# --- Shorts -> long-form bridge (PLAN #6) ----------------------------------
|
||||
|
||||
class BridgeCommentRequest(BaseModel):
|
||||
"""Explicit opt-in to post a clip's first comment on YouTube.
|
||||
|
||||
``video_id`` is the published Short's id; this server does not track the id
|
||||
Postiz assigned at publish time, so the caller supplies it. ``text``
|
||||
defaults to the clip's generated ``first_comment``.
|
||||
"""
|
||||
video_id: str
|
||||
text: Optional[str] = None
|
||||
|
||||
|
||||
def _clip_metadata(job_id: str, clip_index: int) -> Optional[dict]:
|
||||
"""The raw clip dict from a job's metadata.json (or None)."""
|
||||
output_dir = os.path.join(OUTPUT_DIR, job_id)
|
||||
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
|
||||
if not json_files:
|
||||
return None
|
||||
try:
|
||||
with open(json_files[0], "r") as f:
|
||||
data = json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
clips = data.get("shorts", [])
|
||||
if clip_index < 0 or clip_index >= len(clips):
|
||||
return None
|
||||
return clips[clip_index]
|
||||
|
||||
|
||||
@app.get("/api/clip/{job_id}/{clip_index}/bridge")
|
||||
async def get_clip_bridge(job_id: str, clip_index: int, request: Request):
|
||||
"""The generated Shorts->long-form copy and manual Studio checklist.
|
||||
|
||||
Both the "Related video" link and comment pinning are Studio-UI only, so
|
||||
this always carries the manual steps; ``manual_pin_required`` is always
|
||||
true. ``comment_api_configured`` says whether the opt-in comment endpoint
|
||||
below would work on this server.
|
||||
"""
|
||||
job = _job_record(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
await _assert_job_owner(request, job)
|
||||
clip = _clip_metadata(job_id, clip_index)
|
||||
if clip is None:
|
||||
raise HTTPException(status_code=404, detail="Clip not found")
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"clip_index": clip_index,
|
||||
"description_bridge": clip.get("description_bridge") or "",
|
||||
"first_comment": clip.get("first_comment") or "",
|
||||
"related_video_url": clip.get("related_video_url"),
|
||||
"checklist": clip.get("checklist") or [],
|
||||
"manual_pin_required": True,
|
||||
"comment_api_configured": youtube_data.is_configured(),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/clip/{job_id}/{clip_index}/provenance")
|
||||
async def get_clip_provenance(job_id: str, clip_index: int, request: Request):
|
||||
"""The versioned retention provenance record of one clip (PLAN #10).
|
||||
|
||||
Instrumentation only: a stable read of the profile, predicted score, start
|
||||
boundary path, bridge target and publish target the pipeline recorded when
|
||||
it wrote the clip's metadata. The same object also rides along inside the
|
||||
job result's clip dicts; this endpoint is the explicit, versioned handle
|
||||
the future retention/analytics loop can pull. A clip predating the
|
||||
instrumentation has no record, so this answers 404 rather than inventing one.
|
||||
"""
|
||||
job = _job_record(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
await _assert_job_owner(request, job)
|
||||
clip = _clip_metadata(job_id, clip_index)
|
||||
if clip is None:
|
||||
raise HTTPException(status_code=404, detail="Clip not found")
|
||||
provenance = clip.get("provenance")
|
||||
if not isinstance(provenance, dict):
|
||||
raise HTTPException(
|
||||
status_code=404, detail="No provenance recorded for this clip")
|
||||
return {
|
||||
"job_id": job_id,
|
||||
"clip_index": clip_index,
|
||||
"schema_version": provenance.get("schema_version"),
|
||||
"provenance": provenance,
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/clip/{job_id}/{clip_index}/bridge/comment")
|
||||
async def post_clip_bridge_comment(job_id: str, clip_index: int,
|
||||
req: BridgeCommentRequest, request: Request):
|
||||
"""Post the clip's first comment via the YouTube Data API (opt-in).
|
||||
|
||||
Never automatic: the caller triggers it explicitly for one published video.
|
||||
Pinning stays manual (no API). Returns a clear 400 when the server has no
|
||||
YouTube OAuth credentials configured.
|
||||
"""
|
||||
job = _job_record(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
await _assert_job_owner(request, job)
|
||||
clip = _clip_metadata(job_id, clip_index)
|
||||
if clip is None:
|
||||
raise HTTPException(status_code=404, detail="Clip not found")
|
||||
|
||||
if not youtube_data.is_configured():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=("YouTube Data API is not configured on this server; set "
|
||||
f"{youtube_data.CLIENT_ID_ENV}, {youtube_data.CLIENT_SECRET_ENV} "
|
||||
f"and {youtube_data.REFRESH_TOKEN_ENV} to enable first-comment posting."),
|
||||
)
|
||||
|
||||
text = (req.text or clip.get("first_comment") or "").strip()
|
||||
if not text:
|
||||
raise HTTPException(status_code=400, detail="No comment text to post")
|
||||
if not str(req.video_id).strip():
|
||||
raise HTTPException(status_code=400, detail="video_id is required")
|
||||
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
youtube_data.post_first_comment, req.video_id, text)
|
||||
except youtube_data.YoutubeDataError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail)
|
||||
|
||||
return {
|
||||
"posted": True,
|
||||
"video_id": req.video_id,
|
||||
"comment_id": (result or {}).get("id"),
|
||||
# A clear reminder that the API cannot pin.
|
||||
"manual_pin_required": True,
|
||||
}
|
||||
|
||||
|
||||
class RerenderSegment(BaseModel):
|
||||
start: float
|
||||
end: float
|
||||
|
|
@ -4787,29 +4473,12 @@ async def thumbnail_upload(
|
|||
return {"session_id": session_id}
|
||||
|
||||
|
||||
def _channel_profile(channel):
|
||||
"""Resolve an optional channel field to a Profile (PLAN #1).
|
||||
|
||||
Returns None when no channel was given, so a profile-less request behaves
|
||||
exactly as it did before profiles existed. A bad slug is a clear 400.
|
||||
"""
|
||||
slug = str(channel).strip() if channel else ""
|
||||
if not slug:
|
||||
return None
|
||||
from clipwright.pipeline.profiles import ProfileError, load_profile
|
||||
try:
|
||||
return load_profile(slug)
|
||||
except ProfileError as e:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid channel profile: {e}")
|
||||
|
||||
|
||||
@app.post("/api/thumbnail/analyze")
|
||||
async def thumbnail_analyze(
|
||||
request: Request,
|
||||
file: Optional[UploadFile] = File(None),
|
||||
url: Optional[str] = Form(None),
|
||||
session_id: Optional[str] = Form(None),
|
||||
channel: Optional[str] = Form(None),
|
||||
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key")
|
||||
):
|
||||
"""Analyze a video and suggest viral YouTube titles."""
|
||||
|
|
@ -4817,9 +4486,6 @@ async def thumbnail_analyze(
|
|||
if not api_key:
|
||||
raise gemini_missing_error()
|
||||
|
||||
# PLAN #1: resolve the channel before any download/upload so a bad slug
|
||||
# fails fast with a 400 instead of after the work.
|
||||
profile = _channel_profile(channel)
|
||||
pre_transcript = None
|
||||
|
||||
# Check for pre-existing session with background Whisper
|
||||
|
|
@ -4870,10 +4536,7 @@ async def thumbnail_analyze(
|
|||
try:
|
||||
# Run analysis in thread pool (skips Whisper if pre_transcript is available)
|
||||
loop = asyncio.get_event_loop()
|
||||
result = await loop.run_in_executor(
|
||||
None,
|
||||
functools.partial(analyze_video_for_titles, api_key, video_path,
|
||||
pre_transcript, profile=profile))
|
||||
result = await loop.run_in_executor(None, analyze_video_for_titles, api_key, video_path, pre_transcript)
|
||||
|
||||
# Store/update session context
|
||||
if session_id not in thumbnail_sessions:
|
||||
|
|
@ -4984,7 +4647,6 @@ async def thumbnail_generate(
|
|||
count: int = Form(3),
|
||||
burn_text: bool = Form(True),
|
||||
frame: str = Form(""),
|
||||
channel: Optional[str] = Form(None),
|
||||
face: Optional[UploadFile] = File(None),
|
||||
background: Optional[UploadFile] = File(None),
|
||||
):
|
||||
|
|
@ -4999,9 +4661,6 @@ async def thumbnail_generate(
|
|||
if not api_key:
|
||||
raise gemini_missing_error()
|
||||
|
||||
# PLAN #1: resolve the channel up front; a bad slug is a 400, not a 500.
|
||||
profile = _channel_profile(channel)
|
||||
|
||||
# The session carries someone's transcript, titles and frames: only its
|
||||
# owner may generate from it.
|
||||
_sess = thumbnail_sessions.get(session_id)
|
||||
|
|
@ -5054,7 +4713,7 @@ async def thumbnail_generate(
|
|||
generate_thumbnail, api_key, title, session_id, face_path, bg_path,
|
||||
extra_prompt, count, video_context, burn_text=burn_text,
|
||||
thumbnail_text_hint=text_hint, language=language,
|
||||
frame_reference=frame_reference, profile=profile),
|
||||
frame_reference=frame_reference),
|
||||
)
|
||||
|
||||
if not thumbnails:
|
||||
|
|
@ -5106,7 +4765,6 @@ async def thumbnail_frames(session_id: str, request: Request):
|
|||
class ThumbnailDescribeRequest(BaseModel):
|
||||
session_id: str
|
||||
title: str
|
||||
channel: Optional[str] = None
|
||||
|
||||
@app.post("/api/thumbnail/describe")
|
||||
async def thumbnail_describe(
|
||||
|
|
@ -5118,9 +4776,6 @@ async def thumbnail_describe(
|
|||
if not api_key:
|
||||
raise gemini_missing_error()
|
||||
|
||||
# PLAN #1: resolve the channel before the try so a bad slug is a 400.
|
||||
profile = _channel_profile(req.channel)
|
||||
|
||||
if req.session_id not in thumbnail_sessions:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
|
|
@ -5134,15 +4789,12 @@ async def thumbnail_describe(
|
|||
loop = asyncio.get_event_loop()
|
||||
result = await loop.run_in_executor(
|
||||
None,
|
||||
functools.partial(
|
||||
generate_youtube_description,
|
||||
api_key,
|
||||
req.title,
|
||||
segments,
|
||||
session.get("language", "en"),
|
||||
session.get("video_duration", 0),
|
||||
profile=profile,
|
||||
),
|
||||
generate_youtube_description,
|
||||
api_key,
|
||||
req.title,
|
||||
segments,
|
||||
session.get("language", "en"),
|
||||
session.get("video_duration", 0)
|
||||
)
|
||||
return {"description": result.get("description", "")}
|
||||
|
||||
|
|
|
|||
|
|
@ -41,8 +41,6 @@ from urllib.parse import parse_qs, urlparse
|
|||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from clipwright.media import title_validation
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
|
@ -478,7 +476,6 @@ class MetadataRequest(BaseModel):
|
|||
topic: str
|
||||
keyword: Optional[str] = ""
|
||||
audience: Optional[str] = ""
|
||||
channel: Optional[str] = None
|
||||
|
||||
|
||||
_COMMON_RULES = """
|
||||
|
|
@ -546,13 +543,8 @@ def _clean(s: str) -> str:
|
|||
return re.sub(r"\s*—\s*", ", ", (s or "")).strip()
|
||||
|
||||
|
||||
def shape_result(mode: str, data: dict, profile=None) -> dict:
|
||||
"""Validate and tidy the model's JSON into what the page renders.
|
||||
|
||||
For ``titles``, ``profile`` adds the channel's rule checks (PLAN #3) and the
|
||||
result carries a ``violations`` list so the caller can re-ask once. The
|
||||
caller pops ``violations`` before returning it to the client.
|
||||
"""
|
||||
def shape_result(mode: str, data: dict) -> dict:
|
||||
"""Validate and tidy the model's JSON into what the page renders."""
|
||||
if mode == "titles":
|
||||
items = []
|
||||
for t in (data.get("titles") or [])[:12]:
|
||||
|
|
@ -563,11 +555,7 @@ def shape_result(mode: str, data: dict, profile=None) -> dict:
|
|||
items.append({"title": title, "angle": _clean(str(t.get("angle", "")))[:40]})
|
||||
if not items:
|
||||
raise ValueError("no titles")
|
||||
return {
|
||||
"titles": items,
|
||||
"violations": title_validation.validate_titles(
|
||||
[i["title"] for i in items], profile),
|
||||
}
|
||||
return {"titles": items}
|
||||
if mode == "description":
|
||||
desc = _clean(str(data.get("description", "")))[:5000]
|
||||
if not desc:
|
||||
|
|
@ -588,37 +576,6 @@ def shape_result(mode: str, data: dict, profile=None) -> dict:
|
|||
return {"tags": tags, "characters": len(",".join(tags))}
|
||||
|
||||
|
||||
def _profile_for_channel(channel):
|
||||
"""Resolve the optional channel field to a Profile (PLAN #3)."""
|
||||
slug = str(channel or "").strip()
|
||||
if not slug:
|
||||
return None
|
||||
from clipwright.pipeline.profiles import ProfileError, load_profile
|
||||
try:
|
||||
return load_profile(slug)
|
||||
except ProfileError as e:
|
||||
raise HTTPException(status_code=400,
|
||||
detail={"code": "bad_channel", "message": str(e)})
|
||||
|
||||
|
||||
def _retry_titles(prompt, candidate, profile):
|
||||
"""One re-ask with the critique; keeps the first attempt if it fails."""
|
||||
def validate(c):
|
||||
return title_validation.validate_titles([t["title"] for t in c["titles"]], profile)
|
||||
|
||||
def retry_once(violations):
|
||||
try:
|
||||
data = _generate(prompt + "\n\n" + title_validation.critique_block(violations))
|
||||
return shape_result("titles", data, profile)
|
||||
except Exception as e: # a failed re-ask must not lose the first attempt
|
||||
print(f"[free_tools] title retry failed: {e}")
|
||||
return None
|
||||
|
||||
best = title_validation.run_with_validation(lambda: candidate, validate, retry_once)
|
||||
best.pop("violations", None)
|
||||
return best
|
||||
|
||||
|
||||
def _gemini_key():
|
||||
return os.environ.get("GEMINI_API_KEY", "").strip() or None
|
||||
|
||||
|
|
@ -674,20 +631,12 @@ async def youtube_metadata(payload: MetadataRequest, request: Request):
|
|||
raise HTTPException(status_code=503, detail={
|
||||
"code": "not_configured", "message": "This tool needs a Gemini API key on the server."})
|
||||
_enforce("metadata", request)
|
||||
profile = _profile_for_channel(payload.channel)
|
||||
prompt = build_prompt(mode, topic.replace("{", "(").replace("}", ")"), keyword, audience)
|
||||
last = None
|
||||
for _ in range(2):
|
||||
try:
|
||||
data = await asyncio.wait_for(asyncio.to_thread(_generate, prompt), timeout=40)
|
||||
shaped = shape_result(mode, data, profile)
|
||||
# Deterministic title QA (PLAN #3): one re-ask if the titles break
|
||||
# the rules, then keep the better attempt. Never blocks the job.
|
||||
if mode == "titles" and shaped.get("violations"):
|
||||
shaped = await asyncio.wait_for(
|
||||
asyncio.to_thread(_retry_titles, prompt, shaped, profile), timeout=80)
|
||||
shaped.pop("violations", None)
|
||||
return {"mode": mode, **shaped}
|
||||
return {"mode": mode, **shape_result(mode, data)}
|
||||
except asyncio.TimeoutError:
|
||||
last = "timeout"
|
||||
break
|
||||
|
|
|
|||
|
|
@ -1,154 +0,0 @@
|
|||
"""Minimal YouTube Data API v3 client -- first comment only (PLAN #6).
|
||||
|
||||
The Shorts "Related video" link and comment pinning are Studio-UI only and are
|
||||
**not** exposed by any API, so this module deliberately does one thing: post a
|
||||
top-level comment on a video via ``commentThreads.insert``. Pinning that comment
|
||||
stays manual.
|
||||
|
||||
Auth is a real-channel OAuth refresh token (service accounts do not work for
|
||||
this scope). Credentials come from the environment and the integration is
|
||||
**opt-in**: with any of them missing, :func:`is_configured` is false and no
|
||||
network call is ever made. Callers must check :func:`is_configured` (or handle
|
||||
:class:`YoutubeDataError`) before asking for a comment.
|
||||
|
||||
Quota: ``commentThreads.insert`` costs 50 units of the default 10,000/day
|
||||
project quota (~200 comments/day). That is the whole reason posting is a
|
||||
deliberate, caller-triggered action and never automatic.
|
||||
|
||||
Blocking, like ``postiz.py``: call through ``asyncio.to_thread`` from async
|
||||
handlers. Every function accepts an optional pre-built ``httpx.Client`` so tests
|
||||
can inject a ``httpx.MockTransport`` and no live OAuth is ever needed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||
COMMENT_THREADS_URL = "https://www.googleapis.com/youtube/v3/commentThreads"
|
||||
# Required by insert (the comment posting endpoint). Read-only analytics use a
|
||||
# different scope; this module never reads.
|
||||
SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
|
||||
|
||||
# Environment variable names, kept as constants so the API layer can name them
|
||||
# in its "not configured" message without duplicating strings.
|
||||
CLIENT_ID_ENV = "YOUTUBE_OAUTH_CLIENT_ID"
|
||||
CLIENT_SECRET_ENV = "YOUTUBE_OAUTH_CLIENT_SECRET"
|
||||
REFRESH_TOKEN_ENV = "YOUTUBE_OAUTH_REFRESH_TOKEN"
|
||||
TOKEN_URI_ENV = "YOUTUBE_OAUTH_TOKEN_URI"
|
||||
|
||||
|
||||
class YoutubeDataError(Exception):
|
||||
"""A missing config or non-2xx response from the YouTube Data API.
|
||||
|
||||
Carries the status and body so the FastAPI layer can translate it into the
|
||||
same status/detail it would have surfaced otherwise.
|
||||
"""
|
||||
|
||||
def __init__(self, status_code: int, detail: str):
|
||||
super().__init__(detail)
|
||||
self.status_code = status_code
|
||||
self.detail = detail
|
||||
|
||||
|
||||
def _env(name: str, default: Optional[str] = None) -> Optional[str]:
|
||||
value = os.environ.get(name)
|
||||
if value is None:
|
||||
return default
|
||||
value = value.strip()
|
||||
return value or default
|
||||
|
||||
|
||||
def credentials() -> Dict[str, Optional[str]]:
|
||||
"""The OAuth credentials read from the environment (values may be None)."""
|
||||
return {
|
||||
"client_id": _env(CLIENT_ID_ENV),
|
||||
"client_secret": _env(CLIENT_SECRET_ENV),
|
||||
"refresh_token": _env(REFRESH_TOKEN_ENV),
|
||||
"token_uri": _env(TOKEN_URI_ENV, TOKEN_URI),
|
||||
}
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
"""True when a refresh-token flow can run. False = no-op, never called."""
|
||||
creds = credentials()
|
||||
return all(creds[key] for key in ("client_id", "client_secret", "refresh_token"))
|
||||
|
||||
|
||||
def _access_token(client: httpx.Client, creds: Dict[str, Optional[str]]) -> str:
|
||||
resp = client.post(str(creds["token_uri"]), data={
|
||||
"client_id": creds["client_id"],
|
||||
"client_secret": creds["client_secret"],
|
||||
"refresh_token": creds["refresh_token"],
|
||||
"grant_type": "refresh_token",
|
||||
})
|
||||
if resp.status_code != 200:
|
||||
raise YoutubeDataError(
|
||||
502,
|
||||
f"YouTube OAuth token refresh failed: {(resp.text or '')[:300]}",
|
||||
)
|
||||
try:
|
||||
token = (resp.json() or {}).get("access_token")
|
||||
except ValueError:
|
||||
token = None
|
||||
if not token:
|
||||
raise YoutubeDataError(502, "YouTube OAuth token refresh returned no access_token")
|
||||
return token
|
||||
|
||||
|
||||
def post_first_comment(video_id: str, text: str, timeout: float = 60.0,
|
||||
client: Optional[httpx.Client] = None) -> Dict[str, Any]:
|
||||
"""Post ``text`` as a top-level comment on ``video_id``.
|
||||
|
||||
Returns the API's ``commentThreads.insert`` response (id + snippet).
|
||||
|
||||
Raises :class:`YoutubeDataError` when unconfigured, given bad input, or when
|
||||
YouTube rejects the insert. ``client`` is the test seam; pass an
|
||||
``httpx.Client`` built with a ``MockTransport`` to exercise this offline.
|
||||
"""
|
||||
if not video_id or not str(video_id).strip():
|
||||
raise YoutubeDataError(400, "video_id is required")
|
||||
if not text or not str(text).strip():
|
||||
raise YoutubeDataError(400, "comment text is required")
|
||||
if not is_configured():
|
||||
raise YoutubeDataError(
|
||||
400,
|
||||
"YouTube Data API is not configured; set "
|
||||
f"{CLIENT_ID_ENV}, {CLIENT_SECRET_ENV} and {REFRESH_TOKEN_ENV}",
|
||||
)
|
||||
|
||||
owns_client = client is None
|
||||
client = client or httpx.Client(timeout=timeout)
|
||||
try:
|
||||
token = _access_token(client, credentials())
|
||||
resp = client.post(
|
||||
COMMENT_THREADS_URL,
|
||||
params={"part": "snippet"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"snippet": {
|
||||
"videoId": str(video_id).strip(),
|
||||
"topLevelComment": {
|
||||
"snippet": {"textOriginal": str(text)},
|
||||
},
|
||||
}},
|
||||
)
|
||||
finally:
|
||||
if owns_client:
|
||||
client.close()
|
||||
|
||||
if resp.status_code not in (200, 201):
|
||||
# 4xx are the caller's (invalid video / scope); 5xx become 502 so the
|
||||
# API layer does not claim the upstream is down with a gateway code
|
||||
# that came from YouTube, not this server.
|
||||
status = resp.status_code if resp.status_code < 500 else 502
|
||||
raise YoutubeDataError(
|
||||
status,
|
||||
f"YouTube commentThreads.insert failed: {(resp.text or '')[:300]}",
|
||||
)
|
||||
try:
|
||||
return resp.json() or {}
|
||||
except ValueError:
|
||||
return {}
|
||||
|
|
@ -1,909 +0,0 @@
|
|||
"""CODE/TERMINAL vertical layout: an IDE or terminal recording in 9:16.
|
||||
|
||||
The case every screen layout here handles badly: a maximized 1440p editor or a
|
||||
terminal window. The existing SCREENCAST layout treats it as "content over a
|
||||
presenter", which on a code recording means the output is the whole 1440p frame
|
||||
shrunk to a 608px strip — 24px of glyph height at best, unreadable on a phone.
|
||||
|
||||
What a code recording actually needs is the opposite trade. The viewer has to
|
||||
read characters, so the *pane* is cropped to one column of code and scaled up to
|
||||
fill the width, with the source's blur as decorative filler above and below, and
|
||||
the bottom ~15% left clear for captions. When the pane is taller than the output
|
||||
band, a crop window has to follow the active line (a `sendcmd` pan) so the line
|
||||
being typed stays on screen.
|
||||
|
||||
Design, following the ``camera_inset`` pattern:
|
||||
|
||||
- module ``ENABLED`` read from ``CODE_LAYOUT`` (off by default);
|
||||
- ``detect_code_pane`` -> geometry (a self-contained edge/row-column detector,
|
||||
like ``split_layout.detect_split_scenes``: no ``content_ranges`` dead wire);
|
||||
- pure geometry helpers (``pane_from_projections``, ``stable_pane``,
|
||||
``fit_window``, ``follow_sendcmd_lines``) so the decisions are unit-testable
|
||||
without OpenCV;
|
||||
- ``code_filtergraph`` -> crop -> scale -> overlay on a blurred backdrop.
|
||||
|
||||
Everything tunable is an env-overridable constant. The thresholds were set from
|
||||
first principles and *must* be calibrated against a real 1440p corpus with
|
||||
``clipwright/tools/verify_code_layout.py`` before the layout is enabled by
|
||||
default.
|
||||
|
||||
Import-time cost is ``numpy`` only; ``cv2`` is imported lazily inside the frame
|
||||
functions so the unit suite (which has no OpenCV) still collects this module.
|
||||
"""
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
|
||||
from clipwright.media.ffmpeg_utils import blurred_backdrop
|
||||
|
||||
# Off by default: a wrong CODE crop shows a wall of clipped glyphs, which is a
|
||||
# worse failure than leaving a code clip on the TRACK/WIDE default.
|
||||
ENABLED = os.environ.get("CODE_LAYOUT", "0") == "1"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Env-overridable tuning. See clipwright/tools/verify_code_layout.py for the
|
||||
# corpus pass that produces real numbers for these; the defaults are estimates.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Pan the crop window to keep the active line visible on a tall pane.
|
||||
FOLLOW_ENABLED = os.environ.get("CODE_FOLLOW", "1") == "1"
|
||||
|
||||
# Extra zoom on top of "fit the pane width to the output width". 1.0 keeps the
|
||||
# whole pane width; >1 crops a narrower column and scales it up (bigger glyphs).
|
||||
ZOOM = float(os.environ.get("CODE_ZOOM", "1.0"))
|
||||
|
||||
# Minimum horizontal scale (out_w / pane_w). Below this the pane is being
|
||||
# downscaled so far that the text stops being readable, and the caller should
|
||||
# fall back to SCREENCAST/WIDE. At 1440p maximized, out_w/pane_w == 1080/1440 ==
|
||||
# 0.75 exactly, so a maximized editor sits on the boundary and a maximized
|
||||
# ultrawide falls through.
|
||||
MIN_SCALE = float(os.environ.get("CODE_MIN_SCALE", "0.75"))
|
||||
|
||||
# Face/camera band height, as a fraction of out_h, when a cam_box is supplied.
|
||||
CAMERA_BAND_RATIO = float(os.environ.get("CODE_CAMERA_BAND", "0.18"))
|
||||
|
||||
# Bottom band reserved for captions, as a fraction of out_h.
|
||||
CAPTION_BAND_RATIO = float(os.environ.get("CODE_CAPTION_BAND", "0.15"))
|
||||
|
||||
# Pane gates, as a fraction of the frame. A corner panel is not a code pane.
|
||||
PANE_MIN_WIDTH_FRAC = float(os.environ.get("CODE_PANE_MIN_WIDTH", "0.35"))
|
||||
PANE_MIN_HEIGHT_FRAC = float(os.environ.get("CODE_PANE_MIN_HEIGHT", "0.25"))
|
||||
|
||||
# Edge-density floor inside the pane (fraction of pixels above the Sobel
|
||||
# threshold). Flat wallpapers and photos fall below it.
|
||||
EDGE_DENSITY_FLOOR = float(os.environ.get("CODE_EDGE_DENSITY", "0.02"))
|
||||
|
||||
# Temporal stability: the pane centre must stay within this fraction of the
|
||||
# frame across samples, for at least this fraction of them.
|
||||
STABILITY_TOLERANCE = float(os.environ.get("CODE_STABILITY_TOLERANCE", "0.04"))
|
||||
STABILITY_MIN_FRAC = float(os.environ.get("CODE_STABILITY_FRAC", "0.6"))
|
||||
|
||||
# Detection runs on a copy at most this wide. Sobel/close is O(pixels) and the
|
||||
# pane geometry does not need full resolution.
|
||||
DETECT_MAX_WIDTH = int(os.environ.get("CODE_DETECT_WIDTH", "960"))
|
||||
|
||||
# Wide-short morphological close: joins glyphs into horizontal line runs
|
||||
# without merging adjacent text lines (which a square kernel does).
|
||||
CLOSE_KERNEL = (35, 3)
|
||||
|
||||
# Fraction of the projection max that counts as pane edge mass.
|
||||
PROJ_THRESHOLD_RATIO = float(os.environ.get("CODE_PROJ_THRESHOLD", "0.15"))
|
||||
|
||||
# Below this scaled Sobel magnitude a frame contributes no edge map.
|
||||
SOBEL_FLOOR = float(os.environ.get("CODE_SOBEL_FLOOR", "8.0"))
|
||||
SOBEL_RATIO = 0.15
|
||||
|
||||
# Active-line tracking.
|
||||
ACTIVE_MAX_WIDTH = int(os.environ.get("CODE_ACTIVE_WIDTH", "480"))
|
||||
ACTIVE_BAND_FRAC = 0.20
|
||||
ACTIVE_MIN_CONCENTRATION = float(
|
||||
os.environ.get("CODE_ACTIVE_CONCENTRATION", "0.35"))
|
||||
ACTIVE_MIN_MASS = float(os.environ.get("CODE_ACTIVE_MASS", "1500"))
|
||||
|
||||
# Editor classification: syntax highlighting raises chroma variance above a
|
||||
# plain terminal's.
|
||||
EDITOR_SAT_STD = float(os.environ.get("CODE_EDITOR_SAT_STD", "28"))
|
||||
GUTTER_FRACTION = 0.12
|
||||
|
||||
# IDE chrome masking. A maximized editor's window is the whole 2560px of a 1440p
|
||||
# source, so a whole-window pane scales at 1080/2560 ~= 0.42 and trips
|
||||
# MIN_SCALE. What we want is the TEXT COLUMN: the activity bar and sidebar sit
|
||||
# in the left margin and the minimap in the right, each separated from the code
|
||||
# by a sustained blank border. The detector searches within these margins for
|
||||
# that blank run and cuts there; with no chrome (a bare terminal) there is no
|
||||
# run and the full width is kept. Widths vary by theme and zoom — tune
|
||||
# CODE_CHROME_* and CODE_TEXT_* from tools/verify_code_layout.py.
|
||||
CHROME_LEFT_FRAC = float(os.environ.get("CODE_CHROME_LEFT", "0.22"))
|
||||
CHROME_RIGHT_FRAC = float(os.environ.get("CODE_CHROME_RIGHT", "0.10"))
|
||||
CHROME_BOTTOM_FRAC = float(os.environ.get("CODE_CHROME_BOTTOM", "0.03"))
|
||||
# A "gap" is a sustained run of columns below this share of the text max.
|
||||
GAP_FRAC = float(os.environ.get("CODE_GAP_FRAC", "0.08"))
|
||||
GAP_PX = int(os.environ.get("CODE_GAP_PX", "4"))
|
||||
TEXT_CORE_FRAC = float(os.environ.get("CODE_TEXT_CORE", "0.35"))
|
||||
TEXT_MIN_WIDTH_FRAC = float(os.environ.get("CODE_TEXT_MIN_WIDTH", "0.2"))
|
||||
|
||||
# Per-scene verification: share of frames sampled inside the pane that must
|
||||
# still read as code for the scene to keep CODE (otherwise its other verdict
|
||||
# stands). A cutaway to the facecam fails the texture/palette checks.
|
||||
SCENE_CODE_FRAC = float(os.environ.get("CODE_SCENE_FRAC", "0.5"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pure geometry (no cv2): projections -> pane, stability, band layout, sendcmd.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _extent(projection, threshold):
|
||||
"""First/last index above ``threshold`` (end exclusive), or None."""
|
||||
idx = np.flatnonzero(np.asarray(projection, dtype=float) > threshold)
|
||||
if idx.size == 0:
|
||||
return None
|
||||
return int(idx[0]), int(idx[-1]) + 1
|
||||
|
||||
|
||||
def pane_from_projections(row_proj, col_proj, frame_w, frame_h,
|
||||
min_width_frac=PANE_MIN_WIDTH_FRAC,
|
||||
min_height_frac=PANE_MIN_HEIGHT_FRAC,
|
||||
threshold_ratio=PROJ_THRESHOLD_RATIO):
|
||||
"""Locate the code pane from 1-D row/column edge projections.
|
||||
|
||||
``row_proj`` is per-row edge mass (length = pane-space height) and
|
||||
``col_proj`` per-column. The pane is the bounding extent of edge mass above
|
||||
a fraction of each projection's own max: text lines are many separated rows
|
||||
of mass, so a "longest contiguous run" would lock onto a single line. The
|
||||
extent is in the same coordinate space as ``frame_w``/``frame_h`` (detection
|
||||
passes the downscaled size; the fractions are scale-invariant).
|
||||
|
||||
Returns ``(x, y, w, h)`` or None when the box is missing or fails either
|
||||
size gate.
|
||||
"""
|
||||
rows = np.asarray(row_proj, dtype=float)
|
||||
cols = np.asarray(col_proj, dtype=float)
|
||||
if rows.size == 0 or cols.size == 0:
|
||||
return None
|
||||
if rows.max() <= 0 or cols.max() <= 0:
|
||||
return None
|
||||
ry = _extent(rows, threshold_ratio * rows.max())
|
||||
cx = _extent(cols, threshold_ratio * cols.max())
|
||||
if ry is None or cx is None:
|
||||
return None
|
||||
y0, y1 = ry
|
||||
x0, x1 = cx
|
||||
w, h = x1 - x0, y1 - y0
|
||||
if w < min_width_frac * frame_w or h < min_height_frac * frame_h:
|
||||
return None
|
||||
return (x0, y0, w, h)
|
||||
|
||||
|
||||
def _smooth(values, window=9):
|
||||
v = np.asarray(values, dtype=float)
|
||||
if window <= 1 or v.size < window:
|
||||
return v
|
||||
kernel = np.ones(window, dtype=float) / window
|
||||
return np.convolve(v, kernel, mode="same")
|
||||
|
||||
|
||||
def _gaps(below, gap_px):
|
||||
"""(start, end) of every sustained True run in a boolean array."""
|
||||
out = []
|
||||
start = None
|
||||
for i, flag in enumerate(below):
|
||||
if flag and start is None:
|
||||
start = i
|
||||
elif not flag and start is not None:
|
||||
if i - start >= gap_px:
|
||||
out.append((start, i))
|
||||
start = None
|
||||
if start is not None and len(below) - start >= gap_px:
|
||||
out.append((start, len(below)))
|
||||
return out
|
||||
|
||||
|
||||
def text_column_extent(col_proj, frame_w, left_skip_frac=CHROME_LEFT_FRAC,
|
||||
right_skip_frac=CHROME_RIGHT_FRAC,
|
||||
core_frac=TEXT_CORE_FRAC,
|
||||
min_width_frac=TEXT_MIN_WIDTH_FRAC,
|
||||
gap_frac=GAP_FRAC, gap_px=GAP_PX, smooth=9):
|
||||
"""(x0, x1) of the editor text column, with IDE chrome cut off.
|
||||
|
||||
``col_proj`` is per-column edge mass. The whole extent of edge mass is
|
||||
first-to-last above ``core_frac`` of the max (text fills nearly every
|
||||
column across many lines, so a longest-run would lock onto one block). The
|
||||
left and right margins are then searched for a sustained blank border — the
|
||||
gap between the sidebar and the code, and between the code and the
|
||||
minimap — and the extent is cut at the innermost one. A bare terminal has
|
||||
no such border and keeps its full width. Returns None when no run clears
|
||||
``min_width_frac``.
|
||||
"""
|
||||
cols = _smooth(col_proj, smooth)
|
||||
if cols.size == 0:
|
||||
return None
|
||||
top = float(cols.max())
|
||||
if top <= 0:
|
||||
return None
|
||||
core = cols > core_frac * top
|
||||
if not core.any():
|
||||
return None
|
||||
first = int(np.argmax(core))
|
||||
last = int(len(core) - np.argmax(core[::-1]))
|
||||
|
||||
thr = gap_frac * top
|
||||
x0 = first
|
||||
window = cols[first:first + int(round(left_skip_frac * frame_w))]
|
||||
gaps = _gaps(window < thr, max(2, gap_px))
|
||||
if gaps:
|
||||
x0 = first + gaps[-1][1]
|
||||
|
||||
x1 = last
|
||||
rstart = max(x0, last - int(round(right_skip_frac * frame_w)))
|
||||
window = cols[rstart:last]
|
||||
gaps = _gaps(window < thr, max(2, gap_px))
|
||||
if gaps:
|
||||
x1 = rstart + gaps[-1][0]
|
||||
|
||||
if x1 - x0 < min_width_frac * frame_w:
|
||||
return None
|
||||
return x0, x1
|
||||
|
||||
|
||||
def clamp_pane_width(pane, max_width, anchor="left"):
|
||||
"""Narrow a pane to at most ``max_width`` columns.
|
||||
|
||||
Used when the text column is still wider than the readable scale allows
|
||||
(1080 / MIN_SCALE ~= 1440 on a 1440p source): code is left-aligned, so
|
||||
keeping the left edge keeps indentation and line starts. Returns an even
|
||||
``(x, y, w, h)`` tuple.
|
||||
"""
|
||||
x, y, w, h = _pane_box(pane)
|
||||
max_width = int(max_width) - (int(max_width) % 2)
|
||||
if max_width < 2:
|
||||
max_width = 2
|
||||
if w <= max_width:
|
||||
return (x, y, w, h)
|
||||
nx = x + (w - max_width) // 2 if anchor == "center" else x
|
||||
nx = max(0, nx - (nx % 2))
|
||||
return (nx, y, max_width, h)
|
||||
|
||||
|
||||
def _stable_members(boxes, frame_w, frame_h, tolerance):
|
||||
arr = np.asarray(boxes, dtype=float)
|
||||
cx = arr[:, 0] + arr[:, 2] / 2.0
|
||||
cy = arr[:, 1] + arr[:, 3] / 2.0
|
||||
mid_x, mid_y = float(np.median(cx)), float(np.median(cy))
|
||||
close = ((np.abs(cx - mid_x) <= tolerance * frame_w)
|
||||
& (np.abs(cy - mid_y) <= tolerance * frame_h))
|
||||
return arr, close
|
||||
|
||||
|
||||
def stable_pane(boxes, frame_w, frame_h, tolerance=STABILITY_TOLERANCE,
|
||||
min_frac=STABILITY_MIN_FRAC):
|
||||
"""Median box over the samples that agree, or None.
|
||||
|
||||
A pane that jumps around the screen is a moving camera or a slideshow, not a
|
||||
fixed editor window; clustering around the median tolerates one stray sample
|
||||
without tolerating real movement.
|
||||
"""
|
||||
if not boxes:
|
||||
return None
|
||||
arr, close = _stable_members(boxes, frame_w, frame_h, tolerance)
|
||||
if int(close.sum()) < max(2, int(round(min_frac * len(boxes)))):
|
||||
return None
|
||||
return tuple(int(round(v)) for v in np.median(arr[close], axis=0))
|
||||
|
||||
|
||||
def stability_fraction(boxes, frame_w, frame_h, tolerance=STABILITY_TOLERANCE):
|
||||
"""Fraction of samples whose centre agrees with the median."""
|
||||
if not boxes:
|
||||
return 0.0
|
||||
_, close = _stable_members(boxes, frame_w, frame_h, tolerance)
|
||||
return float(close.mean()) if close.size else 0.0
|
||||
|
||||
|
||||
def edge_density(mask, box):
|
||||
"""Fraction of set pixels inside ``box`` (mask may be 0/1 or 0/255)."""
|
||||
x, y, w, h = (int(v) for v in box[:4])
|
||||
m = np.asarray(mask)
|
||||
sub = m[max(0, y):y + h, max(0, x):x + w]
|
||||
if sub.size == 0:
|
||||
return 0.0
|
||||
scale = 255.0 if sub.max() > 1 else 1.0
|
||||
return float(sub.mean()) / scale
|
||||
|
||||
|
||||
def code_bands(out_h, caption_ratio=None):
|
||||
"""(content_h, caption_h): even, positive, and summing to ``out_h``."""
|
||||
ratio = CAPTION_BAND_RATIO if caption_ratio is None else caption_ratio
|
||||
caption_h = int(round(out_h * ratio))
|
||||
caption_h -= caption_h % 2
|
||||
caption_h = max(2, min(caption_h, out_h - 2))
|
||||
content_h = out_h - caption_h
|
||||
return content_h, caption_h
|
||||
|
||||
|
||||
def fit_window(pane_h, scale, band_h):
|
||||
"""(crop_h, scaled_h, needs_follow) for a pane of ``pane_h`` at ``scale``.
|
||||
|
||||
``crop_h`` is the source window height, ``scaled_h`` its height after
|
||||
scaling, both even and clamped so ``scaled_h <= band_h``. ``needs_follow``
|
||||
is True when the pane is taller than the band and only a window can fit.
|
||||
"""
|
||||
pane_h = max(2, int(pane_h))
|
||||
if scale <= 0:
|
||||
return None
|
||||
full_scaled = pane_h * scale
|
||||
if full_scaled <= band_h:
|
||||
scaled_h = int(round(full_scaled))
|
||||
scaled_h += scaled_h % 2
|
||||
scaled_h = max(2, min(scaled_h, band_h))
|
||||
crop_h = pane_h - (pane_h % 2)
|
||||
return max(2, crop_h), scaled_h, False
|
||||
crop_h = int(round(band_h / scale))
|
||||
crop_h += crop_h % 2
|
||||
crop_h = max(2, min(crop_h, pane_h - (pane_h % 2)))
|
||||
scaled_h = band_h - (band_h % 2)
|
||||
return crop_h, max(2, scaled_h), True
|
||||
|
||||
|
||||
def follow_sendcmd_lines(follow, pane_y, window_h, pane_h, start=0.0,
|
||||
target="crop@c"):
|
||||
"""sendcmd lines panning a crop window to the active line.
|
||||
|
||||
``follow`` is ``[(timestamp, source_y), ...]`` where ``timestamp`` is in the
|
||||
source's clock; ``start`` is the segment start, subtracted so the emitted
|
||||
timestamps are relative to the segment (the render seeks per scene). Only
|
||||
change-points are emitted: ``y`` is clamped to the pane and deduped.
|
||||
"""
|
||||
lines = []
|
||||
prev = None
|
||||
lo = int(pane_y)
|
||||
hi = max(lo, int(pane_y + pane_h - window_h))
|
||||
for t, y in follow:
|
||||
rel = float(t) - float(start)
|
||||
if rel < 0:
|
||||
continue
|
||||
top = int(round(float(y) - window_h / 2.0))
|
||||
top = max(lo, min(top, hi))
|
||||
top -= top % 2
|
||||
if top == prev:
|
||||
continue
|
||||
lines.append(f"{rel:.4f} {target} y {top};")
|
||||
prev = top
|
||||
return lines
|
||||
|
||||
|
||||
def _pane_box(pane):
|
||||
if isinstance(pane, dict):
|
||||
return (int(pane["x"]), int(pane["y"]), int(pane["w"]), int(pane["h"]))
|
||||
return tuple(int(v) for v in pane[:4])
|
||||
|
||||
|
||||
def code_filtergraph(pane, out_w, out_h, follow=None, cam_box=None,
|
||||
min_scale=MIN_SCALE, caption_ratio=None, zoom=None):
|
||||
"""Crop the code pane, scale it to ``out_w``, overlay on a blurred backdrop.
|
||||
|
||||
``pane`` is an ``(x, y, w, h)`` tuple or a ``detect_code_pane`` dict in
|
||||
SOURCE coordinates. ``follow`` is a segment-relative
|
||||
``[(t, source_y), ...]`` series from ``active_line_series``; it produces a
|
||||
``sendcmd`` pan when the pane is taller than the content band. ``cam_box``
|
||||
optionally overlays a face in the caption band.
|
||||
|
||||
Returns the filtergraph string ending in ``[v]``, or None when
|
||||
``out_w / pane_w < min_scale`` so the caller can fall back to
|
||||
SCREENCAST/WIDE.
|
||||
"""
|
||||
x, y, w, h = _pane_box(pane)
|
||||
x = max(0, x - (x % 2))
|
||||
y = max(0, y - (y % 2))
|
||||
w = max(2, w - (w % 2))
|
||||
h = max(2, h - (h % 2))
|
||||
|
||||
fit = out_w / float(w)
|
||||
if fit < min_scale:
|
||||
return None
|
||||
|
||||
z = ZOOM if zoom is None else zoom
|
||||
scale = fit * max(0.1, float(z))
|
||||
if scale <= 0:
|
||||
return None
|
||||
|
||||
content_h, caption_h = code_bands(out_h, caption_ratio)
|
||||
|
||||
# Horizontal crop window: at zoom 1 this is the whole pane width.
|
||||
crop_w = int(round(out_w / scale))
|
||||
crop_w += crop_w % 2
|
||||
crop_w = max(2, min(crop_w, w))
|
||||
crop_x = x + (w - crop_w) // 2
|
||||
crop_x = max(0, crop_x - (crop_x % 2))
|
||||
|
||||
fitted = fit_window(h, scale, content_h)
|
||||
if fitted is None:
|
||||
return None
|
||||
crop_h, scaled_h, needs_follow = fitted
|
||||
y_off = max(0, (content_h - scaled_h) // 2)
|
||||
|
||||
window_top = None
|
||||
if needs_follow:
|
||||
window_top = y + (h - crop_h) // 2
|
||||
if follow:
|
||||
window_top = int(round(float(follow[0][1]) - crop_h / 2.0))
|
||||
window_top = max(y, min(window_top, y + h - crop_h))
|
||||
window_top -= window_top % 2
|
||||
|
||||
if needs_follow and follow:
|
||||
lines = follow_sendcmd_lines(follow, y, crop_h, h, start=0.0)
|
||||
else:
|
||||
lines = []
|
||||
|
||||
if lines:
|
||||
# Each line is already ';'-terminated; concatenating avoids the empty
|
||||
# command a second separator would produce.
|
||||
commands = "".join(lines)
|
||||
fg = (f"sendcmd=c='{commands}',"
|
||||
f"crop@c=w={crop_w}:h={crop_h}:x={crop_x}:y={window_top},"
|
||||
f"scale={out_w}:{scaled_h}[code]")
|
||||
else:
|
||||
static_y = (window_top if window_top is not None
|
||||
else y + (h - crop_h) // 2)
|
||||
static_y = max(y, min(static_y, y + h - crop_h))
|
||||
static_y -= static_y % 2
|
||||
fg = (f"crop=w={crop_w}:h={crop_h}:x={crop_x}:y={static_y},"
|
||||
f"scale={out_w}:{scaled_h}[code]")
|
||||
|
||||
parts = []
|
||||
if cam_box is not None:
|
||||
cx, cy, cw, ch = _pane_box(cam_box)
|
||||
cx = max(0, cx - (cx % 2))
|
||||
cy = max(0, cy - (cy % 2))
|
||||
cw = max(2, cw - (cw % 2))
|
||||
ch = max(2, ch - (ch % 2))
|
||||
cam_h = int(round(out_h * CAMERA_BAND_RATIO))
|
||||
cam_h -= cam_h % 2
|
||||
cam_h = max(2, min(cam_h, caption_h))
|
||||
parts.append("[0:v]split=3[bga][fga][cama];")
|
||||
parts.append(f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];")
|
||||
parts.append(f"[fga]{fg};")
|
||||
parts.append(f"[cama]crop=w={cw}:h={ch}:x={cx}:y={cy},"
|
||||
f"scale={out_w}:{cam_h}[cam];")
|
||||
parts.append(f"[bg][code]overlay=x=0:y={y_off}[withcode];")
|
||||
parts.append(f"[withcode][cam]overlay=x=0:y={out_h - caption_h},"
|
||||
f"setsar=1[v]")
|
||||
else:
|
||||
parts.append("[0:v]split=2[bga][fga];")
|
||||
parts.append(f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];")
|
||||
parts.append(f"[fga]{fg};")
|
||||
parts.append(f"[bg][code]overlay=x=0:y={y_off},setsar=1[v]")
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OpenCV detection (lazy import).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _downscale(frame, max_width):
|
||||
import cv2
|
||||
h, w = frame.shape[:2]
|
||||
if w <= max_width:
|
||||
return frame
|
||||
factor = max_width / float(w)
|
||||
return cv2.resize(frame, (max_width, max(2, int(round(h * factor)))),
|
||||
interpolation=cv2.INTER_AREA)
|
||||
|
||||
|
||||
def _edge_maps(frame, max_width=DETECT_MAX_WIDTH):
|
||||
"""Sobel edge mask + wide-short close + row/column projections.
|
||||
|
||||
Returns a dict with the mask, closed mask, projections and the working
|
||||
dimensions, or None when the frame has no gradient (black/frozen).
|
||||
"""
|
||||
import cv2
|
||||
small = _downscale(frame, max_width)
|
||||
gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY)
|
||||
gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3)
|
||||
gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3)
|
||||
mag = cv2.magnitude(gx, gy)
|
||||
top = float(mag.max())
|
||||
if top <= 1e-6:
|
||||
return None
|
||||
threshold = max(SOBEL_FLOOR, SOBEL_RATIO * top)
|
||||
mask = (mag > threshold).astype(np.uint8) * 255
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, CLOSE_KERNEL)
|
||||
closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
|
||||
return {
|
||||
"mask": mask,
|
||||
"closed": closed,
|
||||
"row_proj": closed.sum(axis=1).astype(np.float64),
|
||||
"col_proj": closed.sum(axis=0).astype(np.float64),
|
||||
# The close joins glyphs into line runs, which is what the row
|
||||
# projection needs — but it also bridges the blank IDE chrome borders,
|
||||
# so the column projection for TEXT-COLUMN masking comes from the RAW
|
||||
# mask, where the border survives.
|
||||
"col_proj_raw": mask.sum(axis=0).astype(np.float64),
|
||||
"w": small.shape[1],
|
||||
"h": small.shape[0],
|
||||
}
|
||||
|
||||
|
||||
def _classify_pane(frame, box):
|
||||
"""Editor vs terminal. Defaults to editor when the signal is weak.
|
||||
|
||||
An editor shows a left gutter of stable digit rows (line numbers) and
|
||||
syntax highlighting raises the crop's saturation variance. A terminal has
|
||||
neither: text starts at the left margin and is mostly one foreground colour.
|
||||
"""
|
||||
import cv2
|
||||
x, y, w, h = (int(v) for v in box)
|
||||
crop = frame[max(0, y):y + h, max(0, x):x + w]
|
||||
if crop.size == 0:
|
||||
return "editor"
|
||||
hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)
|
||||
sat_std = float(hsv[:, :, 1].std())
|
||||
|
||||
gutter_w = max(4, int(w * GUTTER_FRACTION))
|
||||
gutter = crop[:, :gutter_w]
|
||||
gg = cv2.cvtColor(gutter, cv2.COLOR_BGR2GRAY)
|
||||
gx = np.abs(cv2.Sobel(gg, cv2.CV_32F, 1, 0, ksize=3))
|
||||
per_col = gx.sum(axis=0)
|
||||
total = float(per_col.sum()) + 1e-6
|
||||
gutter_peak = float(per_col.max() / total) if per_col.size else 0.0
|
||||
|
||||
if sat_std >= EDITOR_SAT_STD and gutter_peak > 0.08:
|
||||
return "editor"
|
||||
if sat_std < EDITOR_SAT_STD and gutter_peak <= 0.08:
|
||||
return "terminal"
|
||||
return "editor"
|
||||
|
||||
|
||||
def detect_code_pane(video_path, samples=12):
|
||||
"""Median code pane across sampled frames, or None.
|
||||
|
||||
Pipeline per sample: downscale to <= DETECT_MAX_WIDTH, Sobel magnitude mask,
|
||||
wide-short morphological close (joins glyphs into line runs), row/column
|
||||
projection -> bounding pane. Gates: pane width/height fractions, in-pane
|
||||
edge-density floor, and temporal stability of the pane centre.
|
||||
|
||||
Returns ``{"x", "y", "w", "h", "mode", "confidence", "frame_w",
|
||||
"frame_h"}`` in source coordinates, or None meaning "use another layout".
|
||||
"""
|
||||
if not ENABLED:
|
||||
return None
|
||||
try:
|
||||
import cv2
|
||||
except ImportError:
|
||||
return None
|
||||
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
return None
|
||||
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
if total <= 0 or frame_w <= 0 or frame_h <= 0:
|
||||
cap.release()
|
||||
return None
|
||||
|
||||
n = max(2, int(samples))
|
||||
boxes = []
|
||||
densities = []
|
||||
votes = {"editor": 0, "terminal": 0}
|
||||
try:
|
||||
for i in range(n):
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, int(i * total / n))
|
||||
ok, frame = cap.read()
|
||||
if not ok:
|
||||
continue
|
||||
maps = _edge_maps(frame)
|
||||
if maps is None:
|
||||
continue
|
||||
det_box = pane_from_projections(
|
||||
maps["row_proj"], maps["col_proj"], maps["w"], maps["h"])
|
||||
if det_box is None:
|
||||
continue
|
||||
# The plain projection returns the whole window; cut it down to the
|
||||
# text column so a maximized 1440p editor does not scale at 0.42.
|
||||
# Raw projection: the morphological close would bridge the chrome
|
||||
# borders this is looking for.
|
||||
text_cols = text_column_extent(maps["col_proj_raw"], maps["w"])
|
||||
if text_cols is not None:
|
||||
x0, x1 = text_cols
|
||||
else:
|
||||
x0, x1 = det_box[0], det_box[0] + det_box[2]
|
||||
y0 = det_box[1]
|
||||
y1 = det_box[1] + det_box[3]
|
||||
# Shave the status bar / window border off the bottom.
|
||||
y1 -= int(round(CHROME_BOTTOM_FRAC * (y1 - y0)))
|
||||
w, h = x1 - x0, y1 - y0
|
||||
if (w < PANE_MIN_WIDTH_FRAC * maps["w"]
|
||||
or h < PANE_MIN_HEIGHT_FRAC * maps["h"]):
|
||||
continue
|
||||
det_box = (x0, y0, w, h)
|
||||
density = edge_density(maps["closed"], det_box)
|
||||
if density < EDGE_DENSITY_FLOOR:
|
||||
continue
|
||||
sx = frame_w / float(maps["w"])
|
||||
sy = frame_h / float(maps["h"])
|
||||
box = (int(round(det_box[0] * sx)), int(round(det_box[1] * sy)),
|
||||
int(round(det_box[2] * sx)), int(round(det_box[3] * sy)))
|
||||
boxes.append(box)
|
||||
densities.append(density)
|
||||
votes[_classify_pane(frame, box)] += 1
|
||||
finally:
|
||||
cap.release()
|
||||
|
||||
if len(boxes) < 2:
|
||||
return None
|
||||
stable = stable_pane(boxes, frame_w, frame_h)
|
||||
if stable is None:
|
||||
return None
|
||||
x, y, w, h = stable
|
||||
if w < PANE_MIN_WIDTH_FRAC * frame_w or h < PANE_MIN_HEIGHT_FRAC * frame_h:
|
||||
return None
|
||||
|
||||
mode = "editor" if votes["editor"] >= votes["terminal"] else "terminal"
|
||||
stable_frac = stability_fraction(boxes, frame_w, frame_h)
|
||||
density = float(np.mean(densities)) if densities else 0.0
|
||||
confidence = max(0.0, min(1.0, 0.6 * stable_frac
|
||||
+ 0.4 * min(1.0, density / (4 * EDGE_DENSITY_FLOOR))))
|
||||
return {"x": x, "y": y, "w": w, "h": h, "mode": mode,
|
||||
"confidence": confidence, "frame_w": frame_w, "frame_h": frame_h}
|
||||
|
||||
|
||||
def _active_point(row_mass, total, band_frac=ACTIVE_BAND_FRAC,
|
||||
min_concentration=ACTIVE_MIN_CONCENTRATION):
|
||||
"""(normalised centroid, concentration, mass) of the top-mass row band.
|
||||
|
||||
The centroid is the mass-weighted centre of the busiest ``band_frac`` of
|
||||
rows, normalised to 0..1 over the region. ``concentration`` is that band's
|
||||
share of all changed pixels: a caret or highlighted line is concentrated, a
|
||||
whole-screen redraw is not.
|
||||
"""
|
||||
n = len(row_mass)
|
||||
if n == 0 or total <= 0:
|
||||
return None
|
||||
k = max(1, int(round(n * band_frac)))
|
||||
order = np.argsort(row_mass)[-k:]
|
||||
band_mass = float(row_mass[order].sum())
|
||||
if band_mass <= 0:
|
||||
return None
|
||||
concentration = band_mass / float(total)
|
||||
if concentration < min_concentration:
|
||||
return None
|
||||
idx = order.astype(float)
|
||||
cy = float((idx * row_mass[order]).sum() / band_mass)
|
||||
return (cy / (n - 1) if n > 1 else 0.0), concentration, band_mass
|
||||
|
||||
|
||||
def _median_smooth(values, window=3):
|
||||
values = np.asarray(values, dtype=float)
|
||||
if window <= 1 or len(values) < window:
|
||||
return values
|
||||
half = window // 2
|
||||
out = values.copy()
|
||||
for i in range(len(values)):
|
||||
lo = max(0, i - half)
|
||||
hi = min(len(values), i + half + 1)
|
||||
out[i] = np.median(values[lo:hi])
|
||||
return out
|
||||
|
||||
|
||||
def active_line_series(video_path, pane, start, end, sample_fps=2.0):
|
||||
"""Track the active line (caret/current-line highlight) over a range.
|
||||
|
||||
Low-res decode at ``sample_fps``; ``absdiff`` between consecutive samples
|
||||
masked to the pane; per-row changed mass; the top-mass band's centroid is
|
||||
kept only when it concentrates >= ``ACTIVE_MIN_CONCENTRATION`` of the change
|
||||
and the band mass clears the floor. The y series is median-smoothed.
|
||||
|
||||
Returns ``[(timestamp, source_y), ...]`` in the source's absolute clock (the
|
||||
caller subtracts the segment start when building sendcmd lines), or None
|
||||
when fewer than three reliable points are found.
|
||||
"""
|
||||
if not ENABLED or not FOLLOW_ENABLED:
|
||||
return None
|
||||
try:
|
||||
import cv2
|
||||
except ImportError:
|
||||
return None
|
||||
if end <= start:
|
||||
return None
|
||||
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
return None
|
||||
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
if frame_w <= 0 or frame_h <= 0:
|
||||
cap.release()
|
||||
return None
|
||||
x, y, w, h = _pane_box(pane)
|
||||
if w <= 0 or h <= 0:
|
||||
cap.release()
|
||||
return None
|
||||
|
||||
step = 1.0 / max(0.1, float(sample_fps))
|
||||
points = []
|
||||
prev_region = None
|
||||
try:
|
||||
t = float(start)
|
||||
while t <= end + 1e-6:
|
||||
cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0)
|
||||
ok, frame = cap.read()
|
||||
if not ok:
|
||||
break
|
||||
small = _downscale(frame, ACTIVE_MAX_WIDTH)
|
||||
sw, sh = small.shape[1], small.shape[0]
|
||||
rx = int(round(x * sw / float(frame_w)))
|
||||
ry = int(round(y * sh / float(frame_h)))
|
||||
rw = max(2, int(round(w * sw / float(frame_w))))
|
||||
rh = max(2, int(round(h * sh / float(frame_h))))
|
||||
rx = max(0, min(rx, sw - 2))
|
||||
ry = max(0, min(ry, sh - 2))
|
||||
rw = max(2, min(rw, sw - rx))
|
||||
rh = max(2, min(rh, sh - ry))
|
||||
region = small[ry:ry + rh, rx:rx + rw]
|
||||
if prev_region is not None and prev_region.shape == region.shape:
|
||||
diff = cv2.absdiff(region, prev_region)
|
||||
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
|
||||
row_mass = gray.sum(axis=1).astype(np.float64)
|
||||
total = float(row_mass.sum())
|
||||
if total >= ACTIVE_MIN_MASS:
|
||||
point = _active_point(row_mass, total)
|
||||
if point is not None:
|
||||
points.append((t, y + point[0] * h))
|
||||
prev_region = region
|
||||
t += step
|
||||
finally:
|
||||
cap.release()
|
||||
|
||||
if len(points) < 3:
|
||||
return None
|
||||
ys = _median_smooth([p[1] for p in points], 3)
|
||||
return [(float(ts), float(yy)) for (ts, _), yy in zip(points, ys)]
|
||||
|
||||
|
||||
def _regular_rows(row_proj, min_period=6, max_period=60, min_peak=0.25):
|
||||
"""True when the row projection has a periodic peak (monospace line pitch).
|
||||
|
||||
Autocorrelation of the mean-subtracted projection; a peak in the plausible
|
||||
line-height band means evenly spaced text lines rather than prose or a UI.
|
||||
"""
|
||||
v = np.asarray(row_proj, dtype=float)
|
||||
if v.size < min_period + 2:
|
||||
return False
|
||||
v = v - v.mean()
|
||||
denom = float((v * v).sum())
|
||||
if denom <= 0:
|
||||
return False
|
||||
ac = np.correlate(v, v, mode="full")[len(v) - 1:]
|
||||
ac = ac / denom
|
||||
hi = min(max_period, len(ac) - 1)
|
||||
if hi <= min_period:
|
||||
return False
|
||||
return float(ac[min_period:hi + 1].max()) >= min_peak
|
||||
|
||||
|
||||
def _texture_ok(maps):
|
||||
"""Edge-density floor + monospace row regularity on an edge-map dict."""
|
||||
density = edge_density(maps["closed"], (0, 0, maps["w"], maps["h"]))
|
||||
if density < EDGE_DENSITY_FLOOR:
|
||||
return False
|
||||
return _regular_rows(maps["row_proj"])
|
||||
|
||||
|
||||
def _palette_ok(crop):
|
||||
"""Editor/terminal palette: dark background or mostly monochrome."""
|
||||
hsv = _hsv(crop)
|
||||
sat_std = float(hsv[:, :, 1].std())
|
||||
dark = float((hsv[:, :, 2] < 102).mean())
|
||||
return bool(dark >= 0.35 or sat_std <= 45.0)
|
||||
|
||||
|
||||
def frame_shows_code(frame, pane):
|
||||
"""True when the pane region of THIS frame still reads as code.
|
||||
|
||||
Text density (edge-density floor + monospace row regularity) plus the
|
||||
editor/terminal palette. A facecam cutaway puts skin/room inside the pane
|
||||
rectangle, which fails both the row pitch and the dark/monochrome palette.
|
||||
"""
|
||||
try:
|
||||
import cv2 # noqa: F401
|
||||
except ImportError:
|
||||
return False
|
||||
x, y, w, h = _pane_box(pane)
|
||||
frame_h, frame_w = frame.shape[:2]
|
||||
x0 = max(0, min(x, frame_w - 2))
|
||||
y0 = max(0, min(y, frame_h - 2))
|
||||
x1 = max(x0 + 2, min(x + w, frame_w))
|
||||
y1 = max(y0 + 2, min(y + h, frame_h))
|
||||
crop = frame[y0:y1, x0:x1]
|
||||
if crop.size == 0:
|
||||
return False
|
||||
maps = _edge_maps(crop)
|
||||
if maps is None:
|
||||
return False
|
||||
return _texture_ok(maps) and _palette_ok(crop)
|
||||
|
||||
|
||||
def scene_shows_code(video_path, pane, start, end, samples=3):
|
||||
"""Sample a scene's frames inside the pane; True on a majority that read
|
||||
as code. A cutaway to the camera fails and keeps the scene's other verdict.
|
||||
"""
|
||||
if end <= start:
|
||||
return False
|
||||
try:
|
||||
import cv2
|
||||
except ImportError:
|
||||
return False
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
return False
|
||||
frames = []
|
||||
try:
|
||||
n = max(1, int(samples))
|
||||
for i in range(n):
|
||||
t = start + (end - start) * (i + 0.5) / n
|
||||
cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0)
|
||||
ok, frame = cap.read()
|
||||
if ok:
|
||||
frames.append(frame)
|
||||
finally:
|
||||
cap.release()
|
||||
if len(frames) < 2:
|
||||
return False
|
||||
good = sum(1 for f in frames if frame_shows_code(f, pane))
|
||||
return good >= max(2, int(round(SCENE_CODE_FRAC * len(frames))))
|
||||
|
||||
|
||||
def looks_like_code(frames):
|
||||
"""Conservative fallback for deployments with no Gemini key.
|
||||
|
||||
``frames`` is a list of BGR arrays. True only when all three hold across the
|
||||
samples: a static pane (centres agree), monospace row regularity, and an
|
||||
editor/terminal palette (dark or mostly monochrome). This is deliberately
|
||||
strict — a false positive demotes a real talking-head clip — and callers
|
||||
MUST NOT invoke it over an explicit operator layout.
|
||||
"""
|
||||
if not frames or len(frames) < 2:
|
||||
return False
|
||||
planes = []
|
||||
row_projs = []
|
||||
sat_stds = []
|
||||
dark_fracs = []
|
||||
for frame in frames:
|
||||
maps = _edge_maps(frame)
|
||||
if maps is None:
|
||||
continue
|
||||
box = pane_from_projections(
|
||||
maps["row_proj"], maps["col_proj"], maps["w"], maps["h"])
|
||||
if box is None:
|
||||
continue
|
||||
if edge_density(maps["closed"], box) < EDGE_DENSITY_FLOOR:
|
||||
continue
|
||||
x, y, w, h = box
|
||||
crop = frame[y:y + h, x:x + w]
|
||||
if crop.size == 0:
|
||||
continue
|
||||
hsv = _hsv(crop)
|
||||
planes.append((x, y, w, h, maps["w"], maps["h"]))
|
||||
row_projs.append(maps["row_proj"])
|
||||
sat_stds.append(float(hsv[:, :, 1].std()))
|
||||
dark_fracs.append(float((hsv[:, :, 2] < 102).mean()))
|
||||
|
||||
if len(planes) < max(2, int(round(0.6 * len(frames)))):
|
||||
return False
|
||||
|
||||
centres_x = np.array([(p[0] + p[2] / 2.0) / p[4] for p in planes])
|
||||
centres_y = np.array([(p[1] + p[3] / 2.0) / p[5] for p in planes])
|
||||
if centres_x.std() > 0.05 or centres_y.std() > 0.05:
|
||||
return False
|
||||
|
||||
median_proj = np.median(np.array(row_projs, dtype=float), axis=0)
|
||||
if not _regular_rows(median_proj):
|
||||
return False
|
||||
|
||||
sat_std = float(np.median(sat_stds))
|
||||
dark = float(np.median(dark_fracs))
|
||||
return bool(dark >= 0.35 or sat_std <= 45.0)
|
||||
|
||||
|
||||
def _hsv(crop):
|
||||
import cv2
|
||||
return cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)
|
||||
|
|
@ -64,7 +64,6 @@ SAMPLE_WIDTH = int(os.environ.get("LAYOUT_SAMPLE_WIDTH", "1024"))
|
|||
DECISION_FLAGS = {
|
||||
"none": [],
|
||||
"screencast": ["screencast_layout"],
|
||||
"code": ["code_layout"],
|
||||
"split": ["split_layout", "active_speaker"],
|
||||
}
|
||||
|
||||
|
|
@ -84,13 +83,11 @@ def apply(decision):
|
|||
must not quietly undo that.
|
||||
"""
|
||||
from clipwright.layouts import active_speaker
|
||||
from clipwright.layouts import code_layout
|
||||
from clipwright.layouts import screencast_layout
|
||||
from clipwright.layouts import split_layout
|
||||
|
||||
modules = {"split_layout": split_layout,
|
||||
"screencast_layout": screencast_layout,
|
||||
"code_layout": code_layout,
|
||||
"active_speaker": active_speaker}
|
||||
|
||||
touched = []
|
||||
|
|
|
|||
|
|
@ -14,14 +14,11 @@ It rides the TRACK path, widening the existing per-frame crop command from
|
|||
x-only to w/h/x/y, so it composes with the camera trajectory instead of fighting
|
||||
it. Off by default (``PUNCH_IN=1``).
|
||||
|
||||
Beat times come from the audio envelope, aligned to the clip-relative word
|
||||
onsets the transcript provides (``emphasis_times(word_times=...)``). The
|
||||
envelope finds the emphasis; the word onset says exactly when it started, so
|
||||
each peak snaps to the nearest word instead of sitting on the loudest
|
||||
syllable. A clip with no envelope beats falls back to the word onsets alone,
|
||||
and without ``word_times`` the beat derivation is exactly what it always was.
|
||||
Beat times come from the audio envelope. The transcript would be a better
|
||||
source (punch on the hook word, not on the loudest syllable), and render() has
|
||||
no transcript today — ``emphasis_times`` is a plain list of seconds, so wiring
|
||||
main.py's word timings in later needs no change here.
|
||||
"""
|
||||
import bisect
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
|
|
@ -62,11 +59,6 @@ BEAT_WINDOW = 0.2
|
|||
MIN_GAP_SECONDS = 18.0
|
||||
BEAT_PROMINENCE = 0.60
|
||||
|
||||
# How far an envelope peak may move to land on a word onset. The envelope frame
|
||||
# is coarse (BEAT_WINDOW); the word's start is exact, so the tolerance is a bit
|
||||
# wider than the frame rather than equal to it.
|
||||
WORD_SNAP_SECONDS = 0.5
|
||||
|
||||
|
||||
def _ease(t):
|
||||
"""Smoothstep on [0, 1]. Linear ramps look mechanical at this duration."""
|
||||
|
|
@ -163,72 +155,32 @@ def sendcmd_lines(boxes, fps, target="crop@c"):
|
|||
return lines
|
||||
|
||||
|
||||
def _snap_to_word(t, words, snap):
|
||||
"""``t`` moved to the closest onset in the sorted ``words``, if within
|
||||
``snap``. Without a word in range the envelope beat is left where it is."""
|
||||
i = bisect.bisect_left(words, t)
|
||||
best, best_d = t, snap
|
||||
for j in (i - 1, i):
|
||||
if 0 <= j < len(words):
|
||||
d = abs(words[j] - t)
|
||||
if d <= best_d:
|
||||
best, best_d = words[j], d
|
||||
return best
|
||||
|
||||
|
||||
def merge_beats(audio_beats, word_times, min_gap=MIN_GAP_SECONDS,
|
||||
snap=WORD_SNAP_SECONDS):
|
||||
"""Punch beats: envelope emphasis, snapped onto the words that carry it.
|
||||
|
||||
The envelope finds where the energy jumped; a word onset is the precise
|
||||
instant to push. Each envelope beat is snapped to the nearest word onset
|
||||
within ``snap`` seconds, which is what turns "the loudest syllable" into
|
||||
"the word that was loud". With no envelope beats at all — silent or flat
|
||||
audio — the word onsets themselves become the beats. The result is thinned
|
||||
to ``min_gap`` so two pushes never overlap. Pure: no audio, no I/O, which
|
||||
is what makes the beat timing testable without a clip.
|
||||
"""
|
||||
words = sorted(word_times or [])
|
||||
if audio_beats:
|
||||
candidates = [_snap_to_word(b, words, snap) if words else b
|
||||
for b in audio_beats]
|
||||
else:
|
||||
candidates = list(words)
|
||||
|
||||
times = []
|
||||
last = -1e9
|
||||
for t in sorted(candidates):
|
||||
if t - last >= min_gap:
|
||||
times.append(round(t, 3))
|
||||
last = t
|
||||
return times
|
||||
|
||||
|
||||
def emphasis_times(video_path, duration, window=BEAT_WINDOW,
|
||||
min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE,
|
||||
word_times=None):
|
||||
"""Seconds where the clip should punch in.
|
||||
min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE):
|
||||
"""Seconds where the audio leaps above its own baseline.
|
||||
|
||||
Audio envelope peaks, merged with ``word_times`` — optional clip-relative
|
||||
word onsets in seconds (clip start = 0), as produced from the transcript.
|
||||
Returns [] for silent, word-less input, which simply means no punches.
|
||||
A stand-in for the hook words until the transcript is wired through. Returns
|
||||
[] for silent or unreadable audio, which simply means no punches.
|
||||
"""
|
||||
from clipwright.layouts import active_speaker
|
||||
|
||||
envelope = active_speaker.audio_envelope(video_path, 0.0, duration,
|
||||
window_s=window)
|
||||
audio_beats = []
|
||||
if envelope:
|
||||
values = np.asarray(envelope, dtype=float)
|
||||
baseline = float(np.median(values))
|
||||
peak = float(values.max())
|
||||
if peak - baseline > 1e-6:
|
||||
threshold = baseline + (peak - baseline) * prominence
|
||||
last = -1e9
|
||||
for i, v in enumerate(values):
|
||||
t = i * window
|
||||
if v >= threshold and t - last >= min_gap:
|
||||
audio_beats.append(t)
|
||||
last = t
|
||||
if not envelope:
|
||||
return []
|
||||
|
||||
return merge_beats(audio_beats, word_times, min_gap=min_gap)
|
||||
values = np.asarray(envelope, dtype=float)
|
||||
baseline = float(np.median(values))
|
||||
peak = float(values.max())
|
||||
if peak - baseline <= 1e-6:
|
||||
return []
|
||||
|
||||
threshold = baseline + (peak - baseline) * prominence
|
||||
times = []
|
||||
last = -1e9
|
||||
for i, v in enumerate(values):
|
||||
t = i * window
|
||||
if v >= threshold and t - last >= min_gap:
|
||||
times.append(round(t, 3))
|
||||
last = t
|
||||
return times
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ import tempfile
|
|||
|
||||
from clipwright.layouts import active_speaker
|
||||
from clipwright.layouts import camera_inset
|
||||
from clipwright.layouts import code_layout
|
||||
from clipwright.layouts import punch_in
|
||||
from clipwright.layouts import screencast_layout
|
||||
from clipwright.layouts import layout_ranges
|
||||
|
|
@ -342,15 +341,12 @@ def _run(cmd):
|
|||
|
||||
|
||||
def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
||||
force_strategy=None, crop_overrides=None, word_times=None):
|
||||
force_strategy=None, crop_overrides=None):
|
||||
"""Full v2 reframe of one clip. Raises on failure (caller falls back).
|
||||
|
||||
``content_ranges`` comes from screencast_layout.detect_content_ranges() on
|
||||
the SOURCE video, already translated into this clip's timeline. When it is
|
||||
None, the render computes it itself on ``input_video`` if the screencast
|
||||
module is on (see below); this used to be a dead wire no production caller
|
||||
filled, so the picker's "screencast" option did nothing. Pass [] to force
|
||||
the upgrade off, or a list to supply pre-computed ranges.
|
||||
the SOURCE video, already translated into this clip's timeline. None or []
|
||||
means the layout never triggers, which is the default.
|
||||
|
||||
``force_strategy`` ('WIDE' / 'TRACK' / any layout the render loop knows)
|
||||
applies that layout to EVERY scene, skipping the classifier and the layout
|
||||
|
|
@ -361,13 +357,8 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
listed keep the automatic camera, so correcting one bad shot never disturbs
|
||||
the ones the tracker got right. Applied AFTER force_strategy: a per-scene
|
||||
hand position always beats the whole-clip choice for the scenes it names.
|
||||
|
||||
``word_times`` are clip-relative word onsets in seconds (clip start = 0)
|
||||
from the transcript, optional. They steer the punch-in beats toward spoken
|
||||
emphasis; None leaves the audio envelope as the only beat source.
|
||||
"""
|
||||
from clipwright.pipeline import main as m
|
||||
auto_content_ranges = content_ranges is None
|
||||
content_ranges = content_ranges or []
|
||||
|
||||
print(" 🚀 Reframe engine v2 (ffmpeg-native render)")
|
||||
|
|
@ -443,57 +434,6 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
if alternates:
|
||||
print(f" 🎬 Speaker-cut layout on {len(alternates)} scene(s)")
|
||||
|
||||
# The SCREENCAST/WIDE/INSET upgrades gate on content_ranges, which no
|
||||
# production caller ever passed: screencast_layout.detect_content_ranges
|
||||
# was called by tests only, so the picker's "screencast" option silently did
|
||||
# nothing (dead wire found in review). Compute them here, once per render,
|
||||
# when the module is on and nothing overrides the layout. CODE does NOT use
|
||||
# this external-ranges path — it self-detects below.
|
||||
if (auto_content_ranges and screencast_layout.ENABLED
|
||||
and not force_strategy and not passthrough):
|
||||
duration = scene_boundaries[-1][1] / fps if scene_boundaries else 0.0
|
||||
try:
|
||||
content_ranges = screencast_layout.detect_content_ranges(
|
||||
input_video, duration)
|
||||
except Exception as e:
|
||||
print(f" ⚠️ On-screen content check failed ({e}).")
|
||||
content_ranges = []
|
||||
|
||||
# CODE is geometric and self-contained, like split_layout: the pane box is
|
||||
# found once for the whole video (screen recordings are usually one long
|
||||
# scene) and then each scene is verified by sampling frames inside that box.
|
||||
# A scene that cuts to the facecam fails the text check and keeps TRACK.
|
||||
# Inserted before SCREENCAST so a code editor with a webcam wins, and the
|
||||
# screencast loop below skips scenes already claimed here.
|
||||
codes = {}
|
||||
code_pane = None
|
||||
if code_layout.ENABLED and not passthrough and not force_strategy:
|
||||
try:
|
||||
code_pane = code_layout.detect_code_pane(input_video)
|
||||
except Exception as e:
|
||||
print(f" ⚠️ Code-pane check failed ({e}) — using other layouts.")
|
||||
code_pane = None
|
||||
if code_pane:
|
||||
max_w = max(2, int(out_w / code_layout.MIN_SCALE))
|
||||
pane_box = code_layout.clamp_pane_width(code_pane, max_w)
|
||||
scale = out_w / float(pane_box[2])
|
||||
print(f" 💻 Code pane {code_pane['w']}x{code_pane['h']} "
|
||||
f"@ {code_pane['x']},{code_pane['y']} "
|
||||
f"mode={code_pane['mode']} conf={code_pane['confidence']:.2f}"
|
||||
f" -> crop {pane_box[2]}px (scale {scale:.2f})")
|
||||
code_pane = dict(code_pane, x=pane_box[0], y=pane_box[1],
|
||||
w=pane_box[2], h=pane_box[3])
|
||||
for scene_idx, (start_f, end_f) in enumerate(scene_boundaries):
|
||||
if strategies[scene_idx] not in ("TRACK", "GENERAL"):
|
||||
continue
|
||||
if code_layout.scene_shows_code(
|
||||
input_video, code_pane, start_f / fps, end_f / fps):
|
||||
strategies[scene_idx] = "CODE"
|
||||
codes[start_f] = code_pane
|
||||
splits.pop(start_f, None)
|
||||
if codes:
|
||||
print(f" 💻 CODE layout on {len(codes)} scene(s)")
|
||||
|
||||
# SCREENCAST wins over SPLIT on the rare scene that qualifies for both: two
|
||||
# faces beside a chart still means the chart is what the shot is about, and
|
||||
# stacking the two speakers would crop it away entirely.
|
||||
|
|
@ -517,9 +457,6 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
if content_ranges:
|
||||
for scene_idx, (plan, centre) in screencast_layout.detect_screencast_scenes(
|
||||
input_video, scenes, strategies, content_ranges).items():
|
||||
# CODE was detected geometrically and wins over the screen layouts.
|
||||
if strategies[scene_idx] == 'CODE':
|
||||
continue
|
||||
# An inset beats both screen plans: it is the only one that can show
|
||||
# the screen whole AND the person at a readable size.
|
||||
if inset:
|
||||
|
|
@ -555,8 +492,7 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
# Beats are found once per clip; each scene takes the ones inside it.
|
||||
beats = []
|
||||
if punch_in.ENABLED:
|
||||
beats = punch_in.emphasis_times(input_video, len(xs) / fps,
|
||||
word_times=word_times)
|
||||
beats = punch_in.emphasis_times(input_video, len(xs) / fps)
|
||||
if beats:
|
||||
print(f" 🔍 Punch-in on {len(beats)} beat(s)")
|
||||
|
||||
|
|
@ -608,22 +544,6 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
left, right = splits[start_f]
|
||||
graph = split_layout.split_filtergraph(
|
||||
orig_w, orig_h, out_w, out_h, left, right)
|
||||
elif strategy == 'CODE' and start_f in codes:
|
||||
pane = codes[start_f]
|
||||
follow = None
|
||||
if code_layout.FOLLOW_ENABLED:
|
||||
try:
|
||||
series = code_layout.active_line_series(
|
||||
input_video, pane, ss, ss + dur)
|
||||
if series:
|
||||
follow = [(t - ss, y) for t, y in series]
|
||||
except Exception:
|
||||
follow = None
|
||||
graph = code_layout.code_filtergraph(
|
||||
pane, out_w, out_h, follow=follow)
|
||||
if graph is None:
|
||||
graph = general_filtergraph(out_w, out_h,
|
||||
orig_w=orig_w, orig_h=orig_h)
|
||||
elif strategy == 'GENERAL':
|
||||
graph = general_filtergraph(out_w, out_h,
|
||||
orig_w=orig_w, orig_h=orig_h)
|
||||
|
|
|
|||
|
|
@ -10,8 +10,6 @@ from google.genai import types
|
|||
from google.genai import errors as genai_errors
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
from clipwright.core.paths import FONTS_DIR
|
||||
from clipwright.media import title_validation
|
||||
from clipwright.pipeline import profile_prompts
|
||||
|
||||
# Text/analysis model (titles, concepts, description). Deliberately NOT tied to
|
||||
# GEMINI_MODEL: the pipeline runs flash-lite for a closed-choice layout pick,
|
||||
|
|
@ -36,14 +34,6 @@ THUMB_MAX_BYTES = 2 * 1024 * 1024 # YouTube's upload limit
|
|||
THUMB_FONT = str(FONTS_DIR / "Anton-Regular.ttf")
|
||||
TEXT_POSITIONS = ("left", "right", "top", "bottom")
|
||||
|
||||
# Mobile viewers (the majority of the audience) watch with YouTube's
|
||||
# timestamp/badge overlays in the bottom-right; keep the headline clear of that
|
||||
# corner and off the right edge.
|
||||
THUMB_SAFE_BOTTOM = 0.20 # bottom fraction reserved for YouTube's UI
|
||||
THUMB_SAFE_RIGHT = 0.05 # margin off the right edge
|
||||
THUMB_SAFE_LEFT = 0.04 # margin off the left edge
|
||||
THUMB_SAFE_TOP = 0.04 # margin off the top edge
|
||||
|
||||
|
||||
def _parse_json(text):
|
||||
"""Gemini JSON, tolerant of code fences and prose around the object."""
|
||||
|
|
@ -72,14 +62,11 @@ def _frame_parts(video_path, n=TITLE_FRAMES, width=TITLE_FRAME_WIDTH):
|
|||
# Titles
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def analyze_video_for_titles(api_key, video_path, transcript=None, profile=None):
|
||||
def analyze_video_for_titles(api_key, video_path, transcript=None):
|
||||
"""
|
||||
Suggests YouTube titles from the transcript plus a handful of frames.
|
||||
Two calls: a wide brainstorm, then a critic that scores and picks a
|
||||
diverse top 10 and pairs each title with a 1-4 word thumbnail hook.
|
||||
|
||||
``profile`` (optional channel Profile, PLAN #1) adds the channel's title and
|
||||
hook rules to both calls; ``None`` leaves the prompts unchanged.
|
||||
Returns: { "titles", "thumbnail_texts", "transcript_summary", "language",
|
||||
"segments", "video_duration", "recommended" }
|
||||
"""
|
||||
|
|
@ -97,11 +84,6 @@ def analyze_video_for_titles(api_key, video_path, transcript=None, profile=None)
|
|||
video_duration = segments[-1]["end"] if segments else 0
|
||||
# Enough transcript for a title; a 3-hour podcast does not need all of it.
|
||||
transcript_text = transcript.get("text", "")[:60000]
|
||||
# Empty for profile=None, so the f-strings below render exactly as before.
|
||||
channel_rules = profile_prompts.clip_rules_block(profile)
|
||||
if channel_rules:
|
||||
print(f"📦 [Thumbnail] Applying channel profile "
|
||||
f"{getattr(profile, 'slug', '')} to title prompts.")
|
||||
|
||||
brainstorm_prompt = f"""You are a YouTube packaging expert (titles + thumbnails) for a channel that wants maximum CTR without lying.
|
||||
|
||||
|
|
@ -127,7 +109,7 @@ TITLE RULES:
|
|||
- Put the main keyword / subject in the first 3 words.
|
||||
- Be specific to THIS video: names, numbers, tools, places from the transcript. Nothing generic.
|
||||
- No ALL CAPS words, at most one exclamation mark, no emojis.
|
||||
{channel_rules}
|
||||
|
||||
OUTPUT JSON:
|
||||
{{
|
||||
"transcript_summary": "...",
|
||||
|
|
@ -172,7 +154,7 @@ Then return the 10 best, ordered best first, with NO two titles using the same a
|
|||
For each of the 10, write the THUMBNAIL TEXT: 1-4 words, ALL CAPS, in {language}, that COMPLEMENTS the title instead of repeating it (the title says what, the thumbnail says the emotion, the number or the twist). Examples of the relationship: title "How I got 10k subscribers in 30 days" -> thumbnail "0 TO 10K"; title "Por qué dejé mi trabajo en Google" -> thumbnail "ME FUI".
|
||||
|
||||
Pick the top 2 and explain in one sentence each why they will win the click.
|
||||
{channel_rules}
|
||||
|
||||
OUTPUT JSON:
|
||||
{{
|
||||
"titles": ["...", ... 10 items],
|
||||
|
|
@ -184,50 +166,21 @@ OUTPUT JSON:
|
|||
}}"""
|
||||
|
||||
print("🧐 [Thumbnail] Scoring titles...")
|
||||
response = client.models.generate_content(
|
||||
model=TEXT_MODEL,
|
||||
contents=[critic_prompt],
|
||||
config=types.GenerateContentConfig(response_mime_type="application/json"),
|
||||
)
|
||||
try:
|
||||
picked = _parse_json(response.text)
|
||||
titles = [t for t in picked.get("titles", []) if isinstance(t, str) and t.strip()]
|
||||
if not titles:
|
||||
raise ValueError("no titles")
|
||||
except (json.JSONDecodeError, AttributeError, ValueError):
|
||||
print(f"⚠️ [Thumbnail] Critic failed, falling back to the brainstorm: {getattr(response, 'text', '')[:300]}")
|
||||
titles = candidates[:10]
|
||||
picked = {"thumbnail_texts": [], "recommended": []}
|
||||
|
||||
def _critic(violations=None):
|
||||
"""One critic call. ``violations`` appends the re-ask critique."""
|
||||
prompt = critic_prompt
|
||||
if violations:
|
||||
prompt = critic_prompt + "\n\n" + title_validation.critique_block(violations)
|
||||
response = client.models.generate_content(
|
||||
model=TEXT_MODEL,
|
||||
contents=[prompt],
|
||||
config=types.GenerateContentConfig(response_mime_type="application/json"),
|
||||
)
|
||||
try:
|
||||
picked_local = _parse_json(response.text)
|
||||
titles_local = [t for t in picked_local.get("titles", [])
|
||||
if isinstance(t, str) and t.strip()]
|
||||
if not titles_local:
|
||||
raise ValueError("no titles")
|
||||
except (json.JSONDecodeError, AttributeError, ValueError):
|
||||
print(f"⚠️ [Thumbnail] Critic failed: {getattr(response, 'text', '')[:300]}")
|
||||
return None
|
||||
texts_local = [str(t) for t in picked_local.get("thumbnail_texts", [])][:len(titles_local)]
|
||||
texts_local += [""] * (len(titles_local) - len(texts_local))
|
||||
return {
|
||||
"titles": titles_local,
|
||||
"thumbnail_texts": texts_local,
|
||||
"recommended": [r for r in picked_local.get("recommended", [])
|
||||
if isinstance(r, dict) and isinstance(r.get("index"), int)
|
||||
and 0 <= r["index"] < len(titles_local)],
|
||||
}
|
||||
|
||||
def _validate(candidate):
|
||||
if not candidate:
|
||||
return []
|
||||
return title_validation.validate_titles(candidate["titles"], profile)
|
||||
|
||||
# Deterministic QA (PLAN #3): one re-ask if the critic's titles break the
|
||||
# channel rules, then keep the best attempt. Never blocks the response.
|
||||
picked = title_validation.run_with_validation(
|
||||
_critic, _validate, lambda violations: _critic(violations))
|
||||
if picked is None:
|
||||
print("⚠️ [Thumbnail] Critic failed, falling back to the brainstorm candidates.")
|
||||
picked = {"titles": candidates[:10], "thumbnail_texts": [], "recommended": []}
|
||||
|
||||
titles = picked["titles"]
|
||||
thumbnail_texts = [str(t) for t in picked.get("thumbnail_texts", [])][:len(titles)]
|
||||
thumbnail_texts += [""] * (len(titles) - len(thumbnail_texts))
|
||||
return {
|
||||
|
|
@ -237,7 +190,9 @@ OUTPUT JSON:
|
|||
"language": language,
|
||||
"segments": segments,
|
||||
"video_duration": video_duration,
|
||||
"recommended": picked.get("recommended", []),
|
||||
"recommended": [r for r in picked.get("recommended", [])
|
||||
if isinstance(r, dict) and isinstance(r.get("index"), int)
|
||||
and 0 <= r["index"] < len(titles)],
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -415,15 +370,11 @@ def _crop_face_reference(frame_path, face_box, out_path):
|
|||
# ---------------------------------------------------------------------------
|
||||
|
||||
def plan_thumbnail_concepts(client, title, count, video_context="", extra_prompt="",
|
||||
thumbnail_text_hint="", has_person=False, language="en",
|
||||
profile=None):
|
||||
thumbnail_text_hint="", has_person=False, language="en"):
|
||||
"""
|
||||
One text call that designs `count` DIFFERENT thumbnails before any pixel is
|
||||
drawn. Asking the image model to invent the concept and render it in one
|
||||
go gives N variations of one idea; splitting it gives N ideas.
|
||||
|
||||
``profile`` (optional channel Profile, PLAN #1) adds the channel's palette,
|
||||
role order and presenter expectation; ``None`` leaves the prompt unchanged.
|
||||
"""
|
||||
person_line = ("A real photo of the presenter is provided and MUST be the focal point, "
|
||||
"with a clear, natural expression that reads at small size (no caricature)."
|
||||
|
|
@ -434,8 +385,6 @@ def plan_thumbnail_concepts(client, title, count, video_context="", extra_prompt
|
|||
hint_line = (f'\nSUGGESTED THUMBNAIL TEXT (use it for the first concept unless it is poor): "{thumbnail_text_hint}"'
|
||||
if thumbnail_text_hint else "")
|
||||
extra_line = f"\nMANDATORY USER INSTRUCTIONS (override everything else):\n{extra_prompt}\n" if extra_prompt else ""
|
||||
# Empty for profile=None, so the f-string below renders exactly as before.
|
||||
channel_rules = profile_prompts.thumbnail_block(profile)
|
||||
prompt = f"""You are a YouTube thumbnail art director. Design {count} DIFFERENT thumbnail concepts for this video.
|
||||
|
||||
VIDEO TITLE: "{title}"
|
||||
|
|
@ -445,18 +394,17 @@ VIDEO CONTEXT: {video_context or "(none)"}
|
|||
The thumbnail must show WHAT the video is about, not only how the presenter feels: name the concrete subject (the product, the tool, the result, the numbers) and build the picture around it. A face alone with two words is the lazy default; use it at most once, and only combined with a strong prop or scene.
|
||||
|
||||
Each concept must use a different device, e.g.: the presenter + a prop that IS the topic (a phone showing vertical clips, a laptop with the app, a counter/badge with the number); before/after or "long video -> short clips" split; product/UI hero shot with the presenter small; a giant number or stat as the hero with the subject behind; "X vs Y" comparison; a red circle/arrow on a detail; a dramatic reveal with depth (foreground object, blurred background). Layered, cinematic, premium: real props, depth of field, rim light, particles, glow on the key object. Never flat, never a plain wall behind the person. No two concepts may share the same text or the same layout.
|
||||
{channel_rules}
|
||||
|
||||
Per concept give:
|
||||
- "text": 1-4 words, ALL CAPS, in {language}. Complements the title (the title says what, the text says the emotion, the number or the twist). Never repeat the title. No emoji.
|
||||
- "text_position": one of "left", "right", "top", "bottom" (where the text block sits; the subject goes on the opposite side).
|
||||
- "text_color": "white" or "yellow" (yellow for money/energy, white otherwise).
|
||||
- "role": exactly one of "emotion", "technical", "curiosity" — the job this concept does for the click. Cover ALL THREE roles across the set (at least one of each): "emotion" is a human face or feeling, "technical" is the product, tool, code, diagram or concrete result, "curiosity" is a question, a reveal or a hidden detail.
|
||||
- "scene": a precise image-generation prompt in English, 2-4 sentences: subject, expression/pose, background, lighting, colours, camera. Say that the text_position side is clean negative space (simple, dark or plain) so a headline can sit there. It must NOT ask for any text, letters, captions or logos in the image.
|
||||
- The image model REFUSES prompts that name or depict real people, companies or brands. Never write a real name (person, company, product, logo) in "scene". Refer to the presenter only as "the person in the provided photo" when a photo is provided, otherwise as a generic, unnamed person or use objects and symbols.
|
||||
- "why": one short sentence on why this earns the click.
|
||||
|
||||
OUTPUT JSON:
|
||||
{{"concepts": [{{"text": "...", "text_position": "left", "text_color": "yellow", "role": "emotion", "scene": "...", "why": "..."}}, ...]}}"""
|
||||
{{"concepts": [{{"text": "...", "text_position": "left", "text_color": "yellow", "scene": "...", "why": "..."}}, ...]}}"""
|
||||
|
||||
response = client.models.generate_content(
|
||||
model=TEXT_MODEL,
|
||||
|
|
@ -468,96 +416,32 @@ OUTPUT JSON:
|
|||
except (json.JSONDecodeError, AttributeError):
|
||||
print(f"⚠️ [Thumbnail] Concept JSON unreadable, using a generic concept: {getattr(response, 'text', '')[:200]}")
|
||||
concepts = []
|
||||
role_order = list(profile.thumbnail.role_order) if profile else None
|
||||
return normalise_concepts(concepts, count, title, thumbnail_text_hint,
|
||||
role_order=role_order)
|
||||
return normalise_concepts(concepts, count, title, thumbnail_text_hint)
|
||||
|
||||
|
||||
# #4: every concept declares the job it does for the click, and the set must
|
||||
# cover emotion + technical. Kept here (not in the prompt alone) because a
|
||||
# prompt is not a contract.
|
||||
CONCEPT_ROLES = ("emotion", "technical", "curiosity")
|
||||
|
||||
_ROLE_SCENES = {
|
||||
"emotion": (
|
||||
"A dramatic, high-contrast YouTube thumbnail centred on a person's face and "
|
||||
"expression (surprise, focus or relief), warm rim light, blurred background, "
|
||||
"the {pos} side clean dark negative space."),
|
||||
"technical": (
|
||||
"A clean product/UI hero shot for a video titled '{title}': the tool, code, "
|
||||
"diagram or result sharp and large, cool cinematic light, the {pos} side "
|
||||
"clean dark negative space."),
|
||||
"curiosity": (
|
||||
"A cinematic reveal for a video titled '{title}': a key detail partly hidden "
|
||||
"or circled, depth of field, dramatic light, the {pos} side clean dark "
|
||||
"negative space."),
|
||||
}
|
||||
|
||||
|
||||
def _role_scene(role, title, position):
|
||||
template = _ROLE_SCENES.get(role, _ROLE_SCENES["curiosity"])
|
||||
return template.format(title=title, pos=position)
|
||||
|
||||
|
||||
def _fallback_concept(title, hint, role, position="left"):
|
||||
return {
|
||||
"text": (hint or "").upper()[:40],
|
||||
"text_position": position,
|
||||
"text_color": "white",
|
||||
"role": role,
|
||||
"scene": _role_scene(role, title, position),
|
||||
"why": f"fallback ({role})",
|
||||
}
|
||||
|
||||
|
||||
def normalise_concepts(concepts, count, title, thumbnail_text_hint="", role_order=None):
|
||||
"""Clamp model output to what the renderer accepts and pad to `count`.
|
||||
|
||||
Also enforces the #4 role mix: every concept carries a role and the set is
|
||||
guaranteed at least one "emotion" and one "technical" concept. A missing
|
||||
role is filled by converting the last available concept to a role-appropriate
|
||||
scene, so no concept is dropped.
|
||||
"""
|
||||
def normalise_concepts(concepts, count, title, thumbnail_text_hint=""):
|
||||
"""Clamp model output to what the renderer accepts and pad to `count`."""
|
||||
cleaned = []
|
||||
for c in concepts:
|
||||
if not isinstance(c, dict) or not c.get("scene"):
|
||||
continue
|
||||
role = c.get("role") if c.get("role") in CONCEPT_ROLES else None
|
||||
cleaned.append({
|
||||
"text": str(c.get("text") or thumbnail_text_hint or "").strip().upper()[:40],
|
||||
"text_position": c.get("text_position") if c.get("text_position") in TEXT_POSITIONS else "left",
|
||||
"text_color": "yellow" if c.get("text_color") == "yellow" else "white",
|
||||
"role": role,
|
||||
"scene": str(c["scene"]),
|
||||
"why": str(c.get("why", "")),
|
||||
})
|
||||
|
||||
order = [r for r in (role_order or []) if r in CONCEPT_ROLES] or list(CONCEPT_ROLES)
|
||||
while len(cleaned) < count:
|
||||
role = order[len(cleaned) % len(order)]
|
||||
cleaned.append(_fallback_concept(title, thumbnail_text_hint, role))
|
||||
cleaned = cleaned[:count]
|
||||
|
||||
if count < 2:
|
||||
return cleaned
|
||||
|
||||
present = {c["role"] for c in cleaned}
|
||||
used: set[int] = set()
|
||||
for role in ("emotion", "technical"):
|
||||
if role in present:
|
||||
continue
|
||||
target = next((c for c in reversed(cleaned)
|
||||
if c["role"] is None and id(c) not in used), None)
|
||||
if target is None:
|
||||
target = next((c for c in reversed(cleaned) if id(c) not in used), None)
|
||||
if target is None:
|
||||
break
|
||||
used.add(id(target))
|
||||
target["role"] = role
|
||||
target["scene"] = _role_scene(role, title, target["text_position"])
|
||||
target["why"] = target["why"] or f"{role} concept"
|
||||
present.add(role)
|
||||
return cleaned
|
||||
cleaned.append({
|
||||
"text": thumbnail_text_hint.upper()[:40],
|
||||
"text_position": "left",
|
||||
"text_color": "white",
|
||||
"scene": (f"A bold, high-contrast YouTube thumbnail scene for a video titled '{title}'. "
|
||||
"Dramatic lighting, vibrant colours, the left third is clean dark negative space."),
|
||||
"why": "fallback",
|
||||
})
|
||||
return cleaned[:count]
|
||||
|
||||
|
||||
def _wrap_lines(draw, text, font, max_width):
|
||||
|
|
@ -618,46 +502,8 @@ def burn_thumbnail_text(img, text, position="left", color="white"):
|
|||
else:
|
||||
x0, y0 = int(W * 0.04), H - total_h - int(H * 0.06) - top_pad
|
||||
|
||||
# Bottom-right safe area (#4): the headline must not sit under YouTube's
|
||||
# timestamp/badge corner nor run off the right edge. Whatever the requested
|
||||
# position, the rendered block is clamped inside the safe box.
|
||||
bottom_limit = int(H * (1.0 - THUMB_SAFE_BOTTOM))
|
||||
right_limit = int(W * (1.0 - THUMB_SAFE_RIGHT))
|
||||
left_limit = int(W * THUMB_SAFE_LEFT)
|
||||
top_limit = int(H * THUMB_SAFE_TOP)
|
||||
|
||||
center_x = W // 2
|
||||
ink_w = widest + stroke
|
||||
ink_h = total_h + stroke
|
||||
if horizontal:
|
||||
block_left, block_right = x0, x0 + ink_w
|
||||
else:
|
||||
block_left, block_right = center_x - ink_w // 2, center_x + ink_w // 2
|
||||
if block_right > right_limit:
|
||||
shift = block_right - right_limit
|
||||
if horizontal:
|
||||
x0 -= shift
|
||||
else:
|
||||
center_x -= shift
|
||||
if block_left < left_limit:
|
||||
shift = left_limit - block_left
|
||||
if horizontal:
|
||||
x0 += shift
|
||||
else:
|
||||
center_x += shift
|
||||
|
||||
visual_top = y0 + top_pad
|
||||
if visual_top < top_limit:
|
||||
y0 += top_limit - visual_top
|
||||
visual_top = top_limit
|
||||
if visual_top + ink_h > bottom_limit:
|
||||
y0 = bottom_limit - ink_h - top_pad
|
||||
y0 = max(y0, -top_pad) # keep the ink on the canvas
|
||||
|
||||
def line_x(line):
|
||||
if horizontal:
|
||||
return x0
|
||||
return center_x - int(draw.textlength(line, font=font)) // 2
|
||||
return x0 if horizontal else (W - draw.textlength(line, font=font)) // 2
|
||||
|
||||
shadow = Image.new("RGBA", img.size, (0, 0, 0, 0))
|
||||
sdraw = ImageDraw.Draw(shadow)
|
||||
|
|
@ -817,13 +663,11 @@ Style: high contrast, saturated colours, crisp subject separation, cinematic lig
|
|||
|
||||
def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_image_path=None,
|
||||
extra_prompt="", count=3, video_context="", burn_text=True,
|
||||
thumbnail_text_hint="", language="en", frame_reference=None,
|
||||
profile=None):
|
||||
thumbnail_text_hint="", language="en", frame_reference=None):
|
||||
"""
|
||||
Generates `count` thumbnails, each from its own concept, in parallel.
|
||||
frame_reference: {"path", "face"} from extract_face_frames, used as the
|
||||
person reference when the user picked a frame instead of uploading a photo.
|
||||
profile: optional channel Profile (PLAN #1), forwarded to the concept call.
|
||||
Returns [{"url", "text", "why"}] (only the ones that rendered).
|
||||
"""
|
||||
client = genai.Client(api_key=api_key)
|
||||
|
|
@ -844,8 +688,7 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag
|
|||
|
||||
concepts = plan_thumbnail_concepts(
|
||||
client, title, count, video_context=video_context, extra_prompt=extra_prompt,
|
||||
thumbnail_text_hint=thumbnail_text_hint, has_person=bool(reference_images),
|
||||
language=language, profile=profile)
|
||||
thumbnail_text_hint=thumbnail_text_hint, has_person=bool(reference_images), language=language)
|
||||
for i, c in enumerate(concepts):
|
||||
print(f"🎨 [Thumbnail] Concept {i + 1}: \"{c['text']}\" ({c['text_position']}) - {c['why']}")
|
||||
|
||||
|
|
@ -877,8 +720,7 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag
|
|||
fallback = True
|
||||
print(f"✅ [Thumbnail] Saved: {out_path}")
|
||||
return {"url": f"/thumbnails/{session_id}/{os.path.basename(out_path)}",
|
||||
"text": concept["text"], "why": concept["why"],
|
||||
"role": concept.get("role"), "fallback": fallback}
|
||||
"text": concept["text"], "why": concept["why"], "fallback": fallback}
|
||||
except Exception as e:
|
||||
print(f"❌ [Thumbnail] Generation {i + 1} failed: {e}")
|
||||
return {"error": str(e)}
|
||||
|
|
@ -897,12 +739,9 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag
|
|||
# Description
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def generate_youtube_description(api_key, title, transcript_segments, language, video_duration,
|
||||
profile=None):
|
||||
def generate_youtube_description(api_key, title, transcript_segments, language, video_duration):
|
||||
"""
|
||||
Uses Gemini to generate a YouTube description with chapter markers from transcript segments.
|
||||
``profile`` (optional channel Profile, PLAN #1) adds the channel's description
|
||||
structure, links and tone; ``None`` leaves the prompt unchanged.
|
||||
Returns: { "description": "full description text with chapters" }
|
||||
"""
|
||||
client = genai.Client(api_key=api_key)
|
||||
|
|
@ -923,9 +762,6 @@ def generate_youtube_description(api_key, title, transcript_segments, language,
|
|||
dur_secs = int(video_duration % 60)
|
||||
duration_str = f"{dur_mins}:{dur_secs:02d}"
|
||||
|
||||
# Empty for profile=None, so the f-string below renders exactly as before.
|
||||
channel_rules = profile_prompts.description_block(profile)
|
||||
|
||||
prompt = f"""You are a YouTube SEO expert. Generate a complete YouTube video description for the following video.
|
||||
|
||||
VIDEO TITLE: "{title}"
|
||||
|
|
@ -947,7 +783,7 @@ REQUIREMENTS:
|
|||
- Place chapters in their own section with a blank line before and after
|
||||
5. Add 5-10 relevant hashtags at the end
|
||||
6. Keep the total description under 5000 characters
|
||||
{channel_rules}
|
||||
|
||||
OUTPUT: Return ONLY the description text (no JSON wrapper, no markdown code blocks). The description should be ready to paste directly into YouTube."""
|
||||
|
||||
print("🤖 [Thumbnail] Generating YouTube description with chapters...")
|
||||
|
|
|
|||
|
|
@ -1,170 +0,0 @@
|
|||
"""Deterministic YouTube title QA (PLAN #3 + #4, merged).
|
||||
|
||||
No LLM call lives here: the rules are the active channel profile's
|
||||
``title_rules`` plus a few universal structural checks, so validation is cheap
|
||||
enough to run on every generated title and cannot itself hallucinate.
|
||||
|
||||
Two entry points:
|
||||
* :func:`validate_title` / :func:`validate_titles` return the list of human-
|
||||
readable violations for one title, or for a set (structural rules).
|
||||
* :func:`run_with_validation` wraps generation: try, and on violations re-ask
|
||||
exactly once with the critique; if the retry does not improve, keep the first
|
||||
attempt. It NEVER raises on a validation failure and never blocks the job.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import Counter
|
||||
|
||||
from clipwright.pipeline.profiles import Profile
|
||||
|
||||
# Task-descriptive openers that describe what the video *does* rather than what
|
||||
# the viewer gets. The profile's ``banned_openers`` add the channel's own.
|
||||
_TASK_OPENERS = (
|
||||
"in this video", "in today's video", "this video", "explaining", "discussing",
|
||||
"talking about", "a look at", "let's", "watch me", "i'm going to",
|
||||
"im going to", "here's how i", "step by step",
|
||||
)
|
||||
_TASK_OPENER_RE = re.compile(
|
||||
r"^(?:" + "|".join(re.escape(o) for o in _TASK_OPENERS) + r")\b", re.I)
|
||||
|
||||
# Words that carry no topic, so a title starting with one has not front-loaded
|
||||
# its keyword. This is the deterministic proxy for ``keyword_position="start"``
|
||||
# (the profile carries no keyword to locate precisely).
|
||||
_STOPWORDS = frozenset({
|
||||
"the", "a", "an", "this", "that", "these", "those", "my", "your", "our",
|
||||
"their", "his", "her", "its", "it", "i", "we", "you", "they", "he", "she",
|
||||
"is", "are", "was", "were", "be", "been", "being", "as", "if", "when",
|
||||
"while", "so", "just", "in", "on", "at", "of", "for", "to", "with", "from",
|
||||
"by", "and", "but", "or",
|
||||
})
|
||||
|
||||
# Broad cue sets for required_signal. Deliberately generous: a false negative
|
||||
# would force a retry, and a false positive only lets a weaker title through.
|
||||
_CONSEQUENCE_RE = re.compile(
|
||||
r"\b(why|because|so that|cost|costs|costing|ruin|ruined|ruins|broke|broken|"
|
||||
r"breaks|lost|lose|loses|win|won|wins|crashed|crash|crashes|fail|failed|"
|
||||
r"fails|failure|change|changed|changes|makes|made|turns|turned|becomes|became|"
|
||||
r"stops|stopped|kills|killed|destroy|destroyed|saved|saves|before|after|"
|
||||
r"mistake|mistakes|warning|warns|secretly|almost|never again|no longer|"
|
||||
r"instead)\b", re.I)
|
||||
_CURIOSITY_RE = re.compile(
|
||||
r"\?|\b(why|how|what|secret|truth|real reason|reason|hidden|nobody|everyone|"
|
||||
r"no one|shouldn'?t|should not|impossible|actually|forgot|forgotten|never|"
|
||||
r"finally|revealed|reveal|mystery|unknown|here'?s|looks like|seems)\b", re.I)
|
||||
|
||||
|
||||
def _first_word(title: str) -> str:
|
||||
match = re.match(r"\s*([A-Za-zÀ-ÿ0-9']+)", title or "")
|
||||
return match.group(1).lower() if match else ""
|
||||
|
||||
|
||||
def validate_title(title: str, profile: Profile | None) -> list[str]:
|
||||
"""Every reason this one title breaks the profile's title rules.
|
||||
|
||||
Structural checks (task-descriptive openers) run with or without a profile;
|
||||
the profile-specific checks are skipped when ``profile`` is None.
|
||||
"""
|
||||
title = (title or "").strip()
|
||||
if not title:
|
||||
return ["title is empty"]
|
||||
|
||||
problems: list[str] = []
|
||||
rules = getattr(profile, "title_rules", None)
|
||||
if rules is not None:
|
||||
if len(title) > rules.max_chars:
|
||||
problems.append(f"{len(title)} chars exceeds the {rules.max_chars}-char maximum")
|
||||
elif len(title) > rules.mobile_chars:
|
||||
problems.append(
|
||||
f"{len(title)} chars exceeds the {rules.mobile_chars}-char mobile limit")
|
||||
lowered = title.lower()
|
||||
for pattern in rules.banned_patterns:
|
||||
if pattern.lower() in lowered:
|
||||
problems.append(f'uses the banned phrase "{pattern}"')
|
||||
for opener in rules.banned_openers:
|
||||
if lowered.startswith(opener.lower()):
|
||||
problems.append(f'opens with the banned opener "{opener}"')
|
||||
break
|
||||
first = _first_word(title)
|
||||
if rules.keyword_position == "start" and first in _STOPWORDS:
|
||||
problems.append(f'starts with the filler word "{first}" instead of the keyword')
|
||||
if rules.number_policy == "avoid" and re.search(r"\d", title):
|
||||
problems.append("uses a number where the channel avoids them")
|
||||
elif rules.number_policy == "require" and not re.search(r"\d", title):
|
||||
problems.append("has no number, which this channel requires")
|
||||
signal = rules.required_signal
|
||||
consequence = bool(_CONSEQUENCE_RE.search(title))
|
||||
curiosity = bool(_CURIOSITY_RE.search(title))
|
||||
if signal == "consequence" and not consequence:
|
||||
problems.append("carries no consequence or stake")
|
||||
elif signal == "curiosity" and not curiosity:
|
||||
problems.append("opens no curiosity gap the video pays off")
|
||||
elif signal == "either" and not (consequence or curiosity):
|
||||
problems.append("carries no consequence or curiosity signal")
|
||||
|
||||
if _TASK_OPENER_RE.match(title):
|
||||
problems.append("opens with a task-descriptive phrase")
|
||||
return problems
|
||||
|
||||
|
||||
def validate_titles(titles, profile: Profile | None) -> list[str]:
|
||||
"""Per-title violations plus the structural rules that span a title set."""
|
||||
clean = [t for t in (titles or []) if isinstance(t, str) and t.strip()]
|
||||
problems: list[str] = []
|
||||
for i, title in enumerate(clean):
|
||||
for problem in validate_title(title, profile):
|
||||
problems.append(f"title {i + 1}: {problem}")
|
||||
|
||||
if not clean:
|
||||
problems.append("no titles")
|
||||
|
||||
firsts = Counter(_first_word(t) for t in clean)
|
||||
for word, count in firsts.items():
|
||||
if word and count > 3:
|
||||
problems.append(f'{count} titles start with the same word "{word}" (max 3)')
|
||||
colons = sum(1 for t in clean if ":" in t)
|
||||
if colons > 2:
|
||||
problems.append(f"{colons} titles use a colon pattern (max 2)")
|
||||
return problems
|
||||
|
||||
|
||||
def critique_block(violations) -> str:
|
||||
"""An instruction block that hands the model the exact violations to fix."""
|
||||
lines = ["VALIDATION FAILED — the previous titles broke these rules:"]
|
||||
lines += [f"- {v}" for v in violations]
|
||||
lines.append("Rewrite the titles so every rule passes; keep every other instruction.")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def run_with_validation(generate, validate, retry_once):
|
||||
"""Try ``generate``; on violations re-ask exactly once and keep the best.
|
||||
|
||||
``generate()`` -> candidate
|
||||
``validate(candidate)`` -> list of violations
|
||||
``retry_once(violations)`` -> a new candidate, or None if it could not run
|
||||
|
||||
Returns the candidate with the fewest violations (the first one on a tie or
|
||||
a failed retry). Never raises because of a validation failure.
|
||||
"""
|
||||
candidate = generate()
|
||||
violations = list(validate(candidate) or [])
|
||||
if not violations:
|
||||
return candidate
|
||||
|
||||
try:
|
||||
retry = retry_once(violations)
|
||||
except Exception as e: # a broken retry must not lose the first attempt
|
||||
print(f"⚠️ [titles] validation retry failed ({e}); keeping the first attempt.")
|
||||
return candidate
|
||||
if retry is None:
|
||||
return candidate
|
||||
|
||||
retry_violations = list(validate(retry) or [])
|
||||
if len(retry_violations) < len(violations):
|
||||
print(f"✅ [titles] retry reduced violations "
|
||||
f"{len(violations)} -> {len(retry_violations)}.")
|
||||
return retry
|
||||
print(f"⚠️ [titles] retry did not improve "
|
||||
f"({len(violations)} -> {len(retry_violations)}); keeping the first attempt.")
|
||||
return candidate
|
||||
|
|
@ -1,207 +0,0 @@
|
|||
"""Shorts -> long-form bridge copy (PLAN #6).
|
||||
|
||||
Pure, network-free helpers that turn the active channel profile (+ its
|
||||
``published_video_history``) into the copy a Short needs to funnel viewers to a
|
||||
long-form video:
|
||||
|
||||
* ``description_bridge`` -- a block appended to the Short's YouTube description;
|
||||
* ``first_comment`` -- the top-level comment to post (and pin).
|
||||
|
||||
Two "related video" features are Studio-UI only and are **not** exposed by any
|
||||
API: the Shorts "Related video" link and comment pinning. Those therefore stay
|
||||
manual, and ``checklist`` spells out the exact Studio steps including the
|
||||
target long-form URL.
|
||||
|
||||
The explicit target wins over the profile history. Callers pass it from the CLI
|
||||
(``--longform-url``) or the API (``related_video_url``); nothing here performs
|
||||
I/O.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Mapping, Optional
|
||||
|
||||
from clipwright.pipeline import profile_prompts
|
||||
from clipwright.pipeline.profiles import Profile
|
||||
|
||||
# Fallback label when the target URL is provided but the profile says nothing.
|
||||
DEFAULT_TARGET_LABEL = "Full video"
|
||||
|
||||
# Keys a published_video_history entry may carry to identify the video. The
|
||||
# first match wins; ``id``/``video_id`` build a watch URL.
|
||||
_URL_KEYS = ("url", "video_url", "watch_url", "link")
|
||||
_ID_KEYS = ("id", "video_id", "youtube_id")
|
||||
_DATE_KEYS = ("published_at", "published", "date", "uploaded_at")
|
||||
|
||||
|
||||
def _entry_url(entry: Mapping) -> Optional[str]:
|
||||
"""The watch URL for one ``published_video_history`` entry, or None."""
|
||||
if not isinstance(entry, Mapping):
|
||||
return None
|
||||
for key in _URL_KEYS:
|
||||
value = entry.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
for key in _ID_KEYS:
|
||||
value = entry.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return f"https://www.youtube.com/watch?v={value.strip()}"
|
||||
return None
|
||||
|
||||
|
||||
def _entry_sort_key(entry: Mapping) -> str:
|
||||
for key in _DATE_KEYS:
|
||||
value = entry.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def target_video(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None) -> Optional[str]:
|
||||
"""The long-form target: the explicit URL, else the newest history entry.
|
||||
|
||||
An explicit ``related_video_url`` always wins. Otherwise the profile's
|
||||
``published_video_history`` is searched for an entry that names a video
|
||||
(``url``/``video_url``/... or an ``id``); the newest by a best-effort date
|
||||
field is chosen, falling back to the last entry listed.
|
||||
"""
|
||||
if isinstance(related_video_url, str) and related_video_url.strip():
|
||||
return related_video_url.strip()
|
||||
history = list(getattr(profile, "published_video_history", None) or [])
|
||||
candidates = [(k, e) for e in history if (k := _entry_url(e))]
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda pair: _entry_sort_key(pair[1]))
|
||||
return candidates[-1][0]
|
||||
|
||||
|
||||
def _target_label(profile: Optional[Profile]) -> str:
|
||||
"""A human label for the target, derived from the profile's description."""
|
||||
template = getattr(profile, "description_template", "") if profile else ""
|
||||
# Templates look like "{hook}\n\nFull video: {link}\n\n#tags" -- lift the
|
||||
# words before "{link}" when they name the long-form video.
|
||||
if "{link}" in template:
|
||||
prefix = template.split("{link}")[0].strip().splitlines()[-1].strip()
|
||||
prefix = prefix.rstrip(":").strip()
|
||||
if prefix and "{hook}" not in prefix:
|
||||
return prefix
|
||||
return DEFAULT_TARGET_LABEL
|
||||
|
||||
|
||||
def _clip_hook(clip: Optional[Mapping]) -> str:
|
||||
"""The clip's hook text if the pipeline produced one, else its title."""
|
||||
if not isinstance(clip, Mapping):
|
||||
return ""
|
||||
for key in ("viral_hook_text", "hook_text", "video_title_for_youtube_short"):
|
||||
value = clip.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _render_description_template(template: str, target: Optional[str],
|
||||
clip: Optional[Mapping]) -> str:
|
||||
"""Fill the profile's ``{hook}``/``{link}`` slots without str.format.
|
||||
|
||||
``str.format`` would explode on any other brace in the template (or
|
||||
hashtags that are fine today); a literal replace can only touch the two
|
||||
documented placeholders.
|
||||
"""
|
||||
rendered = template.replace("{hook}", _clip_hook(clip))
|
||||
rendered = rendered.replace("{link}", target or "")
|
||||
return "\n".join(line.rstrip() for line in rendered.splitlines()).strip()
|
||||
|
||||
|
||||
def description_bridge(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None,
|
||||
clip: Optional[Mapping] = None) -> str:
|
||||
"""The description block: a target CTA plus the profile's description copy.
|
||||
|
||||
The target URL appears first (and in the rendered template when the profile
|
||||
has one). Without a target the channel links/description still render, so a
|
||||
bridge is produced even before a long-form URL is chosen.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
parts: list[str] = []
|
||||
if target:
|
||||
parts.append(f"▶ {_target_label(profile)}: {target}")
|
||||
|
||||
template = (getattr(profile, "description_template", "") if profile else "") or ""
|
||||
rendered = _render_description_template(template, target, clip) if template else ""
|
||||
if rendered:
|
||||
parts.append(rendered)
|
||||
else:
|
||||
# No template: fall back to the profile's plain description block.
|
||||
block = profile_prompts.description_block(profile) if profile else ""
|
||||
if block:
|
||||
parts.append(block.rstrip())
|
||||
|
||||
# The profile's links belong in the bridge even when the template's {link}
|
||||
# slot was empty (no target yet) or the template does not mention them.
|
||||
links = [link for link in (getattr(profile, "links", None) or [])
|
||||
if isinstance(link, str) and link.strip()]
|
||||
if links and not any(link in "\n".join(parts) for link in links):
|
||||
parts.append("More from this channel: " + " | ".join(links))
|
||||
|
||||
return "\n\n".join(p for p in parts if p).strip()
|
||||
|
||||
|
||||
def first_comment(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None,
|
||||
clip: Optional[Mapping] = None) -> str:
|
||||
"""The top-level comment text. Always carries the long-form reference.
|
||||
|
||||
With no target it points at the channel's links (or the description) rather
|
||||
than inventing a URL; it is never empty.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
hook = _clip_hook(clip)
|
||||
if target:
|
||||
text = f"▶ {_target_label(profile)}: {target}"
|
||||
if hook:
|
||||
text += f"\n\n{_target_label(profile)} covers this: {hook}"
|
||||
return text
|
||||
links = list(getattr(profile, "links", None) or [])
|
||||
if links:
|
||||
return f"Watch the long-form videos here: {links[0]}"
|
||||
return "The full long-form video is linked in the description."
|
||||
|
||||
|
||||
def checklist(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None) -> list[str]:
|
||||
"""The manual Studio steps for this Short (both are Studio-UI only).
|
||||
|
||||
The Shorts "Related video" link and comment pinning have no public API, so
|
||||
they are copy-paste steps, not something the server can do.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
target_text = target or "<paste the long-form video URL>"
|
||||
return [
|
||||
"Open YouTube Studio -> Content -> this Short -> Edit.",
|
||||
f"Details -> Related video: set it to {target_text} "
|
||||
"(the Shorts related-video link is Studio-UI only; no API can set it).",
|
||||
"Post the generated first comment "
|
||||
"(or call this clip's bridge/comment endpoint if the YouTube Data API "
|
||||
"is configured).",
|
||||
"Pin the first comment: hover it -> the three-dot menu -> Pin. "
|
||||
"Pinning stays manual (no API).",
|
||||
]
|
||||
|
||||
|
||||
def build_bridge(profile: Optional[Profile],
|
||||
clip: Optional[Mapping] = None,
|
||||
related_video_url: Optional[str] = None) -> dict[str, Any]:
|
||||
"""All bridge fields for one clip, ready to merge into clip metadata.
|
||||
|
||||
``related_video_url`` is the explicit target (CLI ``--longform-url`` / API
|
||||
``related_video_url``); when omitted the profile history is used.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
return {
|
||||
"related_video_url": target,
|
||||
"description_bridge": description_bridge(profile, target, clip),
|
||||
"first_comment": first_comment(profile, target, clip),
|
||||
"checklist": checklist(profile, target),
|
||||
"manual_pin_required": True,
|
||||
}
|
||||
|
|
@ -5,8 +5,6 @@ Standard-library only so both main.py and gemini_worker.py can import it and
|
|||
the logic stays unit-testable without the heavy video dependencies.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# USD per 1M tokens (input, output incl. thinking), from ai.google.dev pricing.
|
||||
MODEL_PRICES = {
|
||||
"gemini-3.5-flash": (1.50, 9.00),
|
||||
|
|
@ -350,185 +348,3 @@ def snap_clip_to_words(start, end, words, video_duration,
|
|||
if new_end <= new_start or new_end - new_start < min_duration:
|
||||
return original
|
||||
return (round(new_start, 3), round(new_end, 3))
|
||||
|
||||
|
||||
# --- Hook-first boundaries (#2a) -------------------------------------------
|
||||
# The first seconds decide the swipe. A model-proposed clip routinely opens on
|
||||
# wind-up ("so today we're going to...") and buries the question, the number or
|
||||
# the stakes 3-8s in. Word timestamps are ground truth, so the start can be
|
||||
# moved onto the first strong spoken hook deterministically — no LLM, no key.
|
||||
#
|
||||
# These are the signal vocabularies the scan combines. A token matching ANY set
|
||||
# is a hook; the EARLIEST such token inside the allowed trim window wins. They
|
||||
# are deliberately conservative: a miss leaves the clip untouched, a false
|
||||
# positive only advances the start a bounded amount (see the env caps).
|
||||
_HOOK_INTERROGATIVES = frozenset({
|
||||
"what", "why", "how", "when", "where", "who", "whom", "whose", "which",
|
||||
"is", "are", "was", "were", "do", "does", "did", "can", "could", "would",
|
||||
"should", "will", "shall",
|
||||
})
|
||||
_HOOK_IMPERATIVES = frozenset({
|
||||
"look", "watch", "imagine", "think", "stop", "try", "check", "see",
|
||||
"listen", "remember", "forget", "consider", "notice", "suppose", "picture",
|
||||
"keep", "take", "put", "go", "come", "use", "make", "let", "dont", "show",
|
||||
"tell", "explain", "build", "create", "write", "read", "open", "close",
|
||||
"click", "press", "type", "install", "run", "fix", "never", "always",
|
||||
})
|
||||
_HOOK_NUMBERS = frozenset({
|
||||
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
|
||||
"nine", "ten", "eleven", "twelve", "hundred", "thousand", "million",
|
||||
"billion", "half", "quarter", "twice", "once", "double", "triple",
|
||||
"dozen", "percent", "first", "second", "third",
|
||||
})
|
||||
_HOOK_CONTRAST = frozenset({
|
||||
"but", "until", "actually", "instead", "except", "however", "though",
|
||||
"although", "whereas", "yet", "still", "suddenly", "wait", "unless",
|
||||
"otherwise", "despite", "nevertheless", "contrary", "opposite", "reverse",
|
||||
})
|
||||
_HOOK_STAKES = frozenset({
|
||||
"never", "always", "first", "worst", "bug", "bugs", "crash", "crashes",
|
||||
"crashed", "crashing", "broke", "broken", "break", "wrong", "lost", "lose",
|
||||
"losing", "fail", "failed", "fails", "failure", "dies", "death", "dead",
|
||||
"kill", "killed", "destroy", "destroyed", "ruin", "ruined", "disaster",
|
||||
"mistake", "error", "errors", "segfault", "danger", "dangerous", "scared",
|
||||
"terrified", "panic", "emergency", "critical", "fatal", "illegal",
|
||||
"corrupt", "corrupted", "hacked", "stolen", "missing", "gone", "worse",
|
||||
})
|
||||
# Pure hesitation / connective words that are never hooks. The scan simply
|
||||
# walks past them, so they end up in the trimmed wind-up; they must not count.
|
||||
_HOOK_FILLER = frozenset({
|
||||
"uh", "um", "erm", "ah", "eh", "hmm", "mmm", "so", "well", "okay", "ok",
|
||||
"yeah", "yep", "right", "and", "then", "like", "basically", "just",
|
||||
"you", "know", "i", "mean", "we", "the", "a", "an", "it", "that", "this",
|
||||
})
|
||||
|
||||
# Conservative defaults: HOOK_FIRST is on, but a start only ever moves a few
|
||||
# seconds and never more than a quarter of the clip.
|
||||
_HOOK_FIRST_DEFAULT_MAX_TRIM = 4.0
|
||||
_HOOK_FIRST_DEFAULT_MAX_FRACTION = 0.25
|
||||
# A trim smaller than this is noise; leaving the clip alone is kinder than a
|
||||
# sub-frame jitter that only complicates the render.
|
||||
_MIN_HOOK_TRIM = 0.2
|
||||
|
||||
|
||||
def _env_float(name, default):
|
||||
"""Read a float env var, falling back to ``default`` on garbage/absence."""
|
||||
import os
|
||||
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return float(raw)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def hook_first_enabled():
|
||||
"""Whether to move clip starts onto the first spoken hook.
|
||||
|
||||
``HOOK_FIRST`` defaults ON (conservatively capped); set it to ``0`` /
|
||||
``false`` / ``no`` / ``off`` to disable the pass for A/B runs.
|
||||
"""
|
||||
import os
|
||||
|
||||
raw = os.environ.get("HOOK_FIRST")
|
||||
if raw is None:
|
||||
return True
|
||||
return str(raw).strip().lower() not in ("", "0", "false", "no", "off")
|
||||
|
||||
|
||||
def _hook_token(raw):
|
||||
"""Normalise a Whisper word to a bare lowercase token.
|
||||
|
||||
Words are inconsistent about a leading space (" word" vs "word") and carry
|
||||
trailing punctuation ("crash!"), so both are stripped before matching.
|
||||
"""
|
||||
token = str(raw or "").strip().lower()
|
||||
token = re.sub(r"^[^0-9a-z]+", "", token)
|
||||
token = re.sub(r"[^0-9a-z]+$", "", token)
|
||||
return token
|
||||
|
||||
|
||||
def _is_hook_token(token):
|
||||
"""True when a normalised token carries one of the hook signals."""
|
||||
if not token or token in _HOOK_FILLER:
|
||||
return False
|
||||
if any(ch.isdigit() for ch in token):
|
||||
return True
|
||||
return (token in _HOOK_INTERROGATIVES
|
||||
or token in _HOOK_IMPERATIVES
|
||||
or token in _HOOK_NUMBERS
|
||||
or token in _HOOK_CONTRAST
|
||||
or token in _HOOK_STAKES)
|
||||
|
||||
|
||||
def find_hook_start(words, clip_start, clip_end, min_duration=15.0,
|
||||
max_trim=None, max_fraction=None):
|
||||
"""The strongest deterministic start for a clip, or ``None``.
|
||||
|
||||
Scans the opening of ``[clip_start, clip_end]`` for the EARLIEST word that
|
||||
matches a hook signal (question, imperative, number/quantity, contrast or
|
||||
stakes — see the vocabularies above). Leading hesitation, silence and
|
||||
filler do not match, so they fall into the trimmed wind-up. Returns the
|
||||
hook word's start when it is a legal trim, else ``None`` (no change — a
|
||||
clip without a clear hook is left exactly where snapping put it).
|
||||
|
||||
``words`` is the whole-video ``[{'w','s','e'}, ...]`` list (same shape
|
||||
``snap_clip_to_words`` takes). The trim is bounded three ways so the pass
|
||||
can never wreck a clip:
|
||||
|
||||
* ``max_trim`` seconds (env ``HOOK_FIRST_MAX_TRIM``, default 4.0)
|
||||
* ``max_fraction`` of the clip's duration (env ``HOOK_FIRST_MAX_FRACTION``,
|
||||
default 0.25)
|
||||
* the remaining clip must still be at least ``min_duration`` seconds.
|
||||
"""
|
||||
try:
|
||||
clip_start = float(clip_start)
|
||||
clip_end = float(clip_end)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
duration = clip_end - clip_start
|
||||
if duration <= 0:
|
||||
return None
|
||||
|
||||
if max_trim is None:
|
||||
max_trim = _env_float("HOOK_FIRST_MAX_TRIM",
|
||||
_HOOK_FIRST_DEFAULT_MAX_TRIM)
|
||||
if max_fraction is None:
|
||||
max_fraction = _env_float("HOOK_FIRST_MAX_FRACTION",
|
||||
_HOOK_FIRST_DEFAULT_MAX_FRACTION)
|
||||
try:
|
||||
max_trim = max(0.0, float(max_trim))
|
||||
max_fraction = max(0.0, float(max_fraction))
|
||||
min_duration = float(min_duration)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
cap = min(max_trim, max_fraction * duration)
|
||||
if cap < _MIN_HOOK_TRIM:
|
||||
return None
|
||||
latest = clip_start + cap
|
||||
|
||||
hook_start = None
|
||||
for word in words or []:
|
||||
try:
|
||||
word_start = float(word.get("s", 0))
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
continue
|
||||
if word_start < clip_start or word_start > latest:
|
||||
continue
|
||||
if word_start >= clip_end:
|
||||
continue
|
||||
if _is_hook_token(_hook_token(word.get("w"))):
|
||||
if hook_start is None or word_start < hook_start:
|
||||
hook_start = word_start
|
||||
|
||||
if hook_start is None:
|
||||
return None
|
||||
trim = hook_start - clip_start
|
||||
if trim < _MIN_HOOK_TRIM:
|
||||
return None
|
||||
if clip_end - hook_start < min_duration:
|
||||
return None
|
||||
return round(hook_start, 3)
|
||||
|
|
|
|||
|
|
@ -157,13 +157,6 @@ Pick ONE layout:
|
|||
in both runs, while overall accuracy fell from 92% to 83-85%. camera_inset.py
|
||||
finds the same five geometrically with no false positives, so that question is
|
||||
answered downstream instead of being asked here.)
|
||||
- "code": a screen recording of code — an IDE or a terminal — where the viewer
|
||||
must read the source itself (a programming tutorial, a live debug, a shell
|
||||
session). ONLY when monospaced text fills the screen and reading it is the
|
||||
point; a slide or a spreadsheet is "screencast", not this. This option is
|
||||
UNVALIDATED: it was added for a CODE layout that is off by default
|
||||
(CODE_LAYOUT) and must be shadow-run on a corpus before it is relied on. When
|
||||
unsure, answer "none" or "screencast".
|
||||
- "split": stack two people. ONLY when two people are visible IN THE SAME SHOT
|
||||
at the same time in most frames, talking to each other. Frames that alternate
|
||||
between one-person close-ups are NOT this, however many people appear.
|
||||
|
|
@ -330,7 +323,7 @@ COPY RULES — ALL text fields (descriptions, title, hook) MUST be written in TR
|
|||
- `why`: one sentence, max 20 words, naming what makes THIS moment worth a
|
||||
clip — the specific hook, claim, number or payoff, not the topic.
|
||||
|
||||
{profile_rules}TRANSCRIPT_LANGUAGE: {language}
|
||||
TRANSCRIPT_LANGUAGE: {language}
|
||||
VIDEO_DURATION_SECONDS: {video_duration}
|
||||
CANDIDATE_WINDOWS_JSON:
|
||||
{windows_json}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ import json
|
|||
import os
|
||||
from typing import Optional
|
||||
|
||||
SCREEN_LAYOUTS = {"screencast", "code", "wide", "inset"}
|
||||
SCREEN_LAYOUTS = {"screencast", "wide", "inset"}
|
||||
FRAMES = int(os.environ.get("HOOK_GROUNDING_FRAMES", "3"))
|
||||
WIDTH = int(os.environ.get("HOOK_GROUNDING_WIDTH", "1024"))
|
||||
# Ignore a blip: the screen stretches must cover this share of the clip.
|
||||
|
|
|
|||
|
|
@ -21,17 +21,12 @@ from google import genai
|
|||
from google.genai import types as genai_types
|
||||
|
||||
from clipwright.media import frame_sampler
|
||||
from clipwright.media.subtitles import merge_continuation_words
|
||||
from clipwright.pipeline import bridge
|
||||
from clipwright.pipeline import gemini_worker
|
||||
from clipwright.pipeline import hook_grounding
|
||||
from clipwright.pipeline.profiles import ProfileError, load_profile
|
||||
from clipwright.pipeline import profile_prompts
|
||||
from clipwright.layouts import layout_picker
|
||||
from clipwright.pipeline import llm_backend
|
||||
from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets,
|
||||
clip_duration_bounds, dedupe_overlapping,
|
||||
find_hook_start, hook_first_enabled,
|
||||
score_batches, shortlist_target,
|
||||
snap_clip_to_words, trim_to_best)
|
||||
from clipwright.media.ffmpeg_utils import (video_encode_args, cut_clip,
|
||||
|
|
@ -48,11 +43,6 @@ load_dotenv()
|
|||
# --- Constants ---
|
||||
ASPECT_RATIO = 9 / 16
|
||||
|
||||
# Active per-channel profile (PLAN #1 v0). Populated from --channel / the
|
||||
# CHANNEL_PROFILE env var in __main__; None when the job runs channel-less.
|
||||
# Nothing reads it for generation yet -- later items (#3/#4/#6) will.
|
||||
ACTIVE_PROFILE = None
|
||||
|
||||
# Load the YOLO model once (Keep for backup or scene analysis if needed)
|
||||
# YOLO_MODEL_PATH lets deployments point at a pre-downloaded weights file so a
|
||||
# volume mounted over the workdir doesn't trigger a re-download at startup.
|
||||
|
|
@ -1310,55 +1300,30 @@ def auto_hook_clip(clip_path, clip, captions=None):
|
|||
|
||||
|
||||
def render_clip(input_video, final_output_video, output_format="auto",
|
||||
force_strategy=None, crop_overrides=None, word_times=None):
|
||||
force_strategy=None, crop_overrides=None):
|
||||
"""Route a cut clip through the right renderer for the chosen output format.
|
||||
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep.
|
||||
``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the
|
||||
clip editor's whole-clip framing override. ``crop_overrides`` positions
|
||||
individual scenes by hand (the per-scene reframing editor) and wins over
|
||||
``force_strategy`` for the scenes it names. ``word_times`` are optional
|
||||
clip-relative word onsets (seconds, clip start = 0) that steer punch-ins."""
|
||||
``force_strategy`` for the scenes it names."""
|
||||
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,
|
||||
force_strategy=force_strategy,
|
||||
crop_overrides=crop_overrides,
|
||||
word_times=word_times)
|
||||
|
||||
|
||||
def clip_word_onsets(transcript, clip_start, clip_end):
|
||||
"""Clip-relative onset seconds for the words spoken inside a clip.
|
||||
|
||||
The punch-in path wants "when a word started" on the cut clip's timeline
|
||||
(0 = ``clip_start``). A word that straddles a boundary still contributes:
|
||||
one already underway when the clip opens lands at 0, one crossing the end
|
||||
lands at the clip's duration. Returns [] when the transcript has no word
|
||||
timings, which leaves the audio envelope as the only beat source.
|
||||
"""
|
||||
if not transcript or clip_end <= clip_start:
|
||||
return []
|
||||
span = clip_end - clip_start
|
||||
onsets = []
|
||||
for seg in transcript.get("segments", []) or []:
|
||||
for word in seg.get("words") or []:
|
||||
if word.get("end", 0) <= clip_start or word.get("start", 0) >= clip_end:
|
||||
continue
|
||||
onset = word.get("start", 0) - clip_start
|
||||
onsets.append(round(min(max(onset, 0.0), span), 3))
|
||||
return sorted(onsets)
|
||||
crop_overrides=crop_overrides)
|
||||
|
||||
|
||||
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO,
|
||||
force_strategy=None, crop_overrides=None, word_times=None):
|
||||
force_strategy=None, crop_overrides=None):
|
||||
"""
|
||||
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).
|
||||
force_strategy / crop_overrides pin layouts and scene crops by hand (v2
|
||||
engine only — the v1 loop below has no layout concept beyond its own
|
||||
classifier). word_times feeds clip-relative word onsets to the punch-in
|
||||
beats (v2 only; the v1 loop has no punch-ins).
|
||||
classifier).
|
||||
"""
|
||||
# v2 engine: analyze downscaled, render natively in ffmpeg. Any failure
|
||||
# falls back to the v1 frame loop below so a v2 edge case can't kill jobs.
|
||||
|
|
@ -1368,8 +1333,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
|
|||
t0 = time.time()
|
||||
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
|
||||
force_strategy=force_strategy,
|
||||
crop_overrides=crop_overrides,
|
||||
word_times=word_times)
|
||||
crop_overrides=crop_overrides)
|
||||
print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s")
|
||||
return result
|
||||
except Exception as e:
|
||||
|
|
@ -1629,93 +1593,6 @@ def clear_transcript_checkpoint(output_dir):
|
|||
print(f"⚠️ Could not remove transcript checkpoint: {e}")
|
||||
|
||||
|
||||
# The only handoff manifest schema this build understands (cadence PLAN #8).
|
||||
HANDOFF_SCHEMA = "clipwright.handoff/1"
|
||||
# The master's measured duration may differ from the manifest's edited timeline
|
||||
# by this fraction before we refuse to align the edited-timeline transcript.
|
||||
HANDOFF_DURATION_TOLERANCE = 0.01
|
||||
|
||||
|
||||
class HandoffError(Exception):
|
||||
"""A cadence handoff manifest is missing, invalid or does not match the master."""
|
||||
|
||||
|
||||
def load_handoff_transcript(manifest_path, input_video, duration):
|
||||
"""Load the cadence-edited transcript a handoff manifest points at.
|
||||
|
||||
Cadence emits word tokens with a leading space and compound fragments
|
||||
without one (cadence PLAN #8, design rule #1), so every segment's words are
|
||||
run through ``merge_continuation_words`` on load. Missing ``words`` lists
|
||||
are left alone.
|
||||
|
||||
The manifest's ``edited.master`` is null in v1: the video passed via ``-i``
|
||||
/ ``-u`` *is* the master, so its measured ``duration`` must match
|
||||
``edited.duration`` within +/-1% or the edited-timeline alignment is not
|
||||
trustworthy. ``sources[].path`` is never opened: those are emitter-local
|
||||
paths (never honor a remote manifest's file references).
|
||||
|
||||
Raises ``HandoffError`` on any problem; the caller decides whether to refuse
|
||||
the job.
|
||||
"""
|
||||
manifest_path = os.path.abspath(manifest_path)
|
||||
try:
|
||||
with open(manifest_path, encoding="utf-8") as f:
|
||||
manifest = json.load(f)
|
||||
except FileNotFoundError:
|
||||
raise HandoffError(f"handoff manifest not found: {manifest_path}")
|
||||
except json.JSONDecodeError as e:
|
||||
raise HandoffError(f"malformed handoff manifest {manifest_path}: {e}")
|
||||
except OSError as e:
|
||||
raise HandoffError(f"could not read handoff manifest {manifest_path}: {e}")
|
||||
if not isinstance(manifest, dict):
|
||||
raise HandoffError(f"handoff manifest {manifest_path} must be a JSON object")
|
||||
|
||||
schema = manifest.get("schema")
|
||||
if schema and schema != HANDOFF_SCHEMA:
|
||||
raise HandoffError(
|
||||
f"unsupported handoff schema {schema!r} (expected {HANDOFF_SCHEMA!r})")
|
||||
|
||||
# Duration gate: -i/-u is the edited master, so it has to match the manifest.
|
||||
edited = manifest.get("edited") or {}
|
||||
edited_duration = edited.get("duration") if isinstance(edited, dict) else None
|
||||
if edited_duration is not None:
|
||||
try:
|
||||
edited_duration = float(edited_duration)
|
||||
except (TypeError, ValueError):
|
||||
raise HandoffError(
|
||||
f"edited.duration must be a number, got {edited_duration!r}")
|
||||
if duration and abs(float(duration) - edited_duration) > \
|
||||
HANDOFF_DURATION_TOLERANCE * edited_duration:
|
||||
raise HandoffError(
|
||||
f"input duration {float(duration):.2f}s for "
|
||||
f"{os.path.basename(str(input_video))} differs from the handoff's "
|
||||
f"edited timeline {edited_duration:.2f}s by more than 1% — refusing "
|
||||
f"the handoff. Pass --transcript explicitly if you need to force it.")
|
||||
|
||||
# transcript.path is resolved relative to the MANIFEST's directory.
|
||||
transcript_ref = manifest.get("transcript")
|
||||
if not isinstance(transcript_ref, dict) or not transcript_ref.get("path"):
|
||||
raise HandoffError("handoff manifest has no transcript.path")
|
||||
transcript_path = os.path.normpath(os.path.join(
|
||||
os.path.dirname(manifest_path), str(transcript_ref["path"])))
|
||||
try:
|
||||
with open(transcript_path, encoding="utf-8") as f:
|
||||
transcript = json.load(f)
|
||||
except FileNotFoundError:
|
||||
raise HandoffError(f"handoff transcript not found: {transcript_path}")
|
||||
except json.JSONDecodeError as e:
|
||||
raise HandoffError(f"malformed handoff transcript {transcript_path}: {e}")
|
||||
except OSError as e:
|
||||
raise HandoffError(f"could not read handoff transcript {transcript_path}: {e}")
|
||||
if not isinstance(transcript, dict) or not transcript.get("segments"):
|
||||
raise HandoffError(f"handoff transcript {transcript_path} has no segments")
|
||||
|
||||
for segment in transcript["segments"]:
|
||||
if isinstance(segment, dict) and isinstance(segment.get("words"), list):
|
||||
segment["words"] = merge_continuation_words(segment["words"])
|
||||
return transcript
|
||||
|
||||
|
||||
CLIP_RETRY_PAUSE_SECONDS = float(os.environ.get("CLIP_RETRY_PAUSE_SECONDS", "10"))
|
||||
|
||||
|
||||
|
|
@ -1730,57 +1607,6 @@ def clip_render_order(shorts):
|
|||
return sorted(range(len(shorts)), key=lambda i: (-score(i), i))
|
||||
|
||||
|
||||
# --- Retention provenance (PLAN #10, "instrument now") ---------------------
|
||||
# Every clip carries one versioned provenance object so a future retention /
|
||||
# analytics loop becomes a data pull instead of a re-architecture. It records
|
||||
# only what the pipeline already produced: the active profile, the model's
|
||||
# predicted score, how the start boundary was chosen (#2a hook-first vs the
|
||||
# plain word snap), whether a long-form bridge target was attached (#6), and
|
||||
# the publish target. Additive: no existing metadata field changes shape. The
|
||||
# loop itself is deliberately NOT built here.
|
||||
PROVENANCE_SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
def build_provenance(clip, profile=None):
|
||||
"""The versioned provenance record for one clip (PLAN #10).
|
||||
|
||||
Reads the ``hook_first`` block #2a writes when it moves a clip start, the
|
||||
merged #6 bridge fields, the model's ``predicted_score`` and the active
|
||||
profile. Anything the pipeline does not have at clip time (e.g. a
|
||||
title-validator version or a chosen thumbnail role) is omitted rather than
|
||||
guessed. Pure and side-effect free so it can be unit tested without a
|
||||
render.
|
||||
"""
|
||||
clip = clip if isinstance(clip, dict) else {}
|
||||
hook_first = clip.get("hook_first")
|
||||
hook_first = hook_first if isinstance(hook_first, dict) else None
|
||||
applied = hook_first is not None
|
||||
related = (clip.get("related_video_url") or "")
|
||||
related = related.strip() if isinstance(related, str) else ""
|
||||
return {
|
||||
"schema_version": PROVENANCE_SCHEMA_VERSION,
|
||||
"profile": getattr(profile, "slug", None) or None,
|
||||
"predicted_score": clip.get("predicted_score"),
|
||||
"hook": {
|
||||
"applied": applied,
|
||||
# Which pass set the final start: the deterministic hook-first trim
|
||||
# (#2a), or the plain word-boundary snap it ran on top of.
|
||||
"source": "hook_first" if applied else "snap",
|
||||
"start": hook_first.get("start") if applied else None,
|
||||
"trim": hook_first.get("trim") if applied else None,
|
||||
"proposed": hook_first.get("proposed") if applied else None,
|
||||
},
|
||||
"bridge": {
|
||||
"present": bool(related),
|
||||
"related_video_url": related or None,
|
||||
},
|
||||
"publish": {
|
||||
"postiz_integration_id": getattr(
|
||||
profile, "default_postiz_integration_id", None),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _free_gpu_cache():
|
||||
try:
|
||||
import torch
|
||||
|
|
@ -1939,11 +1765,6 @@ def get_viral_clips(transcript_result, video_duration):
|
|||
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
|
||||
print(f"\U0001f916 Model: {model_name} | language: {language}")
|
||||
|
||||
# PLAN #1: the active channel profile tunes the copy fields (Short title,
|
||||
# viral hook). ACTIVE_PROFILE is set once at CLI startup; None here renders
|
||||
# an empty block, leaving the prompt byte-identical to a profile-less run.
|
||||
profile_rules = profile_prompts.clip_rules_block(ACTIVE_PROFILE)
|
||||
|
||||
# Full word list — ground truth for snapping cut points.
|
||||
words = []
|
||||
for segment in transcript_result['segments']:
|
||||
|
|
@ -2008,7 +1829,6 @@ def get_viral_clips(transcript_result, video_duration):
|
|||
video_duration=video_duration, language=language,
|
||||
min_clips=lo, max_clips=hi,
|
||||
min_secs=min_secs, max_secs=max_secs,
|
||||
profile_rules=profile_rules,
|
||||
windows_json=json.dumps(_payload(ws), ensure_ascii=False))
|
||||
return build
|
||||
|
||||
|
|
@ -2055,30 +1875,6 @@ def get_viral_clips(transcript_result, video_duration):
|
|||
ns, ne = snap_clip_to_words(s.get("start", 0), s.get("end", 0), words, video_duration,
|
||||
min_duration=min_secs, max_duration=max_secs)
|
||||
s["start"], s["end"] = ns, ne
|
||||
|
||||
# Hook-first boundaries (#2a): move each snapped start onto the first
|
||||
# strong spoken hook, trimming wind-up so the clip opens on the hook.
|
||||
# Deterministic and word-based (no LLM); a clip with no clear hook is
|
||||
# left exactly where the snap put it. The pass is env-capped and on by
|
||||
# default (HOOK_FIRST); see clip_selection.find_hook_start.
|
||||
if hook_first_enabled():
|
||||
moved = 0
|
||||
for s in shorts:
|
||||
old_start = float(s.get("start", 0) or 0)
|
||||
new_start = find_hook_start(words, old_start, s.get("end", 0),
|
||||
min_duration=min_secs)
|
||||
if new_start is None or new_start >= old_start:
|
||||
continue
|
||||
trim = round(old_start - new_start, 3)
|
||||
print(f" Hook-first clip {s.get('source_window_id') or '?'}: "
|
||||
f"start {old_start:.2f} -> {new_start:.2f} (trim {trim:.2f}s)")
|
||||
s["start"] = new_start
|
||||
s["hook_first"] = {"start": new_start, "trim": trim,
|
||||
"proposed": old_start}
|
||||
moved += 1
|
||||
if moved:
|
||||
print(f" Hook-first trimmed {moved} of {len(shorts)} clip start(s).")
|
||||
|
||||
deduped = dedupe_overlapping(shorts)
|
||||
if len(deduped) < len(shorts):
|
||||
print(f" Dropped {len(shorts) - len(deduped)} clip(s) overlapping a "
|
||||
|
|
@ -2236,46 +2032,10 @@ if __name__ == '__main__':
|
|||
help="Output aspect: vertical/auto (9:16), horizontal (keep 16:9), square (1:1).")
|
||||
parser.add_argument('--transcript', type=str,
|
||||
help="Path to a precomputed transcript JSON (transcribe_media shape); skips transcription.")
|
||||
parser.add_argument('--handoff', type=str, default=None,
|
||||
help="Path to a cadence handoff manifest JSON. Loads the "
|
||||
"edited-timeline transcript it points at (relative to "
|
||||
"the manifest), validates the master duration and "
|
||||
"skips transcription.")
|
||||
parser.add_argument('--channel', type=str, default=None,
|
||||
help="Channel profile slug (channels/<slug>.json); "
|
||||
"overrides the CHANNEL_PROFILE env var.")
|
||||
parser.add_argument('--longform-url', type=str, default=None,
|
||||
help="Target long-form video URL for the Shorts->long-form "
|
||||
"bridge copy/checklist (PLAN #6). Optional: without it "
|
||||
"the active profile's published_video_history is used.")
|
||||
|
||||
args = parser.parse_args()
|
||||
output_format = args.format
|
||||
|
||||
# Per-channel profile (PLAN #1 v0): resolve and validate before any work so
|
||||
# a bad profile fails at startup, and hang it off a module global that later
|
||||
# items (#3/#4/#6) will read. The API passes CHANNEL_PROFILE; --channel wins
|
||||
# for local CLI runs. Generation behaviour is deliberately untouched.
|
||||
_channel_slug = args.channel or os.environ.get("CHANNEL_PROFILE") or None
|
||||
if _channel_slug:
|
||||
try:
|
||||
ACTIVE_PROFILE = load_profile(_channel_slug)
|
||||
print(f"📦 Channel profile: {_channel_slug} "
|
||||
f"(tone={ACTIVE_PROFILE.tone or 'unset'})")
|
||||
except ProfileError as e:
|
||||
if args.channel:
|
||||
# An explicit --channel that does not load is a config error.
|
||||
print(f"❌ Channel profile {args.channel!r}: {e}")
|
||||
sys.exit(1)
|
||||
# Env-derived only: warn and keep the run identical to channel-less.
|
||||
print(f"⚠️ Ignoring CHANNEL_PROFILE={_channel_slug!r}: {e}")
|
||||
|
||||
# Shorts -> long-form bridge target (PLAN #6). Explicit --longform-url wins;
|
||||
# otherwise the per-clip generator falls back to the profile history.
|
||||
longform_url = (args.longform_url or os.environ.get("LONGFORM_URL") or "").strip() or None
|
||||
if longform_url:
|
||||
print(f"🔗 Bridge target (long-form): {longform_url}")
|
||||
|
||||
script_start_time = time.time()
|
||||
|
||||
def _ensure_dir(path: str) -> str:
|
||||
|
|
@ -2333,7 +2093,7 @@ if __name__ == '__main__':
|
|||
threading.Thread(target=_early_work, args=(audio_path, audio_duration),
|
||||
daemon=True).start()
|
||||
|
||||
use_early = (not args.skip_analysis and not args.transcript and not args.handoff
|
||||
use_early = (not args.skip_analysis and not args.transcript
|
||||
and os.environ.get("EARLY_AUDIO", "1").strip() != "0"
|
||||
and not os.environ.get("MAX_SOURCE_MINUTES", "").strip()
|
||||
and not os.path.exists(os.path.join(output_dir, TRANSCRIPT_CHECKPOINT)))
|
||||
|
|
@ -2424,23 +2184,10 @@ if __name__ == '__main__':
|
|||
# to Gemini vision (picks clips from the imagery instead of the speech).
|
||||
from clipwright.pipeline.transcribe_backends import NoAudioError
|
||||
transcript = None
|
||||
# Cadence handoff (PLAN #8): the edited-timeline transcript, already
|
||||
# aligned to the master, so there is nothing to transcribe. It wins over
|
||||
# --transcript. A handoff that fails validation is refused (not silently
|
||||
# re-transcribed): the whole point is alignment to the edited timeline,
|
||||
# and guessing would cut clips on the wrong one.
|
||||
if args.handoff:
|
||||
try:
|
||||
transcript = load_handoff_transcript(args.handoff, input_video, duration)
|
||||
print(f"⏩ Using cadence handoff transcript "
|
||||
f"({len(transcript['segments'])} segments) — skipping transcription.")
|
||||
except HandoffError as e:
|
||||
print(f"❌ Handoff refused: {e}")
|
||||
sys.exit(1)
|
||||
# Module handover (issue #68): another module already transcribed this
|
||||
# exact source with the same backend, so reuse its output. Any problem
|
||||
# with the file falls back to transcribing normally rather than failing.
|
||||
elif args.transcript:
|
||||
if args.transcript:
|
||||
try:
|
||||
with open(args.transcript, 'r') as f:
|
||||
transcript = json.load(f)
|
||||
|
|
@ -2503,19 +2250,6 @@ if __name__ == '__main__':
|
|||
else:
|
||||
print(f"🔥 Found {len(clips_data['shorts'])} clips!")
|
||||
|
||||
# Shorts -> long-form bridge copy (PLAN #6): per clip, derive the
|
||||
# description block, first-comment text, target URL and the manual
|
||||
# Studio checklist from the active profile. The explicit
|
||||
# --longform-url wins over the profile's published_video_history.
|
||||
# The related-video link and comment pinning are Studio-UI only
|
||||
# (no API), hence the checklist rather than a server-side action.
|
||||
for _clip in clips_data['shorts']:
|
||||
_clip.update(bridge.build_bridge(
|
||||
ACTIVE_PROFILE, clip=_clip, related_video_url=longform_url))
|
||||
# Retention provenance (PLAN #10): one versioned record per
|
||||
# clip, written with the metadata below. Additive only.
|
||||
_clip['provenance'] = build_provenance(_clip, ACTIVE_PROFILE)
|
||||
|
||||
# Save metadata. Silent videos have no transcript → no subtitles,
|
||||
# which is correct (there's no speech to caption).
|
||||
clips_data['transcript'] = transcript or {"language": "none", "segments": []}
|
||||
|
|
@ -2551,12 +2285,7 @@ if __name__ == '__main__':
|
|||
# is a derived hooked_ file, and captions go last on top of
|
||||
# whichever is current. Each worker writes only its own clip
|
||||
# dict, so the re-dump after the pool is race-free.
|
||||
# Spoken emphasis drives punch-in timing when the source
|
||||
# transcript carries word timestamps; [] falls back to the
|
||||
# audio envelope inside the renderer.
|
||||
word_times = clip_word_onsets(transcript, start, end)
|
||||
success = render_clip(clip_temp_path, clip_final_path, output_format,
|
||||
word_times=word_times)
|
||||
success = render_clip(clip_temp_path, clip_final_path, output_format)
|
||||
if success:
|
||||
print(f" 🎞️ Clip {i+1} framed")
|
||||
deliver_path = clip_final_path
|
||||
|
|
|
|||
|
|
@ -1,169 +0,0 @@
|
|||
"""Calibration tool for the CODE/TERMINAL layout.
|
||||
|
||||
Usage (from the repo root):
|
||||
|
||||
python -m clipwright.tools.verify_code_layout path/to/recording.mp4 \
|
||||
--start 12.0 --duration 8 --out-dir output/code_layout
|
||||
|
||||
It forces the layout on (ignoring ``CODE_LAYOUT``), detects the pane, prints
|
||||
pane / confidence / mode, writes:
|
||||
|
||||
- ``debug_bands.png`` — a schematic of the 9:16 output with the code band and
|
||||
the caption reserve marked;
|
||||
- ``still.png`` — a real render through ``code_filtergraph`` at ``--start``.
|
||||
|
||||
Exit codes: 0 on a detected pane and a rendered still; 1 when nothing detects
|
||||
(so a corpus sweep can flag misses); 2 when cv2 is unavailable.
|
||||
|
||||
The detection thresholds in ``code_layout`` are estimates from first
|
||||
principles. Run this across a set of real 1440p IDE and terminal recordings and
|
||||
tune ``CODE_*`` from what actually lands here.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
DEFAULT_OUT = "output/code_layout"
|
||||
|
||||
|
||||
def _parse_args(argv):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("video", help="path to the source recording")
|
||||
parser.add_argument("--start", type=float, default=0.0,
|
||||
help="segment start in seconds")
|
||||
parser.add_argument("--duration", type=float, default=6.0,
|
||||
help="seconds of active-line tracking to sample")
|
||||
parser.add_argument("--samples", type=int, default=12,
|
||||
help="frames sampled for pane detection")
|
||||
parser.add_argument("--out-w", type=int, default=1080)
|
||||
parser.add_argument("--out-h", type=int, default=1920)
|
||||
parser.add_argument("--out-dir", default=DEFAULT_OUT)
|
||||
parser.add_argument("--no-follow", action="store_true",
|
||||
help="skip active-line tracking (static window)")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def _draw_bands(path, pane, out_w, out_h, graph):
|
||||
"""Schematic of the output: backdrop, code band, caption reserve."""
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
canvas = np.full((out_h, out_w, 3), 32, dtype=np.uint8)
|
||||
content_h, caption_h = _bands(out_h)
|
||||
scale = out_w / float(pane["w"])
|
||||
scaled_h = min(content_h, int(round(pane["h"] * scale)))
|
||||
y_off = max(0, (content_h - scaled_h) // 2)
|
||||
|
||||
cv2.rectangle(canvas, (0, y_off), (out_w - 1, y_off + scaled_h),
|
||||
(40, 160, 40), thickness=-1)
|
||||
cv2.rectangle(canvas, (0, out_h - caption_h), (out_w - 1, out_h - 1),
|
||||
(160, 90, 40), thickness=-1)
|
||||
cv2.putText(canvas, f"pane {pane['w']}x{pane['h']} @ {pane['x']},{pane['y']}",
|
||||
(16, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
|
||||
cv2.putText(canvas, f"code band h={scaled_h}",
|
||||
(16, y_off + max(30, scaled_h // 2)),
|
||||
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)
|
||||
cv2.putText(canvas, "caption reserve",
|
||||
(16, out_h - caption_h + max(30, caption_h // 2)),
|
||||
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
|
||||
if "sendcmd" in graph:
|
||||
cv2.putText(canvas, "sendcmd follow ON",
|
||||
(16, out_h - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7,
|
||||
(80, 220, 255), 2)
|
||||
cv2.imwrite(path, canvas)
|
||||
|
||||
|
||||
def _bands(out_h):
|
||||
from clipwright.layouts import code_layout
|
||||
return code_layout.code_bands(out_h)
|
||||
|
||||
|
||||
def _render_still(video, start, graph, out_path):
|
||||
cmd = [
|
||||
"ffmpeg", "-y", "-loglevel", "error",
|
||||
"-ss", f"{start:.4f}", "-i", video,
|
||||
"-frames:v", "1",
|
||||
"-filter_complex", graph, "-map", "[v]",
|
||||
out_path,
|
||||
]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if proc.returncode != 0:
|
||||
print(f"❌ ffmpeg failed:\n{proc.stderr}")
|
||||
return False
|
||||
return os.path.exists(out_path) and os.path.getsize(out_path) > 0
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
args = _parse_args(argv if argv is not None else sys.argv[1:])
|
||||
try:
|
||||
import cv2 # noqa: F401 (presence check only)
|
||||
except ImportError:
|
||||
print("❌ OpenCV (cv2) is required to run this tool.")
|
||||
return 2
|
||||
|
||||
from clipwright.layouts import code_layout
|
||||
code_layout.ENABLED = True
|
||||
code_layout.FOLLOW_ENABLED = True
|
||||
|
||||
if not os.path.exists(args.video):
|
||||
print(f"❌ No such video: {args.video}")
|
||||
return 1
|
||||
|
||||
os.makedirs(args.out_dir, exist_ok=True)
|
||||
|
||||
pane = code_layout.detect_code_pane(args.video, samples=args.samples)
|
||||
if pane is None:
|
||||
print("❌ No code pane detected — nothing to render. "
|
||||
"Tune CODE_PANE_MIN_* / CODE_EDGE_DENSITY / CODE_STABILITY_*.")
|
||||
return 1
|
||||
|
||||
print(f"✅ Pane: x={pane['x']} y={pane['y']} w={pane['w']} h={pane['h']} "
|
||||
f"({pane['w']}x{pane['h']})")
|
||||
print(f" mode={pane['mode']} confidence={pane['confidence']:.2f} "
|
||||
f"frame={pane['frame_w']}x{pane['frame_h']}")
|
||||
|
||||
# Mirror reframe_v2: if the text column is still wider than the readable
|
||||
# scale allows, crop it to out_w / MIN_SCALE rather than falling back.
|
||||
max_w = max(2, int(args.out_w / code_layout.MIN_SCALE))
|
||||
clamped = code_layout.clamp_pane_width(pane, max_w)
|
||||
if clamped[2] != pane["w"]:
|
||||
print(f" clamped text column {pane['w']} -> {clamped[2]}px "
|
||||
f"(CODE_MIN_SCALE={code_layout.MIN_SCALE})")
|
||||
pane = dict(pane, x=clamped[0], y=clamped[1], w=clamped[2], h=clamped[3])
|
||||
print(f" scale: {args.out_w / float(pane['w']):.2f}")
|
||||
|
||||
follow = None
|
||||
if not args.no_follow:
|
||||
series = code_layout.active_line_series(
|
||||
args.video, pane, args.start, args.start + args.duration)
|
||||
if series:
|
||||
# code_filtergraph expects timestamps relative to the segment start.
|
||||
follow = [(t - args.start, y) for t, y in series]
|
||||
print(f" follow: {len(follow)} points over "
|
||||
f"{follow[0][0]:.1f}-{follow[-1][0]:.1f}s")
|
||||
else:
|
||||
print(" follow: no reliable active-line series (static window)")
|
||||
|
||||
graph = code_layout.code_filtergraph(pane, args.out_w, args.out_h,
|
||||
follow=follow)
|
||||
if graph is None:
|
||||
scale = args.out_w / float(max(1, pane["w"]))
|
||||
print(f"❌ Scale {scale:.2f} < CODE_MIN_SCALE "
|
||||
f"({code_layout.MIN_SCALE}) — this clip falls back to "
|
||||
f"SCREENCAST/WIDE.")
|
||||
return 1
|
||||
|
||||
debug_path = os.path.join(args.out_dir, "debug_bands.png")
|
||||
still_path = os.path.join(args.out_dir, "still.png")
|
||||
_draw_bands(debug_path, pane, args.out_w, args.out_h, graph)
|
||||
if not _render_still(args.video, args.start, graph, still_path):
|
||||
return 1
|
||||
|
||||
print(f"🖼️ wrote {debug_path}")
|
||||
print(f"🖼️ wrote {still_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -159,23 +159,14 @@ const postizHeaders = (key, url) => {
|
|||
|
||||
// Older builds defaulted to a maintainer-hosted Postiz instance and persisted
|
||||
// it to localStorage on mount, so an upgrade could silently keep sending a
|
||||
// user's API key to a server they never chose. Retire that one legacy value
|
||||
// ONCE (guarded by a marker) instead of on every read: blanking it on each load
|
||||
// also threw away a URL the user deliberately saved — a self-hoster's own
|
||||
// instance can legitimately live on that host — and forced them to retype it
|
||||
// every session. The host is assembled from parts so no live reference to it
|
||||
// remains in the source.
|
||||
// user's API key to someone else's server. Recognize that retired default and
|
||||
// treat it as unset. The host is assembled from parts so no live reference to
|
||||
// it remains in the source.
|
||||
const RETIRED_POSTIZ_HOST = ['postiz', 'pbento', 'pt'].join('.');
|
||||
const POSTIZ_URL_RETIRED_KEY = 'postiz_url_retired_v1';
|
||||
const normalizeStoredPostizUrl = (url) => {
|
||||
const base = String(url || '').trim().replace(/\/$/, '');
|
||||
if (!base) return '';
|
||||
let retired = false;
|
||||
try {
|
||||
retired = localStorage.getItem(POSTIZ_URL_RETIRED_KEY) === '1';
|
||||
localStorage.setItem(POSTIZ_URL_RETIRED_KEY, '1');
|
||||
} catch (_) { /* storage unavailable: nothing to migrate */ }
|
||||
return !retired && base === `https://${RETIRED_POSTIZ_HOST}` ? '' : base;
|
||||
return base === `https://${RETIRED_POSTIZ_HOST}` ? '' : base;
|
||||
};
|
||||
|
||||
const SESSION_KEY = 'clipwright_session';
|
||||
|
|
@ -264,9 +255,6 @@ function App() {
|
|||
const [downloadingAll, setDownloadingAll] = useState(false);
|
||||
// Pre-flight quality gate: { info: {max_height, min_height, cookies_invalid}, data }
|
||||
const [qualityGate, setQualityGate] = useState(null);
|
||||
// True while the optional cadence handoff ZIP is being uploaded, before the
|
||||
// process request is sent. Drives the small status line in the left panel.
|
||||
const [handoffUploading, setHandoffUploading] = useState(false);
|
||||
const [logs, setLogs] = useState([]);
|
||||
// When each server log line arrived (epoch s, parallel to logs), from /api/status.
|
||||
const [logTimes, setLogTimes] = useState([]);
|
||||
|
|
@ -685,54 +673,8 @@ function App() {
|
|||
auto_hook_style: data.autoHook ? (data.autoHookStyle || 'pill') : null,
|
||||
// 'auto' is the server default, so only a deliberate choice travels.
|
||||
layouts: data.layout && data.layout !== 'auto' ? data.layout : null,
|
||||
// Channel profile slug (channels/<slug>.json). Absent = no profile, so
|
||||
// the default request stays byte-identical to the pre-feature one.
|
||||
channel: data.channel || null,
|
||||
};
|
||||
|
||||
// Optional cadence handoff bundle: reserve a slot, PUT the ZIP, then pass
|
||||
// its id to /api/process. A failure throws and is caught below, aborting
|
||||
// the job rather than silently re-transcribing the master.
|
||||
let handoffId = null;
|
||||
if (data.handoffFile) {
|
||||
setHandoffUploading(true);
|
||||
setLogs((l) => [...l, `Uploading handoff bundle (${data.handoffFile.name})…`]);
|
||||
try {
|
||||
const createRes = await apiFetch('/api/uploads', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ filename: data.handoffFile.name, kind: 'handoff' }),
|
||||
});
|
||||
if (!createRes.ok) throw new Error(`Handoff upload failed: ${readableError(await createRes.text())}`);
|
||||
const slot = await createRes.json();
|
||||
if (!slot?.upload_id) throw new Error('Handoff upload failed: the server returned no upload id.');
|
||||
// PUT through the app's own API base rather than the absolute
|
||||
// `upload_url` the server returns: behind the dev proxy that URL's host
|
||||
// is the Docker-internal `backend:8000`, which the browser cannot
|
||||
// resolve, so the request dies with a bare "Failed to fetch".
|
||||
const putRes = await apiFetch(`/api/uploads/${encodeURIComponent(slot.upload_id)}`, {
|
||||
method: slot.method || 'PUT',
|
||||
headers: { 'Content-Type': 'application/zip' },
|
||||
body: data.handoffFile,
|
||||
});
|
||||
if (!putRes.ok) throw new Error(`Handoff upload failed: ${readableError(await putRes.text())}`);
|
||||
const putData = await putRes.json().catch(() => ({}));
|
||||
handoffId = putData.upload_id || slot.upload_id || null;
|
||||
if (!handoffId) throw new Error('Handoff upload failed: the server returned no upload id.');
|
||||
setLogs((l) => [...l, 'Handoff bundle attached — transcription will be skipped.']);
|
||||
} catch (e) {
|
||||
const msg = e?.message || String(e);
|
||||
throw new Error(
|
||||
msg.startsWith('Handoff upload failed') ? msg : `Handoff upload failed: ${msg}`,
|
||||
);
|
||||
} finally {
|
||||
setHandoffUploading(false);
|
||||
}
|
||||
}
|
||||
// Only travels when a bundle was attached, so the default request is
|
||||
// byte-identical to today's.
|
||||
if (handoffId) advanced.handoff_id = handoffId;
|
||||
|
||||
if (data.type === 'url') {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
body = JSON.stringify({
|
||||
|
|
@ -1258,13 +1200,6 @@ function App() {
|
|||
</span>
|
||||
</div>
|
||||
|
||||
{handoffUploading && (
|
||||
<div className="mb-4 sm:mb-6 flex items-center gap-2 text-xs text-ink2" role="status" aria-live="polite">
|
||||
<Loader2 size={14} className="animate-spin text-brass shrink-0" />
|
||||
<span>uploading handoff bundle…</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Video Preview */}
|
||||
{processingMedia && (
|
||||
<ProcessingAnimation
|
||||
|
|
|
|||
|
|
@ -1,331 +0,0 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import { Copy, Check, CheckCircle2, AlertCircle, Loader2, Link2, Youtube, MessageSquare } from 'lucide-react';
|
||||
import Modal from './ui/Modal';
|
||||
import { apiFetch } from '../lib/api';
|
||||
|
||||
// Shorts -> long-form bridge (PLAN #6). The related-video link and comment
|
||||
// pinning are Studio-UI only, so this panel always carries the manual steps:
|
||||
// it never pretends the server can set them.
|
||||
//
|
||||
// Copy it? Use the copy buttons. Post the first comment automatically? Only
|
||||
// when you click it, and only on a server with the YouTube Data API wired up.
|
||||
|
||||
// Accept a full YouTube URL or a bare id and return just the id. The published
|
||||
// Short's id is what the comment endpoint needs; people usually have the URL.
|
||||
function videoIdFrom(raw) {
|
||||
const value = String(raw || '').trim();
|
||||
if (!value) return '';
|
||||
const urlMatch = value.match(/(?:v=|\/shorts\/|youtu\.be\/|\/embed\/)([A-Za-z0-9_-]{6,})/);
|
||||
if (urlMatch) return urlMatch[1];
|
||||
const bare = value.match(/^([A-Za-z0-9_-]{6,})$/);
|
||||
return bare ? bare[1] : value;
|
||||
}
|
||||
|
||||
export default function BridgeModal({ isOpen, onClose, jobId, clipIndex }) {
|
||||
const [data, setData] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const [copied, setCopied] = useState(null);
|
||||
|
||||
// Checked-off Studio steps, remembered per clip so closing the sheet while
|
||||
// working through the manual steps doesn't lose your place.
|
||||
const storageKey = `cw_bridge_check_${jobId}_${clipIndex}`;
|
||||
const [checkedSteps, setCheckedSteps] = useState({});
|
||||
|
||||
const [videoId, setVideoId] = useState('');
|
||||
const [posting, setPosting] = useState(false);
|
||||
const [postStatus, setPostStatus] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return undefined;
|
||||
let cancelled = false;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setData(null);
|
||||
setPostStatus(null);
|
||||
setVideoId('');
|
||||
try {
|
||||
setCheckedSteps(JSON.parse(localStorage.getItem(storageKey)) || {});
|
||||
} catch {
|
||||
setCheckedSteps({});
|
||||
}
|
||||
|
||||
apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge`)
|
||||
.then(async (res) => {
|
||||
if (!res.ok) {
|
||||
let detail = '';
|
||||
const text = await res.text().catch(() => '');
|
||||
try {
|
||||
const j = JSON.parse(text);
|
||||
if (typeof j.detail === 'string') detail = j.detail;
|
||||
} catch { /* keep the raw body */ }
|
||||
throw new Error(detail || `Could not load the bridge (${res.status}).`);
|
||||
}
|
||||
return res.json();
|
||||
})
|
||||
.then((payload) => { if (!cancelled) setData(payload); })
|
||||
.catch((e) => { if (!cancelled) setError(e.message || 'Could not load the bridge.'); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
|
||||
return () => { cancelled = true; };
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isOpen, jobId, clipIndex]);
|
||||
|
||||
const handleCopy = async (field, text) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text || '');
|
||||
setCopied(field);
|
||||
setTimeout(() => setCopied(null), 2000);
|
||||
} catch {
|
||||
// clipboard unavailable — silent
|
||||
}
|
||||
};
|
||||
|
||||
const toggleStep = (i) => {
|
||||
setCheckedSteps((prev) => {
|
||||
const next = { ...prev, [i]: !prev[i] };
|
||||
try { localStorage.setItem(storageKey, JSON.stringify(next)); } catch { /* storage unavailable */ }
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handlePostComment = async () => {
|
||||
const vid = videoIdFrom(videoId);
|
||||
if (!vid) return;
|
||||
setPosting(true);
|
||||
setPostStatus(null);
|
||||
try {
|
||||
const res = await apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge/comment`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ video_id: vid, text: data?.first_comment || undefined }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
let detail = '';
|
||||
const text = await res.text().catch(() => '');
|
||||
try {
|
||||
const j = JSON.parse(text);
|
||||
if (typeof j.detail === 'string') detail = j.detail;
|
||||
} catch { /* keep the raw body */ }
|
||||
// A 400 here almost always means the YouTube integration is not
|
||||
// configured; say that plainly and point at the manual route.
|
||||
const fallback = res.status === 400
|
||||
? "This server can't post comments yet — the YouTube Data API isn't set up. Copy the comment above and post it in Studio instead."
|
||||
: `Could not post the comment (${res.status}).`;
|
||||
setPostStatus({ ok: false, msg: detail || fallback });
|
||||
return;
|
||||
}
|
||||
await res.json().catch(() => ({}));
|
||||
setPostStatus({ ok: true, msg: 'Comment posted. Open YouTube Studio and pin it — pinning stays manual.' });
|
||||
} catch (e) {
|
||||
setPostStatus({ ok: false, msg: e.message || 'Could not post the comment.' });
|
||||
} finally {
|
||||
setPosting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// The endpoint reports whether comment posting is available on this server.
|
||||
// An older/absent field is treated as "try it" — a 400 is handled above.
|
||||
const configured = data ? data.comment_api_configured !== false : true;
|
||||
const canPostComment = configured && !!videoId.trim() && !!data?.first_comment;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
eyebrow="YOUTUBE · BRIDGE"
|
||||
title="shorts → long-form"
|
||||
size="lg"
|
||||
>
|
||||
{loading && (
|
||||
<div className="flex items-center justify-center gap-2 py-10 text-sm text-muted lowercase">
|
||||
<Loader2 size={16} className="animate-spin text-brass" /> loading bridge…
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && error && (
|
||||
<div className="px-3 py-2 rounded-input text-xs text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)] flex items-start gap-2">
|
||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
||||
<span className="break-words">{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && data && (
|
||||
<div>
|
||||
<p className="text-xs text-muted leading-snug mb-5">
|
||||
Funnel viewers of this Short to a long-form video. The related-video link and the comment pin live only in YouTube Studio, so those steps stay manual.
|
||||
</p>
|
||||
|
||||
{/* Related-video target */}
|
||||
<section className="mb-5">
|
||||
<label className="eyebrow block mb-1.5">RELATED VIDEO TARGET</label>
|
||||
{data.related_video_url ? (
|
||||
<div className="flex items-center gap-2 bg-paper rounded-input border border-rule px-3 py-2 min-w-0">
|
||||
<Youtube size={14} className="text-muted shrink-0" />
|
||||
<a
|
||||
href={data.related_video_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-ink2 truncate flex-1 min-w-0 hover:text-brass transition-colors"
|
||||
>
|
||||
{data.related_video_url}
|
||||
</a>
|
||||
<button
|
||||
onClick={() => handleCopy('target', data.related_video_url)}
|
||||
aria-label="copy related video url"
|
||||
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
|
||||
>
|
||||
{copied === 'target' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
|
||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
||||
<span>
|
||||
No related video set for this clip yet. Paste the long-form URL into YouTube Studio's
|
||||
{' '}<b className="font-medium">Related video</b> field when you set it up — the checklist below has the steps.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Manual Studio checklist */}
|
||||
<section className="mb-5">
|
||||
<div className="flex items-center justify-between gap-2 mb-2">
|
||||
<label className="eyebrow">STUDIO CHECKLIST</label>
|
||||
<span className="readout">manual · no api</span>
|
||||
</div>
|
||||
{Array.isArray(data.checklist) && data.checklist.length > 0 ? (
|
||||
<ol className="space-y-1.5">
|
||||
{data.checklist.map((step, i) => {
|
||||
const done = !!checkedSteps[i];
|
||||
return (
|
||||
<li key={i}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleStep(i)}
|
||||
aria-pressed={done}
|
||||
className={`w-full text-left flex items-start gap-2.5 px-3 py-2 rounded-input border transition-colors ${done ? 'border-rule bg-paper opacity-70' : 'border-rule hover:bg-paper3'}`}
|
||||
>
|
||||
{done
|
||||
? <CheckCircle2 size={15} className="text-ok mt-0.5 shrink-0" />
|
||||
: <span className="mt-0.5 w-[15px] h-[15px] rounded-full border border-rule2 shrink-0" aria-hidden="true" />}
|
||||
<span className={`text-xs leading-snug ${done ? 'text-muted' : 'text-ink2'}`}>{step}</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
) : (
|
||||
<p className="text-xs text-muted lowercase">no checklist saved for this clip.</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Copy-paste copy */}
|
||||
<section className="mb-5">
|
||||
<div className="flex items-center justify-between gap-2 mb-1.5">
|
||||
<label className="eyebrow">DESCRIPTION BRIDGE</label>
|
||||
<button
|
||||
onClick={() => handleCopy('desc', data.description_bridge)}
|
||||
aria-label="copy description bridge"
|
||||
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
|
||||
>
|
||||
{copied === 'desc' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
{data.description_bridge ? (
|
||||
<p className="text-xs text-ink2 select-all break-words whitespace-pre-wrap bg-paper rounded-input p-3 border border-rule max-h-40 overflow-y-auto custom-scrollbar">
|
||||
{data.description_bridge}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted lowercase bg-paper rounded-input p-3 border border-dashed border-rule">
|
||||
no description copy generated for this clip.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="mb-5">
|
||||
<div className="flex items-center justify-between gap-2 mb-1.5">
|
||||
<label className="eyebrow">FIRST COMMENT</label>
|
||||
<button
|
||||
onClick={() => handleCopy('comment', data.first_comment)}
|
||||
aria-label="copy first comment"
|
||||
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
|
||||
>
|
||||
{copied === 'comment' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
{data.first_comment ? (
|
||||
<p className="text-xs text-ink2 select-all break-words whitespace-pre-wrap bg-paper rounded-input p-3 border border-rule">
|
||||
{data.first_comment}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted lowercase bg-paper rounded-input p-3 border border-dashed border-rule">
|
||||
no first comment generated for this clip.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Optional opt-in comment posting */}
|
||||
<section className="border-t border-rule pt-4">
|
||||
<div className="flex items-center gap-2 mb-1.5">
|
||||
<label className="eyebrow">POST FIRST COMMENT</label>
|
||||
<span className="badge-ok">opt-in</span>
|
||||
</div>
|
||||
<p className="text-xs text-muted leading-snug mb-3">
|
||||
Optional. clipwright never posts on its own — this runs only when you click the button. Pinning the comment still has to be done by hand in Studio.
|
||||
</p>
|
||||
|
||||
{!configured ? (
|
||||
<div className="px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
|
||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
||||
<span>
|
||||
This server has no YouTube Data API credentials, so it can't post for you. Copy the comment above and post it in Studio instead.
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={videoId}
|
||||
onChange={(e) => setVideoId(e.target.value)}
|
||||
className="input-field sm:flex-1"
|
||||
placeholder="published Short video id or URL"
|
||||
aria-label="published Short video id or URL"
|
||||
/>
|
||||
<button
|
||||
onClick={handlePostComment}
|
||||
disabled={posting || !canPostComment}
|
||||
className="btn-primary shrink-0"
|
||||
title={!data.first_comment ? 'No comment text to post' : (videoId.trim() ? undefined : 'Enter the published Short id first')}
|
||||
>
|
||||
{posting
|
||||
? <><Loader2 size={15} className="animate-spin" /> posting…</>
|
||||
: <><MessageSquare size={15} /> post comment</>}
|
||||
</button>
|
||||
</div>
|
||||
{postStatus && (
|
||||
<div className={`px-3 py-2 rounded-input text-xs flex items-start gap-2 ${postStatus.ok
|
||||
? 'text-ok bg-[color-mix(in_oklab,var(--color-ok)_10%,transparent)]'
|
||||
: 'text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)]'}`}
|
||||
>
|
||||
{postStatus.ok
|
||||
? <Check size={14} className="mt-0.5 shrink-0" />
|
||||
: <AlertCircle size={14} className="mt-0.5 shrink-0" />}
|
||||
<span className="break-words">{postStatus.msg}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="readout mt-3 flex items-center gap-1.5">
|
||||
<Link2 size={12} className="shrink-0" /> related-video link + pin: Studio only
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Link2, Upload, FileVideo, X, Info, Loader2, ChevronDown, Paperclip, FileArchive } from 'lucide-react';
|
||||
import { Link2, Upload, FileVideo, X, Info, Loader2, ChevronDown } from 'lucide-react';
|
||||
import { track } from '../lib/analytics';
|
||||
import { getApiUrl } from '../config';
|
||||
|
||||
|
|
@ -61,18 +61,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
const [layout, setLayout] = useState(() => {
|
||||
try { return localStorage.getItem('cw_layout') || 'auto'; } catch { return 'auto'; }
|
||||
});
|
||||
// Channel profile (channels/<slug>.json on the server): tunes how the AI
|
||||
// writes titles, hooks and the description, and how it art-directs the
|
||||
// thumbnail. Per job and off by default, so nothing changes for anyone who
|
||||
// does not use profiles. Fetched from GET /api/channels; when that list is
|
||||
// empty or unreachable the selector simply does not render.
|
||||
const [channels, setChannels] = useState([]);
|
||||
const [channel, setChannel] = useState('none');
|
||||
// Cadence handoff bundle (optional): cadence's ZIP with the manifest and
|
||||
// transcript for the master. Attached to a local-file job so the pipeline
|
||||
// skips transcription. It is not sent with the video form — the parent
|
||||
// uploads it to its own slot on submit and passes back handoff_id.
|
||||
const [handoffFile, setHandoffFile] = useState(null);
|
||||
const infoRef = useRef(null);
|
||||
|
||||
// Close the compatibility popover on any outside click.
|
||||
|
|
@ -111,22 +99,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
// Channel profiles available on this install. A missing route, an empty
|
||||
// directory or a network error all leave the list empty, which keeps the
|
||||
// selector hidden — profiles are opt-in and never block a job.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
fetch(getApiUrl('/api/channels'))
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((data) => {
|
||||
if (cancelled || !data) return;
|
||||
const list = Array.isArray(data.channels) ? data.channels : [];
|
||||
setChannels(list.filter((c) => c && c.slug));
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
// A link pasted in the landing hero: preload it here so the user picks up
|
||||
// where they left off. Not auto-submitted — the rights attestation below
|
||||
// has to be ticked by the user.
|
||||
|
|
@ -152,9 +124,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
autoHook,
|
||||
autoHookStyle,
|
||||
layout,
|
||||
// 'none' = no profile; only a real slug travels, so the default
|
||||
// request stays byte-identical to the pre-feature one.
|
||||
channel: channel === 'none' ? null : channel,
|
||||
};
|
||||
try {
|
||||
localStorage.setItem('cw_auto_hook', autoHook ? '1' : '0');
|
||||
|
|
@ -164,9 +133,7 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
if (mode === 'url' && url) {
|
||||
onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat, ...advanced });
|
||||
} else if (mode === 'file' && file && !fileTooShort) {
|
||||
// The handoff bundle only travels with a local master: it is the
|
||||
// edition cadence cut from that same file.
|
||||
onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat, handoffFile: handoffFile || null, ...advanced });
|
||||
onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat, ...advanced });
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -288,49 +255,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
</div>
|
||||
)}
|
||||
|
||||
{/* Cadence handoff bundle — local file jobs only. Optional:
|
||||
without it nothing changes. With it, the parent uploads the
|
||||
ZIP to its own slot and the pipeline skips transcription. */}
|
||||
{mode === 'file' && (
|
||||
<div className="mt-4" data-tutorial="handoff-bundle">
|
||||
{handoffFile ? (
|
||||
<div className="flex items-center gap-3 rounded-input border border-rule bg-paper3 px-3 py-2.5 min-w-0">
|
||||
<FileArchive size={16} className="shrink-0 text-brass" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm text-ink2">{handoffFile.name}</span>
|
||||
<span className="block text-[11px] leading-relaxed text-muted">
|
||||
skips transcription · must match the master's edit
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setHandoffFile(null)}
|
||||
aria-label="remove handoff bundle"
|
||||
className="p-1 text-muted hover:text-ink hover:bg-paper2 rounded-full transition-colors shrink-0"
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<label className="flex items-start gap-2.5 cursor-pointer select-none text-xs text-muted hover:text-ink2 transition-colors">
|
||||
<input
|
||||
type="file"
|
||||
accept=".zip,application/zip"
|
||||
onChange={(e) => setHandoffFile(e.target.files?.[0] || null)}
|
||||
className="hidden"
|
||||
/>
|
||||
<Paperclip size={14} className="shrink-0 mt-0.5" />
|
||||
<span className="min-w-0">
|
||||
<span className="text-ink2">cadence handoff bundle</span> (.zip, optional)
|
||||
<span className="block text-[11px] leading-relaxed mt-0.5">
|
||||
Skips transcription. The bundle must match the uploaded master's edit.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Output format selector */}
|
||||
<div className="mt-5" data-tutorial="output-format">
|
||||
<p className="eyebrow mb-2">Output format</p>
|
||||
|
|
@ -367,32 +291,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Channel profile — only rendered when the install has profiles,
|
||||
so an empty list or a failed fetch leaves no trace. Tunes the
|
||||
packaging the AI writes for a job: title, hook, description
|
||||
and thumbnail. Defaults to no profile. */}
|
||||
{channels.length > 0 && (
|
||||
<div className="mt-5" data-tutorial="channel-profile">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<p className="eyebrow">channel profile</p>
|
||||
<select
|
||||
value={channel}
|
||||
onChange={(e) => setChannel(e.target.value)}
|
||||
className="input-field !w-auto text-xs py-1.5"
|
||||
aria-label="channel profile"
|
||||
>
|
||||
<option value="none">None (generic)</option>
|
||||
{channels.map((ch) => (
|
||||
<option key={ch.slug} value={ch.slug}>{ch.name || ch.slug}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<p className="text-[11px] leading-relaxed text-muted mt-1.5">
|
||||
Tailors titles, hooks, description and thumbnail for that channel.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Advanced generation controls — collapsed by default; blank = AI decides */}
|
||||
<div className="mt-4">
|
||||
<button
|
||||
|
|
@ -455,7 +353,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
|||
<option value="auto">Auto (AI picks per video)</option>
|
||||
<option value="split">Two speakers stacked</option>
|
||||
<option value="screencast">Screen over presenter</option>
|
||||
<option value="code">Code / terminal (zoom to text)</option>
|
||||
<option value="none">Single crop only</option>
|
||||
</select>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { getApiUrl } from '../config';
|
|||
import { apiFetch } from '../lib/api';
|
||||
import SubtitleModal from './SubtitleModal';
|
||||
import HookModal from './HookModal';
|
||||
import BridgeModal from './BridgeModal';
|
||||
import Modal from './ui/Modal';
|
||||
import { renderInBrowser } from '../lib/renderInBrowser';
|
||||
|
||||
|
|
@ -26,26 +25,17 @@ const PlatformIcon = ({ identifier, size = 16 }) => {
|
|||
return <Share2 size={size} />;
|
||||
};
|
||||
|
||||
// Today as YYYY-MM-DD in the user's own timezone, for the date input's `min`.
|
||||
// Built from local parts (not toISOString, which would shift the day across the
|
||||
// UTC boundary for users west of Greenwich).
|
||||
function todayInputValue() {
|
||||
const n = new Date();
|
||||
return `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
// YYYY-MM-DD (a native date picker's value) + HH:MM parsed into a local Date,
|
||||
// with explicit range checks so 2026-02-31 is rejected instead of silently
|
||||
// rolling over to March.
|
||||
// DD/MM/YYYY + HH:MM parsed into a local Date, with explicit range checks so
|
||||
// 31/02/2026 is rejected instead of silently rolling over to March.
|
||||
function parseSchedule(dateStr, timeStr) {
|
||||
const d = String(dateStr || '').trim();
|
||||
const t = String(timeStr || '').trim();
|
||||
if (!d || !t) return { error: 'Pick a date and a time.' };
|
||||
const dm = d.match(/^(\d{4})-(\d{2})-(\d{2})$/);
|
||||
if (!dm) return { error: 'Date must be in yyyy-mm-dd format.' };
|
||||
const year = Number(dm[1]);
|
||||
if (!d || !t) return { error: 'Enter both a date (dd/mm/yyyy) and a time.' };
|
||||
const dm = d.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
|
||||
if (!dm) return { error: 'Date must be in dd/mm/yyyy format.' };
|
||||
const day = Number(dm[1]);
|
||||
const month = Number(dm[2]);
|
||||
const day = Number(dm[3]);
|
||||
const year = Number(dm[3]);
|
||||
if (month < 1 || month > 12) return { error: 'Month must be between 01 and 12.' };
|
||||
if (day < 1 || day > 31) return { error: 'Day must be between 01 and 31.' };
|
||||
const tm = t.match(/^(\d{1,2}):(\d{2})$/);
|
||||
|
|
@ -224,7 +214,6 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
|||
const [isSubtitling, setIsSubtitling] = useState(false);
|
||||
const [isHooking, setIsHooking] = useState(false);
|
||||
const [showHookModal, setShowHookModal] = useState(false);
|
||||
const [showBridgeModal, setShowBridgeModal] = useState(false);
|
||||
const [editError, setEditError] = useState(null);
|
||||
|
||||
const [clipDuration, setClipDuration] = useState(() => {
|
||||
|
|
@ -935,15 +924,6 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
|||
{isHooking ? 'saving…' : 'edit hook'}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setShowBridgeModal(true)}
|
||||
className={QUIET_BTN}
|
||||
title="Shorts → long-form bridge: related video, first comment, Studio checklist"
|
||||
>
|
||||
<Link2 size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />
|
||||
bridge
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setShowModal(true)}
|
||||
className="btn-primary flex-col gap-1 py-2.5 sm:py-2 px-1 text-[11px] leading-none rounded-input whitespace-nowrap"
|
||||
|
|
@ -1057,7 +1037,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
|||
/>
|
||||
</div>
|
||||
|
||||
{/* Scheduling — native date picker + HH:MM */}
|
||||
{/* Scheduling — dd/mm/yyyy + HH:MM */}
|
||||
<div className="p-3 bg-paper rounded-input border border-rule">
|
||||
<label className="flex items-center justify-between cursor-pointer">
|
||||
<span className="flex items-center gap-2 text-sm text-ink2 lowercase">
|
||||
|
|
@ -1076,12 +1056,13 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
|||
<label className="eyebrow block mb-1.5">DATE · TIME</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="date"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
value={scheduleDate}
|
||||
onChange={(e) => setScheduleDate(e.target.value)}
|
||||
min={todayInputValue()}
|
||||
aria-label="date"
|
||||
className="input-field flex-1 [color-scheme:dark]"
|
||||
placeholder="dd/mm/yyyy"
|
||||
aria-label="date (dd/mm/yyyy)"
|
||||
className="input-field flex-1"
|
||||
/>
|
||||
<input
|
||||
type="time"
|
||||
|
|
@ -1091,7 +1072,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
|||
className="input-field w-[7.5rem] [color-scheme:dark]"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted mt-1.5">pick a day and a time, in your local timezone</p>
|
||||
<p className="text-xs text-muted mt-1.5">e.g. 31/12/2026 at 18:30</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -1195,13 +1176,6 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
|||
onRemove={burnedHook ? handleRemoveHook : null}
|
||||
/>
|
||||
|
||||
<BridgeModal
|
||||
isOpen={showBridgeModal}
|
||||
onClose={() => setShowBridgeModal(false)}
|
||||
jobId={jobId}
|
||||
clipIndex={index}
|
||||
/>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,12 +8,6 @@ services:
|
|||
- .:/app
|
||||
- /app/__pycache__
|
||||
- ./output:/app/output
|
||||
# Persistent, writable cache for the ASR model downloads. Without this the
|
||||
# bind mount above shadows /app/.cache with a host-owned dir the non-root
|
||||
# appuser cannot write (HF cache permission-denied warnings). The named
|
||||
# volume is initialised from the image's appuser-owned dir, so it stays
|
||||
# writable and the model survives container recreates.
|
||||
- huggingface-cache:/app/.cache/huggingface
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
|
|
@ -35,6 +29,3 @@ services:
|
|||
restart: unless-stopped
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
volumes:
|
||||
huggingface-cache:
|
||||
|
|
|
|||
|
|
@ -1,99 +0,0 @@
|
|||
"""L1 API: cadence handoff upload + submit (PLAN #8).
|
||||
|
||||
The bundle rides the existing /api/uploads slot flow (``kind="handoff"``); the
|
||||
test asserts the staged manifest/transcript land in the job dir and the queued
|
||||
child command carries ``--handoff``. The worker never runs here.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
KEY = {"X-Gemini-Key": "test-key"}
|
||||
|
||||
|
||||
def _zip_bytes():
|
||||
manifest = {
|
||||
"schema": "clipwright.handoff/1",
|
||||
"generator": {"name": "cadence", "version": "0.1.0"},
|
||||
"edited": {"duration": 6.0, "master": None},
|
||||
"sources": [{"index": 0, "path": "/emitter/local/rec.mkv"}],
|
||||
"transcript": {"path": "rec.transcript.json"},
|
||||
"candidates": [],
|
||||
}
|
||||
transcript = {
|
||||
"text": " hello world",
|
||||
"language": "en",
|
||||
"segments": [{"start": 0.0, "end": 1.0, "text": " hello world",
|
||||
"words": [{"word": " hello", "start": 0.0, "end": 0.4},
|
||||
{"word": " world", "start": 0.4, "end": 1.0}]}],
|
||||
}
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr("rec.handoff.json", json.dumps(manifest))
|
||||
zf.writestr("rec.transcript.json", json.dumps(transcript))
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
async def _master_upload(client, media_factory):
|
||||
reserved = await client.post("/api/uploads", json={"filename": "master.mp4"})
|
||||
uid = reserved.json()["upload_id"]
|
||||
assert (await client.put(f"/api/uploads/{uid}",
|
||||
content=media_factory.six.read_bytes())).status_code == 200
|
||||
return uid
|
||||
|
||||
|
||||
async def _handoff_upload(client, payload):
|
||||
reserved = await client.post("/api/uploads",
|
||||
json={"filename": "bundle.zip", "kind": "handoff"})
|
||||
assert reserved.status_code == 200
|
||||
assert reserved.json()["kind"] == "handoff"
|
||||
uid = reserved.json()["upload_id"]
|
||||
put = await client.put(f"/api/uploads/{uid}", content=payload)
|
||||
assert put.status_code == 200
|
||||
assert put.json()["kind"] == "handoff"
|
||||
return uid
|
||||
|
||||
|
||||
async def test_handoff_id_stages_bundle_and_queues_the_flag(client, app_state, media_factory):
|
||||
master_id = await _master_upload(client, media_factory)
|
||||
handoff_id = await _handoff_upload(client, _zip_bytes())
|
||||
|
||||
resp = await client.post("/api/process", headers=KEY, json={
|
||||
"upload_id": master_id, "handoff_id": handoff_id, "acknowledged": True})
|
||||
assert resp.status_code == 200, resp.text
|
||||
job = app_state.app.jobs[resp.json()["job_id"]]
|
||||
|
||||
assert "--handoff" in job["cmd"]
|
||||
manifest_path = job["cmd"][job["cmd"].index("--handoff") + 1]
|
||||
assert os.path.exists(manifest_path)
|
||||
staged = json.loads(open(manifest_path, encoding="utf-8").read())
|
||||
assert staged["transcript"]["path"] == "source_transcript.json"
|
||||
assert os.path.exists(os.path.join(os.path.dirname(manifest_path),
|
||||
"source_transcript.json"))
|
||||
# The slot is consumed; the master upload still follows its own path.
|
||||
assert handoff_id not in app_state.app.pending_uploads
|
||||
|
||||
|
||||
async def test_non_zip_handoff_bundle_is_400(client, app_state, media_factory):
|
||||
master_id = await _master_upload(client, media_factory)
|
||||
handoff_id = await _handoff_upload(client, b"not a zip")
|
||||
|
||||
resp = await client.post("/api/process", headers=KEY, json={
|
||||
"upload_id": master_id, "handoff_id": handoff_id, "acknowledged": True})
|
||||
|
||||
assert resp.status_code == 400
|
||||
assert "ZIP" in resp.json()["detail"]
|
||||
|
||||
|
||||
async def test_unknown_handoff_id_is_404(client, app_state, media_factory):
|
||||
master_id = await _master_upload(client, media_factory)
|
||||
|
||||
resp = await client.post("/api/process", headers=KEY, json={
|
||||
"upload_id": master_id, "handoff_id": "nope", "acknowledged": True})
|
||||
|
||||
assert resp.status_code == 404
|
||||
|
|
@ -486,55 +486,6 @@ async def test_describe_success(client, app_state, thumb_stubs, monkeypatch):
|
|||
assert args[1] == "My Title" and args[2] == segments
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Channel profiles reach the Studio generators (PLAN #1)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
async def test_analyze_passes_the_channel_profile(client, app_state, thumb_stubs, monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "k")
|
||||
resp = await client.post(
|
||||
"/api/thumbnail/analyze",
|
||||
data={"channel": "cseea"},
|
||||
files={"file": ("v.mp4", b"video", "video/mp4")})
|
||||
assert resp.status_code == 200, resp.text
|
||||
_, kwargs = thumb_stubs.calls.analyze[0]
|
||||
assert kwargs["profile"].slug == "cseea"
|
||||
|
||||
|
||||
async def test_generate_passes_the_channel_profile(client, app_state, thumb_stubs, monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "k")
|
||||
resp = await client.post(
|
||||
"/api/thumbnail/generate",
|
||||
data={"session_id": "g1", "title": "T", "channel": "pedro"})
|
||||
assert resp.status_code == 200, resp.text
|
||||
_, kwargs = thumb_stubs.calls.generate[0]
|
||||
assert kwargs["profile"].slug == "pedro"
|
||||
|
||||
|
||||
async def test_describe_passes_the_channel_profile(client, app_state, thumb_stubs, monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "k")
|
||||
app_state.app.thumbnail_sessions["d1"] = {
|
||||
"transcript_segments": [{"start": 0.0, "end": 5.0, "text": "hello"}],
|
||||
"language": "en", "video_duration": 5.0}
|
||||
resp = await client.post("/api/thumbnail/describe",
|
||||
json={"session_id": "d1", "title": "T", "channel": "cseea"})
|
||||
assert resp.status_code == 200, resp.text
|
||||
_, kwargs = thumb_stubs.calls.describe[0]
|
||||
assert kwargs["profile"].slug == "cseea"
|
||||
|
||||
|
||||
async def test_unknown_channel_is_400(client, app_state, thumb_stubs, monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "k")
|
||||
app_state.app.thumbnail_sessions["d1"] = {
|
||||
"transcript_segments": [{"start": 0.0, "end": 5.0, "text": "hello"}],
|
||||
"language": "en", "video_duration": 5.0}
|
||||
resp = await client.post("/api/thumbnail/describe",
|
||||
json={"session_id": "d1", "title": "T", "channel": "nope"})
|
||||
assert resp.status_code == 400
|
||||
assert "Invalid channel profile" in resp.json()["detail"]
|
||||
assert thumb_stubs.calls.describe == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# POST /api/thumbnail/publish + GET status
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
|
|
|||
|
|
@ -1,102 +0,0 @@
|
|||
"""L4 — cadence handoff CLI (PLAN #8).
|
||||
|
||||
Runs the REAL ``python -m clipwright.pipeline.main`` with real ffmpeg and the
|
||||
stub_env ASR/Gemini. Proves a valid handoff skips ASR (the metadata transcript
|
||||
is the handoff's, not the canned stub's) and that a bad handoff is refused.
|
||||
"""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
|
||||
|
||||
# 12 tokens in ``text`` so main.speech_is_sparse does not fall back to vision.
|
||||
HANDOFF_TEXT = "This handoff transcript proves the ASR step was skipped entirely -ish here"
|
||||
HANDOFF_WORDS = [
|
||||
{"word": " This", "start": 0.0, "end": 0.3},
|
||||
{"word": " handoff", "start": 0.3, "end": 0.7},
|
||||
{"word": " transcript", "start": 0.7, "end": 1.2},
|
||||
{"word": " proves", "start": 1.2, "end": 1.6},
|
||||
{"word": " the", "start": 1.6, "end": 1.8},
|
||||
{"word": " ASR", "start": 1.8, "end": 2.2},
|
||||
{"word": " step", "start": 2.2, "end": 2.6},
|
||||
{"word": " was", "start": 2.6, "end": 2.9},
|
||||
{"word": " skipped", "start": 2.9, "end": 3.4},
|
||||
{"word": " entirely", "start": 3.4, "end": 4.0},
|
||||
{"word": "-ish", "start": 4.0, "end": 4.3}, # fragment: no leading space
|
||||
{"word": " here", "start": 4.3, "end": 4.8},
|
||||
]
|
||||
|
||||
|
||||
def _write_bundle(tmp_path, *, edited_duration=6.0, transcript_name="rec.transcript.json",
|
||||
write_transcript=True, transcript_ref="rec.transcript.json"):
|
||||
transcript = {
|
||||
"text": HANDOFF_TEXT,
|
||||
"language": "en",
|
||||
"segments": [{"start": 0.0, "end": 4.8, "text": HANDOFF_TEXT,
|
||||
"words": HANDOFF_WORDS}],
|
||||
}
|
||||
if write_transcript:
|
||||
(tmp_path / transcript_name).write_text(json.dumps(transcript), encoding="utf-8")
|
||||
manifest = {
|
||||
"schema": "clipwright.handoff/1",
|
||||
"generator": {"name": "cadence", "version": "0.1.0"},
|
||||
"edited": {"timeline": "voice-audio", "duration": edited_duration, "master": None},
|
||||
"sources": [{"index": 0, "path": "/emitter/local/never-open.mkv"}],
|
||||
"transcript": {"path": transcript_ref},
|
||||
"candidates": [],
|
||||
"chapters": [],
|
||||
}
|
||||
manifest_path = tmp_path / "rec.handoff.json"
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
return manifest_path
|
||||
|
||||
|
||||
def _metadata(out):
|
||||
files = list(out.glob("*_metadata.json"))
|
||||
assert len(files) == 1
|
||||
return json.loads(files[0].read_text())
|
||||
|
||||
|
||||
def test_handoff_skips_asr_and_merges_words(run_pipeline, pipeline_env, media_factory, tmp_path):
|
||||
pipeline_env["AUTO_LAYOUT"] = "0"
|
||||
pipeline_env["FFMPEG_ENCODER"] = "x264"
|
||||
manifest = _write_bundle(tmp_path)
|
||||
out = tmp_path / "out"
|
||||
|
||||
result = run_pipeline(media_factory.six, "-o", str(out), "--handoff", str(manifest))
|
||||
|
||||
assert result.returncode == 0, (
|
||||
f"CLI failed ({result.returncode})\nSTDOUT:\n{result.stdout[-4000:]}\n"
|
||||
f"STDERR:\n{result.stderr[-4000:]}")
|
||||
meta = _metadata(out)
|
||||
words = meta["transcript"]["segments"][0]["words"]
|
||||
# The handoff's words (not the canned ASR stub's) and the fragment merged.
|
||||
assert any(w["word"] == " entirely-ish" for w in words)
|
||||
assert all("canned" not in w["word"] for w in words)
|
||||
assert list(out.glob("*_clip_*.mp4"))
|
||||
|
||||
|
||||
def test_handoff_duration_mismatch_is_refused(run_pipeline, pipeline_env, media_factory, tmp_path):
|
||||
pipeline_env["AUTO_LAYOUT"] = "0"
|
||||
manifest = _write_bundle(tmp_path, edited_duration=60.0)
|
||||
out = tmp_path / "out"
|
||||
|
||||
result = run_pipeline(media_factory.six, "-o", str(out), "--handoff", str(manifest))
|
||||
|
||||
assert result.returncode != 0
|
||||
assert "refusing the handoff" in result.stdout
|
||||
assert "--transcript" in result.stdout
|
||||
assert not list(out.glob("*_metadata.json"))
|
||||
|
||||
|
||||
def test_handoff_missing_transcript_is_refused(run_pipeline, pipeline_env, media_factory, tmp_path):
|
||||
pipeline_env["AUTO_LAYOUT"] = "0"
|
||||
manifest = _write_bundle(tmp_path, write_transcript=False)
|
||||
out = tmp_path / "out"
|
||||
|
||||
result = run_pipeline(media_factory.six, "-o", str(out), "--handoff", str(manifest))
|
||||
|
||||
assert result.returncode != 0
|
||||
assert "transcript not found" in result.stdout
|
||||
assert not list(out.glob("*_metadata.json"))
|
||||
|
|
@ -14,9 +14,6 @@ import pytest
|
|||
|
||||
from clipwright.layouts import layout_ranges
|
||||
from clipwright.layouts import layout_picker
|
||||
from clipwright.layouts import code_layout
|
||||
from clipwright.layouts import camera_inset
|
||||
from clipwright.layouts import active_speaker
|
||||
from clipwright.layouts import punch_in
|
||||
from clipwright.layouts import screencast_layout
|
||||
from clipwright.layouts import split_layout
|
||||
|
|
@ -29,7 +26,6 @@ VERTICAL = 9 / 16
|
|||
_FAKE_LAYOUT_MODULES = {
|
||||
"split_layout": "clipwright.layouts.split_layout",
|
||||
"screencast_layout": "clipwright.layouts.screencast_layout",
|
||||
"code_layout": "clipwright.layouts.code_layout",
|
||||
"active_speaker": "clipwright.layouts.active_speaker",
|
||||
}
|
||||
|
||||
|
|
@ -63,15 +59,6 @@ class TestPickerFlagMapping:
|
|||
assert mods["clipwright.layouts.screencast_layout"].ENABLED is True
|
||||
assert mods["clipwright.layouts.split_layout"].ENABLED is False
|
||||
|
||||
def test_code_enables_only_its_module(self, monkeypatch):
|
||||
# The CODE layout is gated by its own module flag; picking it must not
|
||||
# touch SPLIT or SCREENCAST.
|
||||
mods = fake_modules(monkeypatch)
|
||||
assert layout_picker.apply("code") == ["code_layout"]
|
||||
assert mods["clipwright.layouts.code_layout"].ENABLED is True
|
||||
assert mods["clipwright.layouts.screencast_layout"].ENABLED is False
|
||||
assert mods["clipwright.layouts.split_layout"].ENABLED is False
|
||||
|
||||
def test_none_is_inert(self, monkeypatch):
|
||||
mods = fake_modules(monkeypatch)
|
||||
assert layout_picker.apply("none") == []
|
||||
|
|
@ -117,7 +104,6 @@ class TestApiLayoutEnv:
|
|||
def test_explicit_picks_map_to_their_env_vars(self, layout_env):
|
||||
assert layout_env(["split"])["SPLIT_LAYOUT"] == "1"
|
||||
assert layout_env(["screencast"])["SCREENCAST_LAYOUT"] == "1"
|
||||
assert layout_env(["code"])["CODE_LAYOUT"] == "1"
|
||||
assert layout_env(["punch_in"])["PUNCH_IN"] == "1"
|
||||
|
||||
def test_split_implies_the_speaker_signal(self, layout_env):
|
||||
|
|
@ -257,77 +243,3 @@ class TestLayoutRangesRoundTrip:
|
|||
got = layout_ranges.remap(ranges, [{"start": 5, "end": 12}])
|
||||
assert got == [{"start": 0.0, "end": 5.0, "layout": "split"},
|
||||
{"start": 5.0, "end": 7.0, "layout": "track"}]
|
||||
|
||||
|
||||
# --- CODE precedence --------------------------------------------------------
|
||||
|
||||
class _TC:
|
||||
"""Minimal FrameTimecode stand-in: render only reads ``get_frames``."""
|
||||
|
||||
def __init__(self, frame):
|
||||
self._frame = frame
|
||||
|
||||
def get_frames(self):
|
||||
return self._frame
|
||||
|
||||
|
||||
class _DummyCameraman:
|
||||
crop_width = 640
|
||||
crop_height = 360
|
||||
|
||||
|
||||
class TestCodePrecedence:
|
||||
"""CODE self-detects and wins over SCREENCAST on the same scene, while a
|
||||
scene that fails per-scene verification keeps TRACK."""
|
||||
|
||||
def _wire(self, monkeypatch):
|
||||
from clipwright.pipeline import main as m
|
||||
|
||||
# No ML, no ffmpeg, no Gemini: every external call is a stand-in.
|
||||
monkeypatch.setattr(reframe_v2, "_run", lambda cmd: None)
|
||||
monkeypatch.setattr(reframe_v2, "_analyze_trajectory",
|
||||
lambda *a, **k: [0.0] * 60)
|
||||
monkeypatch.setattr(split_layout, "detect_split_scenes",
|
||||
lambda *a, **k: {})
|
||||
monkeypatch.setattr(camera_inset, "detect", lambda *a, **k: None)
|
||||
monkeypatch.setattr(active_speaker, "ENABLED", False)
|
||||
monkeypatch.setattr(punch_in, "ENABLED", False)
|
||||
monkeypatch.setattr(m, "detect_scenes",
|
||||
lambda *a, **k: ([(_TC(0), _TC(30)),
|
||||
(_TC(30), _TC(60))], 30.0))
|
||||
monkeypatch.setattr(m, "get_video_resolution",
|
||||
lambda *a, **k: (2560, 1440))
|
||||
monkeypatch.setattr(m, "analyze_scenes_strategy",
|
||||
lambda *a, **k: ["TRACK", "TRACK"])
|
||||
monkeypatch.setattr(m, "SmoothedCameraman",
|
||||
lambda *a, **k: _DummyCameraman())
|
||||
monkeypatch.setattr(m, "SpeakerTracker", lambda *a, **k: object())
|
||||
|
||||
# SCREENCAST is on and would claim scene 0...
|
||||
monkeypatch.setattr(screencast_layout, "ENABLED", True)
|
||||
monkeypatch.setattr(screencast_layout, "detect_content_ranges",
|
||||
lambda *a, **k: [(0.0, 20.0, "chart", 0.9)])
|
||||
monkeypatch.setattr(screencast_layout, "detect_screencast_scenes",
|
||||
lambda *a, **k: {0: ("SCREENCAST", (100.0, 100.0))})
|
||||
|
||||
# ...but CODE detects the pane and verifies only scene 0.
|
||||
monkeypatch.setattr(code_layout, "ENABLED", True)
|
||||
monkeypatch.setattr(code_layout, "FOLLOW_ENABLED", False)
|
||||
pane = {"x": 300, "y": 100, "w": 1200, "h": 800, "mode": "editor",
|
||||
"confidence": 0.9, "frame_w": 2560, "frame_h": 1440}
|
||||
monkeypatch.setattr(code_layout, "detect_code_pane",
|
||||
lambda *a, **k: dict(pane))
|
||||
monkeypatch.setattr(
|
||||
code_layout, "scene_shows_code",
|
||||
lambda path, pane, start, end, samples=3: start < 0.5)
|
||||
|
||||
def test_code_wins_over_screencast_and_leaves_other_scenes(
|
||||
self, monkeypatch, tmp_path):
|
||||
self._wire(monkeypatch)
|
||||
final = str(tmp_path / "clip.mp4")
|
||||
assert reframe_v2.render("in.mp4", final, VERTICAL) is True
|
||||
|
||||
by_start = {r["start"]: r["layout"] for r in layout_ranges.read(final)}
|
||||
assert by_start[0.0] == "code" # CODE beat the SCREENCAST claim
|
||||
assert by_start[1.0] == "track" # failed verification, untouched
|
||||
assert "screencast" not in set(by_start.values())
|
||||
|
|
|
|||
|
|
@ -164,9 +164,7 @@ class TestConcepts:
|
|||
assert len(out) == 3
|
||||
assert out[0]["text"] == "ESTO FUNCIONA"
|
||||
assert out[0]["text_position"] == "left"
|
||||
# #4: a role is always present and the set covers emotion + technical.
|
||||
assert {"emotion", "technical"} <= {c["role"] for c in out}
|
||||
assert out[1]["text"] == "HINT"
|
||||
assert out[1]["why"] == "fallback"
|
||||
|
||||
def test_plan_thumbnail_concepts_parses_the_client_json(self):
|
||||
concepts = thumbnail.plan_thumbnail_concepts(_FakeClient(), "A title", 2)
|
||||
|
|
|
|||
|
|
@ -1,101 +0,0 @@
|
|||
"""Shorts -> long-form bridge copy (PLAN #6): pure, deterministic generation.
|
||||
|
||||
The bridge is derived from the active profile (+ its ``published_video_history``)
|
||||
and the clip, with an optional explicit target. No LLM, no network: the same
|
||||
inputs must always yield the same copy.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from clipwright.pipeline import bridge, profiles
|
||||
|
||||
TARGET = "https://www.youtube.com/watch?v=LONGFORM123"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cseea():
|
||||
return profiles.load_profile("cseea")
|
||||
|
||||
|
||||
def _clip():
|
||||
return {"video_title_for_youtube_short": "I broke the world",
|
||||
"viral_hook_text": "I broke the world in one block"}
|
||||
|
||||
|
||||
def test_explicit_target_reaches_every_field(cseea):
|
||||
result = bridge.build_bridge(cseea, clip=_clip(), related_video_url=TARGET)
|
||||
assert result["related_video_url"] == TARGET
|
||||
assert TARGET in result["description_bridge"]
|
||||
assert TARGET in result["first_comment"]
|
||||
assert any(TARGET in step for step in result["checklist"])
|
||||
assert result["manual_pin_required"] is True
|
||||
|
||||
|
||||
def test_checklist_names_the_manual_studio_steps(cseea):
|
||||
result = bridge.build_bridge(cseea, clip=_clip(), related_video_url=TARGET)
|
||||
joined = "\n".join(result["checklist"])
|
||||
assert "Studio" in joined
|
||||
assert "Related video" in joined
|
||||
assert "Pin" in joined
|
||||
assert "no api" in joined.lower()
|
||||
|
||||
|
||||
def test_no_target_uses_profile_links_and_invents_no_url(cseea):
|
||||
result = bridge.build_bridge(cseea, clip=_clip(), related_video_url=None)
|
||||
assert result["related_video_url"] is None
|
||||
# The channel's own links still appear; no watch URL is fabricated.
|
||||
assert "youtube.com/@cseea" in result["description_bridge"]
|
||||
assert "youtube.com/@cseea" in result["first_comment"]
|
||||
assert "watch?v=" not in result["description_bridge"]
|
||||
# The checklist tells the operator to paste the target themselves.
|
||||
assert any("paste" in step.lower() for step in result["checklist"])
|
||||
|
||||
|
||||
def test_published_history_supplies_the_target_when_none_given():
|
||||
profile = profiles.Profile(
|
||||
slug="t",
|
||||
description_template="{hook}\n\nFull video: {link}",
|
||||
links=["https://example.com/channel"],
|
||||
published_video_history=[
|
||||
{"id": "OLD", "published_at": "2026-01-01"},
|
||||
{"id": "NEW", "published_at": "2026-06-01"},
|
||||
],
|
||||
)
|
||||
result = bridge.build_bridge(profile, clip=_clip())
|
||||
assert result["related_video_url"] == "https://www.youtube.com/watch?v=NEW"
|
||||
assert "watch?v=NEW" in result["first_comment"]
|
||||
|
||||
|
||||
def test_explicit_target_wins_over_history_and_url_field_preferred():
|
||||
profile = profiles.Profile(
|
||||
slug="t",
|
||||
published_video_history=[{"url": "https://youtu.be/HISTORY"}],
|
||||
)
|
||||
assert bridge.target_video(profile, TARGET) == TARGET
|
||||
assert bridge.target_video(profile) == "https://youtu.be/HISTORY"
|
||||
|
||||
|
||||
def test_profiles_produce_different_bridge_copy(cseea):
|
||||
pedro = profiles.load_profile("pedro")
|
||||
cseea_bridge = bridge.build_bridge(cseea, clip=_clip(), related_video_url=TARGET)
|
||||
pedro_bridge = bridge.build_bridge(pedro, clip=_clip(), related_video_url=TARGET)
|
||||
assert cseea_bridge["description_bridge"] != pedro_bridge["description_bridge"]
|
||||
assert "#minecraft" in cseea_bridge["description_bridge"]
|
||||
assert "Chapters and source" in pedro_bridge["description_bridge"]
|
||||
|
||||
|
||||
def test_no_profile_still_produces_usable_copy():
|
||||
result = bridge.build_bridge(None, clip=_clip(), related_video_url=TARGET)
|
||||
assert TARGET in result["first_comment"]
|
||||
assert TARGET in result["description_bridge"]
|
||||
assert result["checklist"] # never empty
|
||||
|
||||
|
||||
def test_bridge_fields_merge_into_clip_metadata(cseea):
|
||||
"""The exact merge ``main.py`` performs must land every bridge field."""
|
||||
clip = _clip()
|
||||
clip.update(bridge.build_bridge(cseea, clip=clip, related_video_url=TARGET))
|
||||
assert set(bridge.build_bridge(cseea, clip=clip).keys()) <= set(clip.keys())
|
||||
assert clip["related_video_url"] == TARGET
|
||||
assert isinstance(clip["checklist"], list)
|
||||
assert isinstance(clip["description_bridge"], str) and clip["description_bridge"]
|
||||
assert isinstance(clip["first_comment"], str) and clip["first_comment"]
|
||||
|
|
@ -1,132 +0,0 @@
|
|||
"""Bridge copy + opt-in first-comment endpoints (PLAN #6).
|
||||
|
||||
Confirms the generated copy/checklist is exposed from clip metadata, that the
|
||||
comment endpoint is guarded when the YouTube Data API is unconfigured (clear
|
||||
error, no post), and that posting only happens when the caller opts in.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
app_module = pytest.importorskip("clipwright.api.app")
|
||||
from clipwright.integrations import youtube_data # noqa: E402
|
||||
|
||||
JOB_ID = "bridge-endpoint-test-job"
|
||||
TARGET = "https://www.youtube.com/watch?v=LONGFORM123"
|
||||
|
||||
CHECKLIST = [
|
||||
"Open YouTube Studio -> Content -> this Short -> Edit.",
|
||||
f"Details -> Related video: set it to {TARGET} (no API).",
|
||||
"Post the generated first comment.",
|
||||
"Pin the first comment (no API).",
|
||||
]
|
||||
|
||||
|
||||
def _request(method, path, json_body=None):
|
||||
async def _do():
|
||||
transport = httpx.ASGITransport(app=app_module.app)
|
||||
async with httpx.AsyncClient(transport=transport,
|
||||
base_url="http://testserver") as client:
|
||||
return await client.request(method, path, json=json_body)
|
||||
return asyncio.run(_do())
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def job(tmp_path, monkeypatch):
|
||||
out_root = tmp_path / "output"
|
||||
job_dir = out_root / JOB_ID
|
||||
job_dir.mkdir(parents=True)
|
||||
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
|
||||
|
||||
clip = {
|
||||
"start": 0.0, "end": 30.0,
|
||||
"video_title_for_youtube_short": "I broke the world",
|
||||
"video_url": f"/videos/{JOB_ID}/mytitle_clip_1.mp4",
|
||||
# The fields main.py merges into clip metadata before writing.
|
||||
"related_video_url": TARGET,
|
||||
"description_bridge": f"▶ Full video: {TARGET}",
|
||||
"first_comment": f"▶ Full video: {TARGET}",
|
||||
"checklist": CHECKLIST,
|
||||
"manual_pin_required": True,
|
||||
}
|
||||
meta = {"shorts": [clip], "transcript": {"language": "none", "segments": []},
|
||||
"source_video": "src.mp4", "output_format": "auto"}
|
||||
(job_dir / "mytitle_metadata.json").write_text(json.dumps(meta))
|
||||
|
||||
app_module.jobs[JOB_ID] = {
|
||||
"status": "completed", "logs": [],
|
||||
"result": {"clips": [dict(clip)]}, "user_id": None,
|
||||
}
|
||||
try:
|
||||
yield {"dir": job_dir, "meta_path": job_dir / "mytitle_metadata.json"}
|
||||
finally:
|
||||
app_module.jobs.pop(JOB_ID, None)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def unconfigured(monkeypatch):
|
||||
for name in (youtube_data.CLIENT_ID_ENV, youtube_data.CLIENT_SECRET_ENV,
|
||||
youtube_data.REFRESH_TOKEN_ENV):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
class TestBridgeCopyEndpoint:
|
||||
def test_returns_generated_copy_and_checklist(self, job, unconfigured):
|
||||
resp = _request("GET", f"/api/clip/{JOB_ID}/0/bridge")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["related_video_url"] == TARGET
|
||||
assert TARGET in data["description_bridge"]
|
||||
assert TARGET in data["first_comment"]
|
||||
assert data["checklist"] == CHECKLIST
|
||||
assert data["manual_pin_required"] is True
|
||||
assert data["comment_api_configured"] is False
|
||||
|
||||
def test_unknown_clip_is_404(self, job, unconfigured):
|
||||
resp = _request("GET", f"/api/clip/{JOB_ID}/99/bridge")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
class TestBridgeCommentEndpoint:
|
||||
def test_unconfigured_is_a_clear_400_and_posts_nothing(self, job, unconfigured,
|
||||
monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(app_module.youtube_data, "post_first_comment",
|
||||
lambda *a, **k: calls.append((a, k)))
|
||||
resp = _request("POST", f"/api/clip/{JOB_ID}/0/bridge/comment",
|
||||
{"video_id": "short-1"})
|
||||
assert resp.status_code == 400
|
||||
assert "not configured" in resp.json()["detail"]
|
||||
assert calls == []
|
||||
|
||||
def test_configured_posts_the_first_comment(self, job, monkeypatch):
|
||||
monkeypatch.setenv(youtube_data.CLIENT_ID_ENV, "cid")
|
||||
monkeypatch.setenv(youtube_data.CLIENT_SECRET_ENV, "secret")
|
||||
monkeypatch.setenv(youtube_data.REFRESH_TOKEN_ENV, "refresh")
|
||||
calls = []
|
||||
|
||||
def fake_post(video_id, text):
|
||||
calls.append((video_id, text))
|
||||
return {"id": "comment-1"}
|
||||
|
||||
monkeypatch.setattr(app_module.youtube_data, "post_first_comment", fake_post)
|
||||
resp = _request("POST", f"/api/clip/{JOB_ID}/0/bridge/comment",
|
||||
{"video_id": "short-1"})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["posted"] is True
|
||||
assert resp.json()["comment_id"] == "comment-1"
|
||||
assert resp.json()["manual_pin_required"] is True
|
||||
# The generated first_comment was used; posting is explicit, not auto.
|
||||
assert calls == [("short-1", f"▶ Full video: {TARGET}")]
|
||||
|
||||
def test_caller_can_override_the_comment_text(self, job, monkeypatch):
|
||||
monkeypatch.setenv(youtube_data.CLIENT_ID_ENV, "cid")
|
||||
monkeypatch.setenv(youtube_data.CLIENT_SECRET_ENV, "secret")
|
||||
monkeypatch.setenv(youtube_data.REFRESH_TOKEN_ENV, "refresh")
|
||||
monkeypatch.setattr(app_module.youtube_data, "post_first_comment",
|
||||
lambda video_id, text: {"id": "c"})
|
||||
resp = _request("POST", f"/api/clip/{JOB_ID}/0/bridge/comment",
|
||||
{"video_id": "short-1", "text": "custom"})
|
||||
assert resp.status_code == 200
|
||||
|
|
@ -154,7 +154,7 @@ class TestDetailPromptCarriesTheCount:
|
|||
low, high = clip_count_targets(5)
|
||||
prompt = gw.DETAIL_PROMPT_TEMPLATE.format(
|
||||
video_duration=300, language="es", min_clips=low, max_clips=high,
|
||||
min_secs=15.0, max_secs=60.0, profile_rules="", windows_json="[]")
|
||||
min_secs=15.0, max_secs=60.0, windows_json="[]")
|
||||
assert f"return {low} to {high} clips" in prompt
|
||||
assert "15 to 60 seconds" in prompt
|
||||
# The JSON schema example legitimately keeps braces (they are {{ }} in
|
||||
|
|
|
|||
|
|
@ -1,231 +0,0 @@
|
|||
"""Pure tests for the CODE/TERMINAL layout geometry.
|
||||
|
||||
No OpenCV here on purpose: the detection entry points import cv2 lazily, and CI
|
||||
does not install it. Everything asserted below is decided by the pure helpers
|
||||
(projections -> pane, stability, band fitting, sendcmd lines, filtergraph).
|
||||
"""
|
||||
from clipwright.layouts.code_layout import (
|
||||
CAPTION_BAND_RATIO,
|
||||
clamp_pane_width,
|
||||
code_bands,
|
||||
code_filtergraph,
|
||||
fit_window,
|
||||
follow_sendcmd_lines,
|
||||
pane_from_projections,
|
||||
stable_pane,
|
||||
text_column_extent,
|
||||
)
|
||||
|
||||
HD = (1920, 1080)
|
||||
|
||||
|
||||
def _projections(row_span, col_span, h=1080, w=1920):
|
||||
rows = [0.0] * h
|
||||
cols = [0.0] * w
|
||||
for i in range(*row_span):
|
||||
rows[i] = 100.0
|
||||
for i in range(*col_span):
|
||||
cols[i] = 100.0
|
||||
return rows, cols
|
||||
|
||||
|
||||
class TestPaneFromProjections:
|
||||
def test_locates_the_pane_block(self):
|
||||
rows, cols = _projections((100, 400), (200, 1000))
|
||||
assert pane_from_projections(rows, cols, *HD) == (200, 100, 800, 300)
|
||||
|
||||
def test_ignores_mass_below_the_threshold(self):
|
||||
rows, cols = _projections((100, 400), (200, 1000))
|
||||
# A stray edge column far from the pane is under 15% of the max.
|
||||
cols[1500] = 10.0
|
||||
assert pane_from_projections(rows, cols, *HD) == (200, 100, 800, 300)
|
||||
|
||||
def test_rejects_a_narrow_pane(self):
|
||||
rows, cols = _projections((100, 400), (200, 500))
|
||||
assert pane_from_projections(rows, cols, *HD) is None
|
||||
|
||||
def test_rejects_a_short_pane(self):
|
||||
rows, cols = _projections((100, 200), (200, 1000))
|
||||
assert pane_from_projections(rows, cols, *HD) is None
|
||||
|
||||
def test_empty_projections_are_none(self):
|
||||
assert pane_from_projections([], [], *HD) is None
|
||||
assert pane_from_projections([0, 0], [0, 0], *HD) is None
|
||||
|
||||
|
||||
class TestTextColumnExtent:
|
||||
def test_no_chrome_keeps_the_full_text_width(self):
|
||||
cols = [0.0] * 2560
|
||||
for i in range(100, 2400):
|
||||
cols[i] = 100.0
|
||||
x0, x1 = text_column_extent(cols, 2560)
|
||||
assert 90 <= x0 <= 110
|
||||
assert 2390 <= x1 <= 2410
|
||||
|
||||
def test_sidebar_and_minimap_are_masked(self):
|
||||
cols = [0.0] * 2560
|
||||
for i in range(0, 60): # activity bar
|
||||
cols[i] = 90.0
|
||||
for i in range(80, 400): # sidebar
|
||||
cols[i] = 70.0
|
||||
for i in range(500, 2050): # code text
|
||||
cols[i] = 100.0
|
||||
for i in range(2450, 2560): # minimap
|
||||
cols[i] = 110.0
|
||||
x0, x1 = text_column_extent(cols, 2560)
|
||||
# Cut after the sidebar/editor border and before the minimap border.
|
||||
assert 400 <= x0 <= 520
|
||||
assert 2050 <= x1 <= 2450
|
||||
|
||||
def test_too_narrow_is_none(self):
|
||||
cols = [0.0] * 2560
|
||||
for i in range(0, 100):
|
||||
cols[i] = 100.0
|
||||
assert text_column_extent(cols, 2560) is None
|
||||
|
||||
|
||||
class TestClampPaneWidth:
|
||||
def test_narrows_from_the_left_by_default(self):
|
||||
assert clamp_pane_width((300, 100, 2100, 1200), 1440) == (
|
||||
300, 100, 1440, 1200)
|
||||
|
||||
def test_noop_when_it_already_fits(self):
|
||||
assert clamp_pane_width((300, 100, 1200, 1200), 1440) == (
|
||||
300, 100, 1200, 1200)
|
||||
|
||||
def test_centred_anchor_splits_the_difference(self):
|
||||
assert clamp_pane_width((0, 0, 2000, 1000), 1000, anchor="center") == (
|
||||
500, 0, 1000, 1000)
|
||||
|
||||
def test_odd_width_is_made_even(self):
|
||||
_x, _y, w, _h = clamp_pane_width((0, 0, 2000, 1000), 1441)
|
||||
assert w % 2 == 0 and w <= 1441
|
||||
|
||||
|
||||
class TestStablePane:
|
||||
def test_agreement_returns_the_median(self):
|
||||
boxes = [(100, 100, 800, 300), (105, 102, 800, 300),
|
||||
(98, 99, 802, 301), (300, 300, 800, 300)]
|
||||
box = stable_pane(boxes, *HD)
|
||||
assert box is not None
|
||||
assert abs(box[0] - 100) <= 6 and abs(box[1] - 100) <= 4
|
||||
|
||||
def test_a_scattered_set_is_rejected(self):
|
||||
boxes = [(0, 0, 400, 300), (1500, 800, 400, 300),
|
||||
(700, 400, 400, 300)]
|
||||
assert stable_pane(boxes, *HD) is None
|
||||
|
||||
def test_too_few_samples_is_rejected(self):
|
||||
assert stable_pane([], *HD) is None
|
||||
assert stable_pane([(100, 100, 800, 300)], *HD) is None
|
||||
|
||||
|
||||
class TestCodeBands:
|
||||
def test_bands_fill_the_output_and_are_even(self):
|
||||
content_h, caption_h = code_bands(1920)
|
||||
assert content_h + caption_h == 1920
|
||||
assert content_h % 2 == 0 and caption_h % 2 == 0
|
||||
|
||||
def test_caption_reserve_is_about_fifteen_percent(self):
|
||||
_, caption_h = code_bands(1920)
|
||||
assert abs(caption_h / 1920 - CAPTION_BAND_RATIO) <= 0.01
|
||||
|
||||
def test_large_caption_ratio_still_leaves_a_band(self):
|
||||
content_h, caption_h = code_bands(1000, 0.9)
|
||||
assert content_h >= 2 and caption_h >= 2
|
||||
assert content_h + caption_h == 1000
|
||||
|
||||
|
||||
class TestFitWindow:
|
||||
def test_short_pane_fits_without_follow(self):
|
||||
crop_h, scaled_h, needs_follow = fit_window(300, 2.0, 1632)
|
||||
assert crop_h == 300 and scaled_h == 600
|
||||
assert needs_follow is False
|
||||
|
||||
def test_tall_pane_needs_a_follow_window(self):
|
||||
crop_h, scaled_h, needs_follow = fit_window(2000, 2.7, 1632)
|
||||
assert needs_follow is True
|
||||
assert scaled_h == 1632
|
||||
assert crop_h <= 2000 and crop_h % 2 == 0
|
||||
|
||||
def test_scaled_height_never_exceeds_the_band(self):
|
||||
for pane_h, scale in ((300, 2.0), (2000, 2.7), (1080, 0.75)):
|
||||
_, scaled_h, _ = fit_window(pane_h, scale, 1632)
|
||||
assert scaled_h <= 1632 and scaled_h % 2 == 0
|
||||
|
||||
def test_degenerate_pane_is_clamped_not_zero(self):
|
||||
crop_h, scaled_h, _ = fit_window(10, 0.01, 100)
|
||||
assert crop_h >= 2 and scaled_h >= 2
|
||||
|
||||
|
||||
class TestFollowSendcmd:
|
||||
def test_dedupes_change_points_and_is_segment_relative(self):
|
||||
follow = [(1.0, 100.0), (2.0, 100.0), (3.0, 200.0), (4.0, 200.0)]
|
||||
lines = follow_sendcmd_lines(follow, 0, 100, 500, start=1.0)
|
||||
assert len(lines) == 2
|
||||
assert lines[0].startswith("0.0000")
|
||||
assert lines[1].startswith("2.0000")
|
||||
assert "y 50;" in lines[0]
|
||||
assert "y 150;" in lines[1]
|
||||
|
||||
def test_window_is_clamped_to_the_pane(self):
|
||||
lines = follow_sendcmd_lines(
|
||||
[(0.0, -500.0), (1.0, 99999.0)], 100, 100, 500)
|
||||
ys = [int(ln.split(" y ")[1].rstrip(";")) for ln in lines]
|
||||
assert ys == [100, 500]
|
||||
|
||||
def test_points_before_the_segment_start_are_dropped(self):
|
||||
follow = [(0.0, 100.0), (2.0, 300.0)]
|
||||
lines = follow_sendcmd_lines(follow, 0, 100, 500, start=1.0)
|
||||
assert len(lines) == 1
|
||||
assert lines[0].startswith("1.0000")
|
||||
|
||||
|
||||
class TestCodeFiltergraph:
|
||||
def test_graph_crops_scales_and_overlays(self):
|
||||
graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920)
|
||||
assert graph is not None
|
||||
assert "crop=" in graph
|
||||
assert "scale=1080:600" in graph
|
||||
assert "overlay=x=0:y=" in graph
|
||||
assert graph.endswith("[v]")
|
||||
|
||||
def test_no_follow_means_no_sendcmd(self):
|
||||
graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920, follow=None)
|
||||
assert graph is not None
|
||||
assert "sendcmd" not in graph
|
||||
|
||||
def test_follow_on_a_tall_pane_emits_sendcmd(self):
|
||||
pane = (100, 0, 800, 4000)
|
||||
graph = code_filtergraph(pane, 1080, 1920,
|
||||
follow=[(0.0, 500.0), (2.0, 1500.0)])
|
||||
assert graph is not None
|
||||
assert "sendcmd=c=" in graph
|
||||
assert "crop@c=" in graph
|
||||
assert graph.endswith("[v]")
|
||||
|
||||
def test_follow_without_a_window_does_not_emit_sendcmd(self):
|
||||
graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920,
|
||||
follow=[(0.0, 500.0)])
|
||||
assert graph is not None
|
||||
assert "sendcmd" not in graph
|
||||
|
||||
def test_min_scale_fallback_returns_none(self):
|
||||
# out_w / pane_w = 1080 / 2000 = 0.54 < 0.75.
|
||||
assert code_filtergraph((0, 0, 2000, 800), 1080, 1920) is None
|
||||
|
||||
def test_min_scale_can_be_overridden(self):
|
||||
graph = code_filtergraph((0, 0, 2000, 800), 1080, 1920, min_scale=0.5)
|
||||
assert graph is not None
|
||||
|
||||
def test_accepts_a_detector_dict(self):
|
||||
pane = {"x": 200, "y": 100, "w": 1440, "h": 800, "mode": "editor"}
|
||||
assert code_filtergraph(pane, 1080, 1920) is not None
|
||||
|
||||
def test_camera_box_adds_a_third_branch(self):
|
||||
graph = code_filtergraph((200, 100, 1440, 800), 1080, 1920,
|
||||
cam_box=(0, 0, 300, 200))
|
||||
assert graph is not None
|
||||
assert "split=3" in graph
|
||||
assert "[cam]" in graph
|
||||
assert graph.endswith("[v]")
|
||||
|
|
@ -64,7 +64,7 @@ class TestPromptTemplates:
|
|||
def test_detail_template_carries_the_band(self):
|
||||
text = _templates()["DETAIL_PROMPT_TEMPLATE"].format(
|
||||
video_duration=100, language="es", min_clips=2, max_clips=4,
|
||||
min_secs=10.0, max_secs=20.0, profile_rules="", windows_json="[]")
|
||||
min_secs=10.0, max_secs=20.0, windows_json="[]")
|
||||
assert "10 to 20 seconds" in text
|
||||
assert "return 2 to 4 clips" in text
|
||||
|
||||
|
|
|
|||
|
|
@ -1,166 +0,0 @@
|
|||
"""Cadence handoff ingest (PLAN #8): manifest validation + word merging.
|
||||
|
||||
These exercise ``main.load_handoff_transcript`` directly. The CLI/e2e wiring
|
||||
(real ffmpeg, handoff actually skipping ASR) lives under ``tests/e2e``.
|
||||
"""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
main = pytest.importorskip("clipwright.pipeline.main") # needs cv2/mediapipe stubs
|
||||
|
||||
|
||||
def _write(path, data):
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _transcript(words):
|
||||
return {
|
||||
"text": " So the -Kanal.",
|
||||
"language": "en",
|
||||
"segments": [{"start": 0.0, "end": 0.8, "text": " So the -Kanal.",
|
||||
"words": words}],
|
||||
}
|
||||
|
||||
|
||||
WORDS = [
|
||||
{"word": " So", "start": 0.0, "end": 0.3},
|
||||
{"word": " the", "start": 0.3, "end": 0.5},
|
||||
{"word": "-Kanal.", "start": 0.5, "end": 0.8},
|
||||
]
|
||||
|
||||
|
||||
def _manifest(tmp_path, *, duration=6.0, transcript_rel="recording.transcript.json",
|
||||
schema="clipwright.handoff/1", transcript_ref=None):
|
||||
return {
|
||||
"schema": schema,
|
||||
"generator": {"name": "cadence", "version": "0.1.0"},
|
||||
"edited": {"timeline": "voice-audio", "duration": duration, "master": None},
|
||||
"sources": [{"index": 0, "path": "/abs/recordings/rec.mkv", "duration": 612.3}],
|
||||
"transcript": transcript_ref if transcript_ref is not None
|
||||
else {"path": transcript_rel},
|
||||
"candidates": [],
|
||||
"chapters": [],
|
||||
}
|
||||
|
||||
|
||||
# --- happy path ------------------------------------------------------------
|
||||
|
||||
def test_handoff_loads_and_merges_continuation_words(tmp_path):
|
||||
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path))
|
||||
_write(tmp_path / "recording.transcript.json", _transcript(WORDS))
|
||||
|
||||
result = main.load_handoff_transcript(
|
||||
tmp_path / "recording.handoff.json", tmp_path / "master.mp4", 6.0)
|
||||
|
||||
words = result["segments"][0]["words"]
|
||||
# The leading-space tokens stay boundaries; "-Kanal." (no leading space)
|
||||
# glues onto " the" and extends its end.
|
||||
assert [w["word"] for w in words] == [" So", " the-Kanal."]
|
||||
assert words[1]["end"] == 0.8
|
||||
|
||||
|
||||
def test_transcript_path_resolves_relative_to_the_manifest(tmp_path):
|
||||
sub = tmp_path / "bundle"
|
||||
sub.mkdir()
|
||||
_write(sub / "rec.handoff.json", _manifest(tmp_path, transcript_rel="rec.transcript.json"))
|
||||
_write(sub / "rec.transcript.json", _transcript(WORDS))
|
||||
|
||||
result = main.load_handoff_transcript(sub / "rec.handoff.json", "master.mp4", 5.99)
|
||||
assert result["segments"]
|
||||
|
||||
|
||||
def test_missing_words_list_is_tolerated(tmp_path):
|
||||
transcript = {"language": "en",
|
||||
"segments": [{"start": 0.0, "end": 1.0, "text": " no words"}]}
|
||||
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path))
|
||||
_write(tmp_path / "recording.transcript.json", transcript)
|
||||
|
||||
result = main.load_handoff_transcript(
|
||||
tmp_path / "recording.handoff.json", "master.mp4", 6.0)
|
||||
assert "words" not in result["segments"][0]
|
||||
|
||||
|
||||
# --- failure modes ---------------------------------------------------------
|
||||
|
||||
def test_missing_manifest_is_refused(tmp_path):
|
||||
with pytest.raises(main.HandoffError) as exc:
|
||||
main.load_handoff_transcript(tmp_path / "nope.json", "master.mp4", 6.0)
|
||||
assert "not found" in str(exc.value)
|
||||
|
||||
|
||||
def test_malformed_manifest_json_is_refused(tmp_path):
|
||||
(tmp_path / "bad.handoff.json").write_text("{ not json", encoding="utf-8")
|
||||
with pytest.raises(main.HandoffError) as exc:
|
||||
main.load_handoff_transcript(tmp_path / "bad.handoff.json", "master.mp4", 6.0)
|
||||
assert "malformed handoff manifest" in str(exc.value)
|
||||
|
||||
|
||||
def test_missing_transcript_is_refused(tmp_path):
|
||||
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path))
|
||||
with pytest.raises(main.HandoffError) as exc:
|
||||
main.load_handoff_transcript(
|
||||
tmp_path / "recording.handoff.json", "master.mp4", 6.0)
|
||||
assert "transcript not found" in str(exc.value)
|
||||
|
||||
|
||||
def test_manifest_without_transcript_path_is_refused(tmp_path):
|
||||
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path, transcript_ref={}))
|
||||
with pytest.raises(main.HandoffError) as exc:
|
||||
main.load_handoff_transcript(
|
||||
tmp_path / "recording.handoff.json", "master.mp4", 6.0)
|
||||
assert "transcript.path" in str(exc.value)
|
||||
|
||||
|
||||
def test_transcript_without_segments_is_refused(tmp_path):
|
||||
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path))
|
||||
_write(tmp_path / "recording.transcript.json", {"language": "en", "segments": []})
|
||||
with pytest.raises(main.HandoffError) as exc:
|
||||
main.load_handoff_transcript(
|
||||
tmp_path / "recording.handoff.json", "master.mp4", 6.0)
|
||||
assert "no segments" in str(exc.value)
|
||||
|
||||
|
||||
def test_unknown_schema_is_refused(tmp_path):
|
||||
_write(tmp_path / "recording.handoff.json",
|
||||
_manifest(tmp_path, schema="something.else/9"))
|
||||
_write(tmp_path / "recording.transcript.json", _transcript(WORDS))
|
||||
with pytest.raises(main.HandoffError) as exc:
|
||||
main.load_handoff_transcript(
|
||||
tmp_path / "recording.handoff.json", "master.mp4", 6.0)
|
||||
assert "unsupported handoff schema" in str(exc.value)
|
||||
|
||||
|
||||
# --- duration gate ---------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("measured", [5.96, 6.0, 6.04])
|
||||
def test_duration_within_one_percent_passes(tmp_path, measured):
|
||||
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path, duration=6.0))
|
||||
_write(tmp_path / "recording.transcript.json", _transcript(WORDS))
|
||||
assert main.load_handoff_transcript(
|
||||
tmp_path / "recording.handoff.json", "master.mp4", measured)["segments"]
|
||||
|
||||
|
||||
def test_duration_mismatch_refuses_and_points_at_transcript(tmp_path):
|
||||
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path, duration=6.0))
|
||||
_write(tmp_path / "recording.transcript.json", _transcript(WORDS))
|
||||
with pytest.raises(main.HandoffError) as exc:
|
||||
main.load_handoff_transcript(
|
||||
tmp_path / "recording.handoff.json", "master.mp4", 7.5)
|
||||
message = str(exc.value)
|
||||
assert "refusing the handoff" in message
|
||||
assert "--transcript" in message
|
||||
|
||||
|
||||
# --- never opens source paths ----------------------------------------------
|
||||
|
||||
def test_source_paths_are_never_opened(tmp_path):
|
||||
# A remote manifest may name any path; the loader must not touch it.
|
||||
manifest = _manifest(tmp_path)
|
||||
manifest["sources"] = [{"index": 0, "path": str(tmp_path / "does-not-exist.mkv")}]
|
||||
manifest["edited"]["master"] = {"path": str(tmp_path / "also-missing.mp4")}
|
||||
_write(tmp_path / "recording.handoff.json", manifest)
|
||||
_write(tmp_path / "recording.transcript.json", _transcript(WORDS))
|
||||
assert main.load_handoff_transcript(
|
||||
tmp_path / "recording.handoff.json", "master.mp4", 6.0)["segments"]
|
||||
|
|
@ -1,177 +0,0 @@
|
|||
"""Cadence handoff bundle staging at the API edge (PLAN #8).
|
||||
|
||||
Only the bundle transport is exercised here (ZIP in an /api/uploads slot); the
|
||||
CLI validation of the manifest is covered by tests/test_handoff.py and the
|
||||
tiny-video run under tests/e2e/pipeline.
|
||||
"""
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
app = pytest.importorskip("clipwright.api.app")
|
||||
|
||||
|
||||
def _zip_bytes(entries):
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for name, data in entries.items():
|
||||
zf.writestr(name, data)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _manifest_bytes(transcript_ref="rec.transcript.json",
|
||||
schema="clipwright.handoff/1"):
|
||||
return json.dumps({
|
||||
"schema": schema,
|
||||
"generator": {"name": "cadence", "version": "0.1.0"},
|
||||
"edited": {"duration": 6.0, "master": None},
|
||||
"sources": [{"index": 0, "path": "/abs/rec.mkv"}],
|
||||
"transcript": {"path": transcript_ref},
|
||||
"candidates": [],
|
||||
}).encode("utf-8")
|
||||
|
||||
|
||||
def _transcript_bytes():
|
||||
return json.dumps({
|
||||
"text": "hello",
|
||||
"language": "en",
|
||||
"segments": [{"start": 0.0, "end": 1.0, "text": " hello",
|
||||
"words": [{"word": " hello", "start": 0.0, "end": 1.0}]}],
|
||||
}).encode("utf-8")
|
||||
|
||||
|
||||
def _job_dir(tmp_path):
|
||||
job = tmp_path / "job"
|
||||
job.mkdir()
|
||||
return job
|
||||
|
||||
|
||||
# --- staging ---------------------------------------------------------------
|
||||
|
||||
def test_stages_manifest_and_transcript_into_the_job_dir(tmp_path):
|
||||
job = _job_dir(tmp_path)
|
||||
bundle = tmp_path / "bundle.zip"
|
||||
bundle.write_bytes(_zip_bytes({
|
||||
"rec.handoff.json": _manifest_bytes(),
|
||||
"rec.transcript.json": _transcript_bytes(),
|
||||
}))
|
||||
|
||||
manifest_path = app._stage_handoff_bundle(str(bundle), str(job))
|
||||
|
||||
assert manifest_path == str(job / "cadence_handoff.json")
|
||||
staged = json.loads(Path(manifest_path).read_text())
|
||||
assert staged["transcript"]["path"] == "source_transcript.json"
|
||||
assert staged["edited"]["duration"] == 6.0
|
||||
transcript = json.loads((job / "source_transcript.json").read_text())
|
||||
assert transcript["segments"]
|
||||
|
||||
|
||||
def test_manifest_found_by_schema_when_not_named_handoff_json(tmp_path):
|
||||
job = _job_dir(tmp_path)
|
||||
bundle = tmp_path / "bundle.zip"
|
||||
bundle.write_bytes(_zip_bytes({
|
||||
"cadence-manifest.json": _manifest_bytes(),
|
||||
"rec.transcript.json": _transcript_bytes(),
|
||||
}))
|
||||
manifest_path = app._stage_handoff_bundle(str(bundle), str(job))
|
||||
assert Path(manifest_path).exists()
|
||||
|
||||
|
||||
def test_member_paths_cannot_escape_the_job_dir(tmp_path):
|
||||
job = _job_dir(tmp_path)
|
||||
bundle = tmp_path / "bundle.zip"
|
||||
bundle.write_bytes(_zip_bytes({
|
||||
"../evil.handoff.json": _manifest_bytes(),
|
||||
"../rec.transcript.json": _transcript_bytes(),
|
||||
}))
|
||||
app._stage_handoff_bundle(str(bundle), str(job))
|
||||
assert not (tmp_path / "evil.handoff.json").exists()
|
||||
assert not (tmp_path / "rec.transcript.json").exists()
|
||||
assert (job / "cadence_handoff.json").exists()
|
||||
|
||||
|
||||
def test_non_zip_bundle_is_400(tmp_path):
|
||||
job = _job_dir(tmp_path)
|
||||
not_a_zip = tmp_path / "bundle.bin"
|
||||
not_a_zip.write_bytes(b"not a zip")
|
||||
with pytest.raises(app.HTTPException) as exc:
|
||||
app._stage_handoff_bundle(str(not_a_zip), str(job))
|
||||
assert exc.value.status_code == 400
|
||||
assert "ZIP" in exc.value.detail
|
||||
|
||||
|
||||
def test_bundle_without_a_manifest_is_400(tmp_path):
|
||||
job = _job_dir(tmp_path)
|
||||
bundle = tmp_path / "bundle.zip"
|
||||
bundle.write_bytes(_zip_bytes({"rec.transcript.json": _transcript_bytes()}))
|
||||
with pytest.raises(app.HTTPException) as exc:
|
||||
app._stage_handoff_bundle(str(bundle), str(job))
|
||||
assert exc.value.status_code == 400
|
||||
assert "manifest" in exc.value.detail
|
||||
|
||||
|
||||
def test_manifest_referencing_a_missing_transcript_is_400(tmp_path):
|
||||
job = _job_dir(tmp_path)
|
||||
bundle = tmp_path / "bundle.zip"
|
||||
bundle.write_bytes(_zip_bytes({"rec.handoff.json": _manifest_bytes()}))
|
||||
with pytest.raises(app.HTTPException) as exc:
|
||||
app._stage_handoff_bundle(str(bundle), str(job))
|
||||
assert exc.value.status_code == 400
|
||||
assert "not in the bundle" in exc.value.detail
|
||||
|
||||
|
||||
def test_transcript_without_segments_is_400(tmp_path):
|
||||
job = _job_dir(tmp_path)
|
||||
bundle = tmp_path / "bundle.zip"
|
||||
bundle.write_bytes(_zip_bytes({
|
||||
"rec.handoff.json": _manifest_bytes(),
|
||||
"rec.transcript.json": json.dumps({"segments": []}).encode(),
|
||||
}))
|
||||
with pytest.raises(app.HTTPException) as exc:
|
||||
app._stage_handoff_bundle(str(bundle), str(job))
|
||||
assert exc.value.status_code == 400
|
||||
assert "no segments" in exc.value.detail
|
||||
|
||||
|
||||
# --- /api/uploads handoff slot ---------------------------------------------
|
||||
|
||||
def _client_call(method, path, **kw):
|
||||
async def _do():
|
||||
transport = httpx.ASGITransport(app=app.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c:
|
||||
return await getattr(c, method)(path, **kw)
|
||||
return asyncio.run(_do())
|
||||
|
||||
|
||||
def test_handoff_slot_stores_a_zip_without_a_duration_probe(tmp_path, monkeypatch):
|
||||
uploads = tmp_path / "uploads"
|
||||
uploads.mkdir()
|
||||
monkeypatch.setattr(app, "UPLOAD_DIR", str(uploads))
|
||||
monkeypatch.setattr(app, "pending_uploads", {})
|
||||
|
||||
created = _client_call("post", "/api/uploads",
|
||||
json={"filename": "bundle.zip", "kind": "handoff"})
|
||||
assert created.status_code == 200
|
||||
assert created.json()["kind"] == "handoff"
|
||||
upload_id = created.json()["upload_id"]
|
||||
|
||||
bundle = _zip_bytes({
|
||||
"rec.handoff.json": _manifest_bytes(),
|
||||
"rec.transcript.json": _transcript_bytes(),
|
||||
})
|
||||
put = _client_call("put", f"/api/uploads/{upload_id}", content=bundle)
|
||||
assert put.status_code == 200
|
||||
assert put.json()["kind"] == "handoff"
|
||||
assert "duration_seconds" not in put.json()
|
||||
|
||||
|
||||
def test_unknown_upload_kind_is_400(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(app, "pending_uploads", {})
|
||||
resp = _client_call("post", "/api/uploads",
|
||||
json={"filename": "x.mp4", "kind": "nonsense"})
|
||||
assert resp.status_code == 400
|
||||
|
|
@ -1,170 +0,0 @@
|
|||
"""Hook-first clip boundaries: the pure ``find_hook_start`` pass (#2a).
|
||||
|
||||
The first two seconds decide the swipe, so the pass moves a clip's start off
|
||||
its wind-up and onto the earliest strong spoken token. It is deterministic and
|
||||
word-based (no LLM) and must fail safe: no clear hook -> no change, and the
|
||||
trim is capped by seconds, by fraction of the clip, and by the minimum clip
|
||||
duration.
|
||||
"""
|
||||
|
||||
from clipwright.pipeline.clip_selection import (
|
||||
find_hook_start,
|
||||
hook_first_enabled,
|
||||
)
|
||||
|
||||
|
||||
def _w(word, s, e):
|
||||
return {"w": word, "s": s, "e": e}
|
||||
|
||||
|
||||
class TestPicksEarliestHook:
|
||||
def test_picks_the_earliest_hook_after_the_wind_up(self):
|
||||
words = [
|
||||
_w(" so", 0.0, 0.3),
|
||||
_w(" uh", 0.3, 0.6),
|
||||
_w(" why", 1.2, 1.6), # interrogative — first hook
|
||||
_w(" do", 1.6, 1.8),
|
||||
_w(" we", 1.8, 2.0),
|
||||
]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 1.2
|
||||
|
||||
def test_earliest_wins_across_signal_categories(self):
|
||||
words = [
|
||||
_w(" okay", 0.0, 0.3),
|
||||
_w(" 3", 0.8, 1.1), # number
|
||||
_w(" but", 1.4, 1.7), # contrast
|
||||
_w(" crash", 2.0, 2.4), # stakes
|
||||
]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 0.8
|
||||
|
||||
def test_start_is_absolute_not_relative_to_the_clip(self):
|
||||
words = [_w(" huh", 100.0, 100.3), _w(" why", 103.0, 103.4)]
|
||||
assert find_hook_start(words, 100.0, 140.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 103.0
|
||||
|
||||
def test_a_clip_already_on_its_hook_is_left_alone(self):
|
||||
# trim ~0 is noise; returning None means "do not touch".
|
||||
words = [_w(" bug", 10.0, 10.3), _w(" but", 12.0, 12.3)]
|
||||
assert find_hook_start(words, 10.0, 40.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) is None
|
||||
|
||||
|
||||
class TestTrimCaps:
|
||||
def test_respects_max_trim_seconds(self):
|
||||
words = [_w(" uh", 0.0, 0.3), _w(" why", 6.0, 6.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=4.0, max_fraction=1.0) is None
|
||||
# Just inside the cap it fires.
|
||||
words[1] = _w(" why", 3.9, 4.3)
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=4.0, max_fraction=1.0) == 3.9
|
||||
|
||||
def test_respects_max_fraction_of_the_clip(self):
|
||||
words = [_w(" uh", 0.0, 0.3), _w(" why", 4.0, 4.4)]
|
||||
# duration 20, 10% -> 2.0s cap, so a 4.0s hook is out of reach.
|
||||
assert find_hook_start(words, 0.0, 20.0, min_duration=5.0,
|
||||
max_trim=100.0, max_fraction=0.1) is None
|
||||
# 50% -> 10s cap, the same hook is reachable.
|
||||
assert find_hook_start(words, 0.0, 20.0, min_duration=5.0,
|
||||
max_trim=100.0, max_fraction=0.5) == 4.0
|
||||
|
||||
def test_zero_cap_never_moves(self):
|
||||
words = [_w(" why", 1.0, 1.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=0.0, max_fraction=1.0) is None
|
||||
|
||||
def test_min_duration_wins_over_the_caps(self):
|
||||
# Hook at 2.0 is within the trim cap but would leave 14s < 15s.
|
||||
words = [_w(" why", 2.0, 2.4)]
|
||||
assert find_hook_start(words, 0.0, 16.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) is None
|
||||
|
||||
def test_degenerate_bounds_do_not_crash(self):
|
||||
words = [_w(" why", 1.0, 1.4)]
|
||||
assert find_hook_start(words, 5.0, 5.0, min_duration=15.0) is None
|
||||
assert find_hook_start(words, 0.0, 0.0, min_duration=15.0) is None
|
||||
|
||||
|
||||
class TestNoHook:
|
||||
def test_returns_none_without_a_hook(self):
|
||||
words = [
|
||||
_w(" and", 0.0, 0.3),
|
||||
_w(" then", 0.3, 0.6),
|
||||
_w(" we", 0.6, 0.9),
|
||||
_w(" the", 0.9, 1.2),
|
||||
]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) is None
|
||||
|
||||
def test_filler_alone_is_not_a_hook(self):
|
||||
words = [_w(" um", 0.0, 0.2), _w(" okay", 0.2, 0.5),
|
||||
_w(" yeah", 0.5, 0.8)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) is None
|
||||
|
||||
def test_empty_or_malformed_words_fail_safe(self):
|
||||
assert find_hook_start(None, 0.0, 30.0, min_duration=15.0) is None
|
||||
assert find_hook_start([], 0.0, 30.0, min_duration=15.0) is None
|
||||
assert find_hook_start(["junk", {"no_s": 1}], 1.0, 30.0,
|
||||
min_duration=15.0) is None
|
||||
|
||||
def test_clip_bounds_that_do_not_parse(self):
|
||||
assert find_hook_start([_w(" why", 1.0, 1.4)], None, 30.0) is None
|
||||
|
||||
|
||||
class TestTokenNormalisation:
|
||||
def test_words_without_leading_spaces_still_match(self):
|
||||
words = [_w("uh", 0.0, 0.3), _w("Why", 1.0, 1.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 1.0
|
||||
|
||||
def test_case_and_trailing_punctuation_are_stripped(self):
|
||||
words = [_w(" Uh,", 0.0, 0.3), _w("CRASH!", 1.0, 1.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 1.0
|
||||
|
||||
def test_numeric_tokens_are_hooks(self):
|
||||
assert find_hook_start([_w(" 2024", 1.0, 1.4)], 0.0, 30.0,
|
||||
min_duration=15.0, max_trim=5.0,
|
||||
max_fraction=0.5) == 1.0
|
||||
|
||||
def test_empty_word_text_is_ignored(self):
|
||||
words = [_w("", 0.5, 0.6), _w(" ", 0.6, 0.7), _w(" how", 1.0, 1.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0,
|
||||
max_trim=5.0, max_fraction=0.5) == 1.0
|
||||
|
||||
|
||||
class TestEnvConfig:
|
||||
def test_reads_max_trim_from_env(self, monkeypatch):
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_TRIM", "1.0")
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_FRACTION", "1.0")
|
||||
words = [_w(" uh", 0.0, 0.3), _w(" why", 2.0, 2.4)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) is None
|
||||
words[1] = _w(" why", 0.8, 1.2)
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) == 0.8
|
||||
|
||||
def test_reads_max_fraction_from_env(self, monkeypatch):
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_TRIM", "100")
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_FRACTION", "0.1")
|
||||
words = [_w(" uh", 0.0, 0.3), _w(" why", 4.0, 4.4)]
|
||||
assert find_hook_start(words, 0.0, 20.0, min_duration=5.0) is None
|
||||
|
||||
def test_garbage_env_falls_back_to_defaults(self, monkeypatch):
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_TRIM", "not-a-number")
|
||||
monkeypatch.setenv("HOOK_FIRST_MAX_FRACTION", "")
|
||||
words = [_w(" why", 3.5, 3.9)]
|
||||
assert find_hook_start(words, 0.0, 30.0, min_duration=15.0) == 3.5
|
||||
|
||||
def test_enabled_is_on_by_default(self, monkeypatch):
|
||||
monkeypatch.delenv("HOOK_FIRST", raising=False)
|
||||
assert hook_first_enabled() is True
|
||||
|
||||
def test_enabled_can_be_switched_off(self, monkeypatch):
|
||||
for raw in ("0", "false", "FALSE", "no", "off"):
|
||||
monkeypatch.setenv("HOOK_FIRST", raw)
|
||||
assert hook_first_enabled() is False
|
||||
|
||||
def test_enabled_explicit_true(self, monkeypatch):
|
||||
monkeypatch.setenv("HOOK_FIRST", "1")
|
||||
assert hook_first_enabled() is True
|
||||
|
|
@ -101,8 +101,7 @@ class TestPick:
|
|||
|
||||
class TestValidDecisions:
|
||||
def test_every_valid_decision_maps_to_known_modules(self):
|
||||
known = {"split_layout", "screencast_layout", "code_layout",
|
||||
"active_speaker"}
|
||||
known = {"split_layout", "screencast_layout", "active_speaker"}
|
||||
for decision in layout_picker.VALID:
|
||||
assert set(_module_flags(decision)) <= known
|
||||
|
||||
|
|
|
|||
|
|
@ -1,157 +0,0 @@
|
|||
"""Retention provenance (PLAN #10): one versioned record per clip.
|
||||
|
||||
Instrumentation only. Every clip carries its active profile, predicted score,
|
||||
start-boundary path (#2a hook-first vs the plain word snap), #6 bridge target
|
||||
and publish target, so the future retention/analytics loop is a data pull rather
|
||||
than a re-architecture. The loop itself is deliberately not built here.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
main = pytest.importorskip("clipwright.pipeline.main")
|
||||
from clipwright.pipeline import bridge, profiles # noqa: E402
|
||||
|
||||
|
||||
def _clip():
|
||||
return {
|
||||
"start": 12.3, "end": 42.3,
|
||||
"predicted_score": 85,
|
||||
"video_title_for_youtube_short": "I broke the world",
|
||||
"viral_hook_text": "I broke the world in one block",
|
||||
}
|
||||
|
||||
|
||||
class TestBuildProvenance:
|
||||
def test_schema_version_and_keys_without_profile(self):
|
||||
prov = main.build_provenance(_clip(), None)
|
||||
assert prov["schema_version"] == main.PROVENANCE_SCHEMA_VERSION == 1
|
||||
assert set(prov) == {"schema_version", "profile", "predicted_score",
|
||||
"hook", "bridge", "publish"}
|
||||
assert prov["profile"] is None
|
||||
assert prov["predicted_score"] == 85
|
||||
assert prov["publish"]["postiz_integration_id"] is None
|
||||
assert set(prov["hook"]) == {"applied", "source", "start", "trim",
|
||||
"proposed"}
|
||||
assert set(prov["bridge"]) == {"present", "related_video_url"}
|
||||
|
||||
def test_profile_and_publish_target_are_recorded(self):
|
||||
profile = profiles.Profile(
|
||||
slug="cseea", default_postiz_integration_id="postiz-42")
|
||||
prov = main.build_provenance(_clip(), profile)
|
||||
assert prov["profile"] == "cseea"
|
||||
assert prov["publish"]["postiz_integration_id"] == "postiz-42"
|
||||
|
||||
def test_hook_first_boundary_is_reused(self):
|
||||
clip = _clip()
|
||||
clip["hook_first"] = {"start": 10.0, "trim": 2.3, "proposed": 12.3}
|
||||
prov = main.build_provenance(clip, None)
|
||||
assert prov["hook"] == {"applied": True, "source": "hook_first",
|
||||
"start": 10.0, "trim": 2.3, "proposed": 12.3}
|
||||
|
||||
def test_plain_snap_boundary_is_marked_when_no_hook_moved_it(self):
|
||||
prov = main.build_provenance(_clip(), None)
|
||||
assert prov["hook"]["applied"] is False
|
||||
assert prov["hook"]["source"] == "snap"
|
||||
assert prov["hook"]["start"] is None
|
||||
assert prov["hook"]["trim"] is None
|
||||
assert prov["hook"]["proposed"] is None
|
||||
|
||||
def test_bridge_presence_and_related_target(self):
|
||||
clip = _clip()
|
||||
assert main.build_provenance(clip, None)["bridge"]["present"] is False
|
||||
target = "https://www.youtube.com/watch?v=LONGFORM123"
|
||||
clip.update(bridge.build_bridge(None, clip=clip,
|
||||
related_video_url=target))
|
||||
prov = main.build_provenance(clip, None)
|
||||
assert prov["bridge"] == {"present": True,
|
||||
"related_video_url": target}
|
||||
|
||||
def test_metadata_merge_is_additive_and_round_trips(self):
|
||||
"""The exact main.py sequence: bridge fields then provenance, JSON-safe."""
|
||||
profile = profiles.load_profile("cseea")
|
||||
clip = _clip()
|
||||
before = set(clip)
|
||||
clip.update(bridge.build_bridge(profile, clip=clip,
|
||||
related_video_url="https://youtu.be/x"))
|
||||
clip["provenance"] = main.build_provenance(clip, profile)
|
||||
|
||||
# Additive: the original keys survive untouched.
|
||||
assert before <= set(clip)
|
||||
|
||||
data = {"shorts": [clip]}
|
||||
reloaded = json.loads(json.dumps(data))
|
||||
prov = reloaded["shorts"][0]["provenance"]
|
||||
assert prov["schema_version"] == 1
|
||||
assert prov["profile"] == "cseea"
|
||||
assert set(prov) == {"schema_version", "profile", "predicted_score",
|
||||
"hook", "bridge", "publish"}
|
||||
|
||||
|
||||
app_module = pytest.importorskip("clipwright.api.app")
|
||||
|
||||
JOB_ID = "provenance-endpoint-test-job"
|
||||
|
||||
|
||||
def _request(method, path):
|
||||
async def _do():
|
||||
transport = httpx.ASGITransport(app=app_module.app)
|
||||
async with httpx.AsyncClient(transport=transport,
|
||||
base_url="http://testserver") as client:
|
||||
return await client.request(method, path)
|
||||
return asyncio.run(_do())
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def job(tmp_path, monkeypatch):
|
||||
out_root = tmp_path / "output"
|
||||
job_dir = out_root / JOB_ID
|
||||
job_dir.mkdir(parents=True)
|
||||
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
|
||||
clip = {"start": 0.0, "end": 30.0,
|
||||
"provenance": main.build_provenance(
|
||||
{"start": 0.0, "end": 30.0, "predicted_score": 77}, None)}
|
||||
meta = {"shorts": [clip],
|
||||
"transcript": {"language": "none", "segments": []}}
|
||||
(job_dir / "mytitle_metadata.json").write_text(json.dumps(meta))
|
||||
app_module.jobs[JOB_ID] = {"status": "completed", "logs": [],
|
||||
"result": {"clips": [dict(clip)]},
|
||||
"user_id": None}
|
||||
try:
|
||||
yield job_dir
|
||||
finally:
|
||||
app_module.jobs.pop(JOB_ID, None)
|
||||
|
||||
|
||||
class TestProvenanceEndpoint:
|
||||
def test_returns_the_versioned_record(self, job):
|
||||
resp = _request("GET", f"/api/clip/{JOB_ID}/0/provenance")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["schema_version"] == 1
|
||||
assert data["provenance"]["predicted_score"] == 77
|
||||
assert data["provenance"]["hook"]["source"] == "snap"
|
||||
|
||||
def test_old_clip_without_a_record_is_404(self, tmp_path, monkeypatch):
|
||||
out_root = tmp_path / "output2"
|
||||
job_dir = out_root / "old-job"
|
||||
job_dir.mkdir(parents=True)
|
||||
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
|
||||
meta = {"shorts": [{"start": 0.0, "end": 30.0}],
|
||||
"transcript": {"language": "none", "segments": []}}
|
||||
(job_dir / "mytitle_metadata.json").write_text(json.dumps(meta))
|
||||
app_module.jobs["old-job"] = {"status": "completed", "logs": [],
|
||||
"result": {"clips": [{"start": 0.0}]},
|
||||
"user_id": None}
|
||||
try:
|
||||
resp = _request("GET", "/api/clip/old-job/0/provenance")
|
||||
assert resp.status_code == 404
|
||||
assert "No provenance" in resp.json()["detail"]
|
||||
finally:
|
||||
app_module.jobs.pop("old-job", None)
|
||||
|
||||
def test_unknown_clip_is_404(self, job):
|
||||
resp = _request("GET", f"/api/clip/{JOB_ID}/99/provenance")
|
||||
assert resp.status_code == 404
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
"""Word-aligned punch-in beats: the pure derivation in punch_in.emphasis_times.
|
||||
|
||||
#2b moved beat timing from audio-envelope-only to the envelope snapped onto
|
||||
clip-relative word onsets. These tests pin the merge itself (no audio file
|
||||
needed) and the one behaviour that must not change: no word times -> exactly
|
||||
the old audio-only result.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from clipwright.layouts import punch_in
|
||||
from clipwright.layouts.punch_in import merge_beats
|
||||
|
||||
|
||||
class TestMergeBeats:
|
||||
def test_no_words_is_audio_only(self):
|
||||
assert merge_beats([1.0, 15.0], [], min_gap=4.0) == [1.0, 15.0]
|
||||
assert merge_beats([1.0, 15.0], None, min_gap=4.0) == [1.0, 15.0]
|
||||
|
||||
def test_envelope_beat_snaps_to_a_nearby_word(self):
|
||||
# The envelope peak sits 0.2s off the spoken word: the word is exact.
|
||||
assert merge_beats([10.0], [10.2], min_gap=4.0) == [10.2]
|
||||
|
||||
def test_a_distant_word_does_not_move_the_envelope_beat(self):
|
||||
# 5.0 is nowhere near either peak, so neither peak is re-timed.
|
||||
assert merge_beats([1.0, 30.0], [5.0], min_gap=4.0) == [1.0, 30.0]
|
||||
|
||||
def test_words_become_beats_when_audio_has_none(self):
|
||||
assert merge_beats([], [3.0, 40.0], min_gap=18.0) == [3.0, 40.0]
|
||||
|
||||
def test_beats_are_thinned_to_the_minimum_gap(self):
|
||||
# 2 and 4 collide at gap 10; the earliest wins, 20 keeps its own slot.
|
||||
assert merge_beats([2.0, 4.0, 20.0], [], min_gap=10.0) == [2.0, 20.0]
|
||||
|
||||
def test_result_is_sorted_and_rounded(self):
|
||||
assert merge_beats([12.3456], [], min_gap=4.0) == [12.346]
|
||||
assert merge_beats([], [3.0, 12.3456], min_gap=4.0) == [3.0, 12.346]
|
||||
|
||||
|
||||
class TestEmphasisTimesWithWords:
|
||||
def _envelope_spike(self, monkeypatch, beat_index=10, value=1.0, length=50):
|
||||
from clipwright.layouts import active_speaker
|
||||
envelope = [0.0] * length
|
||||
envelope[beat_index] = value
|
||||
monkeypatch.setattr(active_speaker, "audio_envelope",
|
||||
lambda *a, **k: envelope)
|
||||
return beat_index * 0.2 # window defaults to BEAT_WINDOW
|
||||
|
||||
def test_silent_audio_with_words_still_yields_word_beats(self, monkeypatch):
|
||||
from clipwright.layouts import active_speaker
|
||||
monkeypatch.setattr(active_speaker, "audio_envelope",
|
||||
lambda *a, **k: [])
|
||||
assert punch_in.emphasis_times("x.mp4", 30.0, word_times=[4.0]) == [4.0]
|
||||
|
||||
def test_no_words_keeps_the_old_audio_only_result(self, monkeypatch):
|
||||
beat = self._envelope_spike(monkeypatch, beat_index=10)
|
||||
assert punch_in.emphasis_times("x.mp4", 20.0) == [round(beat, 3)]
|
||||
|
||||
def test_word_snaps_the_envelope_spike_onto_itself(self, monkeypatch):
|
||||
beat = self._envelope_spike(monkeypatch, beat_index=10)
|
||||
times = punch_in.emphasis_times("x.mp4", 20.0, word_times=[beat + 0.1])
|
||||
assert times == [round(beat + 0.1, 3)]
|
||||
|
||||
def test_empty_word_list_is_backward_compatible(self, monkeypatch):
|
||||
beat = self._envelope_spike(monkeypatch, beat_index=5)
|
||||
assert (punch_in.emphasis_times("x.mp4", 20.0, word_times=[])
|
||||
== [round(beat, 3)])
|
||||
|
||||
|
||||
class TestClipWordOnsets:
|
||||
def _onsets(self, transcript, start, end):
|
||||
pytest.importorskip("clipwright.pipeline.main")
|
||||
from clipwright.pipeline.main import clip_word_onsets
|
||||
return clip_word_onsets(transcript, start, end)
|
||||
|
||||
def test_words_become_clip_relative_seconds(self):
|
||||
transcript = {"segments": [{"words": [
|
||||
{"word": "a", "start": 100.0, "end": 100.5},
|
||||
{"word": "b", "start": 102.0, "end": 102.5},
|
||||
{"word": "c", "start": 111.0, "end": 111.5}, # after the clip
|
||||
]}]}
|
||||
assert self._onsets(transcript, 100.0, 110.0) == [0.0, 2.0]
|
||||
|
||||
def test_boundary_words_are_clamped_into_the_clip(self):
|
||||
transcript = {"segments": [{"words": [
|
||||
{"word": "x", "start": 98.0, "end": 101.0}, # starts before
|
||||
{"word": "y", "start": 109.0, "end": 112.0}, # ends after
|
||||
]}]}
|
||||
assert self._onsets(transcript, 100.0, 110.0) == [0.0, 9.0]
|
||||
|
||||
def test_no_transcript_or_words_is_empty(self):
|
||||
assert self._onsets(None, 0.0, 10.0) == []
|
||||
assert self._onsets({"segments": []}, 0.0, 10.0) == []
|
||||
assert self._onsets({"segments": [{"text": "hi"}]}, 0.0, 10.0) == []
|
||||
|
|
@ -56,11 +56,9 @@ def test_normalise_concepts_clamps_and_pads():
|
|||
]
|
||||
out = thumbnail.normalise_concepts(raw, 3, "My title", thumbnail_text_hint="hint")
|
||||
assert len(out) == 3
|
||||
assert out[0]["text"] == "ESTO FUNCIONA"
|
||||
assert out[0]["text_position"] == "left"
|
||||
# #4: a role is always present and the set covers emotion + technical.
|
||||
assert {"emotion", "technical"} <= {c["role"] for c in out}
|
||||
assert out[1]["text"] == "HINT"
|
||||
assert out[0] == {"text": "ESTO FUNCIONA", "text_position": "left", "text_color": "white",
|
||||
"scene": "a desk", "why": ""}
|
||||
assert out[1]["why"] == "fallback" and out[1]["text"] == "HINT"
|
||||
|
||||
|
||||
def test_parse_json_tolerates_fences_and_prose():
|
||||
|
|
|
|||
|
|
@ -1,316 +0,0 @@
|
|||
"""Deterministic title QA and thumbnail roles (PLAN #3 + #4).
|
||||
|
||||
The validator is pure; the retry is exercised with a scripted fake client, both
|
||||
for the Studio brainstorm path and the free_tools endpoint.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from clipwright.api import free_tools as ft
|
||||
from clipwright.media import thumbnail
|
||||
from clipwright.media import title_validation as tv
|
||||
from clipwright.pipeline import profiles
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cseea():
|
||||
return profiles.load_profile("cseea")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def pedro():
|
||||
return profiles.load_profile("pedro")
|
||||
|
||||
|
||||
# --- single-title rules ----------------------------------------------------
|
||||
|
||||
def test_good_cseea_title_has_no_violations(cseea):
|
||||
assert tv.validate_title("Why this Alpha world broke", cseea) == []
|
||||
|
||||
|
||||
def test_banned_phrase_and_opener_are_reported(cseea):
|
||||
assert any("banned phrase" in p for p in tv.validate_title(
|
||||
"How to break Alpha in a tutorial", cseea))
|
||||
assert any("banned opener" in p for p in tv.validate_title(
|
||||
"Exploring Alpha's forgotten mechanic", cseea))
|
||||
|
||||
|
||||
def test_length_limits(cseea):
|
||||
# cseea: max 60, mobile 38. 45 chars is under max but over mobile.
|
||||
over_mobile = "Why this forgotten Alpha mechanic still works"
|
||||
assert 38 < len(over_mobile) <= 60
|
||||
problems = tv.validate_title(over_mobile, cseea)
|
||||
assert any("mobile limit" in p for p in problems)
|
||||
|
||||
over_max = "Why " + "x" * 60
|
||||
assert any("maximum" in p for p in tv.validate_title(over_max, cseea))
|
||||
|
||||
|
||||
def test_number_policy_avoid_and_require(cseea, pedro):
|
||||
assert any("number" in p for p in tv.validate_title(
|
||||
"Why 3 blocks broke the world", cseea))
|
||||
assert tv.validate_title("Why 3 blocks broke the world", pedro) == []
|
||||
|
||||
|
||||
def test_required_signal_consequence_and_curiosity(cseea, pedro):
|
||||
assert any("curiosity" in p for p in tv.validate_title(
|
||||
"Alpha world seed tour", cseea))
|
||||
assert any("consequence" in p for p in tv.validate_title(
|
||||
"Alpha channel overview", pedro))
|
||||
|
||||
|
||||
def test_keyword_position_start_rejects_a_filler_opener(cseea):
|
||||
assert any("filler word" in p for p in tv.validate_title(
|
||||
"The Alpha glitch", cseea))
|
||||
|
||||
|
||||
def test_task_descriptive_opener_is_rejected_without_a_profile():
|
||||
assert any("task-descriptive" in p for p in tv.validate_title(
|
||||
"In this video we break Alpha", None))
|
||||
assert tv.validate_title("Why this Alpha world broke", None) == []
|
||||
|
||||
|
||||
# --- structural rules across a set -----------------------------------------
|
||||
|
||||
def test_more_than_three_same_first_word_is_a_violation():
|
||||
titles = ["Alpha one", "Alpha two", "Alpha three", "Alpha four"]
|
||||
assert any("same word" in p for p in tv.validate_titles(titles, None))
|
||||
|
||||
|
||||
def test_more_than_two_colons_is_a_violation():
|
||||
titles = ["A: one", "B: two", "C: three"]
|
||||
assert any("colon" in p for p in tv.validate_titles(titles, None))
|
||||
|
||||
|
||||
def test_no_titles_is_reported():
|
||||
assert "no titles" in tv.validate_titles([], None)
|
||||
|
||||
|
||||
def test_violations_are_prefixed_with_the_title_number(cseea):
|
||||
problems = tv.validate_titles(["Alpha world seed tour", "Why this broke"], cseea)
|
||||
assert any(p.startswith("title 1:") for p in problems)
|
||||
assert not any(p.startswith("title 2:") for p in problems)
|
||||
|
||||
|
||||
# --- run_with_validation ----------------------------------------------------
|
||||
|
||||
def test_retry_runs_exactly_once_and_keeps_the_better_attempt():
|
||||
calls = {"retry": 0}
|
||||
|
||||
def generate():
|
||||
return ["Alpha channel overview"]
|
||||
|
||||
def validate(candidate):
|
||||
return [] if candidate == ["Why this broke"] else ["bad"]
|
||||
|
||||
def retry_once(violations):
|
||||
calls["retry"] += 1
|
||||
return ["Why this broke"]
|
||||
|
||||
best = tv.run_with_validation(generate, validate, retry_once)
|
||||
assert best == ["Why this broke"]
|
||||
assert calls["retry"] == 1
|
||||
|
||||
|
||||
def test_no_retry_when_the_first_attempt_is_valid():
|
||||
calls = {"retry": 0}
|
||||
best = tv.run_with_validation(
|
||||
lambda: ["Why this broke"],
|
||||
lambda c: [],
|
||||
lambda v: calls.__setitem__("retry", calls["retry"] + 1))
|
||||
assert best == ["Why this broke"]
|
||||
assert calls["retry"] == 0
|
||||
|
||||
|
||||
def test_a_retry_that_does_not_improve_keeps_the_first_attempt():
|
||||
best = tv.run_with_validation(
|
||||
lambda: ["first"], lambda c: ["still bad"], lambda v: ["second"])
|
||||
assert best == ["first"]
|
||||
|
||||
|
||||
def test_a_retry_that_raises_keeps_the_first_attempt():
|
||||
def boom(violations):
|
||||
raise RuntimeError("model down")
|
||||
best = tv.run_with_validation(lambda: ["first"], lambda c: ["bad"], boom)
|
||||
assert best == ["first"]
|
||||
|
||||
|
||||
def test_a_retry_that_returns_none_keeps_the_first_attempt():
|
||||
best = tv.run_with_validation(lambda: ["first"], lambda c: ["bad"],
|
||||
lambda v: None)
|
||||
assert best == ["first"]
|
||||
|
||||
|
||||
# --- the Studio path retries exactly once ----------------------------------
|
||||
|
||||
_GOOD_TITLE = "Why this broke everything"
|
||||
_BAD_TITLE = "Alpha channel overview"
|
||||
|
||||
|
||||
def _prompt_text(contents):
|
||||
if isinstance(contents, str):
|
||||
return contents
|
||||
return "\n".join(c if isinstance(c, str) else (getattr(c, "text", "") or "")
|
||||
for c in (contents or []))
|
||||
|
||||
|
||||
class _RecordingModels:
|
||||
def __init__(self, responses):
|
||||
self.prompts = []
|
||||
self.responses = list(responses)
|
||||
|
||||
def generate_content(self, model=None, contents=None, config=None):
|
||||
self.prompts.append(_prompt_text(contents))
|
||||
return SimpleNamespace(text=self.responses.pop(0))
|
||||
|
||||
|
||||
class _RecordingClient:
|
||||
def __init__(self, responses):
|
||||
self.models = _RecordingModels(responses)
|
||||
|
||||
|
||||
def _critic_json(title):
|
||||
return ('{"titles": ["%s"], "thumbnail_texts": ["A"], "recommended": []}' % title)
|
||||
|
||||
|
||||
_BRAINSTORM = ('{"transcript_summary": "s", "candidates": ["%s", "%s"]}'
|
||||
% (_GOOD_TITLE, _BAD_TITLE))
|
||||
_TRANSCRIPT = {"language": "en", "text": "hello world",
|
||||
"segments": [{"start": 0.0, "end": 10.0, "text": "hello"}]}
|
||||
|
||||
|
||||
def _analyze(monkeypatch, responses, profile):
|
||||
client = _RecordingClient(responses)
|
||||
monkeypatch.setattr(thumbnail, "_frame_parts", lambda *a, **k: [])
|
||||
monkeypatch.setattr(thumbnail, "genai", SimpleNamespace(
|
||||
Client=lambda api_key=None, **k: client))
|
||||
result = thumbnail.analyze_video_for_titles(
|
||||
"key", "video.mp4", transcript=_TRANSCRIPT, profile=profile)
|
||||
return result, client.models.prompts
|
||||
|
||||
|
||||
def test_analyze_retries_once_on_invalid_titles(monkeypatch, pedro):
|
||||
result, prompts = _analyze(
|
||||
monkeypatch, [_BRAINSTORM, _critic_json(_BAD_TITLE), _critic_json(_GOOD_TITLE)], pedro)
|
||||
assert result["titles"] == [_GOOD_TITLE]
|
||||
assert len(prompts) == 3 # brainstorm + critic + one retry
|
||||
assert "VALIDATION FAILED" in prompts[2]
|
||||
|
||||
|
||||
def test_analyze_keeps_the_first_attempt_when_the_retry_is_also_invalid(monkeypatch, pedro):
|
||||
result, prompts = _analyze(
|
||||
monkeypatch, [_BRAINSTORM, _critic_json(_BAD_TITLE), _critic_json(_BAD_TITLE)], pedro)
|
||||
assert result["titles"] == [_BAD_TITLE]
|
||||
assert len(prompts) == 3
|
||||
|
||||
|
||||
def test_analyze_never_blocks_when_the_retry_call_fails(monkeypatch, pedro):
|
||||
# No third response: the retry raises, and the first attempt must still ship.
|
||||
result, prompts = _analyze(monkeypatch, [_BRAINSTORM, _critic_json(_BAD_TITLE)], pedro)
|
||||
assert result["titles"] == [_BAD_TITLE]
|
||||
|
||||
|
||||
def test_analyze_does_not_retry_a_valid_critic(monkeypatch, pedro):
|
||||
result, prompts = _analyze(
|
||||
monkeypatch, [_BRAINSTORM, _critic_json(_GOOD_TITLE)], pedro)
|
||||
assert result["titles"] == [_GOOD_TITLE]
|
||||
assert len(prompts) == 2
|
||||
|
||||
|
||||
# --- #4 roles ---------------------------------------------------------------
|
||||
|
||||
def test_normalise_forces_emotion_and_technical():
|
||||
raw = [
|
||||
{"text": "A", "scene": "s1", "role": "curiosity"},
|
||||
{"text": "B", "scene": "s2", "role": "curiosity"},
|
||||
]
|
||||
out = thumbnail.normalise_concepts(raw, 2, "My title")
|
||||
roles = [c["role"] for c in out]
|
||||
assert "emotion" in roles and "technical" in roles
|
||||
assert len(out) == 2
|
||||
|
||||
|
||||
def test_normalise_uses_role_order_for_padding():
|
||||
out = thumbnail.normalise_concepts([], 2, "My title",
|
||||
role_order=["technical", "emotion", "curiosity"])
|
||||
assert [c["role"] for c in out] == ["technical", "emotion"]
|
||||
|
||||
|
||||
def test_normalise_single_concept_does_not_crash():
|
||||
out = thumbnail.normalise_concepts(
|
||||
[{"text": "A", "scene": "s", "role": "curiosity"}], 1, "My title")
|
||||
assert len(out) == 1
|
||||
|
||||
|
||||
def test_normalise_replaces_an_unknown_role():
|
||||
out = thumbnail.normalise_concepts(
|
||||
[{"text": "A", "scene": "s", "role": "banana"}], 2, "My title")
|
||||
assert all(c["role"] in thumbnail.CONCEPT_ROLES for c in out)
|
||||
|
||||
|
||||
def test_plan_prompt_requires_a_role_and_output_carries_one():
|
||||
concepts = ('{"concepts": ['
|
||||
'{"text": "A", "text_position": "left", "text_color": "yellow",'
|
||||
' "role": "curiosity", "scene": "a desk", "why": "w"},'
|
||||
'{"text": "B", "text_position": "right", "text_color": "white",'
|
||||
' "role": "technical", "scene": "a screen", "why": "w"}]}')
|
||||
client = _RecordingClient([concepts])
|
||||
out = thumbnail.plan_thumbnail_concepts(client, "My title", 2)
|
||||
assert '"role"' in client.models.prompts[0]
|
||||
assert all(c["role"] in thumbnail.CONCEPT_ROLES for c in out)
|
||||
|
||||
|
||||
# --- #4 bottom-right safe area ---------------------------------------------
|
||||
|
||||
def test_burn_text_keeps_clear_of_the_bottom_right_corner():
|
||||
img = Image.new("RGB", (1280, 720), (0, 0, 0))
|
||||
out = thumbnail.burn_thumbnail_text(
|
||||
img, "WHY THIS BROKE EVERYTHING", "bottom", "white").convert("RGB")
|
||||
|
||||
bottom = out.crop((0, int(720 * 0.80), 1280, 720))
|
||||
assert max(bottom.getextrema()[0]) < 60, "ink intrudes into the bottom 20%"
|
||||
right = out.crop((int(1280 * 0.95), 0, 1280, 720))
|
||||
assert max(right.getextrema()[0]) < 60, "ink touches the right edge"
|
||||
# Sanity: something was actually drawn outside the reserved corner.
|
||||
middle = out.crop((0, 0, 1280, int(720 * 0.80)))
|
||||
assert max(middle.getextrema()[0]) > 200
|
||||
|
||||
|
||||
# --- free_tools endpoint ----------------------------------------------------
|
||||
|
||||
def _metadata_client():
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
app = FastAPI()
|
||||
app.include_router(ft.router)
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_metadata_titles_retry_once_on_violations(monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_generate(prompt):
|
||||
calls.append(prompt)
|
||||
if "VALIDATION FAILED" in prompt:
|
||||
return {"titles": [{"title": _GOOD_TITLE, "angle": "a"}]}
|
||||
return {"titles": [{"title": _BAD_TITLE, "angle": "a"}]}
|
||||
|
||||
monkeypatch.setattr(ft, "_gemini_key", lambda: "k")
|
||||
monkeypatch.setattr(ft, "_generate", fake_generate)
|
||||
r = _metadata_client().post("/api/tools/youtube-metadata", json={
|
||||
"mode": "titles", "topic": "A talk about low level systems", "channel": "pedro"})
|
||||
|
||||
assert r.status_code == 200, r.text
|
||||
assert [t["title"] for t in r.json()["titles"]] == [_GOOD_TITLE]
|
||||
assert len(calls) == 2
|
||||
assert "violations" not in r.json()
|
||||
|
||||
|
||||
def test_metadata_unknown_channel_is_400(monkeypatch):
|
||||
monkeypatch.setattr(ft, "_gemini_key", lambda: "k")
|
||||
r = _metadata_client().post("/api/tools/youtube-metadata", json={
|
||||
"mode": "titles", "topic": "A talk about low level systems", "channel": "nope"})
|
||||
assert r.status_code == 400
|
||||
assert r.json()["detail"]["code"] == "bad_channel"
|
||||
|
|
@ -1,130 +0,0 @@
|
|||
"""``integrations.youtube_data`` (PLAN #6): mocked HTTP, never live OAuth.
|
||||
|
||||
Every call goes through an ``httpx.Client`` built on a ``MockTransport``, so no
|
||||
network is touched. The unconfigured path must be a hard no-op: not one request.
|
||||
"""
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from clipwright.integrations import youtube_data
|
||||
|
||||
|
||||
def _configure(monkeypatch):
|
||||
monkeypatch.setenv(youtube_data.CLIENT_ID_ENV, "cid")
|
||||
monkeypatch.setenv(youtube_data.CLIENT_SECRET_ENV, "secret")
|
||||
monkeypatch.setenv(youtube_data.REFRESH_TOKEN_ENV, "refresh")
|
||||
monkeypatch.setenv(youtube_data.TOKEN_URI_ENV, "https://oauth.test/token")
|
||||
|
||||
|
||||
def _unconfigure(monkeypatch):
|
||||
for name in (youtube_data.CLIENT_ID_ENV, youtube_data.CLIENT_SECRET_ENV,
|
||||
youtube_data.REFRESH_TOKEN_ENV):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
class _Recorder:
|
||||
"""Records requests and answers the token + comment calls."""
|
||||
|
||||
def __init__(self, token_status=200, comment_status=200,
|
||||
comment_json=None):
|
||||
self.requests = []
|
||||
self.token_status = token_status
|
||||
self.comment_status = comment_status
|
||||
self.comment_json = comment_json or {
|
||||
"id": "comment-1",
|
||||
"snippet": {"videoId": "short-1"},
|
||||
}
|
||||
|
||||
def handler(self, request):
|
||||
self.requests.append(request)
|
||||
if request.url.path.endswith("/token"):
|
||||
return httpx.Response(self.token_status, json={"access_token": "tok"})
|
||||
return httpx.Response(self.comment_status, json=self.comment_json)
|
||||
|
||||
def client(self):
|
||||
return httpx.Client(transport=httpx.MockTransport(self.handler))
|
||||
|
||||
|
||||
def test_is_configured_tracks_env(monkeypatch):
|
||||
_unconfigure(monkeypatch)
|
||||
assert youtube_data.is_configured() is False
|
||||
_configure(monkeypatch)
|
||||
assert youtube_data.is_configured() is True
|
||||
|
||||
|
||||
def test_unconfigured_is_a_noop_and_makes_no_request(monkeypatch):
|
||||
_unconfigure(monkeypatch)
|
||||
recorder = _Recorder()
|
||||
with pytest.raises(youtube_data.YoutubeDataError) as exc:
|
||||
youtube_data.post_first_comment("short-1", "hello", client=recorder.client())
|
||||
assert exc.value.status_code == 400
|
||||
assert "not configured" in exc.value.detail
|
||||
assert recorder.requests == []
|
||||
|
||||
|
||||
def test_posts_first_comment_with_refresh_token(monkeypatch):
|
||||
_configure(monkeypatch)
|
||||
recorder = _Recorder()
|
||||
result = youtube_data.post_first_comment(
|
||||
"short-1", "watch the full video", client=recorder.client())
|
||||
|
||||
assert result["id"] == "comment-1"
|
||||
assert [r.method for r in recorder.requests] == ["POST", "POST"]
|
||||
token_req, comment_req = recorder.requests
|
||||
assert token_req.url == "https://oauth.test/token"
|
||||
assert b"grant_type=refresh_token" in token_req.content
|
||||
assert b"refresh_token=refresh" in token_req.content
|
||||
|
||||
assert comment_req.url.path.endswith("/commentThreads")
|
||||
assert comment_req.url.params["part"] == "snippet"
|
||||
assert comment_req.headers["authorization"] == "Bearer tok"
|
||||
body = json.loads(comment_req.content)
|
||||
assert body["snippet"]["videoId"] == "short-1"
|
||||
assert (body["snippet"]["topLevelComment"]["snippet"]["textOriginal"]
|
||||
== "watch the full video")
|
||||
|
||||
|
||||
def test_token_failure_is_reported_without_posting(monkeypatch):
|
||||
_configure(monkeypatch)
|
||||
recorder = _Recorder(token_status=401)
|
||||
with pytest.raises(youtube_data.YoutubeDataError) as exc:
|
||||
youtube_data.post_first_comment("short-1", "hi", client=recorder.client())
|
||||
assert exc.value.status_code == 502
|
||||
assert "token refresh failed" in exc.value.detail
|
||||
assert len(recorder.requests) == 1 # never reached commentThreads
|
||||
|
||||
|
||||
def test_comment_error_carries_status_and_truncated_body(monkeypatch):
|
||||
_configure(monkeypatch)
|
||||
recorder = _Recorder(comment_status=403)
|
||||
with pytest.raises(youtube_data.YoutubeDataError) as exc:
|
||||
youtube_data.post_first_comment("short-1", "hi", client=recorder.client())
|
||||
assert exc.value.status_code == 403
|
||||
assert "commentThreads.insert failed" in exc.value.detail
|
||||
|
||||
|
||||
def test_server_error_maps_to_502(monkeypatch):
|
||||
_configure(monkeypatch)
|
||||
recorder = _Recorder(comment_status=500)
|
||||
with pytest.raises(youtube_data.YoutubeDataError) as exc:
|
||||
youtube_data.post_first_comment("short-1", "hi", client=recorder.client())
|
||||
assert exc.value.status_code == 502
|
||||
|
||||
|
||||
def test_missing_inputs_are_refused(monkeypatch):
|
||||
_configure(monkeypatch)
|
||||
recorder = _Recorder()
|
||||
client = recorder.client()
|
||||
with pytest.raises(youtube_data.YoutubeDataError):
|
||||
youtube_data.post_first_comment("", "hi", client=client)
|
||||
with pytest.raises(youtube_data.YoutubeDataError):
|
||||
youtube_data.post_first_comment("short-1", " ", client=client)
|
||||
assert recorder.requests == []
|
||||
|
||||
|
||||
def test_scope_is_force_ssl():
|
||||
# commentThreads.insert requires force-ssl; documented so a refactor cannot
|
||||
# silently drop it.
|
||||
assert youtube_data.SCOPE == "https://www.googleapis.com/auth/youtube.force-ssl"
|
||||
Loading…
Reference in a new issue