feat(quota): offer the first N minutes of a long video instead of a bare wall

93 of the 99 quota walls sampled on 16-sep-2026 were shown to accounts with
their 20 free minutes untouched that had pasted a 21-90 min video: asked to
pay before seeing one clip, most left Stripe without paying.

The 402 now carries partial_minutes (the floored balance, at least
PARTIAL_MIN_MINUTES and shorter than the source). The wall shows 'clip the
first N min' next to the plans and resubmits with max_minutes; the server
reserves min(asked, balance) and sets MAX_SOURCE_MINUTES, and main.py cuts
the source in place before anything reads it, so every later stage and the
editor see a short video. The cut travels in the resume manifest so a
redeploy cannot re-run the whole video on a partial reservation. Status and
the results view say which part of the video the clips came from.
This commit is contained in:
juancarlos.cavero 2026-09-16 21:02:38 +02:00
parent afd29e1718
commit 03c8a1f887
9 changed files with 450 additions and 17 deletions

View file

@ -137,6 +137,26 @@ LLM it logs one line and keeps the transcript hook. `HOOK_GROUNDING=0`
disables it. The detail prompt itself now carries the rule "about this
moment, not the video", which is the cheap half of the same fix.
### The quota wall offers the first N minutes (`app.partial_offer`)
The wall (`TopUpModal`, context `wall`) opens on a 402 from `/api/process`.
Measured on 16-sep-2026, 93 of 99 walls were shown to accounts with their
20 free minutes **untouched** that had pasted a 21-90 min video: the user was
asked for $12 before seeing one clip, and 41 of the 68 subscriptions Stripe
created in 30 days expired unpaid, none of them a card decline. So the 402
now carries `partial_minutes` (the floored balance, when it is at least
`PARTIAL_MIN_MINUTES` and shorter than the source), the wall shows "clip the
first N min" next to the plans, and the dashboard resubmits the same job with
`max_minutes=N`. `reserve_process_minutes` then reserves N (never more than
the balance, whatever the client asks) and sets `MAX_SOURCE_MINUTES` for
`main.py`, whose `cap_source_duration` cuts the downloaded/uploaded file **in
place** before anything reads it, so transcription, the layout picker, the
editor and `/api/source` all see a short video. The cut travels in the
resume manifest: a resumed job downloads the source again and would
otherwise process 45 minutes on a 20-minute reservation. `/api/status` and
the process response carry `partial`, and the results view says which part
of the video the clips came from, with the upsell for the rest.
### Silent footage: the vision fallback (`main.get_visual_clips`)
The moment picker reads the transcript, so a video with nothing said in it

90
app.py
View file

