clipwright/tests/e2e/pipeline/stub_env/sitecustomize.py
pedro-bento 026f3ff271
Some checks failed
CI / unit (pull_request) Failing after 24s
CI / backend-e2e (pull_request) Successful in 1m18s
CI / dashboard-e2e (pull_request) Successful in 1m44s
test: add full E2E coverage (API, pipeline, browser)
Three-level end-to-end suite, all deterministic (no retries, no sleeps, no
unmocked network):

- tests/e2e/api (209 tests): every route in clipwright/api/app.py +
  free_tools — health/config, uploads, process submit matrix + worker/webhook/
  auto-retry/resume, status/source/download-all, edit/effects, transcript/EDL/
  rerender, scenes/reframe, subtitle, hook, Postiz, thumbnails, free tools,
  and the security/path guards.
- tests/e2e/pipeline (136 tests): every stage with real ffmpeg and stubbed
  Gemini/yt-dlp/ASR/ML — download, transcribe, scene detect, selection,
  layout, reframe/render, subtitles, hooks, watermark, thumbnails, plus the
  real CLI full pipeline via stub_env.
- dashboard/e2e (19 Playwright specs): route-interception state machine
  covering every dashboard flow; one real-backend spec left test.fixme.
- Foundation: tests/e2e/conftest.py (state isolation, no-network guard, ffmpeg
  media factory, disk-seeded jobs), FakePopen worker harness, child-process
  stub_env, architecture-consistent fixtures.
- CI: unit + backend-e2e + dashboard-e2e jobs in the python+node container;
  ffmpeg + Playwright installed in-job; no setup-node/cache (act runner).

Verified: unit 790 passed; API E2E 209 passed; pipeline E2E 136 passed;
Playwright 19 passed / 1 skipped.
2026-10-04 21:58:28 +01:00

281 lines
8.7 KiB
Python

