mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-05 01:26:07 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad64286004 | ||
|
|
13619b7cc9 | ||
|
|
ac844b3933 | ||
|
|
da204bd52e | ||
|
|
d98e0d6a5e | ||
|
|
2db5407a5d | ||
|
|
47c6691823 | ||
|
|
d59b5bf3bd |
No files matched your search
@@ -180,7 +180,7 @@ jobs:
|
||||
|
||||
frontend-e2e-smoke:
|
||||
name: "Frontend - E2E Smoke (~2 min)"
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04 # Playwright 1.57 can't install chromium on ubuntu-latest (26.04)
|
||||
needs: changes
|
||||
# Quick smoke tests run on every PR with frontend changes
|
||||
if: github.ref != 'refs/heads/main' && needs.changes.outputs.frontend == 'true'
|
||||
@@ -222,7 +222,7 @@ jobs:
|
||||
|
||||
frontend-e2e-full:
|
||||
name: "Frontend - E2E Full"
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04 # Playwright 1.57 can't install chromium on ubuntu-latest (26.04)
|
||||
needs: changes
|
||||
# Full E2E suite only runs when PR has 'e2e' label (on-demand)
|
||||
if: >-
|
||||
@@ -262,7 +262,7 @@ jobs:
|
||||
# Happy Path Production Test - runs the comprehensive real-user test against prod
|
||||
frontend-e2e-happy-path:
|
||||
name: "Frontend - E2E Happy Path (Production)"
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04 # Playwright 1.57 can't install chromium on ubuntu-latest (26.04)
|
||||
needs: changes
|
||||
# Only runs when PR has 'e2e-happy-path' label
|
||||
if: >-
|
||||
@@ -794,7 +794,7 @@ jobs:
|
||||
|
||||
local-stack-e2e:
|
||||
name: "Local Stack - Full-Journey E2E"
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04 # Playwright 1.57 can't install chromium on ubuntu-latest (26.04)
|
||||
needs: changes
|
||||
# The real backend on the Firestore + GCS emulators with fake workers
|
||||
# (scripts/local-stack.sh), driven through the real web UI by
|
||||
|
||||
@@ -48,7 +48,7 @@ jobs:
|
||||
# =========================================================================
|
||||
e2e-credit-purchase:
|
||||
name: "Stage 1: Credit Purchase"
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04 # Playwright 1.57 can't install chromium on ubuntu-latest (26.04)
|
||||
timeout-minutes: 15
|
||||
if: ${{ github.event.inputs.skip_payment != 'true' && github.event.inputs.use_test_token != 'true' }}
|
||||
permissions:
|
||||
@@ -442,7 +442,7 @@ jobs:
|
||||
# =========================================================================
|
||||
e2e-happy-path:
|
||||
name: "Stage 2: Happy Path"
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04 # Playwright 1.57 can't install chromium on ubuntu-latest (26.04)
|
||||
timeout-minutes: 90
|
||||
needs: e2e-credit-purchase
|
||||
if: |
|
||||
|
||||
@@ -20,7 +20,7 @@ permissions:
|
||||
jobs:
|
||||
e2e-tenant:
|
||||
name: "Tenant E2E: ${{ matrix.tenant }}"
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04 # Playwright 1.57 can't install chromium on ubuntu-latest (26.04)
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
||||
+15
-18
@@ -293,24 +293,21 @@ def require_review_auth_factory(job_id_param: str = "job_id"):
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Check ownership: admin can access all, users only their own jobs
|
||||
if not auth_result.is_admin:
|
||||
if auth_result.user_email and job.user_email:
|
||||
if auth_result.user_email.lower() != job.user_email.lower():
|
||||
logger.warning(
|
||||
f"Review access denied: user {auth_result.user_email} "
|
||||
f"tried to access job {job_id} owned by {job.user_email}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="You don't have permission to access this job's review"
|
||||
)
|
||||
elif job.user_email:
|
||||
# Token auth without email trying to access a job with owner
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="You don't have permission to access this job's review"
|
||||
)
|
||||
# Admin, owner, or a member of the job's tenant portal
|
||||
# (backend/services/job_access.py).
|
||||
from backend.services.job_access import can_access_job
|
||||
|
||||
if not await asyncio.to_thread(
|
||||
can_access_job, job, auth_result.user_email, bool(auth_result.is_admin)
|
||||
):
|
||||
logger.warning(
|
||||
f"Review access denied: user {auth_result.user_email} "
|
||||
f"tried to access job {job_id} owned by {job.user_email}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="You don't have permission to access this job's review"
|
||||
)
|
||||
|
||||
logger.info(f"Review access granted via full auth ({auth_result.user_type}) for job {job_id}")
|
||||
# Who is reviewing — handlers record it on first open
|
||||
|
||||
@@ -22,6 +22,7 @@ from typing import Optional, List, Dict, Any, Tuple, Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.services.job_access import can_access_job
|
||||
from backend.models.job import JobCreate, JobStatus
|
||||
from backend.models.theme import ColorOverrides
|
||||
from backend.services.job_manager import JobManager
|
||||
@@ -1585,10 +1586,9 @@ async def mark_uploads_complete(
|
||||
# an email — trusted API integrations creating jobs on behalf of a
|
||||
# body.user_email — keeps working, as before this check existed.)
|
||||
if (
|
||||
not auth_result.is_admin
|
||||
and auth_result.user_email
|
||||
auth_result.user_email
|
||||
and job.user_email
|
||||
and auth_result.user_email.lower() != job.user_email.lower()
|
||||
and not can_access_job(job, auth_result.user_email, bool(auth_result.is_admin))
|
||||
):
|
||||
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify"))
|
||||
|
||||
@@ -2823,10 +2823,11 @@ def get_style_upload_urls(
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Verify ownership (non-admin users can only modify their own jobs)
|
||||
if auth_result.user_type != UserType.ADMIN:
|
||||
if job.user_email != auth_result.user_email:
|
||||
raise HTTPException(status_code=403, detail="Not authorized to modify this job")
|
||||
# Owner, admin, or a member of the job's tenant portal
|
||||
if not can_access_job(
|
||||
job, auth_result.user_email, auth_result.user_type == UserType.ADMIN, allow_ownerless=False
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="Not authorized to modify this job")
|
||||
|
||||
# Check cutoff - reject if job is too far along
|
||||
try:
|
||||
@@ -2902,10 +2903,11 @@ def complete_style_uploads(
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Verify ownership
|
||||
if auth_result.user_type != UserType.ADMIN:
|
||||
if job.user_email != auth_result.user_email:
|
||||
raise HTTPException(status_code=403, detail="Not authorized to modify this job")
|
||||
# Owner, admin, or a member of the job's tenant portal
|
||||
if not can_access_job(
|
||||
job, auth_result.user_email, auth_result.user_type == UserType.ADMIN, allow_ownerless=False
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="Not authorized to modify this job")
|
||||
|
||||
# Check cutoff
|
||||
try:
|
||||
|
||||
+27
-22
@@ -266,27 +266,15 @@ def _resolve_credits_charged_in_summary(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
|
||||
def _check_job_ownership(job: Job, auth_result: AuthResult) -> bool:
|
||||
"""
|
||||
Check if the authenticated user owns the job or has admin access.
|
||||
Check if the authenticated user may access the job: admin, owner, or a
|
||||
member of the job's tenant portal (see backend/services/job_access.py).
|
||||
|
||||
Returns:
|
||||
True if user can access the job, False otherwise
|
||||
"""
|
||||
# Admins can access all jobs
|
||||
if auth_result.is_admin:
|
||||
return True
|
||||
from backend.services.job_access import can_access_job
|
||||
|
||||
# Check if user owns the job
|
||||
if auth_result.user_email and job.user_email:
|
||||
return auth_result.user_email.lower() == job.user_email.lower()
|
||||
|
||||
# If no user_email on auth (token auth without email), deny access to jobs with user_email
|
||||
# This prevents token-based auth from accessing user jobs
|
||||
if job.user_email:
|
||||
return False
|
||||
|
||||
# Legacy jobs without user_email - allow access for backward compatibility
|
||||
# TODO: Consider restricting this in the future
|
||||
return True
|
||||
return can_access_job(job, auth_result.user_email, bool(auth_result.is_admin))
|
||||
|
||||
|
||||
class EditTrackRequest(BaseModel):
|
||||
@@ -693,8 +681,9 @@ def list_jobs(
|
||||
"""
|
||||
List jobs with optional filters.
|
||||
|
||||
Regular users only see their own jobs. Admins see all jobs.
|
||||
Users on tenant portals only see jobs from their tenant.
|
||||
Admins see all jobs. On the consumer portal users see only their own jobs.
|
||||
On a tenant portal, members of that portal (its email allowlist) see all of the
|
||||
tenant's jobs; jobs are always scoped to the portal's tenant.
|
||||
|
||||
Args:
|
||||
status: Filter by job status (pending, complete, failed, etc.)
|
||||
@@ -753,6 +742,14 @@ def list_jobs(
|
||||
tenant_id = get_tenant_from_request(request)
|
||||
effective_tenant_id = tenant_id if tenant_id else ""
|
||||
|
||||
# Tenant portals are shared workspaces: a member of this portal sees all
|
||||
# of the tenant's jobs, not just the ones they submitted (job_access.py).
|
||||
if user_email_filter and tenant_id:
|
||||
from backend.services.job_access import is_tenant_member
|
||||
|
||||
if is_tenant_member(tenant_id, user_email_filter):
|
||||
user_email_filter = None
|
||||
|
||||
# --- Summary mode: field-projected query returning dicts ---
|
||||
if fields == "summary":
|
||||
exclude_statuses = _HIDE_COMPLETED_STATUSES if hide_completed else None
|
||||
@@ -887,7 +884,12 @@ def delete_job(
|
||||
detail=t(locale, "jobs.cleanupFailed", services=", ".join(incomplete)),
|
||||
)
|
||||
|
||||
job_manager.delete_job(job_id, delete_files=delete_files)
|
||||
job_manager.delete_job(
|
||||
job_id,
|
||||
delete_files=delete_files,
|
||||
archived_by=auth_result.user_email,
|
||||
reason="admin_delete" if auth_result.is_admin else "owner_delete",
|
||||
)
|
||||
|
||||
# A requests-board pick whose owner deleted the job goes back on the board (or is
|
||||
# removed if nobody backs it) instead of staying "in progress" on a dead job.
|
||||
@@ -2810,7 +2812,10 @@ def cleanup_distribution(
|
||||
# Delete the job if requested
|
||||
if delete_job:
|
||||
try:
|
||||
job_manager.delete_job(job_id, delete_files=True)
|
||||
job_manager.delete_job(
|
||||
job_id, delete_files=True, archived_by=auth_result.user_email,
|
||||
reason="cleanup_distribution_delete",
|
||||
)
|
||||
results["job_deleted"] = True
|
||||
logger.info(f"Deleted job {job_id} after distribution cleanup")
|
||||
except Exception as e:
|
||||
@@ -3254,8 +3259,8 @@ async def rerender_with_current_theme(
|
||||
Regenerates title/end screens, the lyrics video, final encodes and CDG/TXT
|
||||
packages from the already-reviewed lyrics and instrumental selection — no
|
||||
review step. Used after a tenant edits their theme. Free (tenant jobs are
|
||||
never charged); only the job owner (still on the tenant allowlist) or an
|
||||
admin may trigger it.
|
||||
never charged); any member of the job's tenant portal (on its allowlist —
|
||||
tenant portals are shared workspaces) or an admin may trigger it.
|
||||
"""
|
||||
locale = get_locale_from_request(http_request)
|
||||
job_manager = JobManager()
|
||||
|
||||
@@ -202,6 +202,7 @@ from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.output.timing_validation import LyricsTimingError
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
|
||||
# Import from the unified style loader
|
||||
from karaoke_gen.style_loader import load_styles_from_gcs
|
||||
@@ -2058,6 +2059,14 @@ async def generate_preview_video(
|
||||
if untimed_line is not None:
|
||||
raise HTTPException(status_code=422, detail=t("en", "review.previewMissingTimings", line=untimed_line[:80]))
|
||||
|
||||
# Songs whose vocals start within 3s get a countdown intro in the preview,
|
||||
# exactly as in the final render, which shifts the preview's timeline by this
|
||||
# many seconds. The client needs it to keep the overlaid instrumental stem and
|
||||
# waveform playhead aligned with the video.
|
||||
countdown_padding_seconds = CountdownProcessor.padding_for_segments_data(
|
||||
updated_data.get("corrected_segments")
|
||||
)
|
||||
|
||||
# Check if GCE preview encoding is enabled
|
||||
use_gce_preview = encoding_service.is_preview_enabled
|
||||
|
||||
@@ -2123,7 +2132,7 @@ async def generate_preview_video(
|
||||
_record_preview_video(job_id, preview_hash, preview_gcs_path)
|
||||
span.set_attribute("preview_cache_hit", True)
|
||||
logger.info(f"Job {job_id}: Preview cache hit: {preview_hash}")
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
return {"status": "success", "preview_hash": preview_hash, "countdown_padding_seconds": countdown_padding_seconds}
|
||||
|
||||
# Upload ASS to GCS
|
||||
with create_span("upload-ass-to-gcs") as upload_ass_span:
|
||||
@@ -2141,6 +2150,23 @@ async def generate_preview_video(
|
||||
bucket_name = settings.gcs_bucket_name
|
||||
style_assets = job.style_assets or {}
|
||||
|
||||
# The ASS has the countdown intro (lyrics shifted +Ns);
|
||||
# the encoder needs audio padded by the same N seconds,
|
||||
# as the final render does. Pad here and hand the
|
||||
# encoder that file, so the worker needs no changes.
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
if result.get("countdown_padding_seconds"):
|
||||
with create_span("pad-preview-audio-for-countdown"):
|
||||
padded_audio_path = await asyncio.to_thread(
|
||||
CountdownProcessor(
|
||||
cache_dir=output_config.cache_dir, logger=logger
|
||||
).create_padded_audio_only,
|
||||
audio_path,
|
||||
)
|
||||
audio_gcs_path = f"jobs/{job_id}/previews/{preview_hash}_audio.flac"
|
||||
await asyncio.to_thread(storage.upload_file, padded_audio_path, audio_gcs_path)
|
||||
span.set_attribute("countdown_padding_seconds", countdown_padding_seconds)
|
||||
|
||||
# Only use background image if user explicitly requested it.
|
||||
# Default is black background for faster preview generation.
|
||||
background_image_gcs_path = None
|
||||
@@ -2160,7 +2186,7 @@ async def generate_preview_video(
|
||||
encode_kwargs = {
|
||||
"job_id": f"preview_{job_id}_{preview_hash}",
|
||||
"ass_gcs_path": f"gs://{bucket_name}/{ass_gcs_path}",
|
||||
"audio_gcs_path": f"gs://{bucket_name}/{job.input_media_gcs_path}",
|
||||
"audio_gcs_path": f"gs://{bucket_name}/{audio_gcs_path}",
|
||||
"output_gcs_path": f"gs://{bucket_name}/{preview_gcs_path}",
|
||||
"background_color": "black",
|
||||
"background_image_gcs_path": background_image_gcs_path,
|
||||
@@ -2179,7 +2205,7 @@ async def generate_preview_video(
|
||||
task.add_done_callback(_background_tasks.discard)
|
||||
|
||||
logger.info(f"Job {job_id}: Preview encode running in background: {preview_hash}")
|
||||
return {"status": "generating", "preview_hash": preview_hash}
|
||||
return {"status": "generating", "preview_hash": preview_hash, "countdown_padding_seconds": countdown_padding_seconds}
|
||||
|
||||
except LyricsTimingError:
|
||||
raise
|
||||
@@ -2199,7 +2225,7 @@ async def generate_preview_video(
|
||||
span.set_attribute("preview_hash", preview_hash)
|
||||
span.set_attribute("success", True)
|
||||
|
||||
return {"status": "success", "preview_hash": preview_hash}
|
||||
return {"status": "success", "preview_hash": preview_hash, "countdown_padding_seconds": countdown_padding_seconds}
|
||||
|
||||
except LyricsTimingError as timing_err:
|
||||
# Untimed lyrics (e.g. custom lyrics not yet tap-synced) — this is a
|
||||
|
||||
@@ -212,8 +212,10 @@ MAX_BULK_RERENDER = 20
|
||||
|
||||
|
||||
def _owner_scope(auth_result: AuthResult) -> Optional[str]:
|
||||
"""Admins act on all the portal's tracks; members only on their own."""
|
||||
return None if auth_result.is_admin else auth_result.user_email
|
||||
"""Every caller here is a portal member (require_tenant_member), and tenant
|
||||
portals are shared workspaces (backend/services/job_access.py), so theme
|
||||
refresh/rerender covers all of the portal's tracks, whoever submitted them."""
|
||||
return None
|
||||
|
||||
|
||||
@router.put("", response_model=SaveResponse)
|
||||
|
||||
@@ -260,6 +260,20 @@ class AccountDeletionService:
|
||||
def _owned_jobs(self, email: str) -> List[Any]:
|
||||
return list(self._jobs().where(filter=FieldFilter("user_email", "==", email)).stream())
|
||||
|
||||
def _archived_jobs(self, email: str) -> List[Any]:
|
||||
"""Deleted jobs kept in ``<jobs>_archive`` (system data, redacted like live jobs).
|
||||
|
||||
Single-field queries only, so the archive needs no composite index;
|
||||
made-for-you is filtered here rather than in the query.
|
||||
"""
|
||||
archive = self.db.collection(f"{self.jobs_collection}_archive")
|
||||
owned = list(archive.where(filter=FieldFilter("user_email", "==", email)).stream())
|
||||
customer = [
|
||||
snap for snap in archive.where(filter=FieldFilter("customer_email", "==", email)).stream()
|
||||
if (snap.to_dict() or {}).get("made_for_you")
|
||||
]
|
||||
return owned + customer
|
||||
|
||||
def _customer_jobs(self, email: str) -> List[Any]:
|
||||
"""Made-for-you orders: owned by the admin, delivered to ``customer_email``."""
|
||||
return list(
|
||||
@@ -442,10 +456,12 @@ class AccountDeletionService:
|
||||
def _scrub_jobs(self, email: str, deletion_id: str) -> dict:
|
||||
totals = {"jobs": 0, "input_objects_deleted": 0, "dropbox_links_revoked": 0}
|
||||
seen = set()
|
||||
for snap in self._owned_jobs(email) + self._customer_jobs(email):
|
||||
if snap.id in seen:
|
||||
tagged = [("live", snap) for snap in self._owned_jobs(email) + self._customer_jobs(email)]
|
||||
tagged += [("archive", snap) for snap in self._archived_jobs(email)]
|
||||
for where, snap in tagged:
|
||||
if (where, snap.id) in seen:
|
||||
continue
|
||||
seen.add(snap.id)
|
||||
seen.add((where, snap.id))
|
||||
result = self._scrub_job(snap, email, deletion_id)
|
||||
totals["jobs"] += 1
|
||||
totals["input_objects_deleted"] += result["input_objects_deleted"]
|
||||
@@ -517,7 +533,8 @@ class AccountDeletionService:
|
||||
if "client_ip" in (data.get("request_metadata") or {}):
|
||||
updates["request_metadata.client_ip"] = DELETE_FIELD
|
||||
if updates:
|
||||
self._jobs().document(job_id).update(updates)
|
||||
# snap.reference: the live job or its archived copy in <jobs>_archive.
|
||||
snap.reference.update(updates)
|
||||
return {"input_objects_deleted": deleted, "dropbox_link_revoked": revoked}
|
||||
|
||||
# Step 8
|
||||
|
||||
@@ -481,6 +481,56 @@ class FirestoreService:
|
||||
logger.error(f"Error deleting jobs by filter: {e}")
|
||||
raise
|
||||
|
||||
# Deleted jobs are archived here (forever) instead of being lost: the job doc
|
||||
# plus its logs and audio-edit sessions, so a deleted job can still be debugged.
|
||||
# Logs go under ``archived_logs`` without ``ttl_expiry``: the TTL policy on the
|
||||
# ``logs`` collection group would otherwise expire them on the original schedule.
|
||||
ARCHIVE_SUBCOLLECTIONS = {"logs": "archived_logs", "audio_edit_sessions": "audio_edit_sessions"}
|
||||
|
||||
@property
|
||||
def archive_collection(self) -> str:
|
||||
return f"{self.collection}_archive"
|
||||
|
||||
def archive_job(
|
||||
self, job_id: str, archived_by: Optional[str] = None, reason: Optional[str] = None
|
||||
) -> bool:
|
||||
"""Copy a job (doc + subcollections) into the archive collection.
|
||||
|
||||
Returns False if the job doesn't exist. Raises on any write failure, so the
|
||||
caller can refuse to delete a job whose archive copy didn't land.
|
||||
"""
|
||||
src = self.db.collection(self.collection).document(job_id)
|
||||
snap = src.get()
|
||||
if not snap.exists:
|
||||
return False
|
||||
dest = self.db.collection(self.archive_collection).document(job_id)
|
||||
data = snap.to_dict() or {}
|
||||
data["archived_at"] = datetime.now(timezone.utc)
|
||||
data["archived_by"] = archived_by
|
||||
data["archive_reason"] = reason
|
||||
dest.set(data)
|
||||
|
||||
copied = {}
|
||||
for src_name, dest_name in self.ARCHIVE_SUBCOLLECTIONS.items():
|
||||
count = 0
|
||||
batch = self.db.batch()
|
||||
pending = 0
|
||||
for doc in src.collection(src_name).stream():
|
||||
entry = doc.to_dict() or {}
|
||||
entry.pop("ttl_expiry", None)
|
||||
batch.set(dest.collection(dest_name).document(doc.id), entry)
|
||||
pending += 1
|
||||
count += 1
|
||||
if pending >= 400:
|
||||
batch.commit()
|
||||
batch = self.db.batch()
|
||||
pending = 0
|
||||
if pending:
|
||||
batch.commit()
|
||||
copied[src_name] = count
|
||||
logger.info(f"Archived job {job_id} to {self.archive_collection} ({copied}) by {archived_by}: {reason}")
|
||||
return True
|
||||
|
||||
def delete_job(self, job_id: str) -> None:
|
||||
"""Delete a job from Firestore."""
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Who may access a job.
|
||||
|
||||
One rule for every route that guards a job:
|
||||
|
||||
- Nomad admins can access every job.
|
||||
- The job's owner (``job.user_email``) can access it.
|
||||
- Tenant portals are shared workspaces: anyone currently allowed to sign in to a
|
||||
tenant's portal (its ``allowed_emails`` / ``allowed_email_domains`` allowlist)
|
||||
can access every job of that tenant, whoever submitted it. Membership is
|
||||
re-checked on every call against the live (cached ~5 min) tenant config, so
|
||||
removing someone from the allowlist also removes their access to the jobs.
|
||||
- Consumer jobs (no tenant) stay private to their owner.
|
||||
|
||||
Andrew's expectation (2026-11-11): "all jobs in the tenant portal are accessible to
|
||||
everyone who has permission to access that portal". Before this, a client logging in
|
||||
with their own email couldn't see jobs bulk-uploaded for them under another address.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def is_tenant_member(tenant_id: Optional[str], user_email: Optional[str]) -> bool:
|
||||
"""True if ``user_email`` may currently use ``tenant_id``'s (active) portal."""
|
||||
if not tenant_id or not user_email:
|
||||
return False
|
||||
try:
|
||||
from backend.services.tenant_service import get_tenant_service
|
||||
|
||||
config = get_tenant_service().get_tenant_config(tenant_id)
|
||||
except Exception as e: # noqa: BLE001 - fail closed: no shared access on lookup errors
|
||||
logger.warning(f"Tenant {tenant_id}: config lookup failed for shared-access check: {e}")
|
||||
return False
|
||||
if not config or not config.is_active:
|
||||
return False
|
||||
return config.is_email_allowed(user_email)
|
||||
|
||||
|
||||
def can_access_job(
|
||||
job,
|
||||
user_email: Optional[str],
|
||||
is_admin: bool,
|
||||
allow_ownerless: bool = True,
|
||||
) -> bool:
|
||||
"""Whether a caller may view and act on ``job`` (see module docstring).
|
||||
|
||||
``allow_ownerless`` keeps each route's pre-existing stance on legacy jobs with
|
||||
no ``user_email``: most routes (job routes, review auth) allowed them; the
|
||||
style-upload routes did not, and pass False.
|
||||
"""
|
||||
if is_admin:
|
||||
return True
|
||||
|
||||
job_email = getattr(job, "user_email", None)
|
||||
if user_email and job_email and user_email.lower() == job_email.lower():
|
||||
return True
|
||||
|
||||
if user_email and is_tenant_member(getattr(job, "tenant_id", None), user_email):
|
||||
return True
|
||||
|
||||
if job_email:
|
||||
# Someone else's job (or token auth without an email): no access.
|
||||
return False
|
||||
|
||||
# Legacy jobs without an owner: unchanged per-route behaviour.
|
||||
return allow_ownerless
|
||||
@@ -567,9 +567,23 @@ class JobManager:
|
||||
|
||||
return urls
|
||||
|
||||
def delete_job(self, job_id: str, delete_files: bool = True) -> None:
|
||||
"""Delete a job, its files, and its logs subcollection."""
|
||||
def delete_job(
|
||||
self,
|
||||
job_id: str,
|
||||
delete_files: bool = True,
|
||||
archived_by: Optional[str] = None,
|
||||
reason: str = "deleted",
|
||||
) -> None:
|
||||
"""Delete a job, its files, and its logs subcollection.
|
||||
|
||||
The job doc, logs and audio-edit sessions are first copied to the archive
|
||||
collection (``jobs_archive``). If that copy fails the delete is aborted, so a
|
||||
deleted job is never lost. Bulk test cleanup (``delete_jobs_by_filter``) does
|
||||
not archive.
|
||||
"""
|
||||
job = self.get_job(job_id)
|
||||
if job:
|
||||
self.firestore.archive_job(job_id, archived_by=archived_by, reason=reason)
|
||||
|
||||
# Refund credit if job never completed (and wasn't already refunded via fail/cancel)
|
||||
if job:
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
Emulator test: deleting a job archives it (doc + logs + audio-edit sessions).
|
||||
|
||||
Run with: ./scripts/run-emulator-tests.sh
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
|
||||
def emulators_running() -> bool:
|
||||
try:
|
||||
requests.get("http://127.0.0.1:8080", timeout=1) # Firestore
|
||||
requests.get("http://127.0.0.1:4443", timeout=1) # GCS (same check as conftest)
|
||||
return True
|
||||
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
|
||||
return False
|
||||
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not emulators_running(),
|
||||
reason="GCP emulators not running. Start with: scripts/start-emulators.sh",
|
||||
)
|
||||
|
||||
os.environ["FIRESTORE_EMULATOR_HOST"] = "127.0.0.1:8080"
|
||||
os.environ["GOOGLE_CLOUD_PROJECT"] = "test-project"
|
||||
|
||||
|
||||
def test_archive_job_copies_doc_and_subcollections_without_ttl():
|
||||
from google.cloud import firestore
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
|
||||
svc = FirestoreService()
|
||||
svc.db = firestore.Client(project="test-project")
|
||||
svc.collection = f"test-archive-jobs-{int(time.time() * 1000)}"
|
||||
|
||||
job_id = "arch-job-1"
|
||||
job_ref = svc.db.collection(svc.collection).document(job_id)
|
||||
job_ref.set({"job_id": job_id, "status": "complete", "artist": "Invented Band", "title": "Made Up Song"})
|
||||
expiry = datetime.now(timezone.utc) + timedelta(days=30)
|
||||
for i in range(3):
|
||||
job_ref.collection("logs").document(f"log{i}").set(
|
||||
{"message": f"line {i}", "ttl_expiry": expiry, "level": "INFO"}
|
||||
)
|
||||
job_ref.collection("audio_edit_sessions").document("s1").set({"edits": 2})
|
||||
|
||||
assert svc.archive_job(job_id, archived_by="admin@nomadkaraoke.com", reason="admin_delete") is True
|
||||
|
||||
arch = svc.db.collection(svc.archive_collection).document(job_id)
|
||||
data = arch.get().to_dict()
|
||||
assert data["artist"] == "Invented Band"
|
||||
assert data["archived_by"] == "admin@nomadkaraoke.com"
|
||||
assert data["archive_reason"] == "admin_delete"
|
||||
assert data["archived_at"] is not None
|
||||
|
||||
logs = {d.id: d.to_dict() for d in arch.collection("archived_logs").stream()}
|
||||
assert sorted(logs) == ["log0", "log1", "log2"]
|
||||
assert all("ttl_expiry" not in entry for entry in logs.values())
|
||||
assert [d.id for d in arch.collection("audio_edit_sessions").stream()] == ["s1"]
|
||||
|
||||
assert svc.archive_job("does-not-exist") is False
|
||||
@@ -699,6 +699,30 @@ def test_completed_made_for_you_order_anonymised(client, db):
|
||||
assert job["customer_notes"] is None
|
||||
|
||||
|
||||
def test_archived_jobs_redacted_not_deleted(client, db):
|
||||
"""Deleted jobs live on in jobs_archive as system data; account deletion redacts them."""
|
||||
_seed_user(db)
|
||||
archived = dict(_seed_job(db, "arch1"), archived_by="admin@nomadkaraoke.com", archive_reason="admin_delete")
|
||||
db.collection("jobs").docs.pop("arch1")
|
||||
db.collection("jobs_archive").docs["arch1"] = archived
|
||||
mfy = dict(_seed_job(db, "arch2", email="admin@nomadkaraoke.com", made_for_you=True, customer_email=EMAIL))
|
||||
db.collection("jobs").docs.pop("arch2")
|
||||
db.collection("jobs_archive").docs["arch2"] = mfy
|
||||
|
||||
body = _delete(client).json()
|
||||
tomb = f"deleted:{body['summary']['deletion_id']}"
|
||||
a1 = db.collection("jobs_archive").docs["arch1"]
|
||||
assert a1["user_email"] == tomb
|
||||
assert a1["creation_ip"] is None
|
||||
assert "client_ip" not in a1["request_metadata"]
|
||||
assert "customer_email" not in a1["state_data"]
|
||||
assert a1["artist"] == "Invented Band" # system data kept
|
||||
assert a1["archive_reason"] == "admin_delete"
|
||||
a2 = db.collection("jobs_archive").docs["arch2"]
|
||||
assert a2["user_email"] == "admin@nomadkaraoke.com"
|
||||
assert a2["customer_email"] == tomb
|
||||
|
||||
|
||||
def test_other_users_jobs_untouched(client, db):
|
||||
_seed_user(db)
|
||||
_seed_job(db, "j9", email=OTHER)
|
||||
|
||||
@@ -515,6 +515,40 @@ class TestJobDeletion:
|
||||
mock_firestore_service.delete_job.assert_called_once_with("test123")
|
||||
|
||||
|
||||
def test_delete_job_archives_first(self, job_manager, mock_firestore_service):
|
||||
"""The job is copied to jobs_archive before the doc is deleted."""
|
||||
existing_job = Job(
|
||||
job_id="test123", status=JobStatus.COMPLETE, progress=100,
|
||||
created_at=datetime.now(UTC), updated_at=datetime.now(UTC), output_files={},
|
||||
)
|
||||
mock_firestore_service.get_job.return_value = existing_job
|
||||
order = []
|
||||
mock_firestore_service.archive_job.side_effect = lambda *a, **k: order.append("archive") or True
|
||||
mock_firestore_service.delete_job.side_effect = lambda *a, **k: order.append("delete")
|
||||
|
||||
job_manager.delete_job("test123", archived_by="admin@nomadkaraoke.com", reason="admin_delete")
|
||||
|
||||
mock_firestore_service.archive_job.assert_called_once_with(
|
||||
"test123", archived_by="admin@nomadkaraoke.com", reason="admin_delete"
|
||||
)
|
||||
assert order == ["archive", "delete"]
|
||||
|
||||
def test_delete_job_aborts_when_archive_fails(self, job_manager, mock_firestore_service):
|
||||
"""A job whose archive copy didn't land is never deleted."""
|
||||
existing_job = Job(
|
||||
job_id="test123", status=JobStatus.COMPLETE, progress=100,
|
||||
created_at=datetime.now(UTC), updated_at=datetime.now(UTC), output_files={},
|
||||
)
|
||||
mock_firestore_service.get_job.return_value = existing_job
|
||||
mock_firestore_service.archive_job.side_effect = RuntimeError("firestore down")
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
job_manager.delete_job("test123")
|
||||
|
||||
mock_firestore_service.delete_job.assert_not_called()
|
||||
mock_firestore_service.delete_logs_subcollection.assert_not_called()
|
||||
|
||||
|
||||
class TestDeleteStateDataKeys:
|
||||
"""Tests for delete_state_data_key and delete_state_data_keys methods.
|
||||
|
||||
|
||||
@@ -1835,7 +1835,9 @@ class TestPreviewVideoAsyncFlow:
|
||||
job.title = "Test Song"
|
||||
return job
|
||||
|
||||
def _run_gce_preview(self, mock_job, *, mp4_exists, background_mock):
|
||||
def _run_gce_preview(self, mock_job, *, mp4_exists, background_mock,
|
||||
updated_data=None, countdown_padding_seconds=None,
|
||||
countdown_processor_cls=None):
|
||||
"""Run generate_preview_video with GCE enabled and heavy deps mocked."""
|
||||
import asyncio
|
||||
from backend.api.routes.review import generate_preview_video
|
||||
@@ -1855,7 +1857,7 @@ class TestPreviewVideoAsyncFlow:
|
||||
async def _run():
|
||||
result = await generate_preview_video(
|
||||
job_id=mock_job.job_id,
|
||||
updated_data={},
|
||||
updated_data=updated_data if updated_data is not None else {},
|
||||
auth_info=("user@test.com", "job_owner"),
|
||||
)
|
||||
# Let any create_task'd background coroutine start
|
||||
@@ -1877,6 +1879,14 @@ class TestPreviewVideoAsyncFlow:
|
||||
"preview_hash": "hash123",
|
||||
"ass_path": "/tmp/preview.ass",
|
||||
}
|
||||
if countdown_padding_seconds is not None:
|
||||
mock_co.generate_preview_video.return_value["countdown_padding_seconds"] = countdown_padding_seconds
|
||||
if countdown_processor_cls is not None:
|
||||
with patch("backend.api.routes.review.CountdownProcessor") as mock_cp:
|
||||
mock_cp.padding_for_segments_data.side_effect = countdown_processor_cls.padding_for_segments_data
|
||||
mock_cp.return_value.create_padded_audio_only.return_value = "/tmp/audio_padded.flac"
|
||||
result = asyncio.run(_run())
|
||||
return result, mock_storage, mock_co
|
||||
result = asyncio.run(_run())
|
||||
return result, mock_storage, mock_co
|
||||
|
||||
@@ -1886,7 +1896,7 @@ class TestPreviewVideoAsyncFlow:
|
||||
background_mock = AsyncMock()
|
||||
result, mock_storage, mock_co = self._run_gce_preview(
|
||||
mock_job, mp4_exists=True, background_mock=background_mock)
|
||||
assert result == {"status": "success", "preview_hash": "hash123"}
|
||||
assert result == {"status": "success", "preview_hash": "hash123", "countdown_padding_seconds": 0.0}
|
||||
background_mock.assert_not_called()
|
||||
# ASS is generated with ass_only=True (no local video render)
|
||||
assert mock_co.generate_preview_video.call_args.kwargs["ass_only"] is True
|
||||
@@ -1897,7 +1907,7 @@ class TestPreviewVideoAsyncFlow:
|
||||
background_mock = AsyncMock()
|
||||
result, mock_storage, _ = self._run_gce_preview(
|
||||
mock_job, mp4_exists=False, background_mock=background_mock)
|
||||
assert result == {"status": "generating", "preview_hash": "hash123"}
|
||||
assert result == {"status": "generating", "preview_hash": "hash123", "countdown_padding_seconds": 0.0}
|
||||
background_mock.assert_called_once()
|
||||
kwargs = background_mock.call_args.kwargs
|
||||
assert kwargs["preview_hash"] == "hash123"
|
||||
@@ -1907,6 +1917,29 @@ class TestPreviewVideoAsyncFlow:
|
||||
# Stale error marker from a previous failed attempt must be cleared
|
||||
mock_storage.delete_file.assert_called_once_with(
|
||||
"jobs/job-preview-async/previews/hash123.error.json", ignore_missing=True)
|
||||
# No countdown → the encoder uses the original input audio as-is.
|
||||
assert kwargs["encode_kwargs"]["audio_gcs_path"] == \
|
||||
"gs://test-bucket/jobs/job-preview-async/audio/input.flac"
|
||||
|
||||
def test_countdown_song_uploads_padded_audio_and_reports_offset(self, mock_job):
|
||||
"""Vocals within 3s: the preview's ASS carries the countdown intro (lyrics
|
||||
shifted +3s), so the encoder must get audio padded by the same 3s, and the
|
||||
client must be told the offset to keep the stem/playhead aligned."""
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
updated_data = {"corrected_segments": [
|
||||
{"text": "hello", "words": [{"text": "hello", "start_time": 0.4, "end_time": 0.9}]},
|
||||
]}
|
||||
background_mock = AsyncMock()
|
||||
result, mock_storage, _ = self._run_gce_preview(
|
||||
mock_job, mp4_exists=False, background_mock=background_mock,
|
||||
updated_data=updated_data, countdown_padding_seconds=3.0,
|
||||
countdown_processor_cls=CountdownProcessor)
|
||||
assert result == {"status": "generating", "preview_hash": "hash123", "countdown_padding_seconds": 3.0}
|
||||
mock_storage.upload_file.assert_any_call(
|
||||
"/tmp/audio_padded.flac", "jobs/job-preview-async/previews/hash123_audio.flac")
|
||||
kwargs = background_mock.call_args.kwargs
|
||||
assert kwargs["encode_kwargs"]["audio_gcs_path"] == \
|
||||
"gs://test-bucket/jobs/job-preview-async/previews/hash123_audio.flac"
|
||||
|
||||
|
||||
class TestPreviewVideoStatusEndpoint:
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Tenant portals are shared workspaces.
|
||||
|
||||
Andrew (2026-11-11): "my expectation is that all jobs in the tenant portal are
|
||||
accessible to everyone who has permission to access that portal."
|
||||
|
||||
Before this, a non-admin only ever saw/opened jobs whose ``user_email`` was their
|
||||
own, even on a tenant portal. A client (Randy) logging in with his own address
|
||||
never saw the 10 jobs Andrew had bulk-uploaded for him under another address,
|
||||
and re-submitted every song. Now any member of a tenant's allowlist can list and
|
||||
open all of that tenant's jobs; consumer jobs stay private to their owner.
|
||||
"""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from backend.models.tenant import TenantAuth, TenantConfig
|
||||
from backend.services import job_access
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
|
||||
MEMBER = "client@gmail.com"
|
||||
TEAMMATE = "colleague@client-label.com"
|
||||
OUTSIDER = "someone@else.com"
|
||||
|
||||
|
||||
def _tenant(active=True, emails=(MEMBER,), domains=("client-label.com",)):
|
||||
return TenantConfig(
|
||||
id="client", name="Client", subdomain="client.nomadkaraoke.com", is_active=active,
|
||||
auth=TenantAuth(allowed_emails=list(emails), allowed_email_domains=list(domains)),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tenant_service():
|
||||
svc = MagicMock()
|
||||
svc.get_tenant_config.side_effect = lambda tid: _tenant() if tid == "client" else None
|
||||
with patch("backend.services.tenant_service.get_tenant_service", return_value=svc):
|
||||
yield svc
|
||||
|
||||
|
||||
def _job(owner="bulk@nomadkaraoke.com", tenant_id="client"):
|
||||
return SimpleNamespace(user_email=owner, tenant_id=tenant_id, job_id="j1")
|
||||
|
||||
|
||||
def _user(email, admin=False):
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.ADMIN if admin else UserType.UNLIMITED,
|
||||
remaining_uses=-1, message="", user_email=email, is_admin=admin, tenant_id="client",
|
||||
)
|
||||
|
||||
|
||||
class TestCanAccessJob:
|
||||
def test_member_can_access_teammates_tenant_job(self, tenant_service):
|
||||
assert job_access.can_access_job(_job(), MEMBER, False)
|
||||
|
||||
def test_domain_member_can_access(self, tenant_service):
|
||||
assert job_access.can_access_job(_job(), TEAMMATE, False)
|
||||
|
||||
def test_member_check_is_case_insensitive(self, tenant_service):
|
||||
assert job_access.can_access_job(_job(), MEMBER.upper(), False)
|
||||
|
||||
def test_outsider_denied(self, tenant_service):
|
||||
assert not job_access.can_access_job(_job(), OUTSIDER, False)
|
||||
|
||||
def test_consumer_jobs_stay_private(self, tenant_service):
|
||||
assert not job_access.can_access_job(_job(owner="a@b.com", tenant_id=""), MEMBER, False)
|
||||
|
||||
def test_member_of_one_tenant_cannot_see_another(self, tenant_service):
|
||||
assert not job_access.can_access_job(_job(tenant_id="other"), MEMBER, False)
|
||||
|
||||
def test_inactive_tenant_not_shared(self, tenant_service):
|
||||
tenant_service.get_tenant_config.side_effect = lambda tid: _tenant(active=False)
|
||||
assert not job_access.can_access_job(_job(), MEMBER, False)
|
||||
|
||||
def test_tenant_without_allowlist_not_shared(self, tenant_service):
|
||||
tenant_service.get_tenant_config.side_effect = lambda tid: _tenant(emails=(), domains=())
|
||||
assert not job_access.can_access_job(_job(), MEMBER, False)
|
||||
|
||||
def test_removed_member_loses_access(self, tenant_service):
|
||||
tenant_service.get_tenant_config.side_effect = lambda tid: _tenant(emails=(), domains=("x.com",))
|
||||
assert not job_access.can_access_job(_job(), MEMBER, False)
|
||||
|
||||
def test_lookup_error_fails_closed(self, tenant_service):
|
||||
tenant_service.get_tenant_config.side_effect = RuntimeError("boom")
|
||||
assert not job_access.can_access_job(_job(), MEMBER, False)
|
||||
|
||||
def test_owner_and_admin_unchanged(self, tenant_service):
|
||||
assert job_access.can_access_job(_job(owner=OUTSIDER, tenant_id=""), OUTSIDER, False)
|
||||
assert job_access.can_access_job(_job(owner="x@y.com", tenant_id=""), None, True)
|
||||
|
||||
def test_token_without_email_denied_on_owned_job(self, tenant_service):
|
||||
assert not job_access.can_access_job(_job(), None, False)
|
||||
|
||||
def test_legacy_ownerless_job_still_accessible(self, tenant_service):
|
||||
assert job_access.can_access_job(_job(owner=None, tenant_id=""), OUTSIDER, False)
|
||||
|
||||
def test_ownerless_can_be_denied_per_route(self, tenant_service):
|
||||
"""Style-upload routes never allowed ownerless jobs to non-admins; keep that."""
|
||||
assert not job_access.can_access_job(
|
||||
_job(owner=None, tenant_id=""), OUTSIDER, False, allow_ownerless=False)
|
||||
# ...but a tenant member still gets the tenant's ownerless jobs.
|
||||
assert job_access.can_access_job(_job(owner=None), MEMBER, False, allow_ownerless=False)
|
||||
|
||||
|
||||
class TestListJobsOnTenantPortal:
|
||||
JOBS = [{"job_id": "bulk1", "user_email": "bulk@nomadkaraoke.com"},
|
||||
{"job_id": "mine", "user_email": MEMBER}]
|
||||
|
||||
def _call(self, auth, tenant_id):
|
||||
from backend.api.routes.jobs import list_jobs
|
||||
with patch("backend.api.routes.jobs.get_locale_from_request", return_value="en"), \
|
||||
patch("backend.api.routes.jobs.get_tenant_from_request", return_value=tenant_id), \
|
||||
patch("backend.api.routes.jobs.job_manager") as jm:
|
||||
jm.list_jobs_summary.return_value = [dict(j) for j in self.JOBS]
|
||||
list_jobs(MagicMock(), fields="summary", auth_result=auth)
|
||||
return jm.list_jobs_summary.call_args.kwargs
|
||||
|
||||
def test_member_lists_all_tenant_jobs(self, tenant_service):
|
||||
kwargs = self._call(_user(MEMBER), "client")
|
||||
assert kwargs["user_email"] is None
|
||||
assert kwargs["tenant_id"] == "client" # still scoped to this tenant
|
||||
|
||||
def test_outsider_on_portal_only_lists_own(self, tenant_service):
|
||||
kwargs = self._call(_user(OUTSIDER), "client")
|
||||
assert kwargs["user_email"] == OUTSIDER
|
||||
|
||||
def test_consumer_portal_still_own_jobs_only(self, tenant_service):
|
||||
kwargs = self._call(_user(MEMBER), None)
|
||||
assert kwargs["user_email"] == MEMBER
|
||||
assert kwargs["tenant_id"] == ""
|
||||
|
||||
|
||||
class TestReviewAuthOnTenantJob:
|
||||
def _call(self, email):
|
||||
from backend.api.dependencies import require_review_auth_factory
|
||||
dep = require_review_auth_factory()
|
||||
auth_service = MagicMock()
|
||||
auth_service.validate_token_full.return_value = _user(email)
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = _job()
|
||||
creds = SimpleNamespace(credentials="tok")
|
||||
with patch("backend.services.job_manager.JobManager", return_value=jm):
|
||||
return asyncio.run(dep(request=MagicMock(), job_id="j1", review_token=None,
|
||||
auth_service=auth_service, credentials=creds, token=None))
|
||||
|
||||
def test_member_can_open_review(self, tenant_service):
|
||||
assert self._call(MEMBER) == ("j1", "full")
|
||||
|
||||
def test_outsider_gets_403(self, tenant_service):
|
||||
with pytest.raises(HTTPException) as e:
|
||||
self._call(OUTSIDER)
|
||||
assert e.value.status_code == 403
|
||||
|
||||
|
||||
class TestCheckJobOwnershipWrapper:
|
||||
def test_uses_shared_rule(self, tenant_service):
|
||||
from backend.api.routes.jobs import _check_job_ownership
|
||||
assert _check_job_ownership(_job(), _user(MEMBER))
|
||||
assert not _check_job_ownership(_job(), _user(OUTSIDER))
|
||||
@@ -319,7 +319,8 @@ def test_save_reports_refreshed_and_outdated(client_for):
|
||||
assert body["refreshed_jobs"] == 3 and body["outdated_job_ids"] == ["a", "b"]
|
||||
assert body["theme_id"] == "randy-vild"
|
||||
refresh.assert_called_once_with("randy-vild", "randy-vild")
|
||||
assert outdated.call_args.args == ("randy-vild", "randy-vild", "randyvild@gmail.com")
|
||||
# Tenant portals are shared workspaces: members act on all the portal's tracks.
|
||||
assert outdated.call_args.args == ("randy-vild", "randy-vild", None)
|
||||
|
||||
|
||||
def test_save_succeeds_even_if_follow_up_work_fails(client_for):
|
||||
@@ -333,10 +334,12 @@ def test_save_succeeds_even_if_follow_up_work_fails(client_for):
|
||||
assert resp.json()["refreshed_jobs"] == 0 and resp.json()["outdated_job_ids"] == []
|
||||
|
||||
|
||||
def test_outdated_jobs_scope_member_vs_admin(client_for):
|
||||
def test_outdated_jobs_cover_whole_portal_for_members_and_admins(client_for):
|
||||
"""Tenant portals are shared workspaces: a member's outdated list covers every
|
||||
track on the portal (not just their own), same as an admin's."""
|
||||
with patch.object(tenant_theme, "outdated_jobs", return_value={"theme_updated_at": None, "job_ids": ["a"]}) as od:
|
||||
assert client_for().get("/api/tenant/theme/outdated-jobs").json()["job_ids"] == ["a"]
|
||||
assert od.call_args.args[2] == "randyvild@gmail.com"
|
||||
assert od.call_args.args[2] is None
|
||||
client_for(email="andrew@nomadkaraoke.com").get("/api/tenant/theme/outdated-jobs")
|
||||
assert od.call_args.args[2] is None
|
||||
|
||||
|
||||
@@ -330,11 +330,19 @@ class TestRerenderRoute:
|
||||
assert start.await_args.kwargs["theme_id"] == "randy-vild"
|
||||
assert start.await_args.kwargs["requested_by"] == "randy@example.com"
|
||||
|
||||
def test_non_owner_forbidden(self, client):
|
||||
resp, start = _call(client, _auth(email="someone@else.com"), _job(), _tenant())
|
||||
def test_non_member_forbidden(self, client):
|
||||
tenant = _tenant()
|
||||
tenant.is_email_allowed.side_effect = lambda e: e == "randy@example.com"
|
||||
resp, start = _call(client, _auth(email="someone@else.com"), _job(), tenant)
|
||||
assert resp.status_code == 403
|
||||
start.assert_not_awaited()
|
||||
|
||||
def test_teammate_on_allowlist_allowed(self, client):
|
||||
"""Tenant portals are shared: another member may re-render a teammate's track."""
|
||||
resp, start = _call(client, _auth(email="colleague@randy.com"), _job(), _tenant())
|
||||
assert resp.status_code == 200
|
||||
start.assert_awaited_once()
|
||||
|
||||
def test_owner_removed_from_allowlist_forbidden(self, client):
|
||||
resp, start = _call(client, _auth(), _job(), _tenant(allowed=False))
|
||||
assert resp.status_code == 403
|
||||
|
||||
+15
-3
@@ -268,6 +268,16 @@ Response includes:
|
||||
- `state_data` - Worker progress details
|
||||
- `timeline` - Processing history
|
||||
|
||||
#### Tenant portals are shared workspaces
|
||||
|
||||
Job access follows one rule (`backend/services/job_access.py`): admins can access every job, owners their own,
|
||||
and **anyone currently allowed to sign in to a tenant portal** (its `allowed_emails` / `allowed_email_domains`)
|
||||
can list, open, review, edit, re-render and delete **every job of that tenant**, whoever submitted it.
|
||||
Membership is re-checked on each request against the live tenant config (cached ~5 min), so removing someone
|
||||
from the allowlist removes their access. Inactive tenants and tenants without an allowlist share nothing.
|
||||
Consumer jobs (no tenant) stay private to their owner. `GET /api/jobs` on a tenant portal is always scoped to
|
||||
that tenant.
|
||||
|
||||
#### List Jobs
|
||||
|
||||
```http
|
||||
@@ -477,6 +487,8 @@ Content-Type: application/json
|
||||
|
||||
Generates a preview video during review. Returns `{"status": "success", "preview_hash": "..."}` when the video is immediately available (cache hit — the hash is deterministic over the correction data — or local render), or `{"status": "generating", "preview_hash": "..."}` when encoding continues in the background on a GCE worker. In the generating case, poll the status endpoint below; the request never waits for the encoder (cold-starting a worker VM can take minutes, longer than Cloudflare's edge timeout).
|
||||
|
||||
Both responses also carry `countdown_padding_seconds` (3.0 or 0.0). When the first word starts within 3s the preview gets the same "3... 2... 1..." intro as the final render: lyrics shifted and audio padded by that many seconds, so video time = song time + `countdown_padding_seconds`. Clients syncing other audio (e.g. instrumental stems) to the preview must subtract it.
|
||||
|
||||
The `use_background_image` option controls whether the preview renders with the theme's background image (slower, ~30-60s) or a solid black background (faster, ~10s). Defaults to black background for speed.
|
||||
|
||||
#### Poll Preview Status
|
||||
@@ -1483,8 +1495,8 @@ re-checks membership (`require_tenant_member`): non-members/spoofed headers →
|
||||
render, so a user who is mid-review is never interrupted. `review_complete` and later jobs are left
|
||||
alone. `refreshed_jobs` counts the jobs updated. `outdated_job_ids` lists the caller's finished tracks
|
||||
made with an older theme, where "older" means the theme's `style_params.json` write time is later
|
||||
than `theme_applied_at`, falling back to `created_at`. Members see their own tracks; admins see all
|
||||
of the tenant's tracks. Editing a finished tenant track (`POST /api/jobs/{id}/edit`) also re-applies
|
||||
than `theme_applied_at`, falling back to `created_at`. It covers all of the tenant's tracks, for
|
||||
members and admins alike (tenant portals are shared workspaces). Editing a finished tenant track (`POST /api/jobs/{id}/edit`) also re-applies
|
||||
the current theme when the track's copy is outdated.
|
||||
- **Rerender-outdated** starts `POST /api/jobs/{id}/rerender` for every outdated track, **quietly**:
|
||||
the `theme_rerender.notify_customer=false` marker suppresses the per-track completion email/push.
|
||||
@@ -2422,7 +2434,7 @@ DELETE /api/jobs/{job_id}?delete_files=true
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Admins can delete any job. Regular users can only delete their own jobs.
|
||||
Admins can delete any job. Regular users can delete their own jobs, and on a tenant portal any job of that tenant (see [Tenant portals are shared workspaces](#tenant-portals-are-shared-workspaces)).
|
||||
|
||||
### Audio Search Management (Admin)
|
||||
|
||||
|
||||
@@ -467,6 +467,8 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
|
||||
|
||||
**Worker Logs**: Stored in subcollection (`jobs/{job_id}/logs`) instead of embedded array to avoid Firestore's 1MB document size limit. TTL policy auto-deletes logs after 30 days. Feature flag: `USE_LOG_SUBCOLLECTION` (default: true). See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#firestore-document-1mb-limit-with-embedded-arrays).
|
||||
|
||||
**Deleted jobs are archived, not lost** (since v0.295.0): `JobManager.delete_job` first copies the job doc to `jobs_archive/{job_id}` (plus `archived_at`, `archived_by`, `archive_reason`: `admin_delete` / `owner_delete` / `cleanup_distribution_delete`), its logs to `jobs_archive/{job_id}/archived_logs` (without `ttl_expiry`, because the TTL policy is on the `logs` collection group, so archived logs are kept forever), and its `audio_edit_sessions`. If the copy fails, the delete is aborted. Archived jobs are kept forever as system data. Account deletion redacts them like live jobs (owner/customer email → `deleted:<uuid>`, IPs, notes and contact fields removed). Bulk test cleanup (`DELETE /api/jobs?…`, `delete_jobs_by_filter`) still hard-deletes. `scripts/get_job.py <id>` falls back to the archive.
|
||||
|
||||
## Encoding Worker: blue-green primary pair + multi-family fallback pool
|
||||
|
||||
> **2026-11 update:** the c4d Spot pair (`encoding-worker-a`/`-b`) is **retired and deleted**. The preferred encoder (and distribution worker) is the AWS EC2 box `aws-encoding-worker-1`; the only GCE VM is the on-demand fallback `encoding-worker-fallback-c2df` (us-central1-f). `config/encoding-worker` keeps `primary_vm`/`secondary_vm` empty, so every selection path routes to a fallback and records it as `active_override_*`. CI blue-green deploys now just validate the new wheel on c2df and stop it again (the AWS override keeps serving); the worker-change gate diffs against `validated_version`. The pair-specific text below is historical.
|
||||
|
||||
@@ -96,9 +96,10 @@ Notifications are sent when:
|
||||
| Variable | Value | Description |
|
||||
|----------|-------|-------------|
|
||||
| `GDRIVE_FOLDER_ID` | `1laRKAyxo0v817SstfM5XkpbWiNKNAMSX` | Root folder of public share |
|
||||
| `NOTIFY_ON_SUCCESS` | `true` | Send daily "all clear" summary |
|
||||
| `NOTIFY_ON_SUCCESS` | `false` (prod) | Send an "all clear" email on every clean run; off in prod because the post-job trigger runs after every job |
|
||||
| `EMAIL_TO` | `gen@nomadkaraoke.com` | Email recipient |
|
||||
| `EMAIL_FROM` | `gen@nomadkaraoke.com` | Email sender |
|
||||
| `IN_FLIGHT_GRACE_MINUTES` | `30` (default) | Tracks with any file created in Drive this recently count as still uploading and are left out of the gap check |
|
||||
|
||||
### Secrets (Cloud Function)
|
||||
|
||||
@@ -202,6 +203,16 @@ The post-job trigger uses a 5-minute Cloud Tasks delay (via `gdrive-validation-q
|
||||
|
||||
**IMPORTANT: Never add new entries to `KNOWN_GAPS`.** The existing known gaps are historical (pre-generator era, over a year old). Every new gap is a real bug that must be investigated and fixed.
|
||||
|
||||
**Tracks still uploading are not gaps.** A job's packaging step uploads MP4, then
|
||||
MP4-720p, then CDG over ~2 minutes, and another job's post-job trigger can run in that
|
||||
window. On 2026-11-07 NOMAD-1871's check ran at 12:24:47 UTC while NOMAD-1872 was
|
||||
uploading (12:23:39–12:25:40) and emailed "CDG/MP4-720p: missing 1872"; the files were
|
||||
all there a minute later. Since then the validator reads each file's Drive `createdTime`
|
||||
and leaves out of the gap check any track with a file created in the last
|
||||
`IN_FLIGHT_GRACE_MINUTES` (30). That track is still checked by its own post-job trigger
|
||||
(which names its `brand_code`) and by the daily 9 PM run. If you get a gap alert for the
|
||||
newest track, first check whether that job was in `packaging` at the alert time.
|
||||
|
||||
**Investigation steps:**
|
||||
|
||||
1. **Identify the missing brand code(s)** from the alert (e.g., "MP4: missing 1295")
|
||||
|
||||
@@ -2540,3 +2540,23 @@ exactly like the old path. Kill switch: `AUTO_APPROVAL_AUDIO_HOLD_ENABLED`.
|
||||
Lesson: an async "second chance" that only runs when no human has touched the
|
||||
job will lose that race to a fast human. Hold the human-facing state until the
|
||||
automatic decision is final, rather than racing it.
|
||||
|
||||
## Character limits don't stop libass wrapping a line into the row below (2026-11-09, v0.295.1)
|
||||
|
||||
NOMAD-1779 shipped with two lyric lines drawn on top of each other near the end. The lines
|
||||
("Mm- mm- mm, mm- …") passed the 40-character `max_line_length` but are made of wide glyphs:
|
||||
~3890px on the 3840px frame. libass wraps an over-wide event by itself, and since rows are
|
||||
exactly one line-height apart, the wrapped half lands on the next row's lyrics.
|
||||
|
||||
- `SubtitlesGenerator.generate_ass` now measures every line in the style font (via
|
||||
`LyricsLine._measure_text`, which scales fonts the way libass does, see `ass_font_scale`)
|
||||
and splits any line wider than `MAX_LINE_WIDTH_FRACTION` (94%) of the frame at a word
|
||||
boundary (`SegmentResizer.split_to_width`, prefers phrase-ending punctuation). It applies to
|
||||
every ASS render: main, portrait, theme previews.
|
||||
- PIL font size ≠ libass font size: libass sizes by ascender+descender, so Avenir Next Bold
|
||||
at 250 draws ~0.73× as wide as `ImageFont.truetype(path, 250)`. Measure through
|
||||
`_measure_text`, never raw PIL.
|
||||
- Scope at the time: 1 of 309 completed jobs since 2026-09-10 had an overlap; 4 more had a
|
||||
line that wrapped into an empty row.
|
||||
- `tests/unit/lyrics_transcriber/output/test_line_width_split.py` renders with real libass and
|
||||
asserts each lyric event draws exactly one row.
|
||||
@@ -61,6 +61,8 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Tenant portals are shared workspaces** (2026-11-11, v0.297.0). Every member of a tenant portal's allowlist can now list and act on all of that tenant's jobs, not only the ones they submitted (one rule in `backend/services/job_access.py`, used by job routes, review auth, file upload guards and the theme refresh/rerender scope). Found when a client logging in with their own email never saw the 10 jobs bulk-uploaded for them under another address and re-submitted every song. Consumer jobs stay owner-only.
|
||||
- **Review preview shows the countdown intro** (2026-11-11, v0.296.0). Songs whose vocals start within 3s got the "3... 2... 1..." intro (+3s lyrics shift, 3s leading silence) only in the final render, so the review preview opened straight on vocals and customers asked for a countdown that was already coming (Randy Vild, Nov 2026). `CorrectionOperations.generate_preview_video` now applies `CountdownProcessor.add_countdown_to_lyrics_if_needed` (local/CLI renders also pad the audio; the GCE preview path uploads padded audio to `previews/{hash}_audio.flac`, so the encoder worker is unchanged). The endpoint returns `countdown_padding_seconds`; `PreviewVideoSection` maps video time to song time so the instrumental stem and waveform playhead stay aligned. Countdown previews hash with a salt so pre-fix cached previews aren't reused.
|
||||
- **Guitar chords in karaoke videos** (2026-10-16, v0.277.0). `OutputGenerator.generate_outputs(chords=[ChordChange(...)])` draws each chord above the word it lands on (it lights up when played) in a row reserved above every line, plus a "now / next" chord box in the top-right corner that also covers intros and instrumental breaks. Chords come from `scripts/medley/detect_chords.py`, an ensemble of ChordMini models over the mix, instrumental and harmonic stems. It's used by the medley script for now (`"chords": true`); there's no job/UI option yet. Theme keys: `chord_color`, `chord_font_size`/`chord_font_ratio`, `chord_max_visible_lines`. See [MEDLEYS.md § Guitar chords](MEDLEYS.md#guitar-chords-optional).
|
||||
- **Customer chord charts + medley mastering fix** (2026-10-17, v0.278.5). `make_medley.py chart` turns a customer's chords-over-lyrics chart (.txt or .docx, capo shapes kept, `ChordChange.capo` shown in the chord box) into timed chords on the reviewed lyrics, with detected chords filling intros and breaks (`scripts/medley/chord_chart.py`). The medley master is now one static gain + limiter instead of single-pass `loudnorm`, which had boosted a near-silent a cappella intro into robotic artifacts. See [MEDLEYS.md](MEDLEYS.md#the-customers-own-chord-chart-chart-step).
|
||||
- **Local E2E stack + email-code sign-in** (2026-10-15, v0.275.0). Plan: [archive/2026-10-15-local-stack-e2e-plan.md](archive/2026-10-15-local-stack-e2e-plan.md).
|
||||
|
||||
@@ -1835,7 +1835,7 @@ function AdminJobsPageContent() {
|
||||
{/* YouTube */}
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className={`w-2 h-2 rounded-full mt-1.5 ${
|
||||
deleteOutputsResult.deleted_services.youtube.status === "deleted"
|
||||
deleteOutputsResult.deleted_services.youtube.status === "success"
|
||||
? "bg-green-500"
|
||||
: deleteOutputsResult.deleted_services.youtube.status === "skipped"
|
||||
? "bg-gray-400"
|
||||
@@ -1844,7 +1844,7 @@ function AdminJobsPageContent() {
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm">YouTube</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{deleteOutputsResult.deleted_services.youtube.status === "deleted" && (
|
||||
{deleteOutputsResult.deleted_services.youtube.status === "success" && (
|
||||
<>Deleted video: <code className="text-xs bg-muted px-1 rounded">{deleteOutputsResult.deleted_services.youtube.video_id}</code></>
|
||||
)}
|
||||
{deleteOutputsResult.deleted_services.youtube.status === "skipped" && (
|
||||
@@ -1853,6 +1853,9 @@ function AdminJobsPageContent() {
|
||||
{deleteOutputsResult.deleted_services.youtube.status === "error" && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.youtube.error}</span>
|
||||
)}
|
||||
{(deleteOutputsResult.deleted_services.youtube.status === "failed" || deleteOutputsResult.deleted_services.youtube.status === "partial") && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.youtube.reason || deleteOutputsResult.deleted_services.youtube.error || "Delete failed, check the job logs"}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1860,7 +1863,7 @@ function AdminJobsPageContent() {
|
||||
{/* Dropbox */}
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className={`w-2 h-2 rounded-full mt-1.5 ${
|
||||
deleteOutputsResult.deleted_services.dropbox.status === "deleted"
|
||||
deleteOutputsResult.deleted_services.dropbox.status === "success"
|
||||
? "bg-green-500"
|
||||
: deleteOutputsResult.deleted_services.dropbox.status === "skipped"
|
||||
? "bg-gray-400"
|
||||
@@ -1869,7 +1872,7 @@ function AdminJobsPageContent() {
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm">Dropbox</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{deleteOutputsResult.deleted_services.dropbox.status === "deleted" && (
|
||||
{deleteOutputsResult.deleted_services.dropbox.status === "success" && (
|
||||
<>Deleted folder: <code className="text-xs bg-muted px-1 rounded break-all">{deleteOutputsResult.deleted_services.dropbox.path}</code></>
|
||||
)}
|
||||
{deleteOutputsResult.deleted_services.dropbox.status === "skipped" && (
|
||||
@@ -1878,6 +1881,9 @@ function AdminJobsPageContent() {
|
||||
{deleteOutputsResult.deleted_services.dropbox.status === "error" && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.dropbox.error}</span>
|
||||
)}
|
||||
{(deleteOutputsResult.deleted_services.dropbox.status === "failed" || deleteOutputsResult.deleted_services.dropbox.status === "partial") && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.dropbox.reason || deleteOutputsResult.deleted_services.dropbox.error || "Delete failed, check the job logs"}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1885,7 +1891,7 @@ function AdminJobsPageContent() {
|
||||
{/* Google Drive */}
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className={`w-2 h-2 rounded-full mt-1.5 ${
|
||||
deleteOutputsResult.deleted_services.gdrive.status === "deleted"
|
||||
deleteOutputsResult.deleted_services.gdrive.status === "success"
|
||||
? "bg-green-500"
|
||||
: deleteOutputsResult.deleted_services.gdrive.status === "skipped"
|
||||
? "bg-gray-400"
|
||||
@@ -1894,7 +1900,7 @@ function AdminJobsPageContent() {
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm">Google Drive</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{deleteOutputsResult.deleted_services.gdrive.status === "deleted" && deleteOutputsResult.deleted_services.gdrive.files && (
|
||||
{deleteOutputsResult.deleted_services.gdrive.status === "success" && deleteOutputsResult.deleted_services.gdrive.files && (
|
||||
<>Deleted {Object.keys(deleteOutputsResult.deleted_services.gdrive.files).length} file(s)</>
|
||||
)}
|
||||
{deleteOutputsResult.deleted_services.gdrive.status === "skipped" && (
|
||||
@@ -1903,6 +1909,14 @@ function AdminJobsPageContent() {
|
||||
{deleteOutputsResult.deleted_services.gdrive.status === "error" && (
|
||||
<span className="text-red-500">{deleteOutputsResult.deleted_services.gdrive.error}</span>
|
||||
)}
|
||||
{(deleteOutputsResult.deleted_services.gdrive.status === "failed" || deleteOutputsResult.deleted_services.gdrive.status === "partial") && (
|
||||
<span className="text-red-500">{
|
||||
deleteOutputsResult.deleted_services.gdrive.files &&
|
||||
Object.values(deleteOutputsResult.deleted_services.gdrive.files).some((ok) => !ok)
|
||||
? `Not deleted: ${Object.entries(deleteOutputsResult.deleted_services.gdrive.files).filter(([, ok]) => !ok).map(([k]) => k).join(", ")}`
|
||||
: deleteOutputsResult.deleted_services.gdrive.reason || deleteOutputsResult.deleted_services.gdrive.error || "Delete failed, check the job logs"
|
||||
}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -30,6 +30,8 @@ interface ApiClient {
|
||||
status: string
|
||||
message?: string
|
||||
preview_hash?: string
|
||||
/** Seconds of countdown intro prepended to the preview (0 when none). */
|
||||
countdown_padding_seconds?: number
|
||||
}>
|
||||
getPreviewVideoStatus: (hash: string) => Promise<{
|
||||
status: string
|
||||
@@ -121,6 +123,11 @@ function PreviewVideoSection(
|
||||
}, [])
|
||||
|
||||
const internalVideoRef = useRef<HTMLVideoElement | null>(null)
|
||||
// Seconds of countdown intro ("3... 2... 1...") the backend prepended to this
|
||||
// preview, exactly as the final render does for songs whose vocals start within
|
||||
// 3s. The video's timeline is song time + this offset; the instrumental stem and
|
||||
// the waveform playhead run on song time, so every sync point converts.
|
||||
const introOffsetRef = useRef(0)
|
||||
const instrumentalAudioRef = useRef<HTMLAudioElement | null>(null)
|
||||
const isInstrumentalRef = useRef(false)
|
||||
isInstrumentalRef.current = isInstrumental
|
||||
@@ -174,7 +181,7 @@ function PreviewVideoSection(
|
||||
if (el && isInstrumentalRef.current) {
|
||||
const audio = instrumentalAudioRef.current
|
||||
if (audio && !audio.paused && audio.currentTime > 0) {
|
||||
el.currentTime = audio.currentTime
|
||||
el.currentTime = audio.currentTime + introOffsetRef.current
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -241,6 +248,7 @@ function PreviewVideoSection(
|
||||
|
||||
const response = await apiClient.generatePreviewVideo(dataToPreview, isDuet)
|
||||
if (cancelled) return
|
||||
introOffsetRef.current = Math.max(0, Number(response.countdown_padding_seconds) || 0)
|
||||
|
||||
if (response.status === 'error' || !response.preview_hash) {
|
||||
setPreviewState({
|
||||
@@ -362,6 +370,23 @@ function PreviewVideoSection(
|
||||
if (!video) return
|
||||
|
||||
const instrumentalActive = () => isInstrumentalRef.current && !!audio
|
||||
// Song time for the current video position (negative during the countdown intro).
|
||||
const songTime = () => video.currentTime - introOffsetRef.current
|
||||
// Put the stem where the video is: parked at 0 during the intro (silence in the
|
||||
// video too), playing from the matching song position after it.
|
||||
const syncAudio = (forceSeek: boolean) => {
|
||||
if (!audio) return
|
||||
const target = songTime()
|
||||
if (target < 0) {
|
||||
if (!audio.paused) audio.pause()
|
||||
if (audio.currentTime !== 0) audio.currentTime = 0
|
||||
return
|
||||
}
|
||||
if (forceSeek || Math.abs(audio.currentTime - target) > AUDIO_SYNC_TOLERANCE_S) {
|
||||
audio.currentTime = target
|
||||
}
|
||||
if (!video.paused && audio.paused) audio.play()?.catch(() => {})
|
||||
}
|
||||
|
||||
const applyMode = () => {
|
||||
const active = instrumentalActive()
|
||||
@@ -370,10 +395,7 @@ function PreviewVideoSection(
|
||||
audio.muted = !active
|
||||
if (active) {
|
||||
audio.playbackRate = video.playbackRate
|
||||
if (Math.abs(audio.currentTime - video.currentTime) > AUDIO_SYNC_TOLERANCE_S) {
|
||||
audio.currentTime = video.currentTime
|
||||
}
|
||||
if (!video.paused) audio.play()?.catch(() => {})
|
||||
syncAudio(false)
|
||||
} else {
|
||||
audio.pause()
|
||||
}
|
||||
@@ -381,22 +403,21 @@ function PreviewVideoSection(
|
||||
|
||||
const onPlay = () => {
|
||||
if (!audio || !instrumentalActive()) return
|
||||
audio.currentTime = video.currentTime
|
||||
audio.play()?.catch(() => {})
|
||||
syncAudio(true)
|
||||
}
|
||||
const onPause = () => audio?.pause()
|
||||
const onSeeked = () => {
|
||||
if (audio) audio.currentTime = video.currentTime
|
||||
if (!audio) return
|
||||
if (instrumentalActive()) syncAudio(true)
|
||||
else audio.currentTime = Math.max(0, songTime())
|
||||
}
|
||||
const onRateChange = () => {
|
||||
if (audio) audio.playbackRate = video.playbackRate
|
||||
}
|
||||
const onTimeUpdateEvt = () => {
|
||||
onTimeUpdate?.(video.currentTime)
|
||||
onTimeUpdate?.(Math.max(0, songTime()))
|
||||
if (!audio || !instrumentalActive()) return
|
||||
if (Math.abs(audio.currentTime - video.currentTime) > AUDIO_SYNC_TOLERANCE_S) {
|
||||
audio.currentTime = video.currentTime
|
||||
}
|
||||
syncAudio(false)
|
||||
}
|
||||
|
||||
applyMode()
|
||||
@@ -453,7 +474,7 @@ function PreviewVideoSection(
|
||||
const video = internalVideoRef.current
|
||||
if (video) {
|
||||
if (seekTo != null) {
|
||||
video.currentTime = seekTo
|
||||
video.currentTime = seekTo + introOffsetRef.current
|
||||
video.play()?.catch(() => {})
|
||||
}
|
||||
return
|
||||
|
||||
@@ -613,4 +613,91 @@ describe('PreviewVideoSection', () => {
|
||||
})
|
||||
expect(audio.src).toBe('http://test/backing.ogg')
|
||||
})
|
||||
|
||||
describe('countdown intro (vocals start within 3s)', () => {
|
||||
// The backend prepends the same "3... 2... 1..." intro the final render adds and
|
||||
// reports its length; the video timeline is song time + that offset, while the
|
||||
// stem and waveform playhead stay on song time.
|
||||
const renderWithCountdown = (onTimeUpdate?: jest.Mock) => {
|
||||
const apiClient = makeApiClient({
|
||||
generatePreviewVideo: jest.fn().mockResolvedValue({
|
||||
status: 'success',
|
||||
preview_hash: 'hash-countdown',
|
||||
countdown_padding_seconds: 3,
|
||||
}),
|
||||
})
|
||||
const ref = createRef<PreviewVideoHandle>()
|
||||
render(
|
||||
<PreviewVideoSection
|
||||
ref={ref}
|
||||
apiClient={apiClient}
|
||||
isModalOpen={true}
|
||||
updatedData={data}
|
||||
instrumentalOptions={instrumentalOptions as any}
|
||||
autoSelection="with_backing"
|
||||
onTimeUpdate={onTimeUpdate}
|
||||
/>
|
||||
)
|
||||
return ref
|
||||
}
|
||||
|
||||
it('seeks the video past the intro when auditioning at a song time', async () => {
|
||||
const ref = renderWithCountdown()
|
||||
await flush()
|
||||
act(() => {
|
||||
ref.current!.auditionInstrumental('clean', 5)
|
||||
})
|
||||
await flush()
|
||||
const video = document.querySelector('video') as HTMLVideoElement
|
||||
expect(video.currentTime).toBe(8)
|
||||
})
|
||||
|
||||
it('reports song time (video time minus the intro) to the playhead', async () => {
|
||||
const onTimeUpdate = jest.fn()
|
||||
renderWithCountdown(onTimeUpdate)
|
||||
await flush()
|
||||
const video = document.querySelector('video') as HTMLVideoElement
|
||||
video.currentTime = 10
|
||||
fireEvent.timeUpdate(video)
|
||||
expect(onTimeUpdate).toHaveBeenLastCalledWith(7)
|
||||
// During the intro the playhead stays at the start of the song.
|
||||
video.currentTime = 1
|
||||
fireEvent.timeUpdate(video)
|
||||
expect(onTimeUpdate).toHaveBeenLastCalledWith(0)
|
||||
})
|
||||
|
||||
it('keeps the stem on song time when the video seeks, parked at 0 during the intro', async () => {
|
||||
const ref = renderWithCountdown()
|
||||
await flush()
|
||||
act(() => {
|
||||
ref.current!.auditionInstrumental('with_backing')
|
||||
})
|
||||
await flush()
|
||||
const video = document.querySelector('video') as HTMLVideoElement
|
||||
const audio = document.querySelector('audio') as HTMLAudioElement
|
||||
video.currentTime = 11
|
||||
fireEvent.seeked(video)
|
||||
expect(audio.currentTime).toBe(8)
|
||||
video.currentTime = 2
|
||||
fireEvent.seeked(video)
|
||||
expect(audio.currentTime).toBe(0)
|
||||
})
|
||||
|
||||
it('uses no offset when the backend reports no countdown', async () => {
|
||||
const onTimeUpdate = jest.fn()
|
||||
render(
|
||||
<PreviewVideoSection
|
||||
apiClient={makeApiClient()}
|
||||
isModalOpen={true}
|
||||
updatedData={data}
|
||||
onTimeUpdate={onTimeUpdate}
|
||||
/>
|
||||
)
|
||||
await flush()
|
||||
const video = document.querySelector('video') as HTMLVideoElement
|
||||
video.currentTime = 10
|
||||
fireEvent.timeUpdate(video)
|
||||
expect(onTimeUpdate).toHaveBeenLastCalledWith(10)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -181,7 +181,9 @@ test.describe(`Tenant Portal Happy Path — ${TENANT_ID}`, () => {
|
||||
let reviewLink = null;
|
||||
const reviewDeadline = Date.now() + T.transcription;
|
||||
while (Date.now() < reviewDeadline) {
|
||||
const link = page.getByRole('link', { name: /review lyrics/i }).first();
|
||||
// Tenant portals are shared workspaces: other runs' jobs are listed too,
|
||||
// so target THIS run's job by id rather than the first Review link.
|
||||
const link = page.locator(`a[href*="#/${createdJobId}"][href$="/review"]`).first();
|
||||
// waitFor (not instant isVisible) so the client-side job-list fetch has
|
||||
// time to render each iteration; reload + retry if not ready yet.
|
||||
try {
|
||||
|
||||
@@ -581,8 +581,8 @@ test.describe('Admin Job Detail Page', () => {
|
||||
job_id: 'test-job-123',
|
||||
message: 'All outputs deleted successfully',
|
||||
deleted_services: {
|
||||
youtube: { status: 'deleted', video_id: 'xyz789' },
|
||||
dropbox: { status: 'deleted', path: '/Karaoke/NK001 - Test Artist - Test Song' },
|
||||
youtube: { status: 'success', video_id: 'xyz789' },
|
||||
dropbox: { status: 'success', path: '/Karaoke/NK001 - Test Artist - Test Song' },
|
||||
gdrive: { status: 'skipped', reason: 'No Google Drive files found' },
|
||||
},
|
||||
cleared_state_data: ['youtube_url', 'youtube_video_id', 'dropbox_link', 'brand_code'],
|
||||
@@ -653,8 +653,8 @@ test.describe('Admin Job Detail Page', () => {
|
||||
message: 'Some outputs could not be deleted',
|
||||
deleted_services: {
|
||||
youtube: { status: 'error', error: 'Video not found or already deleted' },
|
||||
dropbox: { status: 'deleted', path: '/Karaoke/NK001 - Test Artist - Test Song' },
|
||||
gdrive: { status: 'skipped', reason: 'No Google Drive files found' },
|
||||
dropbox: { status: 'success', path: '/Karaoke/NK001 - Test Artist - Test Song' },
|
||||
gdrive: { status: 'partial', files: { mp4: true, cdg: false } },
|
||||
},
|
||||
cleared_state_data: ['dropbox_link', 'brand_code'],
|
||||
outputs_deleted_at: '2026-01-15T10:00:00Z',
|
||||
@@ -693,6 +693,9 @@ test.describe('Admin Job Detail Page', () => {
|
||||
|
||||
// Should show Dropbox success
|
||||
await expect(page.getByText(/NK001.*Test Artist.*Test Song/)).toBeVisible();
|
||||
|
||||
// A partial Drive delete names the file(s) left behind
|
||||
await expect(page.getByText('Not deleted: cdg')).toBeVisible();
|
||||
});
|
||||
|
||||
test('delete outputs button is disabled when outputs already deleted', async ({ page }) => {
|
||||
|
||||
@@ -4459,6 +4459,8 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
|
||||
status: string
|
||||
message?: string
|
||||
preview_hash?: string
|
||||
/** Seconds of countdown intro prepended to the preview (0 when none). */
|
||||
countdown_padding_seconds?: number
|
||||
}> {
|
||||
const body: Record<string, unknown> = { ...data }
|
||||
if (isDuet !== undefined) {
|
||||
|
||||
@@ -53,7 +53,7 @@ gcloud functions deploy "${FUNCTION_NAME}" \
|
||||
--min-instances=0 \
|
||||
--max-instances=1 \
|
||||
--service-account="gdrive-validator@${PROJECT_ID}.iam.gserviceaccount.com" \
|
||||
--set-env-vars="GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,EMAIL_TO=gen@nomadkaraoke.com,EMAIL_FROM=gen@nomadkaraoke.com,NOTIFY_ON_SUCCESS=true" \
|
||||
--set-env-vars="GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,EMAIL_TO=gen@nomadkaraoke.com,EMAIL_FROM=gen@nomadkaraoke.com,NOTIFY_ON_SUCCESS=false,LOG_EXECUTION_ID=true" \
|
||||
--set-secrets="PUSHBULLET_API_KEY=pushbullet-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest" \
|
||||
--project="${PROJECT_ID}"
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import re
|
||||
import json
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Union
|
||||
import functions_framework
|
||||
import requests
|
||||
@@ -38,6 +39,21 @@ EMAIL_FROM = os.environ.get("EMAIL_FROM", "gen@nomadkaraoke.com")
|
||||
# Set to "false" to only receive notifications when issues are detected
|
||||
NOTIFY_ON_SUCCESS = os.environ.get("NOTIFY_ON_SUCCESS", "true").lower() == "true"
|
||||
|
||||
# A track whose newest file landed in Drive this recently is treated as still
|
||||
# uploading: a job's packaging step uploads MP4, then MP4-720p, then CDG over a
|
||||
# couple of minutes, and the post-job trigger for an earlier job can fire right
|
||||
# in the middle (2026-11-07: NOMAD-1871's check flagged NOMAD-1872 mid-upload).
|
||||
# Gaps for such tracks are held back; the track's own post-job trigger (which
|
||||
# names its brand_code) and the daily run still check it once the upload ends.
|
||||
def _grace_minutes() -> int:
|
||||
try:
|
||||
return int(os.environ.get("IN_FLIGHT_GRACE_MINUTES", "30"))
|
||||
except ValueError:
|
||||
return 30
|
||||
|
||||
|
||||
IN_FLIGHT_GRACE_MINUTES = _grace_minutes()
|
||||
|
||||
# Known gaps configuration - matches the local validate_and_sync.py script
|
||||
# These are HISTORICAL ONLY (pre-generator era, before Dec 2024). Do NOT add new entries.
|
||||
# New gaps are bugs — see docs/GDRIVE-VALIDATOR.md § "Sequence Gap Detected" for fix procedure.
|
||||
@@ -93,7 +109,9 @@ def get_drive_service():
|
||||
return build('drive', 'v3', credentials=credentials)
|
||||
|
||||
|
||||
def list_folder_contents(service, folder_id: str) -> dict[str, list[str]]:
|
||||
def list_folder_contents(
|
||||
service, folder_id: str, created_times: dict[str, str] | None = None
|
||||
) -> dict[str, list[str]]:
|
||||
"""
|
||||
List all files in a Google Drive folder and its subfolders.
|
||||
|
||||
@@ -102,6 +120,9 @@ def list_folder_contents(service, folder_id: str) -> dict[str, list[str]]:
|
||||
- CDG/ (contains .zip files)
|
||||
- MP4/ (contains .mp4 files)
|
||||
- MP4-720p/ (contains .mp4 files)
|
||||
|
||||
If ``created_times`` is given, it is filled with ``{filename: createdTime}``
|
||||
(RFC 3339) so the caller can tell which tracks are still being uploaded.
|
||||
"""
|
||||
results = {}
|
||||
|
||||
@@ -134,12 +155,15 @@ def list_folder_contents(service, folder_id: str) -> dict[str, list[str]]:
|
||||
query = f"'{folder_id_inner}' in parents and trashed=false and mimeType!='application/vnd.google-apps.folder'"
|
||||
response = service.files().list(
|
||||
q=query,
|
||||
fields="nextPageToken, files(name)",
|
||||
fields="nextPageToken, files(name, createdTime)",
|
||||
pageSize=1000,
|
||||
pageToken=page_token
|
||||
).execute()
|
||||
|
||||
files.extend([f['name'] for f in response.get('files', [])])
|
||||
for f in response.get('files', []):
|
||||
files.append(f['name'])
|
||||
if created_times is not None and f.get('createdTime'):
|
||||
created_times[f['name']] = f['createdTime']
|
||||
page_token = response.get('nextPageToken')
|
||||
|
||||
if not page_token:
|
||||
@@ -187,10 +211,39 @@ def get_sequence_number(filename: str) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def validate_files(files_by_folder: dict[str, list[str]]) -> dict:
|
||||
def recently_uploaded_sequences(
|
||||
created_times: dict[str, str],
|
||||
now: datetime | None = None,
|
||||
grace_minutes: int = IN_FLIGHT_GRACE_MINUTES,
|
||||
) -> set[int]:
|
||||
"""Sequence numbers that have any file created within the grace window."""
|
||||
now = now or datetime.now(timezone.utc)
|
||||
cutoff = now - timedelta(minutes=grace_minutes)
|
||||
recent = set()
|
||||
for filename, created in created_times.items():
|
||||
seq = get_sequence_number(filename)
|
||||
if seq is None:
|
||||
continue
|
||||
try:
|
||||
ts = datetime.fromisoformat(created.replace("Z", "+00:00"))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
if ts >= cutoff:
|
||||
recent.add(seq)
|
||||
return recent
|
||||
|
||||
|
||||
def validate_files(
|
||||
files_by_folder: dict[str, list[str]], in_flight: set[int] | None = None
|
||||
) -> dict:
|
||||
"""
|
||||
Validate all files and return a dict of issues found.
|
||||
|
||||
``in_flight`` sequence numbers (tracks still uploading) are not reported
|
||||
as gaps.
|
||||
|
||||
Returns:
|
||||
{
|
||||
'duplicates': {'MP4': {1107: ['file1.mp4', 'file2.mp4']}, ...},
|
||||
@@ -255,7 +308,7 @@ def validate_files(files_by_folder: dict[str, list[str]]) -> dict:
|
||||
min_num = min(sequence_numbers)
|
||||
expected_range = set(range(min_num, global_max + 1))
|
||||
excluded = EXCLUDED_NUMBERS.get(folder_name, set())
|
||||
missing = sorted(expected_range - sequence_numbers - excluded)
|
||||
missing = sorted(expected_range - sequence_numbers - excluded - (in_flight or set()))
|
||||
|
||||
if missing:
|
||||
issues['gaps'][folder_name] = missing
|
||||
@@ -501,7 +554,8 @@ def validate_gdrive(request):
|
||||
service = get_drive_service()
|
||||
|
||||
# List all files
|
||||
files_by_folder = list_folder_contents(service, GDRIVE_FOLDER_ID)
|
||||
created_times: dict[str, str] = {}
|
||||
files_by_folder = list_folder_contents(service, GDRIVE_FOLDER_ID, created_times)
|
||||
|
||||
if not files_by_folder:
|
||||
logger.warning("No folders found in Google Drive")
|
||||
@@ -511,7 +565,10 @@ def validate_gdrive(request):
|
||||
}), 200, {"Content-Type": "application/json"}
|
||||
|
||||
# Validate files
|
||||
issues = validate_files(files_by_folder)
|
||||
in_flight = recently_uploaded_sequences(created_times)
|
||||
if in_flight:
|
||||
logger.info("Holding back gap checks for tracks still uploading: %s", sorted(in_flight))
|
||||
issues = validate_files(files_by_folder, in_flight=in_flight)
|
||||
|
||||
# Targeted same-run completeness for the just-published track.
|
||||
if brand_code:
|
||||
|
||||
@@ -31,6 +31,7 @@ from main import ( # noqa: E402
|
||||
expand_gaps,
|
||||
has_issues,
|
||||
check_track_completeness,
|
||||
recently_uploaded_sequences,
|
||||
)
|
||||
|
||||
|
||||
@@ -333,3 +334,35 @@ class TestHasIssues:
|
||||
|
||||
def test_has_gaps(self):
|
||||
assert has_issues({"duplicates": {}, "invalid_filenames": {}, "gaps": {"MP4": [3]}})
|
||||
|
||||
|
||||
class TestInFlightUploads:
|
||||
"""2026-11-07: NOMAD-1871's post-job check ran while NOMAD-1872 was mid-upload
|
||||
(MP4 done, 720p + CDG not yet) and emailed a false sequence-gap alert."""
|
||||
|
||||
NOW = __import__("datetime").datetime(2026, 11, 7, 12, 24, 47, tzinfo=__import__("datetime").timezone.utc)
|
||||
|
||||
def _files(self):
|
||||
return {
|
||||
"MP4": [make_mp4(i) for i in range(100, 106)],
|
||||
"MP4-720p": [make_mp4(i) for i in range(100, 105)],
|
||||
"CDG": [make_cdg(i) for i in range(100, 105)],
|
||||
}
|
||||
|
||||
def test_track_still_uploading_is_not_a_gap(self):
|
||||
created = {make_mp4(105): "2026-11-07T12:24:30.000Z", make_mp4(104): "2026-11-06T09:00:00.000Z"}
|
||||
in_flight = recently_uploaded_sequences(created, now=self.NOW, grace_minutes=30)
|
||||
assert in_flight == {105}
|
||||
issues = validate_files(self._files(), in_flight=in_flight)
|
||||
assert issues["gaps"] == {}
|
||||
|
||||
def test_old_track_missing_is_still_a_gap(self):
|
||||
created = {make_mp4(105): "2026-11-07T10:00:00.000Z"}
|
||||
in_flight = recently_uploaded_sequences(created, now=self.NOW, grace_minutes=30)
|
||||
assert in_flight == set()
|
||||
issues = validate_files(self._files(), in_flight=in_flight)
|
||||
assert issues["gaps"] == {"MP4-720p": [105], "CDG": [105]}
|
||||
|
||||
def test_bad_timestamps_and_non_track_files_ignored(self):
|
||||
created = {"desktop.ini": "2026-11-07T12:24:00Z", make_mp4(105): "garbage"}
|
||||
assert recently_uploaded_sequences(created, now=self.NOW) == set()
|
||||
@@ -14,6 +14,7 @@ This module is invoked from main.py when RUNNER_MODE=ephemeral.
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
@@ -768,33 +769,62 @@ def list_queued_self_hosted_jobs(pat: str) -> list[dict]:
|
||||
"""
|
||||
jobs: list[dict] = []
|
||||
for repo in list_org_repos(pat):
|
||||
try:
|
||||
run_ids: set[int] = set()
|
||||
for status in ("queued", "in_progress"):
|
||||
runs = _github_request(
|
||||
"GET",
|
||||
f"/repos/{GITHUB_ORG}/{repo}/actions/runs?status={status}&per_page=50",
|
||||
pat,
|
||||
)
|
||||
if isinstance(runs, dict):
|
||||
run_ids.update(r["id"] for r in runs.get("workflow_runs", []))
|
||||
for run_id in sorted(run_ids):
|
||||
run_jobs = _github_request(
|
||||
"GET",
|
||||
f"/repos/{GITHUB_ORG}/{repo}/actions/runs/{run_id}/jobs?filter=latest&per_page=100",
|
||||
pat,
|
||||
)
|
||||
if not isinstance(run_jobs, dict):
|
||||
# A one-off network blip (GitHub closing the connection, a timeout, a
|
||||
# 5xx) gets one retry before it pages: a single dropped connection is
|
||||
# not the safety net failing, but a repo that fails twice in a row is.
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
jobs.extend(_queued_self_hosted_jobs_in_repo(repo, pat))
|
||||
break
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if attempt == 1 and _is_transient_github_error(exc):
|
||||
print(f"Retrying {repo} in stalled-job scan after transient error: {exc!r}", flush=True)
|
||||
continue
|
||||
for job in run_jobs.get("jobs", []):
|
||||
labels = job.get("labels", [])
|
||||
if job.get("status") == "queued" and "self-hosted" in labels and can_serve(labels):
|
||||
jobs.append({**job, "repo": repo})
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_log_error(f"Skipping {repo} in stalled-job scan: {exc!r}")
|
||||
_log_error(f"Skipping {repo} in stalled-job scan: {exc!r}")
|
||||
break
|
||||
return jobs
|
||||
|
||||
|
||||
def _queued_self_hosted_jobs_in_repo(repo: str, pat: str) -> list[dict]:
|
||||
"""Queued jobs in one repo that one of our runner families can serve."""
|
||||
jobs: list[dict] = []
|
||||
run_ids: set[int] = set()
|
||||
for status in ("queued", "in_progress"):
|
||||
runs = _github_request(
|
||||
"GET",
|
||||
f"/repos/{GITHUB_ORG}/{repo}/actions/runs?status={status}&per_page=50",
|
||||
pat,
|
||||
)
|
||||
if isinstance(runs, dict):
|
||||
run_ids.update(r["id"] for r in runs.get("workflow_runs", []))
|
||||
for run_id in sorted(run_ids):
|
||||
run_jobs = _github_request(
|
||||
"GET",
|
||||
f"/repos/{GITHUB_ORG}/{repo}/actions/runs/{run_id}/jobs?filter=latest&per_page=100",
|
||||
pat,
|
||||
)
|
||||
if not isinstance(run_jobs, dict):
|
||||
continue
|
||||
for job in run_jobs.get("jobs", []):
|
||||
labels = job.get("labels", [])
|
||||
if job.get("status") == "queued" and "self-hosted" in labels and can_serve(labels):
|
||||
jobs.append({**job, "repo": repo})
|
||||
return jobs
|
||||
|
||||
|
||||
def _is_transient_github_error(exc: BaseException) -> bool:
|
||||
"""True for network-level failures and GitHub 5xx/429 worth one retry.
|
||||
|
||||
Auth/permission/not-found errors (other 4xx) are not transient: retrying
|
||||
won't help, so they page straight away.
|
||||
"""
|
||||
if isinstance(exc, urllib.error.HTTPError):
|
||||
return exc.code == 429 or exc.code >= 500
|
||||
# URLError wraps DNS/connect failures; http.client.RemoteDisconnected is a
|
||||
# ConnectionResetError; socket timeouts are TimeoutError (both OSError).
|
||||
return isinstance(exc, (urllib.error.URLError, http.client.HTTPException, OSError))
|
||||
|
||||
|
||||
def _family_of_runner_name(name: str) -> str | None:
|
||||
"""``gha-gpu-windows-abc123`` → ``gpu-windows``; None if not ours."""
|
||||
if not name.startswith("gha-") or "-" not in name[len("gha-"):]:
|
||||
|
||||
@@ -736,6 +736,73 @@ class TestListQueuedSelfHostedJobs:
|
||||
job_calls = [c for c in req.call_args_list if "/runs/11/jobs" in c.args[1]]
|
||||
assert len(job_calls) == 1
|
||||
|
||||
@staticmethod
|
||||
def _scan_with_runs_failures(ep, failures):
|
||||
"""Scan one repo whose first runs-list calls raise ``failures`` in order."""
|
||||
pending = list(failures)
|
||||
|
||||
def fake_request(method, path, pat, body=None):
|
||||
if path.startswith("/orgs/test-org/repos"):
|
||||
return [{"name": "karaoke-gen"}]
|
||||
if "/actions/runs?status=queued" in path and pending:
|
||||
raise pending.pop(0)
|
||||
if "/actions/runs?status=queued" in path:
|
||||
return {"workflow_runs": [{"id": 11}]}
|
||||
if "/actions/runs?status=in_progress" in path:
|
||||
return {"workflow_runs": []}
|
||||
if "/actions/runs/11/jobs" in path:
|
||||
return {"jobs": [{"id": 1, "status": "queued", "labels": BUILD_LABELS}]}
|
||||
raise AssertionError(path)
|
||||
|
||||
with patch.object(ep, "_github_request", side_effect=fake_request) as req:
|
||||
jobs = ep.list_queued_self_hosted_jobs("ghp_test")
|
||||
return jobs, req
|
||||
|
||||
def test_one_dropped_connection_is_retried_without_paging(self, capsys):
|
||||
import http.client
|
||||
|
||||
ep = _fresh_module()
|
||||
jobs, _ = self._scan_with_runs_failures(
|
||||
ep, [http.client.RemoteDisconnected("Remote end closed connection without response")]
|
||||
)
|
||||
|
||||
assert [(j["repo"], j["id"]) for j in jobs] == [("karaoke-gen", 1)]
|
||||
out = capsys.readouterr().out
|
||||
assert _error_messages(out) == []
|
||||
assert "Retrying karaoke-gen in stalled-job scan" in out
|
||||
|
||||
def test_transient_error_twice_in_a_row_pages(self, capsys):
|
||||
import http.client
|
||||
|
||||
ep = _fresh_module()
|
||||
jobs, _ = self._scan_with_runs_failures(
|
||||
ep, [http.client.RemoteDisconnected("closed"), TimeoutError("timed out")]
|
||||
)
|
||||
|
||||
assert jobs == []
|
||||
assert any("Skipping karaoke-gen in stalled-job scan" in m for m in _error_messages(capsys.readouterr().out))
|
||||
|
||||
def test_auth_error_pages_without_retry(self, capsys):
|
||||
import urllib.error
|
||||
|
||||
ep = _fresh_module()
|
||||
forbidden = urllib.error.HTTPError("https://api.github.com/x", 403, "Forbidden", {}, None)
|
||||
jobs, req = self._scan_with_runs_failures(ep, [forbidden])
|
||||
|
||||
assert jobs == []
|
||||
assert any("Skipping karaoke-gen in stalled-job scan" in m for m in _error_messages(capsys.readouterr().out))
|
||||
runs_calls = [c for c in req.call_args_list if "status=queued" in c.args[1]]
|
||||
assert len(runs_calls) == 1
|
||||
|
||||
def test_github_5xx_is_transient(self):
|
||||
import urllib.error
|
||||
|
||||
ep = _fresh_module()
|
||||
assert ep._is_transient_github_error(urllib.error.HTTPError("u", 502, "Bad Gateway", {}, None))
|
||||
assert ep._is_transient_github_error(urllib.error.HTTPError("u", 429, "Too Many", {}, None))
|
||||
assert not ep._is_transient_github_error(urllib.error.HTTPError("u", 404, "Not Found", {}, None))
|
||||
assert not ep._is_transient_github_error(RuntimeError("403 no access"))
|
||||
|
||||
|
||||
class TestCleanupTriggersRedispatch:
|
||||
def test_redispatch_sees_only_surviving_vms(self):
|
||||
|
||||
@@ -504,6 +504,11 @@ class KaraokeFinalise:
|
||||
self.logger.info(f"Successfully deleted YouTube video with ID: {video_id}")
|
||||
return True
|
||||
except Exception as e:
|
||||
# 404 = the video is already gone (e.g. removed in YouTube Studio).
|
||||
# The goal of the delete is met, so report success, not failure.
|
||||
if getattr(getattr(e, "resp", None), "status", None) == 404:
|
||||
self.logger.warning(f"YouTube video {video_id} not found; treating as already deleted")
|
||||
return True
|
||||
self.logger.error(f"Failed to delete YouTube video with ID {video_id}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ from karaoke_gen.lyrics_transcriber.types import (
|
||||
LyricsData
|
||||
)
|
||||
from karaoke_gen.lyrics_transcriber.correction.corrector import LyricsCorrector
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from karaoke_gen.lyrics_transcriber.lyrics.user_input_provider import UserInputProvider
|
||||
from karaoke_gen.lyrics_transcriber.lyrics.base_lyrics_provider import LyricsProviderConfig, BaseLyricsProvider
|
||||
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
|
||||
@@ -536,8 +537,27 @@ class CorrectionOperations:
|
||||
correction_result, updated_data
|
||||
)
|
||||
|
||||
# Generate a unique hash for this preview
|
||||
# Apply the same countdown intro the final render adds (CountdownProcessor
|
||||
# in the encoding worker): songs whose vocals start within 3s get the
|
||||
# lyrics shifted +3s and a "3... 2... 1..." line. Without this the preview
|
||||
# starts singing immediately while the final video has a cue, so reviewers
|
||||
# think the countdown is missing. Audio padding is done here for the full
|
||||
# render; ass_only callers get countdown_padding_seconds and must pad the
|
||||
# audio they hand to the encoder themselves.
|
||||
countdown_processor = CountdownProcessor(cache_dir=output_config.cache_dir, logger=logger)
|
||||
temp_correction, countdown_padding_seconds = countdown_processor.add_countdown_to_lyrics_if_needed(
|
||||
temp_correction
|
||||
)
|
||||
if countdown_padding_seconds:
|
||||
if not ass_only:
|
||||
audio_filepath = countdown_processor.create_padded_audio_only(audio_filepath)
|
||||
logger.info(f"Preview: added {countdown_padding_seconds}s countdown intro")
|
||||
|
||||
# Generate a unique hash for this preview. Salted when a countdown is
|
||||
# applied so previews cached before countdown support aren't reused.
|
||||
preview_data = json.dumps(updated_data, sort_keys=True).encode("utf-8")
|
||||
if countdown_padding_seconds:
|
||||
preview_data += b"|countdown-v1"
|
||||
preview_hash = hashlib.md5(preview_data).hexdigest()[:12]
|
||||
|
||||
# Propagate duet flag from the outer config OR the request body.
|
||||
@@ -589,6 +609,7 @@ class CorrectionOperations:
|
||||
"status": "success",
|
||||
"preview_hash": preview_hash,
|
||||
"ass_path": preview_outputs.ass,
|
||||
"countdown_padding_seconds": countdown_padding_seconds,
|
||||
}
|
||||
|
||||
if not preview_outputs.video:
|
||||
@@ -600,4 +621,5 @@ class CorrectionOperations:
|
||||
"status": "success",
|
||||
"preview_hash": preview_hash,
|
||||
"video_path": preview_outputs.video,
|
||||
"countdown_padding_seconds": countdown_padding_seconds,
|
||||
}
|
||||
@@ -90,6 +90,54 @@ class CountdownProcessor:
|
||||
|
||||
return modified_result, padded_audio_path, True, self.COUNTDOWN_PADDING_SECONDS
|
||||
|
||||
@classmethod
|
||||
def padding_for_segments_data(cls, segments: Optional[List[dict]]) -> float:
|
||||
"""
|
||||
Countdown padding (seconds) a render of these serialized segments gets.
|
||||
|
||||
Same rule as ``process``/``add_countdown_to_lyrics_if_needed`` but on the
|
||||
plain ``corrected_segments`` dicts a review client sends, so an API can
|
||||
tell the client how far the preview's timeline is shifted without
|
||||
rebuilding a CorrectionResult. A countdown that is already present still
|
||||
means a shifted timeline (and padded audio). 0.0 if no countdown applies.
|
||||
"""
|
||||
if not segments:
|
||||
return 0.0
|
||||
if (segments[0] or {}).get("text") == cls.COUNTDOWN_TEXT:
|
||||
return cls.COUNTDOWN_PADDING_SECONDS
|
||||
for segment in segments:
|
||||
words = (segment or {}).get("words") or []
|
||||
if words:
|
||||
try:
|
||||
first_start = float(words[0].get("start_time"))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
return cls.COUNTDOWN_PADDING_SECONDS if first_start < cls.COUNTDOWN_THRESHOLD_SECONDS else 0.0
|
||||
return 0.0
|
||||
|
||||
def add_countdown_to_lyrics_if_needed(
|
||||
self, correction_result: CorrectionResult
|
||||
) -> Tuple[CorrectionResult, float]:
|
||||
"""
|
||||
Lyrics-only half of ``process``: shift timings and add the countdown
|
||||
segment if the song needs one, without touching any audio.
|
||||
|
||||
Used by the review preview, which must match the final render but pads
|
||||
its audio separately (or has the encoder use pre-padded audio).
|
||||
Already-countdown-processed results are returned unchanged, but still
|
||||
report the padding: their timings are already shifted, so the audio
|
||||
must be padded to match.
|
||||
|
||||
Returns:
|
||||
(possibly modified CorrectionResult, padding seconds the caller must
|
||||
prepend to the audio — 0.0 when the song has no countdown intro)
|
||||
"""
|
||||
if self.has_countdown(correction_result):
|
||||
return correction_result, self.COUNTDOWN_PADDING_SECONDS
|
||||
if not self._needs_countdown(correction_result):
|
||||
return correction_result, 0.0
|
||||
return self._add_countdown_to_result(correction_result), self.COUNTDOWN_PADDING_SECONDS
|
||||
|
||||
def _needs_countdown(self, correction_result: CorrectionResult) -> bool:
|
||||
"""
|
||||
Check if the song needs a countdown intro.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import logging
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import List, Optional
|
||||
from typing import Callable, List, Optional
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.types import LyricsSegment, Word
|
||||
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
|
||||
@@ -257,6 +257,67 @@ class SegmentResizer:
|
||||
self._log_output_segments(resized_segments)
|
||||
return resized_segments
|
||||
|
||||
# Punctuation that ends a phrase: the preferred place to break an over-wide line
|
||||
_PHRASE_END = (",", ".", ";", ":", "!", "?", ")", "—", "-")
|
||||
|
||||
def split_to_width(
|
||||
self,
|
||||
segments: List[LyricsSegment],
|
||||
measure: Callable[[str], float],
|
||||
max_width: float,
|
||||
) -> List[LyricsSegment]:
|
||||
"""Split any segment whose rendered width exceeds ``max_width`` pixels.
|
||||
|
||||
``max_line_length`` is a character budget, which wide-glyph lines can beat:
|
||||
"Mm- mm- mm, mm- mm- mm" is short in characters but wider than the frame.
|
||||
libass then wraps the line itself and the second half lands on the row
|
||||
below, drawing over that row's lyrics. ``measure`` returns a line's pixel
|
||||
width as the renderer will draw it; lines that fit pass through unchanged.
|
||||
|
||||
A single word too wide for the frame can't be split and is kept as is.
|
||||
"""
|
||||
out: List[LyricsSegment] = []
|
||||
for segment in segments:
|
||||
out.extend(self._split_segment_to_width(segment, measure, max_width))
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _words_text(words: List[Word]) -> str:
|
||||
return " ".join(w.text.replace("\n", "").strip() for w in words)
|
||||
|
||||
def _split_segment_to_width(
|
||||
self, segment: LyricsSegment, measure: Callable[[str], float], max_width: float
|
||||
) -> List[LyricsSegment]:
|
||||
words = segment.words
|
||||
if len(words) < 2 or measure(self._words_text(words)) <= max_width:
|
||||
return [segment]
|
||||
|
||||
# Pick the break: prefer one where both halves fit, then a phrase-ending
|
||||
# word before the break, then the most balanced halves.
|
||||
best_key, best_i = None, 1
|
||||
for i in range(1, len(words)):
|
||||
left = measure(self._words_text(words[:i]))
|
||||
right = measure(self._words_text(words[i:]))
|
||||
fits = left <= max_width and right <= max_width
|
||||
phrase_break = words[i - 1].text.strip().endswith(self._PHRASE_END)
|
||||
key = (not fits, not phrase_break, abs(left - right))
|
||||
if best_key is None or key < best_key:
|
||||
best_key, best_i = key, i
|
||||
|
||||
self.logger.warning(
|
||||
f"Line too wide for the frame ({measure(self._words_text(words)):.0f}px > {max_width:.0f}px), "
|
||||
f"splitting at word {best_i} of {len(words)}"
|
||||
)
|
||||
pieces = []
|
||||
for part in (words[:best_i], words[best_i:]):
|
||||
piece = self._create_segment_from_words(self._words_text(part), part, singer=segment.singer)
|
||||
pieces.extend(self._split_segment_to_width(piece, measure, max_width))
|
||||
if segment.translation:
|
||||
shares = split_text_proportionally(segment.translation, [self._display_width(p.text) for p in pieces])
|
||||
for piece, share in zip(pieces, shares):
|
||||
piece.translation = share or None
|
||||
return pieces
|
||||
|
||||
def _clean_text(self, text: str) -> str:
|
||||
"""Clean text by removing newlines and extra whitespace.
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ from karaoke_gen.lyrics_transcriber.output.ass.section_detector import SectionDe
|
||||
from karaoke_gen.lyrics_transcriber.output.ass.config import ScreenConfig, chord_layout, translation_layout
|
||||
from karaoke_gen.lyrics_transcriber.output.ass.chords import ChordChange, assign_chords_to_segments, clean_chords
|
||||
from karaoke_gen.lyrics_transcriber.output.ass.event import Event
|
||||
from karaoke_gen.lyrics_transcriber.output.segment_resizer import SegmentResizer
|
||||
|
||||
|
||||
# Translation rows render at this fraction of the lyric colour's opacity, so they read as
|
||||
@@ -29,6 +30,9 @@ CHORD_BOX_RIGHT = 0.955
|
||||
CHORD_BOX_TOP = 0.045
|
||||
CHORD_BOX_SIZE_RATIO = 1.25 # box chord size / chord-row size
|
||||
CHORD_BOX_NEXT_RATIO = 0.55 # "next" chord size / current chord size
|
||||
# A lyric line may use at most this fraction of the frame width; wider lines are split
|
||||
# (libass would otherwise wrap them into the row below). Leaves room for the outline.
|
||||
MAX_LINE_WIDTH_FRACTION = 0.94
|
||||
|
||||
|
||||
def _ass_colour(color) -> str:
|
||||
@@ -180,6 +184,7 @@ class SubtitlesGenerator:
|
||||
output_path = self._get_output_path(f"{output_prefix} (Karaoke)", "ass")
|
||||
|
||||
try:
|
||||
segments = self._fit_segments_to_width(segments)
|
||||
self.logger.debug(f"Processing {len(segments)} segments")
|
||||
song_duration = self._get_audio_duration(audio_filepath, segments)
|
||||
|
||||
@@ -207,6 +212,36 @@ class SubtitlesGenerator:
|
||||
self.logger.error(f"Failed to generate ASS file: {str(e)}", exc_info=True)
|
||||
raise
|
||||
|
||||
def _fit_segments_to_width(self, segments: List[LyricsSegment]) -> List[LyricsSegment]:
|
||||
"""Split lines that would render wider than the frame.
|
||||
|
||||
Lines are sized by character count upstream, but glyph widths vary a lot
|
||||
("mm- mm- mm" is far wider per character than "it is in"). A line wider
|
||||
than the frame is wrapped by libass onto a second line one row lower,
|
||||
which draws over the next row's lyrics (NOMAD-1779). Measure each line in
|
||||
the real style font, the way libass sizes it, and split the ones that
|
||||
don't fit at a word boundary.
|
||||
"""
|
||||
from karaoke_gen.lyrics_transcriber.output.ass.style import build_karaoke_styles
|
||||
|
||||
karaoke_styles = self.styles.get("karaoke", {})
|
||||
if not segments or not karaoke_styles.get("font"):
|
||||
return segments
|
||||
style = build_karaoke_styles(karaoke_styles, singers=[1], solo=True)[0]
|
||||
style.Fontsize = self.font_size
|
||||
if not style.Fontpath or not os.path.exists(style.Fontpath):
|
||||
# Measuring with PIL's default font would under-measure; leave lines as is.
|
||||
self.logger.warning(f"Font {style.Fontpath!r} not found; skipping line width check")
|
||||
return segments
|
||||
|
||||
measurer = LyricsLine(segment=segments[0], screen_config=self.config, logger=self.logger)
|
||||
|
||||
def measure(text: str) -> float:
|
||||
return measurer._measure_text(measurer._apply_case_transform(text), style)[0]
|
||||
|
||||
max_width = self.config.video_width * MAX_LINE_WIDTH_FRACTION
|
||||
return SegmentResizer(logger=self.logger).split_to_width(segments, measure, max_width)
|
||||
|
||||
def _translation_config(self, base: ScreenConfig) -> ScreenConfig:
|
||||
"""Copy of ``base`` with taller line slots that fit a translation row under each line."""
|
||||
layout = translation_layout(self.font_size, base.line_height, self.styles.get("karaoke", {}))
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.294.2"
|
||||
version = "0.297.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -22,6 +22,11 @@ def get_job(job_id: str) -> dict | None:
|
||||
|
||||
if doc.exists:
|
||||
return doc.to_dict()
|
||||
# Deleted jobs are archived (doc + archived_logs) instead of lost.
|
||||
archived = db.collection('jobs_archive').document(job_id).get()
|
||||
if archived.exists:
|
||||
print(f"(job {job_id} was deleted; showing jobs_archive copy)", file=sys.stderr)
|
||||
return archived.to_dict()
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
"""The review preview gets the same countdown intro as the final render.
|
||||
|
||||
Before this, a song whose vocals start within 3s showed a countdown in the
|
||||
final video (CountdownProcessor in the encoding worker) but none in the review
|
||||
preview, so reviewers asked for a countdown that was already coming.
|
||||
"""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from tests.unit.lyrics_transcriber.correction.test_operations_multisinger import _empty_correction_result
|
||||
|
||||
|
||||
def _updated_data(first_word_start: float) -> dict:
|
||||
return {
|
||||
"corrections": [],
|
||||
"corrected_segments": [{
|
||||
"id": "s1", "text": "hello", "start_time": first_word_start, "end_time": first_word_start + 0.5,
|
||||
"words": [{"id": "w1", "text": "hello", "start_time": first_word_start,
|
||||
"end_time": first_word_start + 0.5}],
|
||||
}],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def run_preview(monkeypatch, tmp_path):
|
||||
captured = {}
|
||||
|
||||
class _StubGenerator:
|
||||
def __init__(self, config, preview_mode=False, **kwargs):
|
||||
pass
|
||||
|
||||
def generate_outputs(self, transcription_corrected, audio_filepath, **kwargs):
|
||||
captured["correction"] = transcription_corrected
|
||||
captured["audio"] = audio_filepath
|
||||
out = MagicMock()
|
||||
out.video = str(tmp_path / "preview.mp4")
|
||||
out.ass = str(tmp_path / "preview.ass")
|
||||
return out
|
||||
|
||||
monkeypatch.setattr(
|
||||
"karaoke_gen.lyrics_transcriber.correction.operations.OutputGenerator", _StubGenerator
|
||||
)
|
||||
padded = str(tmp_path / "audio_padded.flac")
|
||||
pad_calls = []
|
||||
monkeypatch.setattr(
|
||||
CountdownProcessor, "create_padded_audio_only",
|
||||
lambda self, path: pad_calls.append(path) or padded,
|
||||
)
|
||||
(tmp_path / "previews").mkdir(exist_ok=True)
|
||||
cfg = OutputConfig(output_styles_json="", output_dir=str(tmp_path), cache_dir=str(tmp_path))
|
||||
|
||||
def _run(updated_data, ass_only):
|
||||
result = CorrectionOperations.generate_preview_video(
|
||||
correction_result=_empty_correction_result(),
|
||||
updated_data=updated_data,
|
||||
output_config=cfg,
|
||||
audio_filepath=str(tmp_path / "song.flac"),
|
||||
logger=MagicMock(),
|
||||
ass_only=ass_only,
|
||||
)
|
||||
return result, captured, pad_calls, padded
|
||||
|
||||
return _run
|
||||
|
||||
|
||||
def test_early_vocals_get_countdown_in_ass_only_preview(run_preview):
|
||||
result, captured, pad_calls, _ = run_preview(_updated_data(0.4), ass_only=True)
|
||||
assert result["countdown_padding_seconds"] == 3.0
|
||||
segs = captured["correction"].corrected_segments
|
||||
assert segs[0].text == CountdownProcessor.COUNTDOWN_TEXT
|
||||
assert segs[1].words[0].start_time == pytest.approx(3.4)
|
||||
# ass_only callers pad the encoder's audio themselves.
|
||||
assert pad_calls == []
|
||||
|
||||
|
||||
def test_full_local_render_pads_audio(run_preview):
|
||||
result, captured, pad_calls, padded = run_preview(_updated_data(0.4), ass_only=False)
|
||||
assert result["countdown_padding_seconds"] == 3.0
|
||||
assert len(pad_calls) == 1
|
||||
assert captured["audio"] == padded
|
||||
|
||||
|
||||
def test_late_vocals_untouched(run_preview):
|
||||
result, captured, pad_calls, _ = run_preview(_updated_data(10.0), ass_only=False)
|
||||
assert result["countdown_padding_seconds"] == 0.0
|
||||
assert captured["correction"].corrected_segments[0].text == "hello"
|
||||
assert pad_calls == []
|
||||
assert captured["audio"].endswith("song.flac")
|
||||
|
||||
|
||||
def test_countdown_previews_get_a_fresh_hash(run_preview):
|
||||
"""Previews cached before countdown support must not be served again."""
|
||||
import hashlib, json
|
||||
data = _updated_data(0.4)
|
||||
result, *_ = run_preview(data, ass_only=True)
|
||||
legacy = hashlib.md5(json.dumps(data, sort_keys=True).encode("utf-8")).hexdigest()[:12]
|
||||
assert result["preview_hash"] != legacy
|
||||
|
||||
late = _updated_data(10.0)
|
||||
result_late, *_ = run_preview(late, ass_only=True)
|
||||
legacy_late = hashlib.md5(json.dumps(late, sort_keys=True).encode("utf-8")).hexdigest()[:12]
|
||||
assert result_late["preview_hash"] == legacy_late
|
||||
|
||||
|
||||
def test_submitted_countdown_is_not_doubled_but_audio_is_padded(run_preview):
|
||||
"""Corrections that already carry the countdown (timings shifted) must not be
|
||||
shifted again, but the audio must still be padded or lyrics run 3s early."""
|
||||
data = {
|
||||
"corrections": [],
|
||||
"corrected_segments": [
|
||||
{"id": "c", "text": CountdownProcessor.COUNTDOWN_TEXT, "start_time": 0.1, "end_time": 2.9,
|
||||
"words": [{"id": "cw", "text": CountdownProcessor.COUNTDOWN_TEXT, "start_time": 0.1, "end_time": 2.9}]},
|
||||
{"id": "s1", "text": "hello", "start_time": 3.4, "end_time": 3.9,
|
||||
"words": [{"id": "w1", "text": "hello", "start_time": 3.4, "end_time": 3.9}]},
|
||||
],
|
||||
}
|
||||
result, captured, pad_calls, padded = run_preview(data, ass_only=False)
|
||||
assert result["countdown_padding_seconds"] == 3.0
|
||||
segs = captured["correction"].corrected_segments
|
||||
assert [s.text for s in segs] == [CountdownProcessor.COUNTDOWN_TEXT, "hello"]
|
||||
assert segs[1].words[0].start_time == pytest.approx(3.4)
|
||||
assert captured["audio"] == padded
|
||||
@@ -0,0 +1,92 @@
|
||||
"""CountdownProcessor helpers used by the review preview.
|
||||
|
||||
The review preview must show the same countdown intro the final render adds
|
||||
(CountdownProcessor.process in the encoding worker): a song whose vocals start
|
||||
within 3s gets lyrics shifted +3s and a "3... 2... 1..." line. These helpers
|
||||
split that into a lyrics-only step and a dict-level offset check.
|
||||
"""
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult, LyricsSegment, Word
|
||||
|
||||
|
||||
def _result(first_word_start: float) -> CorrectionResult:
|
||||
word = Word(id="w1", text="hello", start_time=first_word_start, end_time=first_word_start + 0.5)
|
||||
seg = LyricsSegment(id="s1", text="hello", words=[word], start_time=first_word_start,
|
||||
end_time=first_word_start + 0.5)
|
||||
return CorrectionResult(
|
||||
original_segments=[seg], corrected_segments=[seg], corrections=[], corrections_made=0,
|
||||
confidence=1.0, reference_lyrics={}, anchor_sequences=[], gap_sequences=[],
|
||||
resized_segments=[], metadata={}, correction_steps=[], word_id_map={}, segment_id_map={},
|
||||
)
|
||||
|
||||
|
||||
class TestPaddingForSegmentsData:
|
||||
def test_early_vocals_need_padding(self):
|
||||
segs = [{"text": "hi", "words": [{"text": "hi", "start_time": 0.5}]}]
|
||||
assert CountdownProcessor.padding_for_segments_data(segs) == 3.0
|
||||
|
||||
def test_late_vocals_need_none(self):
|
||||
segs = [{"text": "hi", "words": [{"text": "hi", "start_time": 12.0}]}]
|
||||
assert CountdownProcessor.padding_for_segments_data(segs) == 0.0
|
||||
|
||||
def test_threshold_is_exclusive(self):
|
||||
segs = [{"text": "hi", "words": [{"text": "hi", "start_time": 3.0}]}]
|
||||
assert CountdownProcessor.padding_for_segments_data(segs) == 0.0
|
||||
|
||||
def test_skips_wordless_segments(self):
|
||||
segs = [{"text": "", "words": []}, {"text": "hi", "words": [{"text": "hi", "start_time": 1.0}]}]
|
||||
assert CountdownProcessor.padding_for_segments_data(segs) == 3.0
|
||||
|
||||
def test_already_counted_down_still_reports_offset(self):
|
||||
"""Timings are already shifted, so the timeline offset is still 3s."""
|
||||
segs = [{"text": CountdownProcessor.COUNTDOWN_TEXT,
|
||||
"words": [{"text": CountdownProcessor.COUNTDOWN_TEXT, "start_time": 0.1}]},
|
||||
{"text": "hi", "words": [{"text": "hi", "start_time": 3.4}]}]
|
||||
assert CountdownProcessor.padding_for_segments_data(segs) == 3.0
|
||||
|
||||
def test_empty_or_malformed(self):
|
||||
assert CountdownProcessor.padding_for_segments_data(None) == 0.0
|
||||
assert CountdownProcessor.padding_for_segments_data([]) == 0.0
|
||||
assert CountdownProcessor.padding_for_segments_data(
|
||||
[{"text": "x", "words": [{"text": "x", "start_time": None}]}]) == 0.0
|
||||
|
||||
|
||||
class TestAddCountdownToLyricsIfNeeded:
|
||||
def test_shifts_and_prepends_countdown(self, tmp_path):
|
||||
cp = CountdownProcessor(cache_dir=str(tmp_path))
|
||||
original = _result(0.4)
|
||||
result, padding = cp.add_countdown_to_lyrics_if_needed(original)
|
||||
assert padding == 3.0
|
||||
assert result.corrected_segments[0].text == CountdownProcessor.COUNTDOWN_TEXT
|
||||
assert result.corrected_segments[1].words[0].start_time == 3.4
|
||||
# The input is not mutated.
|
||||
assert original.corrected_segments[0].words[0].start_time == 0.4
|
||||
|
||||
def test_late_vocals_unchanged(self, tmp_path):
|
||||
cp = CountdownProcessor(cache_dir=str(tmp_path))
|
||||
original = _result(8.0)
|
||||
result, padding = cp.add_countdown_to_lyrics_if_needed(original)
|
||||
assert padding == 0.0
|
||||
assert result is original
|
||||
|
||||
def test_idempotent_but_still_needs_padded_audio(self, tmp_path):
|
||||
"""A result that already has the countdown isn't shifted again, but its
|
||||
audio must still be padded to match the shifted timings."""
|
||||
cp = CountdownProcessor(cache_dir=str(tmp_path))
|
||||
once, _ = cp.add_countdown_to_lyrics_if_needed(_result(0.4))
|
||||
twice, padding = cp.add_countdown_to_lyrics_if_needed(once)
|
||||
assert padding == 3.0
|
||||
assert twice is once
|
||||
assert twice.corrected_segments[1].words[0].start_time == 3.4
|
||||
|
||||
def test_agrees_with_dict_helper(self, tmp_path):
|
||||
cp = CountdownProcessor(cache_dir=str(tmp_path))
|
||||
for start in (0.0, 2.99, 3.0, 7.5):
|
||||
r = _result(start)
|
||||
out, padding = cp.add_countdown_to_lyrics_if_needed(r)
|
||||
segs = [s.to_dict() for s in r.corrected_segments]
|
||||
assert CountdownProcessor.padding_for_segments_data(segs) == padding
|
||||
# ...and on the already-processed result too.
|
||||
_, again = cp.add_countdown_to_lyrics_if_needed(out)
|
||||
assert CountdownProcessor.padding_for_segments_data(
|
||||
[s.to_dict() for s in out.corrected_segments]) == again
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Lines too wide for the frame must be split before libass wraps them.
|
||||
|
||||
Bug (NOMAD-1779, job 58555663): the character-count limit (``max_line_length``) let
|
||||
through lines like "Mm- mm- mm, mm- call me when you're ..." that are short in
|
||||
characters but made of wide glyphs. At 4K they measured ~3890px on a 3840px frame,
|
||||
so libass wrapped each one onto a second physical line, one row lower, on top of the
|
||||
next lyric line: two lines of lyrics drawn over each other.
|
||||
|
||||
``SubtitlesGenerator`` now measures every line in the real style font (scaled as libass
|
||||
scales it) and splits any line wider than ``MAX_LINE_WIDTH_FRACTION`` of the frame.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.output.segment_resizer import SegmentResizer
|
||||
from karaoke_gen.lyrics_transcriber.output.subtitles import MAX_LINE_WIDTH_FRACTION
|
||||
from karaoke_gen.lyrics_transcriber.types import LyricsSegment, Word
|
||||
|
||||
from .ass_render_harness import (
|
||||
FONT_SIZE,
|
||||
WIDTH,
|
||||
ffmpeg_has_libass,
|
||||
generate_ass,
|
||||
lyric_lines,
|
||||
make_segment,
|
||||
render_frames,
|
||||
)
|
||||
|
||||
|
||||
def _seg(words, translation=None):
|
||||
ws = [Word(id=f"w{i}", text=t, start_time=i * 1.0, end_time=i * 1.0 + 0.8) for i, t in enumerate(words)]
|
||||
return LyricsSegment(
|
||||
id="s", text=" ".join(words), words=ws, start_time=0.0, end_time=ws[-1].end_time, translation=translation
|
||||
)
|
||||
|
||||
|
||||
def _measure(text: str) -> float:
|
||||
"""10px per character: easy to reason about."""
|
||||
return len(text) * 10.0
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def resizer():
|
||||
return SegmentResizer(logger=logging.getLogger("test"))
|
||||
|
||||
|
||||
class TestSplitToWidth:
|
||||
def test_line_that_fits_is_unchanged(self, resizer):
|
||||
seg = _seg(["short", "line"])
|
||||
assert resizer.split_to_width([seg], _measure, 200) == [seg]
|
||||
|
||||
def test_too_wide_line_is_split_and_every_piece_fits(self, resizer):
|
||||
seg = _seg(["mm-"] * 12) # 47 chars = 470px
|
||||
out = resizer.split_to_width([seg], _measure, 200)
|
||||
assert len(out) > 1
|
||||
assert all(_measure(s.text) <= 200 for s in out)
|
||||
|
||||
def test_words_and_timing_preserved_in_order(self, resizer):
|
||||
seg = _seg([f"word{i}" for i in range(10)])
|
||||
out = resizer.split_to_width([seg], _measure, 250)
|
||||
assert [w for s in out for w in s.words] == seg.words
|
||||
for s in out:
|
||||
assert s.start_time == s.words[0].start_time
|
||||
assert s.end_time == s.words[-1].end_time
|
||||
assert s.text == " ".join(w.text for w in s.words)
|
||||
|
||||
def test_prefers_breaking_after_a_comma(self, resizer):
|
||||
# Balanced split would be after word 3; the comma after word 2 still fits.
|
||||
seg = _seg(["aaaa", "bbbb,", "cccc", "dddd", "eeee", "ffff"])
|
||||
out = resizer.split_to_width([seg], _measure, 200)
|
||||
assert [s.text for s in out] == ["aaaa bbbb,", "cccc dddd eeee ffff"]
|
||||
|
||||
def test_balanced_split_without_punctuation(self, resizer):
|
||||
seg = _seg(["aaaa", "bbbb", "cccc", "dddd"]) # 19 chars
|
||||
out = resizer.split_to_width([seg], _measure, 150)
|
||||
assert [s.text for s in out] == ["aaaa bbbb", "cccc dddd"]
|
||||
|
||||
def test_single_word_wider_than_frame_is_kept(self, resizer):
|
||||
seg = _seg(["supercalifragilistic"])
|
||||
assert resizer.split_to_width([seg], _measure, 50) == [seg]
|
||||
|
||||
def test_translation_is_shared_between_pieces(self, resizer):
|
||||
seg = _seg(["aaaa", "bbbb", "cccc", "dddd"], translation="uno dos tres cuatro")
|
||||
out = resizer.split_to_width([seg], _measure, 150)
|
||||
assert len(out) == 2
|
||||
assert " ".join(s.translation for s in out) == "uno dos tres cuatro"
|
||||
|
||||
def test_singer_carried_to_pieces(self, resizer):
|
||||
seg = _seg(["aaaa", "bbbb", "cccc", "dddd"])
|
||||
seg.singer = 2
|
||||
assert {s.singer for s in resizer.split_to_width([seg], _measure, 150)} == {2}
|
||||
|
||||
|
||||
# A hum line made of wide glyphs, ~1475px on the 1280px test frame: well clear of the split
|
||||
# threshold on every platform (font layout differs slightly between macOS and Linux).
|
||||
WIDE_HUM = ["Mm-", "mm-", "mm,"] * 4
|
||||
|
||||
|
||||
def _lyric_events(ass_path):
|
||||
with open(ass_path, encoding="utf-8-sig") as f:
|
||||
return [l for l in f if l.startswith("Dialogue") and "\\pos(" in l]
|
||||
|
||||
|
||||
def test_generated_ass_splits_wide_hum_line(tmp_path):
|
||||
ass = generate_ass(tmp_path, [make_segment(WIDE_HUM, start=4.0)])
|
||||
events = _lyric_events(ass)
|
||||
assert len(events) >= 2
|
||||
texts = [re.sub(r"\{[^}]*\}", "", e.split(",", 5)[5]).strip() for e in events]
|
||||
assert " ".join(texts) == " ".join(WIDE_HUM)
|
||||
|
||||
|
||||
def test_generated_ass_leaves_normal_lines_alone(tmp_path):
|
||||
ass = generate_ass(tmp_path, [make_segment(["it", "is", "in", "a", "line"], start=4.0)])
|
||||
assert len(_lyric_events(ass)) == 1
|
||||
|
||||
|
||||
@pytest.mark.skipif(not ffmpeg_has_libass(), reason="ffmpeg with libass not available")
|
||||
def test_every_line_renders_as_one_physical_line(tmp_path):
|
||||
"""Rendered with real libass: a line wider than the frame must not wrap into a second row.
|
||||
|
||||
Unsplit, this line is ~1475px on the 1280px test frame and libass draws its one
|
||||
event as two rows (the second one lands where the next lyric line goes).
|
||||
"""
|
||||
ass = generate_ass(tmp_path, [make_segment(WIDE_HUM, start=4.0)])
|
||||
events = _lyric_events(ass)
|
||||
frame = render_frames(ass, [5.0]).frames[5.0]
|
||||
lines = lyric_lines(frame)
|
||||
assert len(lines) == len(events), f"{len(events)} lyric events rendered as {len(lines)} rows"
|
||||
for line in lines:
|
||||
assert line.bottom - line.top < FONT_SIZE * 1.5 # one row of text, not two
|
||||
assert line.right - line.left <= WIDTH * MAX_LINE_WIDTH_FRACTION
|
||||
@@ -472,6 +472,25 @@ def test_delete_youtube_video_failure(mock_auth, finaliser_for_yt, mock_youtube_
|
||||
mock_youtube_service.videos().delete.assert_called_once_with(id=video_id)
|
||||
finaliser_for_yt.logger.error.assert_any_call(f"Failed to delete YouTube video with ID {video_id}: API Error")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_delete_youtube_video_already_gone_404_counts_as_deleted(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""A 404 means the video was already removed (e.g. in YouTube Studio): success, not failure."""
|
||||
from googleapiclient.errors import HttpError
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
resp = MagicMock(status=404, reason="Not Found")
|
||||
mock_youtube_service.videos.return_value.delete.return_value.execute.side_effect = HttpError(resp, b"{}")
|
||||
assert finaliser_for_yt.delete_youtube_video("gone_video") is True
|
||||
finaliser_for_yt.logger.error.assert_not_called()
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_delete_youtube_video_403_still_fails(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Other HTTP errors (e.g. 403 wrong channel) are still failures."""
|
||||
from googleapiclient.errors import HttpError
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
resp = MagicMock(status=403, reason="Forbidden")
|
||||
mock_youtube_service.videos.return_value.delete.return_value.execute.side_effect = HttpError(resp, b"{}")
|
||||
assert finaliser_for_yt.delete_youtube_video("other_video") is False
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_delete_youtube_video_dry_run(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test video deletion dry run."""
|
||||
|
||||
Reference in new issue
Block a user