@ -247,10 +247,51 @@ def _check_probe_rate(user_id):
times.append(now)
async def reserve_process_minutes(request, url, input_path, job_id):
def partial_offer(minutes_required: float, minutes_remaining: float) -> int:
"""Minutes of the source we can offer to clip instead of a 402, or 0.
The offer is the caller's whole remaining balance, floored to full minutes
(the reservation is in whole minutes), and only when it is both worth
clipping (``PARTIAL_MIN_MINUTES``) and actually shorter than the source.
"""
from cloud import config as _cfg # plain constants; importable with billing off
offer = int(math.floor(max(0.0, float(minutes_remaining or 0))))
if offer < _cfg.PARTIAL_MIN_MINUTES or offer >= minutes_required:
return 0
return offer
def plan_partial_minutes(minutes_required: int, minutes_remaining: float, max_minutes):
"""How many minutes to reserve for a source of ``minutes_required``.
Returns ``(reserve, partial)``: ``partial`` is None for a normal whole-video
job, or ``{"processed_minutes", "total_minutes"}`` when the caller asked
(``max_minutes``) to clip only the first part. The slice is capped by the
balance as well as by the request, so a client cannot name a bigger cut
than it can pay for; when the slice would be too small the request falls
through to the ordinary quota check (and its 402).
"""
if max_minutes is None:
return minutes_required, None
try:
asked = float(max_minutes)
except (TypeError, ValueError):
return minutes_required, None
from cloud import config as _cfg
cap = int(math.floor(min(asked, max(0.0, float(minutes_remaining or 0)))))
if minutes_required <= cap or cap < _cfg.PARTIAL_MIN_MINUTES:
return minutes_required, None
return cap, {"processed_minutes": cap, "total_minutes": minutes_required}
async def reserve_process_minutes(request, url, input_path, job_id, max_minutes=None):
"""Meter a managed /api/process request.
Returns (user_id, priority, reservation_id, plan).
Returns (user_id, priority, reservation_id, plan, partial).
``partial`` is None unless the caller asked (``max_minutes``) to clip only
the first part of a source its balance cannot cover whole; then it is the
``plan_partial_minutes`` dict and only that many minutes are reserved.
BYOK / self-host requests don't consume minutes (priority 2, no reservation).
For a managed (entitled, no BYOK header) request this probes the input
@ -263,10 +304,10 @@ async def reserve_process_minutes(request, url, input_path, job_id):
on the operator's key for free. Only skip metering when billing is off.
"""
if not BILLING_ENABLED:
return None, 2, None, None
return None, 2, None, None, None
user = await _user_from_request(request)
if not managed_keys.has_active_entitlement(user):
return None, 2, None, None # shouldn't happen (resolve_gemini would have 402'd)
return None, 2, None, None, None # shouldn't happen (resolve_gemini would have 402'd)
priority = _cloud_config.PLAN_PRIORITY.get(user.plan, 1)
@ -290,6 +331,7 @@ async def reserve_process_minutes(request, url, input_path, job_id):
"error": "quota_exceeded",
"minutes_required": 1,
"minutes_remaining": balance["remaining"],
"partial_minutes": 0,
})
# Probe rate limit: probing costs a (cheap) proxied metadata call. The
@ -326,17 +368,22 @@ async def reserve_process_minutes(request, url, input_path, job_id):
pass
minutes = max(1, math.ceil(minutes))
# A source longer than the balance can be clipped in part instead of
# refused: the wall offers "the first N minutes" (``partial_minutes`` in
# the 402 below) and the client resubmits with ``max_minutes``.
reserve, partial = plan_partial_minutes(minutes, balance["remaining"], max_minutes)
try:
reservation_id = await _metering.reserve_minutes(user.id, minutes, job_id)
reservation_id = await _metering.reserve_minutes(user.id, reserve, job_id)
except _metering.QuotaExceeded as e:
_maybe_send_quota_email(user)
raise HTTPException(status_code=402, detail={
"error": "quota_exceeded",
"minutes_required": e.required,
"minutes_remaining": e.remaining,
"partial_minutes": partial_offer(e.required, e.remaining),
})
return user.id, priority, reservation_id, user.plan
return user.id, priority, reservation_id, user.plan, partial
async def reserve_managed_action(request, minutes, job_id, job_type):
@ -856,7 +903,8 @@ def _install_drain_signal_handler():
def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, watermark,
webhook_url=None, webhook_secret=None, base_url=None):
webhook_url=None, webhook_secret=None, base_url=None,
partial=None):
try:
path = os.path.join(OUTPUT_DIR, job_id, _RESUME_FILE)
with open(path, "w") as f:
@ -873,6 +921,9 @@ def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, water
"webhook_url": webhook_url,
"webhook_secret": webhook_secret,
"base_url": base_url,
# A resumed job downloads the source again, so the cut must
# travel with it: only these minutes were reserved.
"partial": partial,
}, f)
except Exception as e:
print(f"⚠️ Could not write resume manifest for {job_id}: {e}")
@ -964,6 +1015,11 @@ def _resume_interrupted_jobs() -> set:
env["WATERMARK"] = "1"
else:
env.pop("WATERMARK", None)
partial = m.get("partial")
if partial and partial.get("processed_minutes"):
env["MAX_SOURCE_MINUTES"] = str(partial["processed_minutes"])
else:
env.pop("MAX_SOURCE_MINUTES", None)
m["attempts"] = attempts
try:
@ -981,6 +1037,7 @@ def _resume_interrupted_jobs() -> set:
'user_id': None if user_id is None else user_id,
'reservation_id': reservation_id,
'watermark': bool(m.get("watermark")),
'partial': partial or None,
'webhook_url': m.get("webhook_url"),
'webhook_secret': m.get("webhook_secret"),
'base_url': m.get("base_url"),
@ -2242,6 +2299,7 @@ async def process_endpoint(
thumbnail_session_id: Optional[str] = Form(None),
captions: Optional[str] = Form(None),
upload_id: Optional[str] = Form(None),
max_minutes: Optional[str] = Form(None),
):
api_key = await resolve_gemini(request)
if not api_key and not (llm_backend.active() and not BILLING_ENABLED):
@ -2276,6 +2334,7 @@ async def process_endpoint(
thumbnail_session_id = body.get("thumbnail_session_id")
captions = body.get("captions")
upload_id = body.get("upload_id")
max_minutes = body.get("max_minutes")
# Normalize output format (auto = keep pipeline default).
if output_format not in ("vertical", "horizontal", "square"):
@ -2523,7 +2582,12 @@ async def process_endpoint(
print(f"[attestation] job={job_id} ip={attestation['ip']} source={attestation['source']} ack=true")
# Meter + reserve minutes for managed users (no-op for BYOK / self-host).
user_id, priority, reservation_id, user_plan = await reserve_process_minutes(request, url, input_path, job_id)
user_id, priority, reservation_id, user_plan, partial = await reserve_process_minutes(
request, url, input_path, job_id, max_minutes=max_minutes)
if partial:
# main.py cuts the source down to this many minutes before anything
# reads it, so the whole pipeline (and the editor) sees a short video.
env["MAX_SOURCE_MINUTES"] = str(partial["processed_minutes"])
if user_plan == "free":
# Free-plan clips carry a burned-in watermark (applied by the main.py
# subprocess after each clip renders).
@ -2545,6 +2609,7 @@ async def process_endpoint(
'user_id': user_id,
'reservation_id': reservation_id,
'watermark': env.get("WATERMARK") == "1",
'partial': partial,
'webhook_url': webhook_url,
'webhook_secret': webhook_secret,
'base_url': api_base,
@ -2565,11 +2630,11 @@ async def process_endpoint(
_write_resume_manifest(job_id, cmd, priority, user_id, reservation_id,
watermark=jobs[job_id]['watermark'],
webhook_url=webhook_url, webhook_secret=webhook_secret,
base_url=api_base)
base_url=api_base, partial=partial)
_enqueue_job(job_id, priority)
return {"job_id": job_id, "status": "queued"}
return {"job_id": job_id, "status": "queued", "partial": partial}
def _job_view_from_disk(job_id):
"""What the disk says about a job this instance does not hold in memory.
@ -2620,7 +2685,10 @@ async def get_status(job_id: str, request: Request):
return {
"status": _presented_status(job_id, job),
"logs": _visible_logs(job['logs']),
"result": job.get('result')
"result": job.get('result'),
# Set when only the first part of the source was clipped (quota wall
# offer), so the dashboard can say so next to the clips.
"partial": job.get('partial'),
}

View file

@ -61,6 +61,15 @@ BILLING_ATTENTION_STATES = ("past_due", "unpaid", "incomplete", "paused")
# within 24h), so blocking that would only stop the retry.
CHECKOUT_BLOCKING_STATES = ("active", "trialing", "past_due", "unpaid", "paused")
# Smallest slice of a long video worth offering instead of the quota wall.
# A user whose remaining minutes cannot cover the whole source is offered its
# first N minutes (N = what they have left) so they see clips before paying:
# 93 of the 99 walls sampled to 16-sep-2026 were shown to accounts with their
# 20 free minutes untouched, pasting a 21-90 min video, and most left Stripe
# without paying. Below this many minutes the slice cannot hold a few 15-60 s
# clips, so the wall stays as it was.
PARTIAL_MIN_MINUTES = 5
# Minute cap DURING the trial (across all plans). Kept for grandfathered
# 'trialing' subscriptions; removable once no subscription has status
# 'trialing'.

View file

@ -206,6 +206,9 @@ function App() {
const [tutorialPhase, setTutorialPhase] = useState(null); // null | intro | coach | celebrate
const [showTrialUpgrade, setShowTrialUpgrade] = useState(false);
const [topUpInfo, setTopUpInfo] = useState({});
// {processed_minutes, total_minutes} when the running/finished job clips
// only the first part of the source (the quota wall's free offer).
const [partialJob, setPartialJob] = useState(null);
// Durable R2 URLs (per clip index) for the current job — used as a fallback when
// the ephemeral local /videos/ files have been cleaned up (e.g. after a reload).
const [durableClips, setDurableClips] = useState({});
@ -660,6 +663,8 @@ function App() {
setResults(data.result);
}
if (data.partial) setPartialJob(data.partial);
if (data.status === 'completed') {
setStatus('complete');
clearInterval(interval);
@ -845,6 +850,7 @@ function App() {
setQualityGate(null);
setProjectState(null);
setNoSource(false);
setPartialJob(null);
try {
let body;
@ -864,6 +870,9 @@ function App() {
auto_hook_style: data.autoHook ? (data.autoHookStyle || 'classic') : null,
// 'auto' is the server default, so only a deliberate choice travels.
layouts: data.layout && data.layout !== 'auto' ? data.layout : null,
// Set when the user took the quota wall's "clip the first N minutes"
// offer: the server reserves N minutes and cuts the source to them.
max_minutes: data.maxMinutes || null,
};
if (data.type === 'url') {
@ -910,6 +919,7 @@ function App() {
}
setJobId(resData.job_id);
setPartialJob(resData.partial || null);
if (data.type === 'thumbnail_session') {
setProcessingMedia({ type: 'server', payload: `/api/source/${resData.job_id}` });
}
@ -925,7 +935,21 @@ function App() {
if (me?.status === 'trialing') {
setShowTrialUpgrade(true);
} else {
setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining });
// The wall can offer the first N minutes of this same submission on
// the minutes they have: same data, plus max_minutes.
const partial = e.partialMinutes || 0;
setTopUpInfo({
required: e.minutesRequired,
remaining: e.minutesRemaining,
partialMinutes: partial,
onPartial: partial
? () => {
track('PartialClipChosen', { props: { required: e.minutesRequired, partial } });
setShowTopUp(false);
handleProcess({ ...data, maxMinutes: partial }, forceLowQuality);
}
: null,
});
setShowTopUp(true);
}
return;
@ -946,6 +970,7 @@ function App() {
setProcessingMedia(null);
setProjectState(null);
setNoSource(false);
setPartialJob(null);
localStorage.removeItem(SESSION_KEY);
};
@ -1879,9 +1904,20 @@ function App() {
{status === 'complete' && results?.clips?.length > 0 && (
<div className="mb-2 space-y-2">
{/* Partial job: the clips on screen come from the first N
minutes only. Say so, and sell the rest of the video. */}
{partialJob && (
<button
onClick={() => { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); }}
className="w-full text-left px-3 py-2.5 rounded-input bg-paper3 border border-brass/40 hover:border-brass text-sm transition-colors"
>
<span className="text-ink">These clips come from the first {partialJob.processed_minutes} of {partialJob.total_minutes} minutes.</span>{' '}
<span className="text-brass font-medium">Clip the whole video →</span>
</button>
)}
{/* Peak-moment upsell: they just SAW their clips — sell while
they're proud of the result, before asking for stars. */}
{plan === 'free' && (
{plan === 'free' && !partialJob && (
<button
onClick={() => { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); }}
className="w-full text-left px-3 py-2.5 rounded-input bg-paper3 border border-brass/40 hover:border-brass text-sm transition-colors"
@ -2167,6 +2203,8 @@ function App() {
onClose={() => setShowTopUp(false)}
required={topUpInfo.required}
remaining={topUpInfo.remaining}
partialMinutes={topUpInfo.partialMinutes}
onPartial={topUpInfo.onPartial}
context={topUpInfo.context || 'wall'}
/>
)}

View file

@ -36,7 +36,14 @@ const PLAN_BLURBS = {
// 'upsell' = user opened it voluntarily (results banner, header meter)
// — different framing: they still HAVE minutes, sell the watermark
// removal + permanence instead of "you ran out".
export default function TopUpModal({ onClose, required, remaining, context = 'wall' }) {
// partialMinutes / onPartial: the server's offer to clip only the first N
// minutes of the blocked video on the minutes the user has (see
// app.partial_offer). Most walls open on an account that has not spent a
// single free minute and pasted a 21-90 min video (93 of 99 sampled,
// 16-sep-2026): they are being asked to pay before seeing one clip. The offer
// turns that wall into a first run; the plans stay the way to the whole video.
export default function TopUpModal({ onClose, required, remaining, partialMinutes = 0, onPartial = null,
context = 'wall' }) {
const [plans, setPlans] = useState([]);
const [topups, setTopups] = useState([]);
const [showTopups, setShowTopups] = useState(false);
@ -103,6 +110,8 @@ export default function TopUpModal({ onClose, required, remaining, context = 'wa
}).format((a || 0) / 100);
const blockedByLength = typeof required === 'number' && typeof remaining === 'number';
const partialOffer = !isUpsell && partialMinutes > 0 && typeof onPartial === 'function';
const remainingShown = Math.max(0, Math.round((remaining || 0) * 10) / 10);
return (
<Modal isOpen onClose={onClose} eyebrow="UPGRADE"
@ -113,12 +122,26 @@ export default function TopUpModal({ onClose, required, remaining, context = 'wa
? <>Every clip comes out <b className="text-ink font-medium">ready to post</b> and stays in your
library for good. On the free plan they carry a watermark and are deleted after 7 days.</>
: blockedByLength
? <>This video needs <b className="text-ink font-medium">{required} min</b> and you have{' '}
<b className="text-ink font-medium">{Math.max(0, Math.round((remaining || 0) * 10) / 10)} min</b> left
this month. Pick a plan and it starts rendering right away.</>
? <>This video is <b className="text-ink font-medium">{required} min</b> long and you have{' '}
<b className="text-ink font-medium">{remainingShown} min</b> this month. Pick a plan and the
whole video starts rendering right away.</>
: <>You've used your free minutes for this month. Pick a plan and keep clipping right away.</>}
</p>
{partialOffer && (
<div className="mb-5 card p-4 flex flex-col sm:flex-row sm:items-center gap-3">
<div className="flex-1 text-sm text-ink2">
<b className="text-ink font-medium">Or see it first:</b> clip the first{' '}
<b className="text-ink font-medium">{partialMinutes} min</b> now with the minutes you have,
and decide with the clips in front of you.
</div>
<button onClick={onPartial} disabled={busyPrice !== null}
className="btn-ghost whitespace-nowrap">
Clip the first {partialMinutes} min
</button>
</div>
)}
<div className="grid sm:grid-cols-3 gap-3">
{plans.map((entry) => {
const highlight = entry.plan === 'creator';

View file

@ -17,6 +17,8 @@ import { allows } from './consent';
// 'wall' | 'upsell' | 'pricing')
// - CheckoutRedirected — Stripe returned a URL and we are sending them there
// - CheckoutFailed — /api/billing/checkout errored, `reason` says why
// - PartialClipChosen — the wall's "clip the first N min" taken instead of a
// plan (`required` / `partial` minutes)
// - Subscribed — plan activated after checkout
// - SocialNudgeSeen — post-generation "connect socials" banner rendered
// - SocialNudgeConnect — its connect button clicked (opens hosted connect page)

View file

@ -15,6 +15,8 @@ export class QuotaError extends Error {
this.name = 'QuotaError';
this.minutesRequired = detail?.minutes_required;
this.minutesRemaining = detail?.minutes_remaining;
// Minutes of the source the server offers to clip instead (0 = no offer).
this.partialMinutes = Number(detail?.partial_minutes) || 0;
}
}

63
main.py
View file

@ -13,6 +13,7 @@ from scenedetect.detectors import ContentDetector
from ultralytics import YOLO
import torch
import os
import math
import numpy as np
from tqdm import tqdm
import yt_dlp
@ -722,6 +723,63 @@ def plan_download_attempts(direct_first, statics, paid, have_hd, youtube=True):
return plan
def cap_source_duration(input_video, max_minutes):
"""Cut ``input_video`` down to its first ``max_minutes`` minutes, in place.
Set through ``MAX_SOURCE_MINUTES`` by app.py when the user accepted the
quota wall's "clip the first N minutes" offer: only N minutes were
reserved, so nothing downstream may see more of the source than that.
Cutting the file itself (rather than passing a window around) keeps every
later stage byte-identical: transcription, the layout picker, the clip
editor's re-renders and ``/api/source`` all read the same path. A source
already within the cap is left untouched.
Stream copy first (seconds, no quality loss; the cut lands on a packet
boundary a fraction of a second past N). If the container refuses a copy
the fallback re-encodes, which is slow but rare.
"""
try:
secs = float(max_minutes) * 60.0
except (TypeError, ValueError):
return input_video
if secs <= 0:
return input_video
duration = 0.0
try:
cap = cv2.VideoCapture(input_video)
fps = cap.get(cv2.CAP_PROP_FPS) or 0.0
duration = (int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) / fps) if fps else 0.0
cap.release()
except Exception:
duration = 0.0
if duration and duration <= secs + 1.0:
return input_video
root, ext = os.path.splitext(input_video)
tmp = f"{root}.capped{ext or '.mp4'}"
attempts = [
["-c", "copy"],
["-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-c:a", "aac", "-b:a", "160k"],
]
for codec_args in attempts:
cmd = ["ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", input_video,
"-t", f"{secs:.3f}", *codec_args, "-movflags", "+faststart", tmp]
try:
subprocess.run(cmd, check=True, capture_output=True, timeout=3600)
os.replace(tmp, input_video)
shown = f"{int(math.ceil(duration / 60))}" if duration else "?"
print(f"✂️ Clipping the first {float(max_minutes):g} min of {shown}: "
f"that is what the plan's remaining minutes cover.")
return input_video
except Exception as e:
try:
os.remove(tmp)
except OSError:
pass
print(f"⚠️ Could not cut the source to {float(max_minutes):g} min "
f"({' '.join(codec_args[:2])}): {str(e)[:200]}")
raise RuntimeError(f"could not cut the source to its first {float(max_minutes):g} minutes")
def download_youtube_video(url, output_dir="."):
"""
Downloads a YouTube video using yt-dlp.
@ -1873,6 +1931,11 @@ if __name__ == '__main__':
print(f"❌ Input file not found: {input_video}")
exit(1)
# Quota-wall offer: only the first N minutes were paid for (see
# cap_source_duration). Must run before anything reads the file.
if os.environ.get("MAX_SOURCE_MINUTES", "").strip():
input_video = cap_source_duration(input_video, os.environ["MAX_SOURCE_MINUTES"])
# Layout choice is per SOURCE video, not per clip: one upload and one call
# instead of one per clip, and the answer is a property of the material
# ("this is a screencast"), which does not change between its own clips.

View file

@ -0,0 +1,208 @@
"""The quota wall's "clip the first N minutes" offer.
Most walls open on an account with its free minutes untouched that pasted a
21-90 min video (93 of 99 sampled to 16-sep-2026): the user is asked to pay
before seeing a single clip, and most leave Stripe without paying. Instead of
a bare 402 the server now offers to clip the first N minutes (N = the balance),
the client resubmits with ``max_minutes``, only N are reserved and main.py cuts
the source to N before anything reads it.
"""
import asyncio
import json
import os
import shutil
import subprocess
import httpx
import pytest
app_module = pytest.importorskip("app")
from cloud import config # noqa: E402
class TestPartialOffer:
def test_offers_the_floored_balance(self):
assert app_module.partial_offer(45, 20.0) == 20
assert app_module.partial_offer(45, 12.7) == 12
def test_no_offer_below_the_floor(self, monkeypatch):
monkeypatch.setattr(config, "PARTIAL_MIN_MINUTES", 5)
assert app_module.partial_offer(45, 4.9) == 0
assert app_module.partial_offer(45, 0) == 0
assert app_module.partial_offer(45, None) == 0
def test_no_offer_when_the_balance_covers_the_video(self):
# Then the 402 came from something else (concurrency, rounding): don't
# offer to cut a video that fits.
assert app_module.partial_offer(20, 20.0) == 0
assert app_module.partial_offer(15, 20.0) == 0
class TestPlanPartialMinutes:
def test_whole_video_when_not_asked(self):
assert app_module.plan_partial_minutes(45, 20.0, None) == (45, None)
def test_slice_capped_by_request_and_balance(self):
reserve, partial = app_module.plan_partial_minutes(45, 20.0, 20)
assert reserve == 20
assert partial == {"processed_minutes": 20, "total_minutes": 45}
# A client cannot name a bigger cut than it can pay for.
reserve, partial = app_module.plan_partial_minutes(45, 8.4, 20)
assert (reserve, partial["processed_minutes"]) == (8, 8)
# Nor does asking for less than the balance reserve more than asked.
reserve, _ = app_module.plan_partial_minutes(45, 20.0, 10)
assert reserve == 10
def test_fits_whole_means_no_partial(self):
assert app_module.plan_partial_minutes(15, 20.0, 20) == (15, None)
assert app_module.plan_partial_minutes(20, 20.0, 20) == (20, None)
def test_too_small_slice_falls_through_to_the_402(self, monkeypatch):
monkeypatch.setattr(config, "PARTIAL_MIN_MINUTES", 5)
# Reserving the whole 45 then raises QuotaExceeded as before.
assert app_module.plan_partial_minutes(45, 3.0, 20) == (45, None)
def test_garbage_request_is_ignored(self):
assert app_module.plan_partial_minutes(45, 20.0, "lots") == (45, None)
# --------------------------------------------------------------------------- #
# Endpoint: max_minutes reaches the reservation, the cut reaches the job
# --------------------------------------------------------------------------- #
def _post_process(json_body):
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.post("/api/process", json=json_body,
headers={"X-Gemini-Key": "test-key"})
return asyncio.run(_do())
def _get_status(job_id):
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.get(f"/api/status/{job_id}")
return asyncio.run(_do())
@pytest.fixture()
def dirs(tmp_path, monkeypatch):
out_root = tmp_path / "output"
up_root = tmp_path / "uploads"
out_root.mkdir()
up_root.mkdir()
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(up_root))
monkeypatch.setattr(app_module, "jobs", {})
monkeypatch.setattr(app_module, "job_queue", asyncio.PriorityQueue())
async def _probe(url):
return {"max_height": 1080, "duration": 45 * 60}
monkeypatch.setattr(app_module, "_probe_youtube_quality", _probe)
return out_root, up_root
def _stub_reservation(monkeypatch, partial):
seen = {}
async def _reserve(request, url, input_path, job_id, max_minutes=None):
seen["max_minutes"] = max_minutes
return 7, 1, "res-1", "free", partial
monkeypatch.setattr(app_module, "reserve_process_minutes", _reserve)
return seen
def test_max_minutes_reaches_the_reservation_and_the_job(dirs, monkeypatch):
out_root, _ = dirs
partial = {"processed_minutes": 20, "total_minutes": 45}
seen = _stub_reservation(monkeypatch, partial)
resp = _post_process({"url": "https://www.youtube.com/watch?v=long",
"acknowledged": True, "max_minutes": 20})
assert resp.status_code == 200, resp.text
body = resp.json()
assert seen["max_minutes"] == 20
assert body["partial"] == partial
job = app_module.jobs[body["job_id"]]
assert job["env"]["MAX_SOURCE_MINUTES"] == "20"
assert job["partial"] == partial
# The status poll carries it, so the dashboard can label the clips.
assert _get_status(body["job_id"]).json()["partial"] == partial
# And the resume manifest, so a redeploy mid-job does not re-run the
# whole 45 minutes on a 20-minute reservation.
manifest = json.load(open(os.path.join(out_root, body["job_id"], app_module._RESUME_FILE)))
assert manifest["partial"] == partial
def test_whole_video_job_is_untouched(dirs, monkeypatch):
_stub_reservation(monkeypatch, None)
resp = _post_process({"url": "https://www.youtube.com/watch?v=ok", "acknowledged": True})
assert resp.status_code == 200
job = app_module.jobs[resp.json()["job_id"]]
assert "MAX_SOURCE_MINUTES" not in job["env"]
assert resp.json()["partial"] is None
assert job["partial"] is None
def test_resumed_partial_job_keeps_its_cut(dirs, monkeypatch):
out_root, _ = dirs
monkeypatch.setattr(app_module, "INSTANCE_ID", "me")
monkeypatch.setattr(app_module, "_draining", False)
monkeypatch.setattr(app_module, "_running_jobs", set())
d = out_root / "cut"
d.mkdir()
(d / app_module._RESUME_FILE).write_text(json.dumps({
"cmd": ["python", "main.py"], "priority": 2, "user_id": None,
"reservation_id": "res-cut", "watermark": False, "attempts": 0,
"partial": {"processed_minutes": 20, "total_minutes": 45},
}))
(out_root / "whole").mkdir()
(out_root / "whole" / app_module._RESUME_FILE).write_text(json.dumps({
"cmd": ["python", "main.py"], "priority": 2, "user_id": None,
"reservation_id": "res-whole", "watermark": False, "attempts": 0,
}))
monkeypatch.setenv("MAX_SOURCE_MINUTES", "3") # a stale value must not leak in
app_module._resume_interrupted_jobs()
assert app_module.jobs["cut"]["env"]["MAX_SOURCE_MINUTES"] == "20"
assert app_module.jobs["cut"]["partial"]["processed_minutes"] == 20
assert "MAX_SOURCE_MINUTES" not in app_module.jobs["whole"]["env"]
assert app_module.jobs["whole"]["partial"] is None
# --------------------------------------------------------------------------- #
# main.cap_source_duration: the cut itself
# --------------------------------------------------------------------------- #
@pytest.mark.skipif(not shutil.which("ffmpeg") or not shutil.which("ffprobe"),
reason="needs ffmpeg")
class TestCapSourceDuration:
@pytest.fixture()
def source(self, tmp_path):
main = pytest.importorskip("main")
path = tmp_path / "src.mp4"
subprocess.run([
"ffmpeg", "-y", "-loglevel", "error",
"-f", "lavfi", "-i", "testsrc=size=320x240:rate=25",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100",
"-t", "150", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest",
str(path)], check=True)
return main, str(path)
@staticmethod
def _seconds(path):
out = subprocess.check_output([
"ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=nw=1:nk=1", path]).decode().strip()
return float(out)
def test_cuts_in_place_to_the_first_minutes(self, source):
main, path = source
assert main.cap_source_duration(path, 2) == path
assert 119 <= self._seconds(path) <= 122
assert not os.path.exists(path.replace(".mp4", ".capped.mp4"))
def test_shorter_source_is_left_alone(self, source):
main, path = source
before = os.path.getsize(path)
main.cap_source_duration(path, 3)
assert os.path.getsize(path) == before
assert 149 <= self._seconds(path) <= 151