"""Interpreter-startup stubs injected into the pipeline CLI child via PYTHONPATH.
This file is named ``sitecustomize`` so CPython imports it automatically at
startup, *before* the ``-m clipwright.pipeline.main`` module body runs. That
lets us satisfy the heavy imports at the top of ``main.py`` (``ultralytics``,
``mediapipe``) and replace the two network/ML edges — ASR and Gemini — with
deterministic fakes. The real CLI then runs the real pipeline with real ffmpeg
and zero network / zero ML.
Kept intentionally dependency-free (stdlib only) so it imports cleanly in the
thin ``requirements-e2e.txt`` environment.
"""
import json
import sys
import types
from types import SimpleNamespace
# ---------------------------------------------------------------------------
# Fake ultralytics / mediapipe: main.py imports these at module level.
# ---------------------------------------------------------------------------
class _FakeYOLO:
def __init__(self, *args, **kwargs):
self.args = args
def __call__(self, *args, **kwargs):
return []
def predict(self, *args, **kwargs):
return []
def track(self, *args, **kwargs):
return []
class _FakeFaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
def _install_module(name, module):
sys.modules[name] = module
def _fake_ultralytics():
mod = types.ModuleType("ultralytics")
mod.YOLO = _FakeYOLO
return mod
def _fake_mediapipe():
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
face_detection.FaceDetection = _FakeFaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
return mp
_install_module("ultralytics", _fake_ultralytics())
_install_module("mediapipe", _fake_mediapipe())
_install_module("mediapipe.solutions", sys.modules["mediapipe"].solutions)
_install_module("mediapipe.solutions.face_detection",
sys.modules["mediapipe"].solutions.face_detection)
# ---------------------------------------------------------------------------
# Canned transcript: patch transcribe_backends so no ASR model is loaded.
# ---------------------------------------------------------------------------
_CANNED_TRANSCRIPT = {
"text": "This is a canned transcript for the end-to-end pipeline tests.",
"language": "en",
"segments": [
{
"start": 0.0,
"end": 3.0,
"text": " This is a canned transcript",
"words": [
{"word": " This", "start": 0.0, "end": 0.4},
{"word": " is", "start": 0.4, "end": 0.7},
{"word": " a", "start": 0.7, "end": 0.9},
{"word": " canned", "start": 0.9, "end": 1.4},
{"word": " transcript", "start": 1.4, "end": 2.2},
],
},
{
"start": 3.0,
"end": 6.0,
"text": " for the end-to-end pipeline tests.",
"words": [
{"word": " for", "start": 3.0, "end": 3.3},
{"word": " the", "start": 3.3, "end": 3.5},
{"word": " end-to-end", "start": 3.5, "end": 4.4},
{"word": " pipeline", "start": 4.4, "end": 5.1},
{"word": " tests.", "start": 5.1, "end": 5.9},
],
},
],
}
def _fake_transcribe_media(media_path):
return json.loads(json.dumps(_CANNED_TRANSCRIPT))
def _fake_release_models():
return None
try:
from clipwright.pipeline import transcribe_backends as _tb
_tb.transcribe_media = _fake_transcribe_media
_tb.release_models = _fake_release_models
except Exception as _exc: # pragma: no cover - surfaced in the child's stderr
print(f"[stub_env] could not patch transcribe_backends: {_exc}", file=sys.stderr)
# ---------------------------------------------------------------------------
# Scripted Gemini client. The real SDK is imported by main.py and the stage
# modules; we replace only ``genai.Client`` (they all call ``genai.Client(...)``
# on the module object, so the patch reaches every caller).
# ---------------------------------------------------------------------------
class _FakeResponse:
"""Surface consumed by gemini_worker / main._run_gemini_stage.
``parsed`` is None so the real JSON parser runs against ``.text`` — this
exercises the production parse path instead of bypassing it.
"""
def __init__(self, text):
self.text = text
self.parsed = None
self.prompt_feedback = None
self.candidates = []
self.usage_metadata = None
def _prompt_text(contents):
if isinstance(contents, str):
return contents
parts = []
for item in contents or []:
text = getattr(item, "text", None)
if isinstance(item, str):
parts.append(item)
elif text:
parts.append(text)
return "\n".join(parts)
def _extract_windows(prompt):
"""Parse the JSON array embedded after ``WINDOWS_JSON:`` / ``..._WINDOWS_JSON:``."""
for marker in ("WINDOWS_JSON:", "CANDIDATE_WINDOWS_JSON:"):
if marker not in prompt:
continue
tail = prompt.split(marker, 1)[1]
for stop in ("\n\nReturn only:", "\n\nReturn only"):
if stop in tail:
tail = tail.split(stop, 1)[0]
try:
return json.loads(tail.strip())
except Exception:
return []
return []
def _score_response(prompt):
windows = _extract_windows(prompt)
return json.dumps({
"windows": [
{
"id": w.get("id"),
"start": float(w.get("start", 0)),
"end": float(w.get("end", 1)),
"score": 85,
"reason": "stub score",
}
for w in windows
]
})
def _detail_response(prompt):
windows = _extract_windows(prompt)
if not windows:
windows = [{"start": 0, "end": 6, "id": "w0"}]
return json.dumps({
"shorts": [
{
"start": float(w.get("start", 0)),
"end": float(w.get("end", 1)),
"source_window_id": w.get("id") or "w0",
"predicted_score": 85,
"video_description_for_tiktok": "Stub #test #clip",
"video_description_for_instagram": "Stub #test #clip",
"video_title_for_youtube_short": "Stub clip",
"viral_hook_text": "Stub hook",
"why": "stub moment",
}
for w in windows
]
})
def _visual_response(prompt):
return json.dumps({
"shorts": [
{
"start": 0.0,
"end": 5.0,
"predicted_score": 80,
"video_description_for_tiktok": "Stub #test #clip",
"video_description_for_instagram": "Stub #test #clip",
"video_title_for_youtube_short": "Stub visual clip",
"viral_hook_text": "Stub visual hook",
}
]
})
def _response_for(prompt):
if "RANK these candidate windows" in prompt:
return _score_response(prompt)
if "Choose the BEST short clips" in prompt:
return _detail_response(prompt)
if "This video has NO speech/audio" in prompt:
return _visual_response(prompt)
if "These frames come from ONE short clip" in prompt:
return json.dumps({
"on_screen": "a screen",
"viral_hook_text": "Stub grounded hook",
"video_title_for_youtube_short": "Stub grounded title",
})
if "You are choosing how to re-frame" in prompt:
return json.dumps({"layout": "none", "confidence": 0.95, "why": "talking head"})
if "preparing a landscape video" in prompt:
return json.dumps({"ranges": []})
return "{}"
class _FakeModels:
def generate_content(self, model=None, contents=None, config=None):
return _FakeResponse(_response_for(_prompt_text(contents)))
class _FakeFiles:
def upload(self, file=None, config=None):
return SimpleNamespace(name="files/stub-video")
def get(self, name=None):
return SimpleNamespace(state=SimpleNamespace(name="ACTIVE"))
def delete(self, name=None):
return None
class _FakeClient:
def __init__(self, api_key=None, **kwargs):
self.models = _FakeModels()
self.files = _FakeFiles()
try:
from google import genai as _genai
_genai.Client = _FakeClient
except Exception as _exc: # pragma: no cover - surfaced in the child's stderr
print(f"[stub_env] could not patch google.genai.Client: {_exc}", file=sys.stderr)