From 83ad1feababba8bd6a1436a2dfb5be8e78c4aff1 Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Sun, 4 Oct 2026 20:40:38 +0100 Subject: [PATCH] refactor: move backend into the clipwright package Restructure the 37 root-level Python modules into a proper package: clipwright/{core,api,pipeline,layouts,media,integrations,tools} - Rewrite every local import (module-level and deferred) to absolute clipwright.. form; no legacy root shims or re-exports. - Add clipwright/core/paths.py and route fonts/assets/cookies through it. - Entry points: uvicorn clipwright.api.app:app; jobs run as python -m clipwright.pipeline.main; probe as -m ...quality_probe. - child_env() appends REPO_ROOT to PYTHONPATH so the -m workers work. - transcribe_backends: sys.modules key now clipwright.media.scene_detection. - Tooling: root pyproject.toml (pytest pythonpath=[.], ruff), shared requirements-test.txt, CI installs it, Docker PYTHONPATH=/app. - Tests: all imports/fakes/source-scans repointed; new tests/test_package_layout.py enforces no root modules, docstring-only __init__, and no legacy imports. - Docs/comments updated for the new layout. Backend: 744 passed, 19 skipped. Frontend lint+build green. --- .env.example | 2 +- .github/workflows/ci.yml | 15 +-- Dockerfile | 7 +- README.md | 21 +++++ clipwright/__init__.py | 1 + clipwright/api/__init__.py | 1 + app.py => clipwright/api/app.py | 57 ++++++----- free_tools.py => clipwright/api/free_tools.py | 0 media_auth.py => clipwright/api/media_auth.py | 0 .../api/restoring_static.py | 0 clipwright/core/__init__.py | 1 + clipwright/core/paths.py | 31 ++++++ .../core/security_utils.py | 0 clipwright/integrations/__init__.py | 1 + .../integrations/file_hosts.py | 0 .../integrations/postiz.py | 0 .../integrations/yt_clients.py | 0 clipwright/layouts/__init__.py | 1 + .../layouts/active_speaker.py | 2 +- .../layouts/camera_inset.py | 6 +- .../layouts/layout_picker.py | 8 +- .../layouts/layout_ranges.py | 0 .../layouts/panel_layout.py | 4 +- punch_in.py => clipwright/layouts/punch_in.py | 2 +- .../layouts/reframe_v2.py | 18 ++-- .../layouts/screencast_layout.py | 6 +- .../layouts/split_layout.py | 4 +- clipwright/media/__init__.py | 1 + .../media/edit_builder.py | 0 editor.py => clipwright/media/editor.py | 6 +- .../media/ffmpeg_utils.py | 0 .../media/frame_sampler.py | 0 hooks.py => clipwright/media/hooks.py | 5 +- recut.py => clipwright/media/recut.py | 8 +- .../media/scene_detection.py | 0 subtitles.py => clipwright/media/subtitles.py | 7 +- thumbnail.py => clipwright/media/thumbnail.py | 9 +- .../media/watermarked.py | 0 clipwright/pipeline/__init__.py | 1 + .../pipeline/clip_selection.py | 0 .../pipeline/gemini_worker.py | 2 +- .../pipeline/hook_grounding.py | 8 +- .../pipeline/llm_backend.py | 2 +- main.py => clipwright/pipeline/main.py | 50 +++++----- .../pipeline/quality_probe.py | 11 ++- .../pipeline/transcribe_backends.py | 4 +- clipwright/tools/__init__.py | 1 + .../tools/verify_aesthetic.py | 2 +- .../tools/verify_custom_hook.py | 2 +- .../tools/verify_hooks.py | 2 +- dashboard/seo/pages.js | 2 +- dashboard/src/components/HookModal.jsx | 6 +- .../src/remotion/compositions/HookOverlay.tsx | 10 +- dashboard/src/remotion/lib/fonts.ts | 2 +- docs/compliance/retencion.md | 7 +- pyproject.toml | 30 ++++++ remotion/src/compositions/HookOverlay.tsx | 4 +- requirements-test.txt | 14 +++ tests/conftest.py | 10 +- tests/test_active_speaker.py | 2 +- tests/test_ai_disclosure.py | 2 +- tests/test_audit_hardening.py | 56 +++++++---- tests/test_auto_retry.py | 2 +- tests/test_camera_inset.py | 2 +- tests/test_caption_presets.py | 6 +- tests/test_cleanup_live_jobs.py | 2 +- tests/test_clip_floor.py | 2 +- tests/test_clip_ready_marker.py | 7 +- tests/test_clip_render_order.py | 2 +- tests/test_clip_selection.py | 4 +- tests/test_deploy_drain.py | 2 +- tests/test_download_plan.py | 2 +- tests/test_edit_builder.py | 2 +- tests/test_ffmpeg_utils.py | 4 +- tests/test_filename_limits.py | 4 +- tests/test_frame_sampler.py | 2 +- tests/test_free_tools.py | 2 +- tests/test_gemini_block_split.py | 4 +- tests/test_gemini_retry.py | 8 +- tests/test_gemini_upload_unicode_name.py | 9 +- tests/test_generation_controls.py | 3 +- tests/test_hook_grounding.py | 4 +- tests/test_hook_layers.py | 2 +- tests/test_hooks.py | 4 +- tests/test_layout_picker.py | 38 +++++--- tests/test_layout_ranges.py | 10 +- tests/test_llm_backend.py | 8 +- tests/test_media_path_guard.py | 6 +- tests/test_no_blocking_http_in_async.py | 2 +- tests/test_package_layout.py | 94 +++++++++++++++++++ tests/test_panel_layout.py | 6 +- tests/test_phantom_clips.py | 2 +- tests/test_postiz.py | 4 +- tests/test_process_handover.py | 2 +- tests/test_punch_in.py | 10 +- tests/test_recut.py | 2 +- tests/test_reframe_endpoint.py | 6 +- tests/test_reframe_v2.py | 10 +- tests/test_rerender_endpoint.py | 4 +- tests/test_restoring_static.py | 2 +- tests/test_scene_cut_reset.py | 2 +- tests/test_screencast_layout.py | 4 +- tests/test_short_source_gate.py | 2 +- tests/test_source_access.py | 2 +- tests/test_sparse_speech.py | 2 +- tests/test_speaker_tracker.py | 2 +- tests/test_split_layout.py | 4 +- tests/test_ssrf_guard.py | 6 +- tests/test_subtitles.py | 50 +++++----- tests/test_thumbnail_studio.py | 7 +- tests/test_transcribe_backends.py | 18 ++-- tests/test_transcript_checkpoint.py | 2 +- tests/test_watermark_delivery.py | 18 ++-- tests/test_youtube_non_video_urls.py | 2 +- tests/test_yt_clients.py | 2 +- 115 files changed, 557 insertions(+), 305 deletions(-) create mode 100644 clipwright/__init__.py create mode 100644 clipwright/api/__init__.py rename app.py => clipwright/api/app.py (99%) rename free_tools.py => clipwright/api/free_tools.py (100%) rename media_auth.py => clipwright/api/media_auth.py (100%) rename restoring_static.py => clipwright/api/restoring_static.py (100%) create mode 100644 clipwright/core/__init__.py create mode 100644 clipwright/core/paths.py rename security_utils.py => clipwright/core/security_utils.py (100%) create mode 100644 clipwright/integrations/__init__.py rename file_hosts.py => clipwright/integrations/file_hosts.py (100%) rename postiz.py => clipwright/integrations/postiz.py (100%) rename yt_clients.py => clipwright/integrations/yt_clients.py (100%) create mode 100644 clipwright/layouts/__init__.py rename active_speaker.py => clipwright/layouts/active_speaker.py (99%) rename camera_inset.py => clipwright/layouts/camera_inset.py (98%) rename layout_picker.py => clipwright/layouts/layout_picker.py (97%) rename layout_ranges.py => clipwright/layouts/layout_ranges.py (100%) rename panel_layout.py => clipwright/layouts/panel_layout.py (99%) rename punch_in.py => clipwright/layouts/punch_in.py (99%) rename reframe_v2.py => clipwright/layouts/reframe_v2.py (98%) rename screencast_layout.py => clipwright/layouts/screencast_layout.py (98%) rename split_layout.py => clipwright/layouts/split_layout.py (99%) create mode 100644 clipwright/media/__init__.py rename edit_builder.py => clipwright/media/edit_builder.py (100%) rename editor.py => clipwright/media/editor.py (99%) rename ffmpeg_utils.py => clipwright/media/ffmpeg_utils.py (100%) rename frame_sampler.py => clipwright/media/frame_sampler.py (100%) rename hooks.py => clipwright/media/hooks.py (99%) rename recut.py => clipwright/media/recut.py (97%) rename scene_detection.py => clipwright/media/scene_detection.py (100%) rename subtitles.py => clipwright/media/subtitles.py (99%) rename thumbnail.py => clipwright/media/thumbnail.py (99%) rename watermarked.py => clipwright/media/watermarked.py (100%) create mode 100644 clipwright/pipeline/__init__.py rename clip_selection.py => clipwright/pipeline/clip_selection.py (100%) rename gemini_worker.py => clipwright/pipeline/gemini_worker.py (99%) rename hook_grounding.py => clipwright/pipeline/hook_grounding.py (97%) rename llm_backend.py => clipwright/pipeline/llm_backend.py (98%) rename main.py => clipwright/pipeline/main.py (98%) rename quality_probe.py => clipwright/pipeline/quality_probe.py (93%) rename transcribe_backends.py => clipwright/pipeline/transcribe_backends.py (99%) create mode 100644 clipwright/tools/__init__.py rename verify_aesthetic.py => clipwright/tools/verify_aesthetic.py (95%) rename verify_custom_hook.py => clipwright/tools/verify_custom_hook.py (94%) rename verify_hooks.py => clipwright/tools/verify_hooks.py (94%) create mode 100644 pyproject.toml create mode 100644 requirements-test.txt create mode 100644 tests/test_package_layout.py diff --git a/.env.example b/.env.example index d3a9ff6..cbdda93 100644 --- a/.env.example +++ b/.env.example @@ -72,7 +72,7 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image # close-ups of a real person; the clock runs from the last download. # THUMBNAIL_RETENTION_SECONDS=86400 -# Per-IP rate limiting (rate_limit.py). "/". +# Per-IP rate limiting. "/". # Defaults: auth 30/600, process 60/3600. Set RATE_LIMIT_ENABLED=0 # to turn the whole thing off (self-host behind your own firewall). # RATE_LIMIT_ENABLED=1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c6db46..8660be5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,17 +16,12 @@ jobs: container: nikolaik/python-nodejs:python3.11-nodejs20 steps: - uses: actions/checkout@v4 - # Everything the collected tests import at module level, WITHOUT the - # heavy ML stack (torch/ultralytics/mediapipe/faster-whisper) — the - # pipeline modules import those lazily behind their feature gates, and - # the tests exercise the gated-off paths. numpy+opencv cover the layout - # modules, fastapi/python-multipart cover importing app.py for the MCP - # endpoint tests, google-genai covers gemini_worker. + # Shared thin test environment (see requirements-test.txt): everything the + # collected tests import at module level, WITHOUT the heavy ML stack + # (torch/ultralytics/mediapipe/faster-whisper), which the pipeline modules + # import lazily behind their feature gates. - name: Install test dependencies - run: > - pip install pytest pillow httpx pydantic numpy - opencv-python-headless python-dotenv google-genai fastapi - python-multipart + run: pip install -r requirements-test.txt - name: Run tests run: pytest tests/ -v diff --git a/Dockerfile b/Dockerfile index 28713dd..a16c400 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,6 +31,11 @@ FROM python:3.11-slim WORKDIR /app +# The FastAPI app lives in the `clipwright` package and job workers are launched +# as `python -m clipwright.pipeline.main`, so the repo root must be importable +# regardless of the process cwd. +ENV PYTHONPATH=/app + # Install FFmpeg, OpenCV deps, Node.js + npm + git (for yt-dlp JS + bgutil build). # fontconfig + fonts-liberation back the subtitle font choices: without real # fonts libass falls back to DejaVu for every UI option (issue #57). @@ -126,4 +131,4 @@ EXPOSE 8000 HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=2 \ CMD curl -sf http://127.0.0.1:8000/health/ready > /dev/null || exit 1 -CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"] +CMD ["uvicorn", "clipwright.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"] diff --git a/README.md b/README.md index 6ee5907..c3067ff 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,27 @@ curl -X POST http://localhost:8000/api/process \ Add `webhook_url` for exactly one callback when the job ends; with `webhook_secret` the body is signed `X-Clipwright-Signature: sha256=…`. Interactive docs are at `/docs`. +## Project structure + +``` +clipwright/ # Python backend package + core/ # shared helpers (security, filesystem paths) + api/ # FastAPI app, auth, free tools + pipeline/ # download → transcribe → clip orchestration, Gemini, quality probe + layouts/ # reframing: active speaker, split/screencast/panel, punch-in + media/ # FFmpeg helpers, subtitles, hooks, thumbnails, recut + integrations/ # Postiz, YouTube, file hosts + tools/ # local verification scripts (python -m clipwright.tools.verify_hooks) +dashboard/ # React + Vite dashboard (its own build) +remotion/ # Remotion compositions used by the renderer +render-service/ # Node render microservice (its own Dockerfile) +cli/ # published `clipwright` HTTP client (own pyproject) +tests/ # pytest suite (pythonpath = ["."]) +fonts/ assets/ # shared runtime resources (kept at repo root) +``` + +The backend runs from the source tree (no install step): `uvicorn clipwright.api.app:app` serves the API and clip jobs run as `python -m clipwright.pipeline.main`. + ## Tech stack Python 3.11 · FastAPI · google-genai · faster-whisper · ultralytics (YOLOv8) · MediaPipe · FFmpeg · React 18 · Vite · Tailwind · Docker Compose. diff --git a/clipwright/__init__.py b/clipwright/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/clipwright/api/__init__.py b/clipwright/api/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/api/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/app.py b/clipwright/api/app.py similarity index 99% rename from app.py rename to clipwright/api/app.py index 0694359..a703544 100644 --- a/app.py +++ b/clipwright/api/app.py @@ -1,5 +1,5 @@ import os -import llm_backend +from clipwright.pipeline import llm_backend import re import sys import uuid @@ -26,11 +26,12 @@ from fastapi.responses import FileResponse, JSONResponse from starlette.background import BackgroundTask from pydantic import BaseModel import httpx -import recut -import layout_ranges -import watermarked -import media_auth -import postiz +from clipwright.media import recut +from clipwright.layouts import layout_ranges +from clipwright.media import watermarked +from clipwright.api import media_auth +from clipwright.integrations import postiz +from clipwright.core.paths import REPO_ROOT load_dotenv() @@ -61,7 +62,6 @@ QUALITY_GATE_MIN_HEIGHT = int(os.environ.get("QUALITY_GATE_MIN_HEIGHT", "720")) # managed minutes and dies with "no usable clips" (prod 20-ago: 3 of 5 recent # failures were exactly this, one user retrying the same 24s video). MIN_SOURCE_SECONDS = int(os.environ.get("MIN_SOURCE_SECONDS", "45")) -QUALITY_PROBE_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_probe.py") # Server credentials the pipeline subprocesses (main.py, quality_probe.py) never # read: main.py and everything it imports use GEMINI_API_KEY / LLM_* / the @@ -88,6 +88,11 @@ def child_env(base=None): env = dict(os.environ if base is None else base) for name in CHILD_ENV_DENYLIST: env.pop(name, None) + # The pipeline modules run as ``-m clipwright.pipeline.``; make the + # package importable regardless of the child's cwd. + env["PYTHONPATH"] = os.pathsep.join( + filter(None, [env.get("PYTHONPATH"), str(REPO_ROOT)]) + ) return env @@ -466,7 +471,7 @@ def _reapply_captions(job_id, clip_index, video_path): if not transcript or clip_index >= len(clips): return None clip = clips[clip_index] - import main as _main + from clipwright.pipeline import main as _main # A recut clip is a concatenation of source segments, so the flat # start..end window is wrong for it — caption against the clip-relative # remapped transcript instead (same trick /api/subtitle uses). @@ -1409,7 +1414,7 @@ async def _deliver_webhook(url, body: bytes, secret): headers = {"Content-Type": "application/json", "User-Agent": "Clipwright-Webhook/1.0"} if secret: headers["X-Clipwright-Signature"] = _sign_webhook(body, secret) - from security_utils import assert_public_url, UnsafeURLError + from clipwright.core.security_utils import assert_public_url, UnsafeURLError loop = asyncio.get_event_loop() for attempt, delay in enumerate(WEBHOOK_RETRY_DELAYS, 1): if delay: @@ -1477,7 +1482,7 @@ app = FastAPI(lifespan=lifespan) # Free public tools behind the /tools SEO pages: YouTube transcript (existing # captions only, never the GPU) and the title/description/tag generator. -import free_tools as _free_tools +from clipwright.api import free_tools as _free_tools app.include_router(_free_tools.router) # Enable CORS for frontend. Self-host allows any origin (permissive wildcard). @@ -1495,7 +1500,7 @@ app.add_middleware( # Mount static files for serving videos. ``guard`` refuses non-deliverables # (``*_metadata.json``, ``.owner``, ``.resume.json``) so they are never served. -from restoring_static import RestoringStaticFiles +from clipwright.api.restoring_static import RestoringStaticFiles app.mount("/videos", RestoringStaticFiles( directory=OUTPUT_DIR, guard=_media_guard), name="videos") @@ -1761,7 +1766,7 @@ async def _probe_youtube_quality(url: str) -> dict: def _run(): try: proc = subprocess.run( - [sys.executable, QUALITY_PROBE_SCRIPT, "--url", url], + [sys.executable, "-m", "clipwright.pipeline.quality_probe", "--url", url], capture_output=True, timeout=75, env=child_env(), ) return json.loads(proc.stdout.decode(errors="replace").strip() or "{}") @@ -1779,8 +1784,8 @@ async def _validate_source_url(url: str): search / playlist / channel page (yt_clients). The download and the metering probe check the same things again; this is the one in front of the quality probe, which used to have none.""" - from security_utils import assert_public_url, UnsafeURLError - from yt_clients import youtube_non_video_reason + from clipwright.core.security_utils import assert_public_url, UnsafeURLError + from clipwright.integrations.yt_clients import youtube_non_video_reason try: await asyncio.get_event_loop().run_in_executor(None, assert_public_url, url) except UnsafeURLError as e: @@ -2103,7 +2108,7 @@ async def process_endpoint( # Completion callback: reject unsafe targets NOW (clear 400) — delivery # re-validates anyway, but failing at submit is the debuggable behavior. if webhook_url: - from security_utils import assert_public_url, UnsafeURLError + from clipwright.core.security_utils import assert_public_url, UnsafeURLError try: await asyncio.get_event_loop().run_in_executor( None, assert_public_url, webhook_url) @@ -2146,7 +2151,7 @@ async def process_endpoint( # outside Docker is whatever interpreter happens to be first — not the venv # running this server. Every job then dies on `import cv2`. The quality # probe above already gets this right. - cmd = [sys.executable, "-u", "main.py"] # -u for unbuffered + cmd = [sys.executable, "-u", "-m", "clipwright.pipeline.main"] # -u for unbuffered env = child_env() if api_key: env["GEMINI_API_KEY"] = api_key # Override with key from request @@ -2170,7 +2175,7 @@ async def process_endpoint( # byte-for-byte; the dashboard sends an explicit value either way. if str(auto_hook).lower() in ("1", "true", "yes"): env["AUTO_HOOK"] = "1" - from hooks import HOOK_STYLES + from clipwright.media.hooks import HOOK_STYLES if auto_hook_style in HOOK_STYLES: env["AUTO_HOOK_STYLE"] = auto_hook_style print(f"[auto-hook] job={job_id} style={env.get('AUTO_HOOK_STYLE', 'classic')}") @@ -2540,10 +2545,10 @@ async def download_all_clips(job_id: str, request: Request): # Files live on local disk in this self-host fork, so there is nothing to restore. -from editor import VideoEditor -from subtitles import generate_srt, generate_ass, burn_subtitles, CAPTION_PRESETS -from hooks import add_hook_to_video -from thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail, +from clipwright.media.editor import VideoEditor +from clipwright.media.subtitles import generate_srt, generate_ass, burn_subtitles, CAPTION_PRESETS +from clipwright.media.hooks import add_hook_to_video +from clipwright.media.thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail, generate_youtube_description, extract_face_frames) class EditRequest(BaseModel): @@ -3195,7 +3200,7 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request): def build(): import cv2 - import main as m + from clipwright.pipeline import main as m # Stable for the files the browser fetches (no accumulation), unique # for the temp cut (no collision between overlapping requests). @@ -4413,19 +4418,19 @@ async def thumbnail_upload( vpath = video_path # Download YouTube video if URL was provided if not vpath and url: - from main import download_youtube_video + from clipwright.pipeline.main import download_youtube_video loop = asyncio.get_event_loop() vpath, _ = await loop.run_in_executor(None, download_youtube_video, url, UPLOAD_DIR) thumbnail_sessions[session_id]["video_path"] = vpath - from main import transcribe_video + from clipwright.pipeline.main import transcribe_video loop = asyncio.get_event_loop() try: transcript = await loop.run_in_executor(None, transcribe_video, vpath) finally: # See transcribe_backends.release_models: the API process is # long-lived and the GPU is shared with every running job. - import transcribe_backends + from clipwright.pipeline import transcribe_backends await loop.run_in_executor(None, transcribe_backends.release_models) segments = transcript.get("segments", []) duration = segments[-1]["end"] if segments else 0 @@ -4492,7 +4497,7 @@ async def thumbnail_analyze( session_id = str(uuid.uuid4()) if url: - from main import download_youtube_video + from clipwright.pipeline.main import download_youtube_video video_path, _ = await asyncio.get_event_loop().run_in_executor( None, download_youtube_video, url, UPLOAD_DIR) else: diff --git a/free_tools.py b/clipwright/api/free_tools.py similarity index 100% rename from free_tools.py rename to clipwright/api/free_tools.py diff --git a/media_auth.py b/clipwright/api/media_auth.py similarity index 100% rename from media_auth.py rename to clipwright/api/media_auth.py diff --git a/restoring_static.py b/clipwright/api/restoring_static.py similarity index 100% rename from restoring_static.py rename to clipwright/api/restoring_static.py diff --git a/clipwright/core/__init__.py b/clipwright/core/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/core/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/clipwright/core/paths.py b/clipwright/core/paths.py new file mode 100644 index 0000000..7c1ef27 --- /dev/null +++ b/clipwright/core/paths.py @@ -0,0 +1,31 @@ +"""Canonical filesystem locations for the Clipwright backend. + +The importable package lives at ``/clipwright`` while the shared runtime +resources (``fonts/``, ``assets/``, ``yolov8n.pt``) stay at the repository root. +Keeping the constants here means every module resolves them the same way, +independently of the current working directory or of how deep a module sits in +the package. +""" + +from __future__ import annotations + +from pathlib import Path + +# .../clipwright +PACKAGE_DIR = Path(__file__).resolve().parent.parent +# Repository root (also the Docker WORKDIR /app). +REPO_ROOT = PACKAGE_DIR.parent + +FONTS_DIR = REPO_ROOT / "fonts" +ASSETS_DIR = REPO_ROOT / "assets" +UPLOADS_DIR = REPO_ROOT / "uploads" +OUTPUT_DIR = REPO_ROOT / "output" + +__all__ = [ + "PACKAGE_DIR", + "REPO_ROOT", + "FONTS_DIR", + "ASSETS_DIR", + "UPLOADS_DIR", + "OUTPUT_DIR", +] diff --git a/security_utils.py b/clipwright/core/security_utils.py similarity index 100% rename from security_utils.py rename to clipwright/core/security_utils.py diff --git a/clipwright/integrations/__init__.py b/clipwright/integrations/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/integrations/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/file_hosts.py b/clipwright/integrations/file_hosts.py similarity index 100% rename from file_hosts.py rename to clipwright/integrations/file_hosts.py diff --git a/postiz.py b/clipwright/integrations/postiz.py similarity index 100% rename from postiz.py rename to clipwright/integrations/postiz.py diff --git a/yt_clients.py b/clipwright/integrations/yt_clients.py similarity index 100% rename from yt_clients.py rename to clipwright/integrations/yt_clients.py diff --git a/clipwright/layouts/__init__.py b/clipwright/layouts/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/layouts/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/active_speaker.py b/clipwright/layouts/active_speaker.py similarity index 99% rename from active_speaker.py rename to clipwright/layouts/active_speaker.py index a3147f3..7b55da5 100644 --- a/active_speaker.py +++ b/clipwright/layouts/active_speaker.py @@ -220,7 +220,7 @@ def speaker_xs(held, centres, crop_w, orig_w, n_frames, fps, def verdicts_for_scene(video_path, start_f, end_f, fps, centres): """Per-window speaker verdicts for one scene, from its two face centres.""" - import split_layout + from clipwright.layouts import split_layout start_s = start_f / fps duration_s = (end_f - start_f) / fps diff --git a/camera_inset.py b/clipwright/layouts/camera_inset.py similarity index 98% rename from camera_inset.py rename to clipwright/layouts/camera_inset.py index c95b1c0..afc55bb 100644 --- a/camera_inset.py +++ b/clipwright/layouts/camera_inset.py @@ -20,7 +20,7 @@ them with margin. """ import os -from ffmpeg_utils import blurred_backdrop +from clipwright.media.ffmpeg_utils import blurred_backdrop CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the # frame) still counts as anchored to it @@ -159,8 +159,8 @@ def detect(video_path, samples=10): """ import cv2 import numpy as np - import main as m - import screencast_layout + from clipwright.pipeline import main as m + from clipwright.layouts import screencast_layout cap = cv2.VideoCapture(video_path) if not cap.isOpened(): diff --git a/layout_picker.py b/clipwright/layouts/layout_picker.py similarity index 97% rename from layout_picker.py rename to clipwright/layouts/layout_picker.py index 9fa6ef2..a34e150 100644 --- a/layout_picker.py +++ b/clipwright/layouts/layout_picker.py @@ -82,9 +82,9 @@ def apply(decision): stacking regardless of what the model thinks, and a model that says "none" must not quietly undo that. """ - import active_speaker - import screencast_layout - import split_layout + from clipwright.layouts import active_speaker + from clipwright.layouts import screencast_layout + from clipwright.layouts import split_layout modules = {"split_layout": split_layout, "screencast_layout": screencast_layout, @@ -191,7 +191,7 @@ def pick(video_path, video_duration): # raises, and an unimportable SDK is just one more reason to fall back. from google import genai from google.genai import types as genai_types - import gemini_worker + from clipwright.pipeline import gemini_worker frames = sample_frames(video_path) if not frames: diff --git a/layout_ranges.py b/clipwright/layouts/layout_ranges.py similarity index 100% rename from layout_ranges.py rename to clipwright/layouts/layout_ranges.py diff --git a/panel_layout.py b/clipwright/layouts/panel_layout.py similarity index 99% rename from panel_layout.py rename to clipwright/layouts/panel_layout.py index c04f286..5f7c671 100644 --- a/panel_layout.py +++ b/clipwright/layouts/panel_layout.py @@ -24,7 +24,7 @@ import os import numpy as np -import split_layout +from clipwright.layouts import split_layout ENABLED = os.environ.get("PANEL_LAYOUT", "0") == "1" @@ -223,7 +223,7 @@ def detect_panel_scenes(video_path, scenes, strategies, samples=None): # Below the gate on purpose: main pulls torch/mediapipe, and the disabled # path (the default, and what CI exercises) must not pay that import. import cv2 - import main as m + from clipwright.pipeline import main as m cap = cv2.VideoCapture(video_path) if not cap.isOpened(): diff --git a/punch_in.py b/clipwright/layouts/punch_in.py similarity index 99% rename from punch_in.py rename to clipwright/layouts/punch_in.py index 320fcb0..c76ba8f 100644 --- a/punch_in.py +++ b/clipwright/layouts/punch_in.py @@ -162,7 +162,7 @@ def emphasis_times(video_path, duration, window=BEAT_WINDOW, A stand-in for the hook words until the transcript is wired through. Returns [] for silent or unreadable audio, which simply means no punches. """ - import active_speaker + from clipwright.layouts import active_speaker envelope = active_speaker.audio_envelope(video_path, 0.0, duration, window_s=window) diff --git a/reframe_v2.py b/clipwright/layouts/reframe_v2.py similarity index 98% rename from reframe_v2.py rename to clipwright/layouts/reframe_v2.py index cfb3a75..dbb6748 100644 --- a/reframe_v2.py +++ b/clipwright/layouts/reframe_v2.py @@ -21,13 +21,13 @@ import os import subprocess import tempfile -import active_speaker -import camera_inset -import punch_in -import screencast_layout -import layout_ranges -import split_layout -from ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value, +from clipwright.layouts import active_speaker +from clipwright.layouts import camera_inset +from clipwright.layouts import punch_in +from clipwright.layouts import screencast_layout +from clipwright.layouts import layout_ranges +from clipwright.layouts import split_layout +from clipwright.media.ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value, QUALITY_FAST, METADATA_SCRUB) ANALYSIS_MAX_WIDTH = 640 @@ -255,7 +255,7 @@ def _analyze_trajectory(input_video, scenes_boundaries, scene_strategies, """Replays v1's per-frame decision loop on a downscaled ffmpeg-decoded stream. Returns xs: crop x per frame (None on GENERAL frames).""" import numpy as np - import main as m + from clipwright.pipeline import main as m small_w = min(ANALYSIS_MAX_WIDTH, orig_w) if small_w % 2: @@ -362,7 +362,7 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, segment's own encode, instead of main.apply_watermark re-encoding the finished clip once more. """ - import main as m + from clipwright.pipeline import main as m content_ranges = content_ranges or [] print(" 🚀 Reframe engine v2 (ffmpeg-native render)") diff --git a/screencast_layout.py b/clipwright/layouts/screencast_layout.py similarity index 98% rename from screencast_layout.py rename to clipwright/layouts/screencast_layout.py index af1d604..8e8b317 100644 --- a/screencast_layout.py +++ b/clipwright/layouts/screencast_layout.py @@ -123,7 +123,7 @@ def detect_faces_full_res(frame): screencast candidates only. """ import cv2 - import main as m + from clipwright.pipeline import main as m h, w, _ = frame.shape rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) @@ -178,7 +178,7 @@ def detect_content_ranges(video_path, video_duration): from google import genai from google.genai import types as genai_types - import gemini_worker + from clipwright.pipeline import gemini_worker model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite' print("🔎 Checking for full-width on-screen content…") @@ -268,7 +268,7 @@ def detect_screencast_scenes(video_path, scenes, strategies, ranges, samples=6): # Below the gate on purpose: main pulls torch/mediapipe, and the disabled # path (the default, and what CI exercises) must not pay that import. import cv2 - import main as m + from clipwright.pipeline import main as m cap = cv2.VideoCapture(video_path) if not cap.isOpened(): diff --git a/split_layout.py b/clipwright/layouts/split_layout.py similarity index 99% rename from split_layout.py rename to clipwright/layouts/split_layout.py index 15325e6..7f3e90a 100644 --- a/split_layout.py +++ b/clipwright/layouts/split_layout.py @@ -18,7 +18,7 @@ import os import numpy as np -import frame_sampler +from clipwright.media import frame_sampler ENABLED = os.environ.get("SPLIT_LAYOUT", "0") == "1" @@ -221,7 +221,7 @@ def detect_split_scenes(video_path, scenes, strategies, samples=None): touching the single-speaker material that is most of the corpus. """ import cv2 - import main as m + from clipwright.pipeline import main as m if not ENABLED: return {} diff --git a/clipwright/media/__init__.py b/clipwright/media/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/media/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/edit_builder.py b/clipwright/media/edit_builder.py similarity index 100% rename from edit_builder.py rename to clipwright/media/edit_builder.py diff --git a/editor.py b/clipwright/media/editor.py similarity index 99% rename from editor.py rename to clipwright/media/editor.py index 4b10309..9158cd1 100644 --- a/editor.py +++ b/clipwright/media/editor.py @@ -8,9 +8,9 @@ from google import genai from google.genai import types from pydantic import BaseModel -import gemini_worker -from edit_builder import build_filter_string -from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB +from clipwright.pipeline import gemini_worker +from clipwright.media.edit_builder import build_filter_string +from clipwright.media.ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB class EditDecision(BaseModel): diff --git a/ffmpeg_utils.py b/clipwright/media/ffmpeg_utils.py similarity index 100% rename from ffmpeg_utils.py rename to clipwright/media/ffmpeg_utils.py diff --git a/frame_sampler.py b/clipwright/media/frame_sampler.py similarity index 100% rename from frame_sampler.py rename to clipwright/media/frame_sampler.py diff --git a/hooks.py b/clipwright/media/hooks.py similarity index 99% rename from hooks.py rename to clipwright/media/hooks.py index 279e9e5..3eb5e0f 100644 --- a/hooks.py +++ b/clipwright/media/hooks.py @@ -6,7 +6,8 @@ import urllib.request import uuid from PIL import Image, ImageDraw, ImageFont, ImageFilter -from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB +from clipwright.media.ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB +from clipwright.core.paths import FONTS_DIR def _truncate_bytes(text, max_bytes): @@ -21,7 +22,7 @@ def _truncate_bytes(text, max_bytes): return encoded[:max_bytes].decode("utf-8", "ignore") FONT_URL = "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Bold.ttf" -FONT_DIR = "fonts" +FONT_DIR = str(FONTS_DIR) FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf") # Bundled (SIL OFL, see fonts/Montserrat-OFL.txt): the "pill" look's sans. PILL_FONT_PATH = os.path.join(FONT_DIR, "Montserrat-ExtraBold.ttf") diff --git a/recut.py b/clipwright/media/recut.py similarity index 97% rename from recut.py rename to clipwright/media/recut.py index d9ed6b7..4c886fd 100644 --- a/recut.py +++ b/clipwright/media/recut.py @@ -24,7 +24,7 @@ import subprocess import time import uuid -from ffmpeg_utils import (METADATA_SCRUB, QUALITY_FAST, audio_encode_args, +from clipwright.media.ffmpeg_utils import (METADATA_SCRUB, QUALITY_FAST, audio_encode_args, video_encode_args) # EDL limits. Deliberately generous — the editor is for humans fixing cuts, @@ -109,7 +109,7 @@ def rebase_segments(segments, range_start, range_end=None): def snap_segments(segments, transcript, source_duration): """Snap each segment's bounds onto word boundaries (ground truth beats millisecond arithmetic — same rationale as the pipeline's snapping).""" - from clip_selection import snap_clip_to_words + from clipwright.pipeline.clip_selection import snap_clip_to_words words = transcript_words(transcript) if not words: @@ -316,7 +316,7 @@ def perform_recut(*, input_path, segments, output_dir, clean_name, # No reframe means no fresh layout sidecar; the captions would fall # back to the bottom on a stacked clip. Carry the input's layout # ranges through the cut instead (empty when the input has none). - import layout_ranges + from clipwright.layouts import layout_ranges layout_ranges.write(out_path, [ (r["start"], r["end"], r["layout"]) for r in layout_ranges.remap(layout_ranges.read(input_path), segments)]) @@ -338,5 +338,5 @@ def perform_recut(*, input_path, segments, output_dir, clean_name, def _main_attr(name): - import main # heavy — resolved only when a real render/caption runs + from clipwright.pipeline import main # heavy — resolved only when a real render/caption runs return getattr(main, name) diff --git a/scene_detection.py b/clipwright/media/scene_detection.py similarity index 100% rename from scene_detection.py rename to clipwright/media/scene_detection.py diff --git a/subtitles.py b/clipwright/media/subtitles.py similarity index 99% rename from subtitles.py rename to clipwright/media/subtitles.py index 78a22a8..9abe1c6 100644 --- a/subtitles.py +++ b/clipwright/media/subtitles.py @@ -3,8 +3,9 @@ import re import subprocess import sys -from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY, +from clipwright.media.ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY, METADATA_SCRUB) +from clipwright.core.paths import FONTS_DIR _STDIO_CONFIGURED = False @@ -119,7 +120,7 @@ def transcribe_audio(video_path): Returns transcript in the same format as main.py for compatibility. """ # Lazy import: transcribe_backends imports helpers from this module. - from transcribe_backends import transcribe_media + from clipwright.pipeline.transcribe_backends import transcribe_media _log(f"🎙️ Transcribing audio from: {video_path}") transcript = transcribe_media(video_path) @@ -629,7 +630,7 @@ def subtitles_filter(srt_path, alignment=2, fontsize=16, # Let libass see the fonts bundled with the app (e.g. Anton for Impact) # even when the system fontconfig has no cache for them. - fonts_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts") + fonts_dir = str(FONTS_DIR) safe_fonts_dir = _escape_ffmpeg_filter_value(fonts_dir) # The first option is named explicitly (filename=) rather than positional: diff --git a/thumbnail.py b/clipwright/media/thumbnail.py similarity index 99% rename from thumbnail.py rename to clipwright/media/thumbnail.py index e4d460d..9cfe85e 100644 --- a/thumbnail.py +++ b/clipwright/media/thumbnail.py @@ -9,6 +9,7 @@ from google import genai 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 # Text/analysis model (titles, concepts, description). Deliberately NOT tied to # GEMINI_MODEL: the pipeline runs flash-lite for a closed-choice layout pick, @@ -30,7 +31,7 @@ TITLE_MAX_CHARS = 65 THUMB_W, THUMB_H = 1280, 720 THUMB_MAX_BYTES = 2 * 1024 * 1024 # YouTube's upload limit -THUMB_FONT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts", "Anton-Regular.ttf") +THUMB_FONT = str(FONTS_DIR / "Anton-Regular.ttf") TEXT_POSITIONS = ("left", "right", "top", "bottom") @@ -49,7 +50,7 @@ def _parse_json(text): def _frame_parts(video_path, n=TITLE_FRAMES, width=TITLE_FRAME_WIDTH): """Evenly spaced frames as Gemini image parts (empty list on any failure).""" try: - from layout_picker import sample_frames + from clipwright.layouts.layout_picker import sample_frames return [types.Part.from_bytes(data=b, mime_type="image/jpeg") for b in sample_frames(video_path, n=n, width=width)] except Exception as e: @@ -70,7 +71,7 @@ def analyze_video_for_titles(api_key, video_path, transcript=None): "segments", "video_duration", "recommended" } """ if transcript is None: - from main import transcribe_video + from clipwright.pipeline.main import transcribe_video print("🎬 [Thumbnail] Transcribing video...") transcript = transcribe_video(video_path) else: @@ -265,7 +266,7 @@ def extract_face_frames(video_path, session_id, n=5, samples=40): thumbnails dir. Returns [{"url", "path", "time", "face": [x, y, w, h]}]. """ import cv2 - from main import detect_face_candidates + from clipwright.pipeline.main import detect_face_candidates out_dir = os.path.join("output", "thumbnails", session_id, "frames") os.makedirs(out_dir, exist_ok=True) diff --git a/watermarked.py b/clipwright/media/watermarked.py similarity index 100% rename from watermarked.py rename to clipwright/media/watermarked.py diff --git a/clipwright/pipeline/__init__.py b/clipwright/pipeline/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/pipeline/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/clip_selection.py b/clipwright/pipeline/clip_selection.py similarity index 100% rename from clip_selection.py rename to clipwright/pipeline/clip_selection.py diff --git a/gemini_worker.py b/clipwright/pipeline/gemini_worker.py similarity index 99% rename from gemini_worker.py rename to clipwright/pipeline/gemini_worker.py index 0f98517..685d4d1 100644 --- a/gemini_worker.py +++ b/clipwright/pipeline/gemini_worker.py @@ -10,7 +10,7 @@ from google import genai from google.genai import types as genai_types from pydantic import BaseModel -from clip_selection import (clip_count_targets, clip_duration_bounds, +from clipwright.pipeline.clip_selection import (clip_count_targets, clip_duration_bounds, lookup_model_prices) load_dotenv() diff --git a/hook_grounding.py b/clipwright/pipeline/hook_grounding.py similarity index 97% rename from hook_grounding.py rename to clipwright/pipeline/hook_grounding.py index cb70785..12d744e 100644 --- a/hook_grounding.py +++ b/clipwright/pipeline/hook_grounding.py @@ -42,7 +42,7 @@ def screen_video() -> bool: (verified on a product update video: every GENERAL scene was a stats card), even when the width gate did not upgrade it to SCREENCAST.""" try: - import screencast_layout + from clipwright.layouts import screencast_layout return bool(getattr(screencast_layout, "ENABLED", False)) except Exception: return False @@ -50,7 +50,7 @@ def screen_video() -> bool: def screen_ranges(ranges, on_screen_video=None): """(start, end) pairs, clip seconds, of the stretches rendered on-screen.""" - import layout_ranges + from clipwright.layouts import layout_ranges layouts = set(SCREEN_LAYOUTS) if screen_video() if on_screen_video is None else on_screen_video: layouts.add("general") @@ -125,7 +125,7 @@ def _ask_gemini(frames, prompt, api_key): """One vision call; returns the parsed dict. Split out so tests can stub it.""" from google import genai from google.genai import types as genai_types - import gemini_worker + from clipwright.pipeline import gemini_worker client = genai.Client(api_key=api_key) model_name = os.environ.get("GEMINI_MODEL") or "gemini-3.1-flash-lite" @@ -151,7 +151,7 @@ def reground(clip_path, clip, transcript, start, end) -> Optional[dict]: "keeping the transcript hook.") return None try: - import gemini_worker + from clipwright.pipeline import gemini_worker times = sample_times(clip.get("layout_ranges"), float(end) - float(start)) frames = frames_at(clip_path, times) diff --git a/llm_backend.py b/clipwright/pipeline/llm_backend.py similarity index 98% rename from llm_backend.py rename to clipwright/pipeline/llm_backend.py index 4ba16da..96a5cbf 100644 --- a/llm_backend.py +++ b/clipwright/pipeline/llm_backend.py @@ -108,7 +108,7 @@ def generate_json(prompt: str, schema: Type[BaseModel], model: Optional[str] = N provider. Raises on HTTP errors, empty bodies and schema violations; the retry policy lives in the caller, same as for Gemini. """ - import gemini_worker # local import: keeps this module free of the google SDK + from clipwright.pipeline import gemini_worker # local import: keeps this module free of the google SDK url = f"{base_url()}/chat/completions" model = model or model_name() diff --git a/main.py b/clipwright/pipeline/main.py similarity index 98% rename from main.py rename to clipwright/pipeline/main.py index a0fd78d..4f6a580 100644 --- a/main.py +++ b/clipwright/pipeline/main.py @@ -23,16 +23,17 @@ import mediapipe as mp from google import genai from google.genai import types as genai_types -import frame_sampler -import gemini_worker -import hook_grounding -import layout_picker -import llm_backend -from clip_selection import (build_transcript_windows, clip_count_targets, +from clipwright.media import frame_sampler +from clipwright.pipeline import gemini_worker +from clipwright.pipeline import hook_grounding +from clipwright.layouts import layout_picker +from clipwright.pipeline import llm_backend +from clipwright.core.paths import ASSETS_DIR +from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets, clip_duration_bounds, dedupe_overlapping, score_batches, shortlist_target, snap_clip_to_words, trim_to_best) -from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY, +from clipwright.media.ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY, QUALITY_FAST, METADATA_SCRUB) from dotenv import load_dotenv import json @@ -633,7 +634,7 @@ def analyze_scenes_strategy(video_path, scenes): return strategies def detect_scenes(video_path): - import scene_detection + from clipwright.media import scene_detection return scene_detection.detect_scenes(video_path) def get_video_resolution(video_path): @@ -836,14 +837,14 @@ def download_youtube_video(url, output_dir=".", on_audio=None): """ # SSRF guard: block non-http(s) schemes and private/loopback/metadata hosts # before handing the URL to yt-dlp. - from security_utils import assert_public_url + from clipwright.core.security_utils import assert_public_url assert_public_url(url) # Throwaway hosts agents fall back to (tmpfiles.org) hand out short-lived # signed links; refresh through the host's page so yt-dlp gets the file. - import file_hosts + from clipwright.integrations import file_hosts url = file_hosts.resolve(url) # Reject non-video YouTube links before the download starts. - from yt_clients import NotASingleVideo, youtube_non_video_reason + from clipwright.integrations.yt_clients import NotASingleVideo, youtube_non_video_reason reason = youtube_non_video_reason(url) if reason: raise NotASingleVideo(f"This link is {reason}.") @@ -899,7 +900,7 @@ def download_youtube_video(url, output_dir=".", on_audio=None): # explicit `default,mweb` because the authed defaults alone return # "Video unavailable" on a share of videos, from every IP, and that was # what fed the per-GB proxy (6-sep-2026, verified in the prod container). - from yt_clients import hd_extractor_args, fallback_extractor_args + from clipwright.integrations.yt_clients import hd_extractor_args, fallback_extractor_args hd_args = hd_extractor_args(_bgutil_http, _bgutil_script) fallback_args = fallback_extractor_args(_bgutil_http, _bgutil_script) @@ -1210,7 +1211,7 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges= if not transcript or not transcript.get('segments'): return None # silent video: nothing to caption try: - import subtitles as _subs + from clipwright.media import subtitles as _subs style = _subs.AUTO_CAPTION_STYLE output_dir = os.path.dirname(clip_path) stem = os.path.basename(clip_path) @@ -1242,7 +1243,7 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges= out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}") if split_ranges is None: - import layout_ranges as _layouts + from clipwright.layouts import layout_ranges as _layouts split_ranges = _layouts.split_ranges(_layouts.read(clip_path)) if not _subs.generate_ass( transcript, clip_start, clip_end, ass_path, @@ -1302,7 +1303,7 @@ def auto_hook_clip(clip_path, clip, captions=None): except ValueError: seconds = 5.0 try: - from hooks import add_hook_to_video, HOOK_STYLES + from clipwright.media.hooks import add_hook_to_video, HOOK_STYLES if style not in HOOK_STYLES: style = "pill" output_dir = os.path.dirname(clip_path) @@ -1378,8 +1379,7 @@ WATERMARK_OPACITY = 0.85 def watermark_logo_path(): - return os.path.join(os.path.dirname(os.path.abspath(__file__)), - "assets", "watermark.png") + return str(ASSETS_DIR / "watermark.png") def watermark_filter(vw, vh, video="[0:v]", logo="[1:v]", out=""): @@ -1451,7 +1451,7 @@ def mark_delivery(final_path, marker=None): be made: the mark must never cost the user the clip (same fail-open rule apply_watermark has always had). """ - import watermarked + from clipwright.media import watermarked out_path = os.path.join(os.path.dirname(final_path), watermarked.marked_name(final_path)) if os.path.exists(out_path) and os.path.getsize(out_path) > 0: @@ -1484,7 +1484,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE # falls back to the v1 frame loop below so a v2 edge case can't kill jobs. if os.environ.get("REFRAME_ENGINE", "v2").strip().lower() != "v1": try: - import reframe_v2 + from clipwright.layouts import reframe_v2 t0 = time.time() result = reframe_v2.render(input_video, final_output_video, aspect_ratio, force_strategy=force_strategy, @@ -1536,7 +1536,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE # Same delivery floor as the v2 engine — a fallback render is still the clip # the user posts, so it must not ship sub-HD. The frame loop below already # resizes every cropped frame to these dims, so nothing else changes. - from reframe_v2 import delivery_size + from clipwright.layouts.reframe_v2 import delivery_size OUTPUT_WIDTH, OUTPUT_HEIGHT = delivery_size(original_width, original_height, aspect_ratio) @@ -1776,7 +1776,7 @@ def _free_gpu_cache(): def transcribe_video(video_path): print("🎙️ Transcribing video...") - from transcribe_backends import transcribe_media, release_models, host_asr_slot + from clipwright.pipeline.transcribe_backends import transcribe_media, release_models, host_asr_slot # At most ASR_HOST_SLOTS jobs transcribe on the GPU at once, host-wide. # Inside the slot, the model's VRAM is handed back before the long render @@ -2308,7 +2308,7 @@ if __name__ == '__main__': _w = int(_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) _h = int(_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) _cap.release() - from reframe_v2 import source_already_fits # imports main back + from clipwright.layouts.reframe_v2 import source_already_fits # imports main back # A source already shot vertical has no width to reorganise, and # the render passes it through whatever the model says. Asking # anyway costs a Gemini call per upload to be ignored. @@ -2340,7 +2340,7 @@ if __name__ == '__main__': # 3. Transcribe — unless the video has no audio, in which case fall back # to Gemini vision (picks clips from the imagery instead of the speech). - from transcribe_backends import NoAudioError + from clipwright.pipeline.transcribe_backends import NoAudioError transcript = None # Module handover (issue #68): another module already transcribed this # exact source with the same backend, so reuse its output. Any problem @@ -2453,7 +2453,7 @@ if __name__ == '__main__': deliver_path = clip_final_path # Which stretches were stacked (SPLIT): captions go on the # seam there, and /api/subtitle needs it again later. - import layout_ranges as _layouts + from clipwright.layouts import layout_ranges as _layouts clip['layout_ranges'] = _layouts.read(clip_final_path) # The hook was written from the transcript alone. When the # render put this clip's meaning on the screen, rewrite hook @@ -2505,7 +2505,7 @@ if __name__ == '__main__': if os.environ.get("WATERMARK") == "1": # Tells the /videos guard that the clean twins in this # directory are not for serving (watermarked.MARKER_FILE). - import watermarked + from clipwright.media import watermarked watermarked.mark_job(output_dir) with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool: # Best clip first: the pool starts work in submission order, so diff --git a/quality_probe.py b/clipwright/pipeline/quality_probe.py similarity index 93% rename from quality_probe.py rename to clipwright/pipeline/quality_probe.py index 1fd55b5..db85838 100644 --- a/quality_probe.py +++ b/clipwright/pipeline/quality_probe.py @@ -16,15 +16,16 @@ import sys from dotenv import load_dotenv +from clipwright.core.paths import REPO_ROOT + load_dotenv() def _find_cookies_path(): # Mirrors main.py's cookie discovery. - script_dir = os.path.dirname(os.path.abspath(__file__)) for candidate in [ - os.path.join(script_dir, 'www.youtube.com_cookies.txt'), - os.path.join(script_dir, 'cookies.txt'), + str(REPO_ROOT / 'www.youtube.com_cookies.txt'), + str(REPO_ROOT / 'cookies.txt'), '/app/cookies.txt', ]: if os.path.exists(candidate): @@ -44,8 +45,8 @@ def main() -> int: # result is the fail-open "unknown", so the caller carries on and the # real probe / download refuse the URL with their own message. try: - from security_utils import assert_public_url - from yt_clients import youtube_non_video_reason + from clipwright.core.security_utils import assert_public_url + from clipwright.integrations.yt_clients import youtube_non_video_reason assert_public_url(args.url) if youtube_non_video_reason(args.url): raise ValueError("not a single video") diff --git a/transcribe_backends.py b/clipwright/pipeline/transcribe_backends.py similarity index 99% rename from transcribe_backends.py rename to clipwright/pipeline/transcribe_backends.py index 9da46a1..576f60b 100644 --- a/transcribe_backends.py +++ b/clipwright/pipeline/transcribe_backends.py @@ -32,7 +32,7 @@ import tempfile import threading import time -from subtitles import ( +from clipwright.media.subtitles import ( get_whisper_config, WHISPER_TRANSCRIBE_PARAMS, merge_continuation_words, @@ -368,7 +368,7 @@ def release_models(): del whisper, parakeet # TransNetV2 is the other torch tenant an in-process pipeline leaves # behind (scene_detection keeps it as a module singleton too). - tn2 = sys.modules.get("scene_detection") + tn2 = sys.modules.get("clipwright.media.scene_detection") if tn2 is not None: tn2._tn2_model = None import gc diff --git a/clipwright/tools/__init__.py b/clipwright/tools/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/tools/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/verify_aesthetic.py b/clipwright/tools/verify_aesthetic.py similarity index 95% rename from verify_aesthetic.py rename to clipwright/tools/verify_aesthetic.py index b288f86..e4f5ee9 100644 --- a/verify_aesthetic.py +++ b/clipwright/tools/verify_aesthetic.py @@ -2,7 +2,7 @@ import os import shutil # Check if PIL is installed, if not we can't run this locally but it will run in docker try: - from hooks import create_hook_image + from clipwright.media.hooks import create_hook_image except ImportError: print("⚠️ PIL not found locally. Please run this inside the Docker container.") # Mocking for local check if needed or just exit diff --git a/verify_custom_hook.py b/clipwright/tools/verify_custom_hook.py similarity index 94% rename from verify_custom_hook.py rename to clipwright/tools/verify_custom_hook.py index e645927..028bffc 100644 --- a/verify_custom_hook.py +++ b/clipwright/tools/verify_custom_hook.py @@ -1,6 +1,6 @@ import os try: - from hooks import create_hook_image + from clipwright.media.hooks import create_hook_image except ImportError: print("⚠️ PIL not found locally. Run inside Docker.") exit(1) diff --git a/verify_hooks.py b/clipwright/tools/verify_hooks.py similarity index 94% rename from verify_hooks.py rename to clipwright/tools/verify_hooks.py index 9c7a51c..a1bee1b 100644 --- a/verify_hooks.py +++ b/clipwright/tools/verify_hooks.py @@ -1,6 +1,6 @@ import os import shutil -from hooks import create_hook_image +from clipwright.media.hooks import create_hook_image def verify(): print("🧪 Verifying Hook Image Generation...") diff --git a/dashboard/seo/pages.js b/dashboard/seo/pages.js index 963350d..76282c5 100644 --- a/dashboard/seo/pages.js +++ b/dashboard/seo/pages.js @@ -1754,7 +1754,7 @@ ${faqBlock([ ${sources([ 'Opus Clip tier minutes and prices checked 2026-07-27 on their public pricing page.', 'Inset detection and layout accuracy figures are our own measurements on a 48-video internal corpus, 2026-08.', - 'Silent-footage thresholds (8 words, 5 words per minute) and the vision fallback are in main.py; Gemini video token rates from Google\'s published pricing.', + 'Silent-footage thresholds (8 words, 5 words per minute) and the vision fallback are in clipwright/pipeline/main.py; Gemini video token rates from Google\'s published pricing.', `Inset, WIDE and screencast layout implementations in the project source at git.pbento.pt/pedro-bento/clipwright.`, ])} `, diff --git a/dashboard/src/components/HookModal.jsx b/dashboard/src/components/HookModal.jsx index a77c4d6..8bb3c9e 100644 --- a/dashboard/src/components/HookModal.jsx +++ b/dashboard/src/components/HookModal.jsx @@ -11,7 +11,7 @@ const ENTRANCE_OPTIONS = [ { value: 'none', label: 'None' }, ]; -// Must mirror hooks.py HOOK_STYLES. +// Must mirror clipwright/media/hooks.py HOOK_STYLES. const HOOK_STYLES = [ { value: 'pill', label: 'Pills', box: 'rgba(255,255,255,0.98)', text: '#000', sans: true }, { value: 'classic', label: 'Classic', box: 'rgba(255,255,255,0.94)', text: '#000' }, @@ -22,7 +22,7 @@ const HOOK_STYLES = [ { value: 'outline_yellow', label: 'Outline+', box: 'transparent', text: '#FFD600', outline: true }, ]; -// Must mirror hooks.py HOOK_FONTS (all bundled: /fonts/*.ttf). +// Must mirror clipwright/media/hooks.py HOOK_FONTS (all bundled: /fonts/*.ttf). const FONT_OPTIONS = [ { value: 'montserrat', label: 'Montserrat' }, { value: 'anton', label: 'Anton' }, @@ -33,7 +33,7 @@ const FONT_CSS = { anton: { fontFamily: "'Anton-Regular', Impact, sans-serif", fontWeight: 400 }, serif: { fontFamily: "'Noto Serif', Georgia, serif", fontWeight: 700 }, }; -// The style's own typeface when none is picked (what hooks.py renders). +// The style's own typeface when none is picked (what clipwright/media/hooks.py renders). const styleFont = (st) => (st === 'pill' ? 'montserrat' : 'serif'); const POSITION_OPTIONS = [ diff --git a/dashboard/src/remotion/compositions/HookOverlay.tsx b/dashboard/src/remotion/compositions/HookOverlay.tsx index 808a00c..a53009d 100644 --- a/dashboard/src/remotion/compositions/HookOverlay.tsx +++ b/dashboard/src/remotion/compositions/HookOverlay.tsx @@ -25,7 +25,7 @@ const SIZE_SCALE: Record = { L: 1.3, }; -// Percentages must match hooks.py's overlay_y math (top 20% / bottom 70%), +// Percentages must match clipwright/media/hooks.py's overlay_y math (top 20% / bottom 70%), // or the preview drifts from what the server path renders. const POSITION_STYLE: Record = { top: { top: "20%", bottom: "auto" }, @@ -33,13 +33,13 @@ const POSITION_STYLE: Record = { bottom: { top: "70%", bottom: "auto" }, }; -// Must mirror hooks.py HOOK_STYLES (the server-side FFmpeg fallback). +// Must mirror clipwright/media/hooks.py HOOK_STYLES (the server-side FFmpeg fallback). interface HookLook { box: string | null; text: string; outlinePx: number; shadow: boolean; - /** One rounded box per line (hooks.py _draw_pills) instead of one card. */ + /** One rounded box per line (clipwright/media/hooks.py _draw_pills) instead of one card. */ pills?: boolean; } @@ -127,7 +127,7 @@ const HookBox: React.FC = ({ config, displayFrames }) => { const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top; const look = HOOK_LOOKS[config.style ?? "pill"] ?? HOOK_LOOKS.pill; - // Typeface and size as hooks.py: the chosen font, else the style's own; + // Typeface and size as clipwright/media/hooks.py: the chosen font, else the style's own; // font size = factor x the 90%-of-width box. const typeface = HOOK_FONTS[config.font ?? (look.pills ? "montserrat" : "serif")] ?? HOOK_FONTS.serif; const fontSize = Math.round(1080 * 0.9 * typeface.factor * scale); @@ -135,7 +135,7 @@ const HookBox: React.FC = ({ config, displayFrames }) => { if (look.pills) { // box-decoration-break: clone gives every wrapped line its own padded, - // rounded box, the same stack hooks.py draws for the FFmpeg path. + // rounded box, the same stack clipwright/media/hooks.py draws for the FFmpeg path. return (
= { montserrat: { family: `'${MONTSERRAT_FONT_FAMILY}', 'Montserrat', sans-serif`, weight: 800, factor: 0.064 }, diff --git a/docs/compliance/retencion.md b/docs/compliance/retencion.md index 813d93b..62eac71 100644 --- a/docs/compliance/retencion.md +++ b/docs/compliance/retencion.md @@ -33,15 +33,14 @@ La retención de fotos de actor se retiró con la función de vídeo UGC | Qué | Plazo | Dónde se aplica | |---|---|---| -| Clips y proyectos en el disco local | Hasta que los borres o caduque el barrido de trabajos | `app.cleanup_jobs`, `JOB_RETENTION_SECONDS` | +| Clips y proyectos en el disco local | Hasta que los borres o caduque el barrido de trabajos | `clipwright.api.app.cleanup_jobs`, `JOB_RETENTION_SECONDS` | ## 3. Base de datos de la aplicación (si usas cuentas) | Qué | Plazo | Dónde se aplica | |---|---|---| -| Datos de cuenta y proyectos | Mientras exista la cuenta; **inmediato** al borrarla | `app.py`, la ruta de borrado de cuenta | -| **Declaración de derechos** (IP truncada a /24, user-agent, fecha, origen) | Con el proyecto al que pertenece → hasta 5 años | `app.py` (captura) → `Project.state.rights_attestation` | -| `proxy_usage` (host de la URL, id de trabajo; **sin usuario**) | Contabilidad de costes; sin datos personales | `metering.py` | +| Datos de cuenta y proyectos | Mientras exista la cuenta; **inmediato** al borrarla | `clipwright/api/app.py`, la ruta de borrado de cuenta | +| **Declaración de derechos** (IP truncada a /24, user-agent, fecha, origen) | Con el proyecto al que pertenece → hasta 5 años | `clipwright/api/app.py` (captura) → `Project.state.rights_attestation` | ## 4. Navegador del usuario (localStorage, nunca cookies de terceros) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..ba47db1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,30 @@ +# The backend is not packaged or published: it runs from a bind-mounted source +# tree (docker-compose.yml) and `requirements.txt` is the single runtime +# dependency source for the Docker image. This file therefore carries tool +# configuration only — no [build-system] and no [project] table — which also +# avoids colliding with the published `clipwright` CLI distribution under +# `cli/`. + +[tool.pytest.ini_options] +minversion = "7.0" +testpaths = ["tests"] +# Makes the repo-root `clipwright/` package importable without a sys.path hack +# in tests/conftest.py. +pythonpath = ["."] + +[tool.ruff] +line-length = 100 +target-version = "py311" +extend-exclude = [ + "dashboard", + "render-service", + "remotion", + "cli", + "output", + "uploads", +] + +[tool.ruff.lint] +# Correctness only for now: keep this migration reviewable. Style/import rules +# can be ratcheted later without conflicting with the structural change. +select = ["E4", "E7", "E9", "F"] diff --git a/remotion/src/compositions/HookOverlay.tsx b/remotion/src/compositions/HookOverlay.tsx index 061c806..961bb5c 100644 --- a/remotion/src/compositions/HookOverlay.tsx +++ b/remotion/src/compositions/HookOverlay.tsx @@ -26,7 +26,7 @@ const POSITION_STYLE: Record = { bottom: { top: "68%", bottom: "auto" }, }; -// Must mirror hooks.py HOOK_STYLES so preview == burned output. +// Must mirror clipwright/media/hooks.py HOOK_STYLES so preview == burned output. interface HookLook { box: string | null; text: string; @@ -126,7 +126,7 @@ const HookBox: React.FC = ({ config, displayFrames }) => { const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top; const look = HOOK_LOOKS[config.style ?? "classic"] ?? HOOK_LOOKS.classic; - // Base font size: 5% of 1080 width (matches hooks.py logic) + // Base font size: 5% of 1080 width (matches clipwright/media/hooks.py logic) const baseFontSize = 1080 * 0.05; const fontSize = Math.round(baseFontSize * scale); diff --git a/requirements-test.txt b/requirements-test.txt new file mode 100644 index 0000000..3a452c3 --- /dev/null +++ b/requirements-test.txt @@ -0,0 +1,14 @@ +# Thin test environment: everything the collected tests import at module level, +# WITHOUT the heavy ML stack (torch/ultralytics/mediapipe/faster-whisper). The +# pipeline modules import those lazily behind their feature gates, and the tests +# exercise the gated-off paths. +pytest +pillow +httpx +pydantic +numpy +opencv-python-headless +python-dotenv +google-genai +fastapi +python-multipart diff --git a/tests/conftest.py b/tests/conftest.py index b551e8a..0a79c82 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,7 @@ -import os -import sys +"""Shared pytest configuration. -# Make the repo root importable so tests can import the app modules directly. -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +The repo-root ``clipwright/`` package is made importable by +``[tool.pytest.ini_options] pythonpath = ["."]`` in the root ``pyproject.toml``, +so no manual ``sys.path`` manipulation is needed here. This module is kept for +future shared fixtures. +""" diff --git a/tests/test_active_speaker.py b/tests/test_active_speaker.py index 044a209..895b4c3 100644 --- a/tests/test_active_speaker.py +++ b/tests/test_active_speaker.py @@ -1,4 +1,4 @@ -from active_speaker import ( +from clipwright.layouts.active_speaker import ( attribute_windows, hold, is_conversation, diff --git a/tests/test_ai_disclosure.py b/tests/test_ai_disclosure.py index 9d3b1b3..ca535f7 100644 --- a/tests/test_ai_disclosure.py +++ b/tests/test_ai_disclosure.py @@ -13,7 +13,7 @@ import os import pytest Image = pytest.importorskip("PIL.Image") -thumbnail = pytest.importorskip("thumbnail") +thumbnail = pytest.importorskip("clipwright.media.thumbnail") TRAINED = b"trainedAlgorithmicMedia" diff --git a/tests/test_audit_hardening.py b/tests/test_audit_hardening.py index 24322bc..629b28f 100644 --- a/tests/test_audit_hardening.py +++ b/tests/test_audit_hardening.py @@ -14,7 +14,9 @@ import os import httpx import pytest -app_module = pytest.importorskip("app") +app_module = pytest.importorskip("clipwright.api.app") + +from clipwright.core import security_utils # noqa: E402 def _client_call(method, path, **kw): @@ -105,7 +107,7 @@ def test_youtube_search_page_is_refused_before_any_probe(dirs, monkeypatch): probed.append(u) return {} monkeypatch.setattr(app_module, "_probe_youtube_quality", _probe) - monkeypatch.setattr("security_utils.assert_public_url", lambda u: u) + monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u) resp = _post_process({"url": "https://www.youtube.com/results?search_query=x", "acknowledged": True}) assert resp.status_code == 400 @@ -194,29 +196,51 @@ def test_child_env_drops_server_secrets(monkeypatch): def test_pipeline_code_reads_none_of_the_dropped_secrets(): - """If main.py (or anything it imports) ever needs one of these, the + """If the pipeline (or anything it imports) ever needs one of these, the denylist would silently break jobs: fail here instead.""" import ast - root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - local = {f[:-3] for f in os.listdir(root) if f.endswith(".py")} - seen, stack = set(), ["main", "quality_probe"] + from pathlib import Path + + root = Path(__file__).resolve().parents[1] + package = root / "clipwright" + # Every importable module name -> its source file, e.g. + # ``clipwright.media.subtitles`` -> clipwright/media/subtitles.py. + sources = {} + for path in package.rglob("*.py"): + parts = list(path.relative_to(root).with_suffix("").parts) + if parts[-1] == "__init__": + parts = parts[:-1] + sources[".".join(parts)] = path + + seen, stack = set(), ["clipwright.pipeline.main", "clipwright.pipeline.quality_probe"] while stack: mod = stack.pop() - if mod in seen: + if mod in seen or mod not in sources: continue seen.add(mod) - src = open(os.path.join(root, mod + ".py"), encoding="utf-8").read() + src = sources[mod].read_text(encoding="utf-8") for name in app_module.CHILD_ENV_DENYLIST: assert f'"{name}"' not in src and f"'{name}'" not in src, (mod, name) for node in ast.walk(ast.parse(src)): - names = [] if isinstance(node, ast.Import): - names = [a.name.split(".")[0] for a in node.names] - elif isinstance(node, ast.ImportFrom) and node.module: - names = [node.module.split(".")[0]] - for n in names: - if n in local: - stack.append(n) + targets = [a.name for a in node.names] + elif isinstance(node, ast.ImportFrom): + if node.level: + base = mod.split(".")[:-1] + base = base[: len(base) - (node.level - 1)] + prefix = ".".join(base) + base_mod = f"{prefix}.{node.module}" if node.module else prefix + else: + base_mod = node.module or "" + if node.module: + targets = [base_mod] + [f"{base_mod}.{a.name}" for a in node.names] + else: + targets = [f"{base_mod}.{a.name}" for a in node.names] + else: + continue + for target in targets: + if target in sources: + stack.append(target) def test_job_env_has_no_server_secrets(dirs, calls, monkeypatch): @@ -240,7 +264,7 @@ import subprocess class TestSafetyCap: @pytest.fixture() def source(self, tmp_path): - main = pytest.importorskip("main") + main = pytest.importorskip("clipwright.pipeline.main") path = tmp_path / "src.mp4" subprocess.run([ "ffmpeg", "-y", "-loglevel", "error", diff --git a/tests/test_auto_retry.py b/tests/test_auto_retry.py index 3b22c4e..5309adf 100644 --- a/tests/test_auto_retry.py +++ b/tests/test_auto_retry.py @@ -9,7 +9,7 @@ import json import pytest -app_module = pytest.importorskip("app") +app_module = pytest.importorskip("clipwright.api.app") @pytest.fixture diff --git a/tests/test_camera_inset.py b/tests/test_camera_inset.py index 7b22318..479e9c0 100644 --- a/tests/test_camera_inset.py +++ b/tests/test_camera_inset.py @@ -1,4 +1,4 @@ -from camera_inset import ( +from clipwright.layouts.camera_inset import ( INSET_ASPECT, inset_box, inset_filtergraph, diff --git a/tests/test_caption_presets.py b/tests/test_caption_presets.py index bf6c5dc..cd446d4 100644 --- a/tests/test_caption_presets.py +++ b/tests/test_caption_presets.py @@ -2,7 +2,7 @@ import asyncio import re -from subtitles import AUTO_CAPTION_STYLE, CAPTION_PRESETS, line_budget +from clipwright.media.subtitles import AUTO_CAPTION_STYLE, CAPTION_PRESETS, line_budget def test_dashboard_offers_every_server_preset(): @@ -28,14 +28,14 @@ def test_line_budget_shrinks_with_size_and_wide_fonts(): def test_unknown_preset_is_a_400(): import pytest from fastapi import HTTPException - from app import SubtitleRequest, add_subtitles + from clipwright.api.app import SubtitleRequest, add_subtitles with pytest.raises(HTTPException) as exc: asyncio.run(add_subtitles(SubtitleRequest(job_id="j", clip_index=0, preset="nope"), None)) assert exc.value.status_code == 400 def test_preset_fills_only_fields_not_sent(): - from app import SubtitleRequest + from clipwright.api.app import SubtitleRequest req = SubtitleRequest(job_id="j", clip_index=0, preset="hormozi", highlight_color="#00FF00") merged = req.model_copy(update={k: v for k, v in CAPTION_PRESETS["hormozi"].items() if k not in req.model_fields_set}) diff --git a/tests/test_cleanup_live_jobs.py b/tests/test_cleanup_live_jobs.py index 2f496e9..e0696a1 100644 --- a/tests/test_cleanup_live_jobs.py +++ b/tests/test_cleanup_live_jobs.py @@ -9,7 +9,7 @@ import time import pytest -app_module = pytest.importorskip("app") +app_module = pytest.importorskip("clipwright.api.app") OLD = 2 * 3600 # older than the 1 h JOB_RETENTION_SECONDS the fixture sets diff --git a/tests/test_clip_floor.py b/tests/test_clip_floor.py index 4dde4cf..8f28986 100644 --- a/tests/test_clip_floor.py +++ b/tests/test_clip_floor.py @@ -9,7 +9,7 @@ import json import pytest -main = pytest.importorskip("main") +main = pytest.importorskip("clipwright.pipeline.main") def _transcript(n_segments=40): diff --git a/tests/test_clip_ready_marker.py b/tests/test_clip_ready_marker.py index 2c63912..62bc3ca 100644 --- a/tests/test_clip_ready_marker.py +++ b/tests/test_clip_ready_marker.py @@ -10,10 +10,13 @@ main.py now announces each clip once its whole chain is done and names the file to serve; app.py consumes the marker the way it already consumes PROXY_BYTES. """ import io +from pathlib import Path import pytest -app = pytest.importorskip("app") +app = pytest.importorskip("clipwright.api.app") + +MAIN_PY = Path(__file__).resolve().parents[1] / "clipwright" / "pipeline" / "main.py" def _feed(job_id, *lines): @@ -69,7 +72,7 @@ class TestMainAnnouncesTheDeliveredFile: Announcing the pre-caption path would put the poller back on a file the pipeline is about to supersede, which is the bug this fixes. """ - main_src = open("main.py", encoding="utf-8").read() + main_src = MAIN_PY.read_text(encoding="utf-8") caption_at = main_src.index("captioned = auto_caption_clip(") # The free plan's served file is a wm_ copy of the captioned final # (mark_delivery), so the marker must also come after that step. diff --git a/tests/test_clip_render_order.py b/tests/test_clip_render_order.py index b660f53..73e1872 100644 --- a/tests/test_clip_render_order.py +++ b/tests/test_clip_render_order.py @@ -1,7 +1,7 @@ """The strongest clip renders first, so it is the first one the user sees.""" import pytest -main = pytest.importorskip("main") +main = pytest.importorskip("clipwright.pipeline.main") def test_best_score_first(): diff --git a/tests/test_clip_selection.py b/tests/test_clip_selection.py index c546ba4..c984b58 100644 --- a/tests/test_clip_selection.py +++ b/tests/test_clip_selection.py @@ -3,7 +3,7 @@ import re import pytest -from clip_selection import ( +from clipwright.pipeline.clip_selection import ( build_transcript_windows, clip_count_targets, dedupe_overlapping, @@ -157,7 +157,7 @@ class TestClipCountTargets: class TestDetailPromptCarriesTheCount: def test_template_formats_with_the_targets(self): - gw = pytest.importorskip("gemini_worker") + gw = pytest.importorskip("clipwright.pipeline.gemini_worker") low, high = clip_count_targets(5) prompt = gw.DETAIL_PROMPT_TEMPLATE.format( video_duration=300, language="es", min_clips=low, max_clips=high, diff --git a/tests/test_deploy_drain.py b/tests/test_deploy_drain.py index d3c63c7..e22e16b 100644 --- a/tests/test_deploy_drain.py +++ b/tests/test_deploy_drain.py @@ -13,7 +13,7 @@ import time import httpx import pytest -app_module = pytest.importorskip("app") +app_module = pytest.importorskip("clipwright.api.app") @pytest.fixture diff --git a/tests/test_download_plan.py b/tests/test_download_plan.py index 84f6b63..74ccfe2 100644 --- a/tests/test_download_plan.py +++ b/tests/test_download_plan.py @@ -7,7 +7,7 @@ bytes) -> per-GB paid proxy (720p cost cap) -> conservative fallback. The """ import pytest -main = pytest.importorskip("main") +main = pytest.importorskip("clipwright.pipeline.main") plan = main.plan_download_attempts diff --git a/tests/test_edit_builder.py b/tests/test_edit_builder.py index d24a1c1..0209ec9 100644 --- a/tests/test_edit_builder.py +++ b/tests/test_edit_builder.py @@ -1,6 +1,6 @@ import pytest -from edit_builder import EFFECT_LIMITS, build_filter_string, normalize_edits +from clipwright.media.edit_builder import EFFECT_LIMITS, build_filter_string, normalize_edits def _edit(type_, start, end, strength=0.0): diff --git a/tests/test_ffmpeg_utils.py b/tests/test_ffmpeg_utils.py index c8eb41f..be2c4d4 100644 --- a/tests/test_ffmpeg_utils.py +++ b/tests/test_ffmpeg_utils.py @@ -2,8 +2,8 @@ import subprocess import pytest -import ffmpeg_utils -from ffmpeg_utils import ( +from clipwright.media import ffmpeg_utils +from clipwright.media.ffmpeg_utils import ( AI_DISCLOSURE, DELIVERY, METADATA_SCRUB, diff --git a/tests/test_filename_limits.py b/tests/test_filename_limits.py index 399d280..a006940 100644 --- a/tests/test_filename_limits.py +++ b/tests/test_filename_limits.py @@ -6,8 +6,8 @@ already being ~300 bytes, and the derived temp name pushed it further. """ import pytest -main = pytest.importorskip("main") # cv2 etc., absent in minimal CI -hooks = pytest.importorskip("hooks") +main = pytest.importorskip("clipwright.pipeline.main") # cv2 etc., absent in minimal CI +hooks = pytest.importorskip("clipwright.media.hooks") # ext4/APFS cap a single name at 255 bytes. FS_LIMIT = 255 diff --git a/tests/test_frame_sampler.py b/tests/test_frame_sampler.py index 658d55c..a963870 100644 --- a/tests/test_frame_sampler.py +++ b/tests/test_frame_sampler.py @@ -2,7 +2,7 @@ import cv2 import numpy as np import pytest -import frame_sampler +from clipwright.media import frame_sampler N_FRAMES = 60 diff --git a/tests/test_free_tools.py b/tests/test_free_tools.py index 70819d7..508a4e6 100644 --- a/tests/test_free_tools.py +++ b/tests/test_free_tools.py @@ -10,7 +10,7 @@ import pytest from fastapi import FastAPI from fastapi.testclient import TestClient -import free_tools as ft +from clipwright.api import free_tools as ft class TestExtractVideoId: diff --git a/tests/test_gemini_block_split.py b/tests/test_gemini_block_split.py index 7eded77..fab23a6 100644 --- a/tests/test_gemini_block_split.py +++ b/tests/test_gemini_block_split.py @@ -1,7 +1,7 @@ """A policy block on a batch of windows must bisect, not kill the job.""" import pytest -main = pytest.importorskip("main") -import gemini_worker +main = pytest.importorskip("clipwright.pipeline.main") +from clipwright.pipeline import gemini_worker def _windows(n): diff --git a/tests/test_gemini_retry.py b/tests/test_gemini_retry.py index 130ca1f..05a5383 100644 --- a/tests/test_gemini_retry.py +++ b/tests/test_gemini_retry.py @@ -9,7 +9,7 @@ import pytest # main pulls in cv2/torch/mediapipe at import time; the minimal CI env lacks # them, so skip there. Runs fully in the container/local where deps exist. -main = pytest.importorskip("main") +main = pytest.importorskip("clipwright.pipeline.main") class _FakeResponse: @@ -112,7 +112,7 @@ def test_policy_block_fails_fast_without_retrying(): _Models.calls += 1 return _BlockedResponse() - import gemini_worker + from clipwright.pipeline import gemini_worker with pytest.raises(gemini_worker.GeminiBlockedError) as exc: main._run_gemini_stage(_client(_Models()), "m", "prompt", object) assert _Models.calls == 1 @@ -120,7 +120,7 @@ def test_policy_block_fails_fast_without_retrying(): def test_blocked_finish_reason_also_raises(): - import gemini_worker + from clipwright.pipeline import gemini_worker class _Cand: class _FR: @@ -137,7 +137,7 @@ def test_blocked_finish_reason_also_raises(): def test_clean_response_is_not_flagged_as_blocked(): - import gemini_worker + from clipwright.pipeline import gemini_worker class _Resp: prompt_feedback = None diff --git a/tests/test_gemini_upload_unicode_name.py b/tests/test_gemini_upload_unicode_name.py index 7908dda..3c2758f 100644 --- a/tests/test_gemini_upload_unicode_name.py +++ b/tests/test_gemini_upload_unicode_name.py @@ -12,7 +12,7 @@ import io import httpx import pytest -import gemini_worker +from clipwright.pipeline import gemini_worker def _prepared_headers(file_arg, mime_type=None): @@ -77,7 +77,12 @@ def test_every_whole_file_upload_goes_through_the_helper(): import re root = pathlib.Path(__file__).resolve().parent.parent offenders = [] - for name in ("main.py", "editor.py", "screencast_layout.py", "thumbnail.py"): + for name in ( + "clipwright/pipeline/main.py", + "clipwright/media/editor.py", + "clipwright/layouts/screencast_layout.py", + "clipwright/media/thumbnail.py", + ): src = (root / name).read_text() if re.search(r"\.files\.upload\(", src): offenders.append(name) diff --git a/tests/test_generation_controls.py b/tests/test_generation_controls.py index 6ec4e5e..c30dabe 100644 --- a/tests/test_generation_controls.py +++ b/tests/test_generation_controls.py @@ -9,7 +9,7 @@ import os import pytest -import clip_selection +from clipwright.pipeline import clip_selection @pytest.fixture(autouse=True) @@ -49,6 +49,7 @@ def _templates(): """The prompt template constants, read without importing gemini_worker (which pulls google-genai — absent in the thin CI env).""" mod = ast.parse(open(os.path.join(os.path.dirname(__file__), "..", + "clipwright", "pipeline", "gemini_worker.py")).read()) return { node.targets[0].id: node.value.value diff --git a/tests/test_hook_grounding.py b/tests/test_hook_grounding.py index 31dccb7..cc79bfd 100644 --- a/tests/test_hook_grounding.py +++ b/tests/test_hook_grounding.py @@ -7,8 +7,8 @@ detail pass only ever reads the transcript. """ import pytest -import gemini_worker -import hook_grounding as hg +from clipwright.pipeline import gemini_worker +from clipwright.pipeline import hook_grounding as hg SCREEN = [{"start": 0, "end": 30, "layout": "screencast"}] diff --git a/tests/test_hook_layers.py b/tests/test_hook_layers.py index f7dc377..9e957fd 100644 --- a/tests/test_hook_layers.py +++ b/tests/test_hook_layers.py @@ -10,7 +10,7 @@ import time import pytest -app_module = pytest.importorskip("app") +app_module = pytest.importorskip("clipwright.api.app") _strip_burned_captions = app_module._strip_burned_captions _strip_burned_hook = app_module._strip_burned_hook diff --git a/tests/test_hooks.py b/tests/test_hooks.py index b41c607..dad4321 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -4,7 +4,7 @@ import os from PIL import Image, ImageDraw, ImageFont -from hooks import ( +from clipwright.media.hooks import ( HOOK_STYLES, _break_long_word, _emoji_scale, @@ -135,7 +135,7 @@ class TestCreateHookImage: def test_pill_hook_image_stacks_one_box_per_line(tmp_path): """Two lines of text -> two rows of box pixels with a boxless column beside the shorter one (it is its own pill, not one shared card).""" - from hooks import create_hook_image + from clipwright.media.hooks import create_hook_image from PIL import Image out = tmp_path / "pill.png" path, w, h = create_hook_image("una frase bastante larga para partirse en dos lineas", diff --git a/tests/test_layout_picker.py b/tests/test_layout_picker.py index 845b224..b419fc5 100644 --- a/tests/test_layout_picker.py +++ b/tests/test_layout_picker.py @@ -1,18 +1,30 @@ import sys import types -import layout_picker -from layout_picker import _module_flags, apply, pick +from clipwright import layouts +from clipwright.layouts import layout_picker +from clipwright.layouts.layout_picker import _module_flags, apply, pick + +# Decision labels are bare layout names; the modules they switch on live in the +# ``clipwright.layouts`` package and are imported lazily by apply(). +_FAKE_LAYOUT_MODULES = { + "split_layout": "clipwright.layouts.split_layout", + "screencast_layout": "clipwright.layouts.screencast_layout", + "active_speaker": "clipwright.layouts.active_speaker", +} def fake_modules(monkeypatch, **initial): """Install stand-in layout modules so apply() can be tested without them.""" made = {} - for name in ("split_layout", "screencast_layout", "active_speaker"): - module = types.ModuleType(name) - module.ENABLED = initial.get(name, False) - monkeypatch.setitem(sys.modules, name, module) - made[name] = module + for label, dotted in _FAKE_LAYOUT_MODULES.items(): + module = types.ModuleType(dotted) + module.ENABLED = initial.get(label, False) + monkeypatch.setitem(sys.modules, dotted, module) + # apply() does ``from clipwright.layouts import