diff --git a/backend/.gitignore b/backend/.gitignore index 9d42a524..ed910aa4 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -29,6 +29,8 @@ tmp/ # Google Cloud .gcloud/ *.json +# Allow i18n translation files +!translations/*.json # Testing .pytest_cache/ diff --git a/backend/api/routes/admin.py b/backend/api/routes/admin.py index af5ade24..cc1acfae 100644 --- a/backend/api/routes/admin.py +++ b/backend/api/routes/admin.py @@ -11,10 +11,11 @@ import logging from datetime import datetime, timedelta, timezone from typing import Tuple, List, Optional, Any, Dict -from fastapi import APIRouter, Depends, HTTPException +from fastapi import APIRouter, Depends, HTTPException, Request from pydantic import BaseModel from backend.api.dependencies import require_admin +from backend.i18n import t, get_locale_from_request from backend.services.auth_service import UserType, AuthResult from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION from backend.services.job_manager import JobManager diff --git a/backend/api/routes/audio_search.py b/backend/api/routes/audio_search.py index 47b3063a..439e44d2 100644 --- a/backend/api/routes/audio_search.py +++ b/backend/api/routes/audio_search.py @@ -53,6 +53,7 @@ from backend.exceptions import InsufficientCreditsError from backend.services.tracing import add_span_attribute from backend.services.firestore_service import FirestoreService from pathlib import Path +from backend.i18n import t, get_locale_from_request logger = logging.getLogger(__name__) @@ -309,17 +310,17 @@ def _validate_and_prepare_selection( """ job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail=f"Job {job_id} not found") + raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id)) # Get search results from state_data search_results = job.state_data.get('audio_search_results', []) if not search_results: - raise HTTPException(status_code=400, detail="No search results available") + raise HTTPException(status_code=400, detail=t("en", "audioSearch.noSearchResults")) if selection_index < 0 or selection_index >= len(search_results): raise HTTPException( status_code=400, - detail=f"Invalid selection index {selection_index}. Valid range: 0-{len(search_results)-1}" + detail=t("en", "audioSearch.invalidSelectionIndex", selection_index=selection_index, max=len(search_results)-1) ) selected = search_results[selection_index] @@ -594,12 +595,14 @@ async def search_audio( - Interactive mode (default): Returns results, user calls /select endpoint - Auto mode (auto_download=True): Automatically selects and downloads best """ + locale = get_locale_from_request(request) + # Check tenant feature flag tenant_config = get_tenant_config_from_request(request) if tenant_config and not tenant_config.features.audio_search: raise HTTPException( status_code=403, - detail="Audio search is not available for this portal" + detail=t(locale, "audioSearch.notEnabled") ) try: @@ -966,12 +969,14 @@ async def search_audio_standalone( Credits are checked here (early feedback) but NOT deducted — deduction happens when the job is created via create-from-search. """ + locale = get_locale_from_request(request) + # Check tenant feature flag tenant_config = get_tenant_config_from_request(request) if tenant_config and not tenant_config.features.audio_search: raise HTTPException( status_code=403, - detail="Audio search is not available for this portal" + detail=t(locale, "audioSearch.notEnabled") ) try: @@ -1098,14 +1103,14 @@ async def get_audio_search_results( """ job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail=f"Job {job_id} not found") - + raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id)) + search_results = job.state_data.get('audio_search_results', []) - + if not search_results: raise HTTPException( status_code=400, - detail="No search results available for this job" + detail=t("en", "audioSearch.noSearchResults") ) return { @@ -1136,7 +1141,7 @@ async def select_audio_source( """ job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail=f"Job {job_id} not found") + raise HTTPException(status_code=404, detail=t("en", "audioSearch.jobNotFound", job_id=job_id)) # Verify job is awaiting selection if job.status != JobStatus.AWAITING_AUDIO_SELECTION: diff --git a/backend/api/routes/auth.py b/backend/api/routes/auth.py index 4c5bab60..e6def200 100644 --- a/backend/api/routes/auth.py +++ b/backend/api/routes/auth.py @@ -9,7 +9,7 @@ Provides endpoints for: import logging from typing import Optional from datetime import datetime -from fastapi import APIRouter, HTTPException, BackgroundTasks +from fastapi import APIRouter, HTTPException, BackgroundTasks, Request from pydantic import BaseModel from backend.services.credential_manager import ( @@ -18,6 +18,7 @@ from backend.services.credential_manager import ( CredentialCheckResult, ) from backend.config import get_settings +from backend.i18n import t, get_locale_from_request logger = logging.getLogger(__name__) router = APIRouter(prefix="/auth", tags=["auth"]) @@ -125,15 +126,16 @@ async def get_credentials_status(): @router.get("/status/{service}", response_model=CredentialStatusResponse) -async def get_service_credential_status(service: str): +async def get_service_credential_status(service: str, request: Request): """ Get the status of a specific service's OAuth credentials. - + Args: service: One of "youtube", "gdrive", "dropbox" """ + locale = get_locale_from_request(request) manager = get_credential_manager() - + if service == "youtube": result = manager.check_youtube_credentials() elif service == "gdrive": @@ -141,7 +143,7 @@ async def get_service_credential_status(service: str): elif service == "dropbox": result = manager.check_dropbox_credentials() else: - raise HTTPException(status_code=400, detail=f"Unknown service: {service}") + raise HTTPException(status_code=400, detail=t(locale, "auth.unknownService", service=service)) return CredentialStatusResponse( service=result.service, @@ -153,42 +155,43 @@ async def get_service_credential_status(service: str): @router.post("/validate", response_model=CredentialValidationResponse) -async def validate_credentials(request: CredentialValidationRequest): +async def validate_credentials(request: CredentialValidationRequest, http_request: Request): """ Validate that credentials are available for requested services. - + Use this before submitting a job to ensure all required credentials are valid. """ + locale = get_locale_from_request(http_request) manager = get_credential_manager() invalid_services = [] - + if request.youtube: result = manager.check_youtube_credentials() if result.status != CredentialStatus.VALID: invalid_services.append("youtube") - + if request.gdrive: result = manager.check_gdrive_credentials() if result.status != CredentialStatus.VALID: invalid_services.append("gdrive") - + if request.dropbox: result = manager.check_dropbox_credentials() if result.status != CredentialStatus.VALID: invalid_services.append("dropbox") - + if invalid_services: return CredentialValidationResponse( valid=False, invalid_services=invalid_services, - message=f"The following services need re-authorization: {', '.join(invalid_services)}" + message=t(locale, "auth.invalidCredentials", services=", ".join(invalid_services)) ) - + return CredentialValidationResponse( valid=True, invalid_services=[], - message="All requested credentials are valid" + message=t(locale, "auth.validCredentials") ) @@ -197,40 +200,41 @@ async def validate_credentials(request: CredentialValidationRequest): # =========================================================================== @router.post("/youtube/device", response_model=DeviceAuthStartResponse) -async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None): +async def start_youtube_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None): """ Start YouTube device authorization flow. - + This initiates a device auth flow that allows authorization from any device. The user must visit the verification URL and enter the user code. - + Client credentials are loaded from Secret Manager ('youtube-client-credentials') unless explicitly provided in the request body. - + After starting, poll /auth/youtube/device/{device_code} to check for completion. """ + locale = get_locale_from_request(http_request) if http_request else "en" manager = get_credential_manager() - + try: device_info = manager.start_youtube_device_auth( client_id=request.client_id if request else None, client_secret=request.client_secret if request else None ) - + return DeviceAuthStartResponse( device_code=device_info.device_code, user_code=device_info.user_code, verification_url=device_info.verification_url, expires_in=device_info.expires_in, interval=device_info.interval, - instructions=f"Visit {device_info.verification_url} and enter code: {device_info.user_code}" + instructions=t(locale, "auth.youtubeAuthInstructions", verification_url=device_info.verification_url, user_code=device_info.user_code) ) - + except Exception as e: logger.error(f"Failed to start YouTube device auth: {e}") - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=t(locale, "auth.youtubeAuthStartFailed", error=str(e))) @router.get("/youtube/device/{device_code}", response_model=DeviceAuthPollResponse) @@ -259,35 +263,36 @@ async def poll_youtube_device_auth(device_code: str): @router.post("/gdrive/device", response_model=DeviceAuthStartResponse) -async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None): +async def start_gdrive_device_auth(request: Optional[DeviceAuthStartRequest] = None, http_request: Request = None): """ Start Google Drive device authorization flow. - + Client credentials are loaded from Secret Manager ('gdrive-client-credentials') unless explicitly provided in the request body. - + After starting, poll /auth/gdrive/device/{device_code} to check for completion. """ + locale = get_locale_from_request(http_request) if http_request else "en" manager = get_credential_manager() - + try: device_info = manager.start_gdrive_device_auth( client_id=request.client_id if request else None, client_secret=request.client_secret if request else None ) - + return DeviceAuthStartResponse( device_code=device_info.device_code, user_code=device_info.user_code, verification_url=device_info.verification_url, expires_in=device_info.expires_in, interval=device_info.interval, - instructions=f"Visit {device_info.verification_url} and enter code: {device_info.user_code}" + instructions=t(locale, "auth.gdriveLinkInstructions", verification_url=device_info.verification_url, user_code=device_info.user_code) ) - + except Exception as e: logger.error(f"Failed to start Google Drive device auth: {e}") - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=t(locale, "auth.gdriveAuthStartFailed", error=str(e))) @router.get("/gdrive/device/{device_code}", response_model=DeviceAuthPollResponse) @@ -311,19 +316,20 @@ async def poll_gdrive_device_auth(device_code: str): # =========================================================================== @router.post("/test-alert") -async def test_credential_alert(background_tasks: BackgroundTasks): +async def test_credential_alert(background_tasks: BackgroundTasks, request: Request): """ Test the credential alert mechanism. - + Sends a test alert to Discord if configured. """ + locale = get_locale_from_request(request) settings = get_settings() discord_url = settings.get_secret("discord-alert-webhook") - + if not discord_url: raise HTTPException( status_code=400, - detail="Discord alert webhook not configured" + detail=t(locale, "auth.discordAlertNotConfigured") ) manager = get_credential_manager() diff --git a/backend/api/routes/catalog.py b/backend/api/routes/catalog.py index 044e11b3..716539b7 100644 --- a/backend/api/routes/catalog.py +++ b/backend/api/routes/catalog.py @@ -14,6 +14,7 @@ from pydantic import BaseModel, Field from backend.api.dependencies import require_auth from backend.services.auth_service import AuthResult +from backend.i18n import t, get_locale_from_request logger = logging.getLogger(__name__) @@ -26,7 +27,7 @@ RATE_LIMIT_MAX_REQUESTS = 20 RATE_LIMIT_WINDOW_SECONDS = 60 -def _check_rate_limit(user_email: str) -> None: +def _check_rate_limit(user_email: str, locale: str = "en") -> None: """Check per-user rate limit. Raises 429 if exceeded.""" now = time.monotonic() window_start = now - RATE_LIMIT_WINDOW_SECONDS @@ -37,12 +38,12 @@ def _check_rate_limit(user_email: str) -> None: # Remove expired entries timestamps = _rate_limit_windows[user_email] - _rate_limit_windows[user_email] = [t for t in timestamps if t > window_start] + _rate_limit_windows[user_email] = [ts for ts in timestamps if ts > window_start] if len(_rate_limit_windows[user_email]) >= RATE_LIMIT_MAX_REQUESTS: raise HTTPException( status_code=429, - detail=f"Rate limit exceeded. Maximum {RATE_LIMIT_MAX_REQUESTS} catalog requests per minute.", + detail=t(locale, "catalog.rateLimitExceeded", max_requests=RATE_LIMIT_MAX_REQUESTS), ) _rate_limit_windows[user_email].append(now) @@ -107,6 +108,7 @@ class CommunityCheckResponse(BaseModel): @router.get("/artists", response_model=list[ArtistResult]) async def search_artists( + request: Request, q: str = Query(..., min_length=2, description="Artist name search query"), limit: int = Query(10, ge=1, le=50, description="Maximum results"), auth_result: AuthResult = Depends(require_auth), @@ -115,7 +117,8 @@ async def search_artists( Search for artists by name. Returns canonical MusicBrainz/Spotify artist data for autocomplete in job creation forms. """ - _check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown") + locale = get_locale_from_request(request) + _check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale) from backend.services.catalog_proxy_service import search_artists results = await search_artists(q, limit) @@ -124,6 +127,7 @@ async def search_artists( @router.get("/tracks", response_model=list[TrackResult]) async def search_tracks( + request: Request, q: str = Query(..., min_length=2, description="Track name search query"), artist: Optional[str] = Query(None, description="Filter by artist name"), limit: int = Query(10, ge=1, le=50, description="Maximum results"), @@ -133,7 +137,8 @@ async def search_tracks( Search for tracks by name, optionally filtered by artist. Returns canonical Spotify track data for autocomplete in job creation forms. """ - _check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown") + locale = get_locale_from_request(request) + _check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale) from backend.services.catalog_proxy_service import search_tracks results = await search_tracks(q, artist, limit) @@ -142,6 +147,7 @@ async def search_tracks( @router.post("/community-check", response_model=CommunityCheckResponse) async def check_community_versions( + request: Request, body: CommunityCheckRequest, auth_result: AuthResult = Depends(require_auth), ): @@ -149,7 +155,8 @@ async def check_community_versions( Check if a song already has community-approved karaoke versions on YouTube via karaokenerds.com. Non-blocking — just informs the user. """ - _check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown") + locale = get_locale_from_request(request) + _check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale) from backend.services.karaokenerds_service import check_community_versions result = await check_community_versions(body.artist, body.title) diff --git a/backend/api/routes/file_upload.py b/backend/api/routes/file_upload.py index 1a0197fb..75d28e12 100644 --- a/backend/api/routes/file_upload.py +++ b/backend/api/routes/file_upload.py @@ -45,6 +45,7 @@ from backend.services.youtube_download_service import ( get_youtube_download_service, YouTubeDownloadError, ) +from backend.i18n import t, get_locale_from_request logger = logging.getLogger(__name__) @@ -350,7 +351,8 @@ async def _trigger_audio_worker_only(job_id: str) -> None: def _prepare_theme_for_job( job_id: str, theme_id: str, - color_overrides: Optional[Dict[str, str]] = None + color_overrides: Optional[Dict[str, str]] = None, + locale: str = "en" ) -> Tuple[str, Dict[str, str], Optional[str]]: """ Prepare theme style files for a job. @@ -359,6 +361,7 @@ def _prepare_theme_for_job( job_id: The job ID theme_id: Theme identifier color_overrides: Optional color override dict + locale: Locale for error messages Returns: Tuple of (style_params_gcs_path, style_assets, youtube_description) @@ -372,7 +375,7 @@ def _prepare_theme_for_job( if not theme_service.theme_exists(theme_id): raise HTTPException( status_code=400, - detail=f"Theme not found: {theme_id}. Use GET /api/themes to list available themes." + detail=t(locale, "fileUpload.invalidTheme", theme_id=theme_id) ) # Convert dict to ColorOverrides model if provided @@ -465,6 +468,8 @@ async def upload_and_create_job( The style_params JSON can reference the uploaded images/fonts by their original filenames, and the backend will update the paths to GCS locations. """ + locale = get_locale_from_request(request) + # Check tenant feature flag tenant_config = get_tenant_config_from_request(request) if tenant_config and not tenant_config.features.file_upload: @@ -699,7 +704,7 @@ async def upload_and_create_job( if effective_theme_id and not has_custom_style_files: try: theme_style_params_path, theme_style_assets, theme_youtube_desc = _prepare_theme_for_job( - job_id, effective_theme_id, parsed_color_overrides or None + job_id, effective_theme_id, parsed_color_overrides or None, locale=locale ) logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}") except HTTPException: @@ -896,7 +901,7 @@ async def upload_and_create_job( return { "status": "success", "job_id": job_id, - "message": "Files uploaded successfully. Processing started.", + "message": t(locale, "fileUpload.uploadSuccess"), "filename": file.filename, "style_assets_uploaded": list(style_assets.keys()) if style_assets else [], "server_version": VERSION, @@ -909,7 +914,7 @@ async def upload_and_create_job( raise except Exception as e: logger.error(f"Error uploading files: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) from e + raise HTTPException(status_code=500, detail=t(locale, "fileUpload.uploadError", error=str(e))) from e # ============================================================================ @@ -1110,6 +1115,8 @@ async def create_job_with_upload_urls( - Works with any HTTP client (no HTTP/2 required) - Resumable uploads possible with GCS """ + locale = get_locale_from_request(request) + # Check tenant feature flag tenant_config = get_tenant_config_from_request(request) if tenant_config and not tenant_config.features.file_upload: @@ -1121,14 +1128,14 @@ async def create_job_with_upload_urls( try: # Validate files list if not body.files: - raise HTTPException(status_code=400, detail="At least one file is required") - + raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided")) + # Check that audio file is included audio_files = [f for f in body.files if f.file_type == 'audio'] if not audio_files: - raise HTTPException(status_code=400, detail="An audio file is required") + raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided")) if len(audio_files) > 1: - raise HTTPException(status_code=400, detail="Only one audio file is allowed") + raise HTTPException(status_code=400, detail=t(locale, "fileUpload.multipleAudioFilesNotAllowed")) # Validate file types and extensions for file_info in body.files: @@ -1271,7 +1278,7 @@ async def create_job_with_upload_urls( # If theme is set and no style_params uploaded, prepare theme style now if effective_theme_id and not has_style_params_upload: style_params_path, style_assets, youtube_desc = _prepare_theme_for_job( - job_id, effective_theme_id, body.color_overrides + job_id, effective_theme_id, body.color_overrides, locale=locale ) # Update job with theme style data update_data = { @@ -1307,7 +1314,7 @@ async def create_job_with_upload_urls( return CreateJobWithUploadUrlsResponse( status="success", job_id=job_id, - message="Job created. Upload files to the provided URLs, then call /api/jobs/{job_id}/uploads-complete", + message=t(locale, "fileUpload.urlCreationSuccess"), upload_urls=upload_urls, server_version=VERSION ) @@ -1318,12 +1325,13 @@ async def create_job_with_upload_urls( raise except Exception as e: logger.error(f"Error creating job with upload URLs: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) from e + raise HTTPException(status_code=500, detail=t(locale, "fileUpload.urlCreationError", error=str(e))) from e @router.post("/jobs/{job_id}/uploads-complete") async def mark_uploads_complete( job_id: str, + request: Request, background_tasks: BackgroundTasks, body: UploadsCompleteRequest, auth_result: AuthResult = Depends(require_auth) @@ -1342,22 +1350,23 @@ async def mark_uploads_complete( - Update job with GCS paths - Trigger audio and lyrics workers """ + locale = get_locale_from_request(request) try: # Get job and verify it exists job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail=f"Job {job_id} not found") - + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) + # Verify job is in pending state if job.status != JobStatus.PENDING: raise HTTPException( status_code=400, - detail=f"Job {job_id} is not in pending state (current: {job.status}). Cannot complete uploads." + detail=t(locale, "jobs.notCompleted", status=job.status) ) - + # Validate required files if 'audio' not in body.uploaded_files: - raise HTTPException(status_code=400, detail="Audio file upload is required") + raise HTTPException(status_code=400, detail=t(locale, "fileUpload.noAudioFileProvided")) # Build GCS paths for uploaded files and validate they exist update_data = {} @@ -1495,7 +1504,7 @@ async def mark_uploads_complete( return { "status": "success", "job_id": job_id, - "message": "Uploads validated. Processing started.", + "message": t(locale, "fileUpload.uploadsCompleteSuccess"), "files_validated": body.uploaded_files, "style_assets": list(style_assets.keys()) if style_assets else [], "server_version": VERSION, @@ -1506,7 +1515,7 @@ async def mark_uploads_complete( raise except Exception as e: logger.error(f"Error completing uploads for job {job_id}: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) from e + raise HTTPException(status_code=500, detail=t(locale, "fileUpload.uploadsCompleteError", error=str(e))) from e # ============================================================================ @@ -1589,6 +1598,8 @@ async def create_job_from_url( Note: YouTube rate limiting may cause occasional download failures. The backend will retry automatically. """ + locale = get_locale_from_request(request) + # Check tenant feature flag tenant_config = get_tenant_config_from_request(request) if tenant_config and not tenant_config.features.youtube_url: @@ -1744,7 +1755,7 @@ async def create_job_from_url( # If theme is set, prepare theme style now if effective_theme_id: style_params_path, style_assets, youtube_desc = _prepare_theme_for_job( - job_id, effective_theme_id, body.color_overrides + job_id, effective_theme_id, body.color_overrides, locale=locale ) # Update job with theme style data update_data = { @@ -1803,7 +1814,7 @@ async def create_job_from_url( job_manager.fail_job(job_id, f"YouTube download failed: {e}") raise HTTPException( status_code=500, - detail=f"YouTube download failed: {e}" + detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e)) ) else: # For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker @@ -1897,6 +1908,8 @@ async def create_finalise_only_job( The endpoint returns signed URLs for uploading all the prep files. """ + locale = get_locale_from_request(request) + # Check tenant feature flag - finalise-only requires file upload capability tenant_config = get_tenant_config_from_request(request) if tenant_config and not tenant_config.features.file_upload: @@ -2057,7 +2070,7 @@ async def create_finalise_only_job( # If theme is set and no style_params uploaded, prepare theme style now if effective_theme_id and not has_style_params_upload: style_params_path, style_assets, youtube_desc = _prepare_theme_for_job( - job_id, effective_theme_id, body.color_overrides + job_id, effective_theme_id, body.color_overrides, locale=locale ) # Update job with theme style data update_data = { diff --git a/backend/api/routes/jobs.py b/backend/api/routes/jobs.py index f0470797..147456da 100644 --- a/backend/api/routes/jobs.py +++ b/backend/api/routes/jobs.py @@ -38,6 +38,7 @@ from backend.services.tracing import add_span_attribute from backend.api.dependencies import require_admin, require_auth from backend.services.auth_service import AuthResult from backend.services.metrics import metrics +from backend.i18n import t, get_locale_from_request from backend.middleware.tenant import get_tenant_from_request from backend.utils.test_data import is_test_email from backend.exceptions import InsufficientCreditsError @@ -84,6 +85,7 @@ async def create_job( 3. Both workers update job state as they progress 4. When both complete, job transitions to AWAITING_REVIEW """ + locale = get_locale_from_request(http_request) try: # Determine job owner email: # All authentication methods must provide a user_email for job ownership @@ -95,7 +97,7 @@ async def create_job( logger.error("Authentication succeeded but no user_email provided") raise HTTPException( status_code=500, - detail="Authentication error: no user identity available" + detail=t(locale, "jobs.authError") ) # Admins can optionally create jobs on behalf of other users @@ -114,7 +116,7 @@ async def create_job( if not effective_theme_id: raise HTTPException( status_code=422, - detail="No default theme configured. Please contact support or specify a theme_id." + detail=t(locale, "jobs.noDefaultTheme") ) logger.info(f"Applying default theme: {effective_theme_id}") @@ -156,7 +158,7 @@ async def create_job( return JobResponse( status="success", job_id=job.job_id, - message="Job created successfully. Processing started." + message=t(locale, "jobs.created") ) except InsufficientCreditsError: raise @@ -172,16 +174,18 @@ async def create_job( @router.get("/{job_id}", response_model=Job) async def get_job( job_id: str, + request: Request, auth_result: AuthResult = Depends(require_auth) ) -> Job: """Get job status and details.""" + locale = get_locale_from_request(request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership - users can only see their own jobs, admins can see all if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to access this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess")) # If job is complete, include download URLs if job.status == JobStatus.COMPLETE: @@ -236,6 +240,7 @@ class EditTrackResponse(BaseModel): async def edit_completed_track( job_id: str, request: EditTrackRequest, + http_request: Request, background_tasks: BackgroundTasks, auth_result: AuthResult = Depends(require_auth), ): @@ -249,30 +254,31 @@ async def edit_completed_track( No additional credits are consumed — the original credit covers re-edits. """ + locale = get_locale_from_request(http_request) import re from datetime import timezone from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to edit this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionEdit")) # Only completed jobs can be edited if job.status != JobStatus.COMPLETE.value and job.status != "complete": raise HTTPException( status_code=400, - detail=f"Only completed jobs can be edited. Current status: {job.status}" + detail=t(locale, "jobs.notCompleted", status=job.status) ) # Prevent editing if outputs already deleted (edit already in progress) if job.outputs_deleted_at: raise HTTPException( status_code=400, - detail="This job is already being edited (outputs were already deleted)" + detail=t(locale, "jobs.alreadyBeingEdited") ) user_email = auth_result.user_email or "unknown" @@ -397,8 +403,7 @@ async def edit_completed_track( if critical_failures: raise HTTPException( status_code=500, - detail=f"Cleanup failed for {', '.join(critical_failures)}. " - f"Job not modified. Please try again or contact support." + detail=t(locale, "jobs.cleanupFailed", services=", ".join(critical_failures)) ) # --- Phase 2: Update job record --- @@ -504,7 +509,7 @@ async def edit_completed_track( return EditTrackResponse( status="success", job_id=job_id, - message="Track reopened for editing. Previous outputs have been removed.", + message=t(locale, "jobs.reopened"), review_url=f"/app/jobs#/{job_id}/review", review_token=review_token, metadata_updated=metadata_updated, @@ -598,17 +603,19 @@ async def list_jobs( created_after_dt = None created_before_dt = None + locale = get_locale_from_request(request) + if created_after: try: created_after_dt = datetime.fromisoformat(created_after.replace('Z', '+00:00')) except ValueError as e: - raise HTTPException(status_code=400, detail=f"Invalid created_after format: {created_after}") from e + raise HTTPException(status_code=400, detail=t(locale, "jobs.invalidDatetimeFormat", field="created_after", value=created_after)) from e if created_before: try: created_before_dt = datetime.fromisoformat(created_before.replace('Z', '+00:00')) except ValueError as e: - raise HTTPException(status_code=400, detail=f"Invalid created_before format: {created_before}") from e + raise HTTPException(status_code=400, detail=t(locale, "jobs.invalidDatetimeFormat", field="created_before", value=created_before)) from e # Determine user_email filter based on admin status # Admins see all jobs, regular users only see their own @@ -683,24 +690,26 @@ async def list_jobs( raise except Exception as e: logger.error(f"Error listing jobs: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=t(locale, "jobs.listError", error=str(e))) @router.delete("/{job_id}") async def delete_job( job_id: str, + request: Request, delete_files: bool = True, auth_result: AuthResult = Depends(require_auth) ) -> dict: """Delete a job and optionally its output files.""" + locale = get_locale_from_request(request) try: job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership - users can only delete their own jobs if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to delete this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionDelete")) # Recycle any unreturned brand code before deleting the job record state_data = job.state_data or {} @@ -727,11 +736,12 @@ async def delete_job( raise except Exception as e: logger.error(f"Error deleting job {job_id}: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=t(locale, "jobs.deleteError", job_id=job_id, error=str(e))) @router.delete("") async def bulk_delete_jobs( + request: Request, environment: Optional[str] = None, client_id: Optional[str] = None, status: Optional[JobStatus] = None, @@ -763,13 +773,15 @@ async def bulk_delete_jobs( """ from datetime import datetime + locale = get_locale_from_request(request) + # Require at least one filter to prevent accidental deletion of all jobs if not any([environment, client_id, status, created_before]): raise HTTPException( status_code=400, - detail="At least one filter (environment, client_id, status, created_before) is required" + detail=t(locale, "jobs.deletionRequiresFilters") ) - + # Require explicit confirmation if not confirm: # Return preview of what would be deleted @@ -790,7 +802,7 @@ async def bulk_delete_jobs( return { "status": "preview", - "message": "Add &confirm=true to execute deletion", + "message": t(locale, "jobs.deletionPreview"), "jobs_to_delete": len(jobs), "sample_jobs": [ { @@ -832,7 +844,7 @@ async def bulk_delete_jobs( except Exception as e: logger.error(f"Error bulk deleting jobs: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=t(locale, "jobs.bulkDeleteError", error=str(e))) # ============================================================================ @@ -842,6 +854,7 @@ async def bulk_delete_jobs( @router.get("/{job_id}/review-data") async def get_review_data( job_id: str, + request: Request, auth_result: AuthResult = Depends(require_auth) ) -> Dict[str, Any]: """ @@ -850,18 +863,19 @@ async def get_review_data( Returns corrections JSON URL and audio URL. Frontend loads these to render the review UI. """ + locale = get_locale_from_request(request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to access this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess")) if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]: raise HTTPException( status_code=400, - detail=f"Job not ready for review (current status: {job.status})" + detail=t(locale, "jobs.reviewNotReady", status=job.status) ) # Get URLs from file_urls @@ -880,13 +894,13 @@ async def get_review_data( if not corrections_url: raise HTTPException( status_code=500, - detail="Corrections data not available" + detail=t(locale, "jobs.correctionsUnavailable") ) if not audio_url: raise HTTPException( status_code=500, - detail="Audio not available for review" + detail=t(locale, "jobs.audioUnavailable") ) # Generate signed URLs for direct access @@ -906,6 +920,7 @@ async def get_review_data( async def start_review( job_id: str, request: StartReviewRequest, + http_request: Request, auth_result: AuthResult = Depends(require_auth) ) -> dict: """ @@ -913,22 +928,23 @@ async def start_review( This helps track that the user is actively working on the review. """ + locale = get_locale_from_request(http_request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to access this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess")) success = job_manager.transition_to_state( job_id=job_id, new_status=JobStatus.IN_REVIEW, message="User started reviewing lyrics" ) - + if not success: - raise HTTPException(status_code=400, detail="Cannot start review") + raise HTTPException(status_code=400, detail=t(locale, "jobs.reviewCannotStart")) return {"status": "success", "job_status": "in_review"} @@ -937,6 +953,7 @@ async def start_review( async def submit_corrections( job_id: str, submission: CorrectionsSubmission, + http_request: Request, background_tasks: BackgroundTasks, auth_result: AuthResult = Depends(require_auth) ) -> dict: @@ -948,18 +965,19 @@ async def submit_corrections( Can be called multiple times to save progress. """ + locale = get_locale_from_request(http_request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to modify this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify")) if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]: raise HTTPException( status_code=400, - detail=f"Job not in review state (current status: {job.status})" + detail=t(locale, "jobs.jobNotInReviewState", status=job.status) ) try: @@ -995,7 +1013,7 @@ async def submit_corrections( return { "status": "success", "job_status": "in_review", - "message": "Corrections saved. Call /complete-review when done." + "message": t(locale, "jobs.correctionsProcessing") } except Exception as e: @@ -1007,6 +1025,7 @@ async def submit_corrections( async def submit_edit_log( job_id: str, edit_log: Dict[str, Any], + request: Request, auth_result: AuthResult = Depends(require_auth) ) -> dict: """ @@ -1017,12 +1036,13 @@ async def submit_edit_log( Stored to GCS as jobs/{job_id}/lyrics/edit_log_{session_id}.json. """ + locale = get_locale_from_request(request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to modify this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify")) session_id = edit_log.get("session_id", "unknown") entries = edit_log.get("entries", []) @@ -1049,13 +1069,14 @@ async def submit_edit_log( except Exception as e: logger.error(f"Error saving edit log for job {job_id}: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=t(locale, "jobs.editLogSaveFailed", job_id=job_id, error=str(e))) @router.post("/{job_id}/create-custom-instrumental") async def create_custom_instrumental( job_id: str, request: CreateCustomInstrumentalRequest, + http_request: Request, auth_result: AuthResult = Depends(require_auth) ) -> dict: """ @@ -1064,17 +1085,18 @@ async def create_custom_instrumental( Downloads the clean instrumental and backing vocals stems, applies mute regions, combines them, uploads to GCS, and returns a signed URL for playback. """ + locale = get_locale_from_request(http_request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to modify this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify")) if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]: raise HTTPException( status_code=400, - detail=f"Job not in review state (current status: {job.status})" + detail=t(locale, "jobs.jobNotInReviewState", status=job.status) ) # Get stem paths from job @@ -1085,7 +1107,7 @@ async def create_custom_instrumental( if not clean_path or not backing_path: raise HTTPException( status_code=400, - detail="Job missing required stems (instrumental_clean and/or backing_vocals)" + detail=t(locale, "jobs.stemsMissing") ) try: @@ -1133,12 +1155,13 @@ async def create_custom_instrumental( except Exception as e: logger.error(f"Error creating custom instrumental for job {job_id}: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=t(locale, "jobs.customInstrumentalFailed", job_id=job_id, error=str(e))) @router.post("/{job_id}/upload-instrumental") async def upload_custom_instrumental( job_id: str, + request: Request, file: UploadFile = File(...), auth_result: AuthResult = Depends(require_auth) ) -> dict: @@ -1149,17 +1172,18 @@ async def upload_custom_instrumental( The file is stored to GCS and its path recorded in the job's stems metadata. The user can then select 'custom' as their instrumental_selection when completing review. """ + locale = get_locale_from_request(request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to modify this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify")) if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]: raise HTTPException( status_code=400, - detail=f"Job not in review state (current status: {job.status})" + detail=t(locale, "jobs.reviewNotInState", status=job.status) ) # Determine extension from filename or content type @@ -1202,11 +1226,9 @@ async def upload_custom_instrumental( if diff > 0.5: raise HTTPException( status_code=400, - detail=( - f"Duration mismatch: uploaded file is {upload_duration:.1f}s " - f"but original audio is {original_duration:.1f}s. " - f"The instrumental must be exactly {original_duration:.1f}s (±0.5s)." - ), + detail=t(locale, "jobs.durationMismatch", + upload_duration=f"{upload_duration:.1f}", + original_duration=f"{original_duration:.1f}"), ) # Convert to FLAC for consistency with the rest of the pipeline @@ -1225,7 +1247,7 @@ async def upload_custom_instrumental( raise except Exception as e: logger.error(f"Job {job_id}: Error processing uploaded instrumental: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=f"Failed to process audio file: {str(e)}") + raise HTTPException(status_code=500, detail=t(locale, "jobs.audioProcessingFailed", error=str(e))) finally: if tmp_path and os.path.exists(tmp_path): os.unlink(tmp_path) @@ -1278,6 +1300,7 @@ async def _get_audio_duration_ffprobe_signed(job_id: str, job, storage: StorageS @router.post("/{job_id}/complete-review") async def complete_review( job_id: str, + request: Request, background_tasks: BackgroundTasks, auth_result: AuthResult = Depends(require_auth), body: Optional[CompleteReviewRequest] = None @@ -1294,18 +1317,19 @@ async def complete_review( 3. Worker uses OutputGenerator to create with_vocals.mkv 4. Job transitions to INSTRUMENTAL_SELECTED then GENERATING_VIDEO """ + locale = get_locale_from_request(request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to modify this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify")) if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]: raise HTTPException( status_code=400, - detail=f"Job not in review state (current status: {job.status})" + detail=t(locale, "jobs.reviewNotInState", status=job.status) ) # Check for 0-segment lyrics — fail early with user-friendly message @@ -1320,12 +1344,7 @@ async def complete_review( if segment_count == 0 and len(corrected_segments) == 0: raise HTTPException( status_code=400, - detail=( - "Cannot complete review: no lyrics were detected in the audio. " - "This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). " - "You can go back and paste lyrics manually using 'Replace All', " - "or cancel this job and try again with an audio file that contains vocals." - ) + detail=t(locale, "jobs.noLyricsDetected") ) try: @@ -1352,18 +1371,19 @@ async def complete_review( return { "status": "success", "job_status": "review_complete", - "message": "Review complete. Video rendering started." + "message": t(locale, "jobs.reviewCompleteStartRendering") } except Exception as e: logger.error(f"Error completing review for job {job_id}: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=t(locale, "jobs.reviewCompleteError", job_id=job_id, error=str(e))) @router.post("/{job_id}/select-instrumental") async def select_instrumental( job_id: str, selection: InstrumentalSelection, + request: Request, background_tasks: BackgroundTasks, auth_result: AuthResult = Depends(require_auth) ) -> dict: @@ -1383,18 +1403,19 @@ async def select_instrumental( Returns: Status and confirmation of selection """ + locale = get_locale_from_request(request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to access this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess")) if job.status != JobStatus.AWAITING_INSTRUMENTAL_SELECTION: raise HTTPException( status_code=400, - detail=f"Job not awaiting instrumental selection (current status: {job.status})" + detail=t(locale, "jobs.reviewNotInState", status=job.status) ) try: @@ -1420,17 +1441,18 @@ async def select_instrumental( "status": "success", "job_status": "instrumental_selected", "selection": selection.selection, - "message": "Instrumental selected. Video generation started." + "message": t(locale, "jobs.instrumentalSelected") } except Exception as e: logger.error(f"Error selecting instrumental for job {job_id}: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=t(locale, "jobs.instrumentalSelectionError", job_id=job_id, error=str(e))) @router.get("/{job_id}/download-urls") async def get_download_urls( job_id: str, + request: Request, auth_result: AuthResult = Depends(require_auth) ) -> dict: """ @@ -1439,13 +1461,14 @@ async def get_download_urls( Returns a dictionary mapping file types to download URLs. Uses the streaming download endpoint which proxies through the backend. """ + locale = get_locale_from_request(request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to access this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess")) file_urls = job.file_urls or {} download_urls = {} @@ -1489,6 +1512,7 @@ async def download_file( job_id: str, category: str, file_key: str, + request: Request, auth_result: AuthResult = Depends(require_auth) ): """ @@ -1497,16 +1521,17 @@ async def download_file( This endpoint proxies the file from GCS through the backend, so no client-side authentication is required. """ + locale = get_locale_from_request(request) from fastapi.responses import StreamingResponse import tempfile job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to access this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess")) file_urls = job.file_urls or {} category_files = file_urls.get(category) @@ -1599,6 +1624,7 @@ async def download_file( async def cancel_job( job_id: str, request: CancelJobRequest, + http_request: Request, auth_result: AuthResult = Depends(require_auth) ) -> dict: """ @@ -1606,13 +1632,14 @@ async def cancel_job( Jobs can be cancelled at any stage before completion. """ + locale = get_locale_from_request(http_request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to cancel this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify")) success = job_manager.cancel_job(job_id, reason=request.reason) @@ -1629,6 +1656,7 @@ async def cancel_job( @router.post("/{job_id}/retry") async def retry_job( job_id: str, + request: Request, background_tasks: BackgroundTasks, auth_result: AuthResult = Depends(require_auth) ) -> dict: @@ -1644,20 +1672,21 @@ async def retry_job( The retry logic determines the appropriate stage to resume from based on what files/state already exist. """ + locale = get_locale_from_request(request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to retry this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionModify")) if job.status not in [JobStatus.FAILED, JobStatus.CANCELLED]: raise HTTPException( status_code=400, - detail=f"Only failed or cancelled jobs can be retried (current status: {job.status})" + detail=t(locale, "jobs.notCompleted", status=job.status) ) - + try: # Determine retry point based on what's already complete error_details = job.error_details or {} @@ -1906,6 +1935,7 @@ async def retry_job( @router.get("/{job_id}/logs") async def get_worker_logs( job_id: str, + request: Request, since_index: int = 0, worker: Optional[str] = None, auth_result: AuthResult = Depends(require_auth) @@ -1932,13 +1962,14 @@ async def get_worker_logs( "total_logs": 42 } """ + locale = get_locale_from_request(request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) # Check ownership - users can only see logs for their own jobs if not _check_job_ownership(job, auth_result): - raise HTTPException(status_code=403, detail="You don't have permission to access logs for this job") + raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess")) logs = job_manager.get_worker_logs(job_id, since_index=since_index, worker=worker) total = job_manager.get_worker_logs_count(job_id) @@ -1953,6 +1984,7 @@ async def get_worker_logs( @router.post("/{job_id}/cleanup-distribution") async def cleanup_distribution( job_id: str, + request: Request, delete_job: bool = True, auth_result: AuthResult = Depends(require_admin) ) -> dict: @@ -1972,9 +2004,10 @@ async def cleanup_distribution( Returns: Cleanup results for each service """ + locale = get_locale_from_request(request) job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) state_data = job.state_data or {} results = { @@ -2191,6 +2224,8 @@ async def create_job_from_search( Credit deduction happens here (inside job_manager.create_job). """ + locale = get_locale_from_request(request) + # Lazy imports from audio_search to avoid circular imports at module level from backend.api.routes.audio_search import ( _validate_and_prepare_selection, @@ -2201,7 +2236,7 @@ async def create_job_from_search( try: user_email = auth_result.user_email if not user_email: - raise HTTPException(status_code=401, detail="Authentication required") + raise HTTPException(status_code=401, detail=t(locale, "jobs.authError")) # Read the session non-destructively for validation. # consume_search_session (atomic read+delete) is called later, just before job creation, @@ -2328,7 +2363,7 @@ async def create_job_from_search( from backend.api.routes.file_upload import _prepare_theme_for_job try: style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job( - job_id, effective_theme_id, {} + job_id, effective_theme_id, {}, locale=locale ) theme_update = { 'style_params_gcs_path': style_params_path, @@ -2389,6 +2424,7 @@ async def create_job_from_search( async def change_visibility( job_id: str, request: ChangeVisibilityRequest, + http_request: Request, auth_result: AuthResult = Depends(require_auth), ): """ @@ -2402,10 +2438,11 @@ async def change_visibility( - Resets custom styling to default Nomad theme - Regenerates screens, re-renders video, publishes publicly """ + locale = get_locale_from_request(http_request) job_manager = JobManager() job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound")) user_email = auth_result.user_email or "unknown" is_admin = auth_result.is_admin diff --git a/backend/api/routes/push.py b/backend/api/routes/push.py index 6296f39b..badbb2b2 100644 --- a/backend/api/routes/push.py +++ b/backend/api/routes/push.py @@ -18,6 +18,7 @@ from backend.config import get_settings from backend.api.dependencies import require_auth, require_admin from backend.services.auth_service import AuthResult from backend.services.push_notification_service import get_push_notification_service +from backend.i18n import t, get_locale_from_request logger = logging.getLogger(__name__) @@ -127,18 +128,20 @@ async def subscribe_push( 1. Request body tenant_id field (explicit from frontend) 2. Tenant middleware (X-Tenant-ID header or subdomain detection) """ + locale = get_locale_from_request(http_request) + settings = get_settings() if not settings.enable_push_notifications: - raise HTTPException(status_code=503, detail="Push notifications are not enabled") + raise HTTPException(status_code=503, detail=t(locale, "push.disabled")) if not auth_result.user_email: - raise HTTPException(status_code=401, detail="User email not available") + raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable")) push_service = get_push_notification_service() # Validate keys if "p256dh" not in subscribe_request.keys or "auth" not in subscribe_request.keys: - raise HTTPException(status_code=400, detail="Missing required keys (p256dh, auth)") + raise HTTPException(status_code=400, detail=t(locale, "push.missingEncryptionKeys")) # Resolve tenant_id: prefer explicit from body, fall back to middleware tenant_id = subscribe_request.tenant_id @@ -154,17 +157,18 @@ async def subscribe_push( ) if not success: - raise HTTPException(status_code=500, detail="Failed to save subscription") + raise HTTPException(status_code=500, detail=t(locale, "push.subscriptionSaveFailed")) return SubscribeResponse( status="success", - message="Push subscription registered successfully" + message=t(locale, "push.subscriptionRegistered") ) @router.post("/unsubscribe", response_model=UnsubscribeResponse) async def unsubscribe_push( request: UnsubscribeRequest, + http_request: Request, auth_result: AuthResult = Depends(require_auth) ): """ @@ -172,8 +176,10 @@ async def unsubscribe_push( Requires authentication. Users can only remove their own subscriptions. """ + locale = get_locale_from_request(http_request) + if not auth_result.user_email: - raise HTTPException(status_code=401, detail="User email not available") + raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable")) push_service = get_push_notification_service() @@ -186,17 +192,18 @@ async def unsubscribe_push( # Don't error if subscription wasn't found - might already be removed return UnsubscribeResponse( status="success", - message="Subscription removed (or was not found)" + message=t(locale, "push.subscriptionNotFound") ) return UnsubscribeResponse( status="success", - message="Push subscription removed successfully" + message=t(locale, "push.subscriptionRemoved") ) @router.get("/subscriptions", response_model=SubscriptionsListResponse) async def list_subscriptions( + request: Request, auth_result: AuthResult = Depends(require_auth) ): """ @@ -204,8 +211,10 @@ async def list_subscriptions( Requires authentication. """ + locale = get_locale_from_request(request) + if not auth_result.user_email: - raise HTTPException(status_code=401, detail="User email not available") + raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable")) push_service = get_push_notification_service() @@ -220,6 +229,7 @@ async def list_subscriptions( @router.post("/test", response_model=TestNotificationResponse) async def send_test_notification( request: TestNotificationRequest, + http_request: Request, auth_result: AuthResult = Depends(require_admin) ): """ @@ -227,12 +237,14 @@ async def send_test_notification( Admin only. Useful for testing push notification setup. """ + locale = get_locale_from_request(http_request) + settings = get_settings() if not settings.enable_push_notifications: - raise HTTPException(status_code=503, detail="Push notifications are not enabled") + raise HTTPException(status_code=503, detail=t(locale, "push.disabled")) if not auth_result.user_email: - raise HTTPException(status_code=401, detail="User email not available") + raise HTTPException(status_code=401, detail=t(locale, "push.userEmailNotAvailable")) push_service = get_push_notification_service() @@ -247,5 +259,5 @@ async def send_test_notification( return TestNotificationResponse( status="success", sent_count=sent_count, - message=f"Test notification sent to {sent_count} device(s)" + message=t(locale, "push.testNotificationSent", sent_count=sent_count) ) diff --git a/backend/api/routes/rate_limits.py b/backend/api/routes/rate_limits.py index 2455547e..864476f4 100644 --- a/backend/api/routes/rate_limits.py +++ b/backend/api/routes/rate_limits.py @@ -10,12 +10,13 @@ import logging from datetime import datetime from typing import List, Optional -from fastapi import APIRouter, Depends, HTTPException +from fastapi import APIRouter, Depends, HTTPException, Request from pydantic import BaseModel from backend.api.dependencies import require_admin from backend.services.auth_service import AuthResult from backend.services.email_validation_service import get_email_validation_service, EmailValidationService +from backend.i18n import t, get_locale_from_request logger = logging.getLogger(__name__) router = APIRouter(prefix="/admin/rate-limits", tags=["admin", "rate-limits"]) @@ -106,13 +107,13 @@ async def add_disposable_domain( domain = request.domain.lower().strip() if not domain or "." not in domain: - raise HTTPException(status_code=400, detail="Invalid domain format") + raise HTTPException(status_code=400, detail=t("en", "admin.invalidDomainFormat")) email_validation.add_disposable_domain(domain, auth_result.user_email) return SuccessResponse( success=True, - message=f"Domain '{domain}' added to disposable domains blocklist" + message=t("en", "admin.domainAddedToBl", domain=domain) ) @@ -126,11 +127,11 @@ async def remove_disposable_domain( domain = domain.lower().strip() if not email_validation.remove_disposable_domain(domain, auth_result.user_email): - raise HTTPException(status_code=404, detail="Domain not found in blocklist") + raise HTTPException(status_code=404, detail=t("en", "admin.domainNotFoundInBl")) return SuccessResponse( success=True, - message=f"Domain '{domain}' removed from disposable domains blocklist" + message=t("en", "admin.domainRemovedFromBl", domain=domain) ) @@ -143,9 +144,9 @@ async def add_allowlisted_domain( email_validation = get_email_validation_service() domain = request.domain.lower().strip() if not domain or "." not in domain: - raise HTTPException(status_code=400, detail="Invalid domain format") + raise HTTPException(status_code=400, detail=t("en", "admin.invalidDomainFormat")) email_validation.add_allowlisted_domain(domain, auth_result.user_email) - return SuccessResponse(success=True, message=f"Domain '{domain}' added to allowlist") + return SuccessResponse(success=True, message=t("en", "admin.domainAddedToAllowlist", domain=domain)) @router.delete("/blocklists/allowlisted-domains/{domain}", response_model=SuccessResponse) @@ -157,8 +158,8 @@ async def remove_allowlisted_domain( email_validation = get_email_validation_service() domain = domain.lower().strip() if not email_validation.remove_allowlisted_domain(domain, auth_result.user_email): - raise HTTPException(status_code=404, detail="Domain not found in allowlist") - return SuccessResponse(success=True, message=f"Domain '{domain}' removed from allowlist") + raise HTTPException(status_code=404, detail=t("en", "admin.domainNotFoundInAllowlist")) + return SuccessResponse(success=True, message=t("en", "admin.domainRemovedFromAllowlist", domain=domain)) @router.post("/blocklists/sync", response_model=SuccessResponse) @@ -181,7 +182,7 @@ async def trigger_sync( return SuccessResponse( success=True, - message=f"Synced {result['external_count']} external domains ({result['added']} added, {result['removed']} removed)" + message=t("en", "admin.syncComplete", external_count=result['external_count'], added=result['added'], removed=result['removed']) ) @@ -195,13 +196,13 @@ async def add_blocked_email( email = request.email.lower().strip() if not email or "@" not in email: - raise HTTPException(status_code=400, detail="Invalid email format") + raise HTTPException(status_code=400, detail=t("en", "admin.invalidEmailFormat")) email_validation.add_blocked_email(email, auth_result.user_email) return SuccessResponse( success=True, - message=f"Email '{email}' added to blocked emails list" + message=t("en", "admin.emailAddedToBl", email=email) ) @@ -215,11 +216,11 @@ async def remove_blocked_email( email = email.lower().strip() if not email_validation.remove_blocked_email(email, auth_result.user_email): - raise HTTPException(status_code=404, detail="Email not found in blocklist") + raise HTTPException(status_code=404, detail=t("en", "admin.emailNotFoundInBl")) return SuccessResponse( success=True, - message=f"Email '{email}' removed from blocked emails list" + message=t("en", "admin.emailRemovedFromBl", email=email) ) @@ -233,13 +234,13 @@ async def add_blocked_ip( ip_address = request.ip_address.strip() if not ip_address: - raise HTTPException(status_code=400, detail="Invalid IP address") + raise HTTPException(status_code=400, detail=t("en", "admin.invalidIPAddress")) email_validation.add_blocked_ip(ip_address, auth_result.user_email) return SuccessResponse( success=True, - message=f"IP '{ip_address}' added to blocked IPs list" + message=t("en", "admin.ipAddedToBl", ip_address=ip_address) ) @@ -253,11 +254,11 @@ async def remove_blocked_ip( ip_address = ip_address.strip() if not email_validation.remove_blocked_ip(ip_address, auth_result.user_email): - raise HTTPException(status_code=404, detail="IP not found in blocklist") + raise HTTPException(status_code=404, detail=t("en", "admin.ipNotFoundInBl")) return SuccessResponse( success=True, - message=f"IP '{ip_address}' removed from blocked IPs list" + message=t("en", "admin.ipRemovedFromBl", ip_address=ip_address) ) @@ -303,12 +304,12 @@ async def retry_youtube_upload( if not queue_service.retry_upload(job_id): raise HTTPException( status_code=404, - detail=f"Upload not found or not in retryable state for job {job_id}" + detail=t("en", "admin.youtubeUploadNotFound", job_id=job_id) ) return SuccessResponse( success=True, - message=f"YouTube upload for job {job_id} queued for retry" + message=t("en", "admin.youtubeUploadQueuedForRetry", job_id=job_id) ) @@ -341,5 +342,5 @@ async def trigger_youtube_queue_processing( return SuccessResponse( success=True, - message="YouTube queue processing started in background" + message=t("en", "admin.youtubeQueueProcessingStarted") ) diff --git a/backend/api/routes/review.py b/backend/api/routes/review.py index 72585cd0..323e6654 100644 --- a/backend/api/routes/review.py +++ b/backend/api/routes/review.py @@ -36,6 +36,7 @@ from backend.services.encoding_service import get_encoding_service from backend.api.dependencies import require_auth, require_review_auth from backend.services.auth_service import UserType from backend.config import get_settings +from backend.i18n import t, get_locale_from_request # LyricsTranscriber imports for preview generation from karaoke_gen.lyrics_transcriber.types import CorrectionResult @@ -113,12 +114,12 @@ async def get_correction_data( job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]: raise HTTPException( status_code=400, - detail=f"Job not ready for review (current status: {job.status})" + detail=t("en", "review.reviewNotReady", status=job.status) ) # Check for updated corrections first (from previous review sessions where user edited lyrics) @@ -139,7 +140,7 @@ async def get_correction_data( if not storage.file_exists(corrections_gcs): raise HTTPException( status_code=404, - detail="Corrections data not found. Lyrics processing may not be complete." + detail=t("en", "review.correctionsNotFound") ) # Download and return corrections data @@ -224,7 +225,7 @@ async def get_correction_data( except Exception as e: logger.error(f"Job {job_id}: Error loading corrections: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=f"Error loading corrections: {str(e)}") + raise HTTPException(status_code=500, detail=t("en", "review.correctionsLoadFailed", error=str(e))) @router.get("/{job_id}/audio/{audio_hash}") @@ -260,11 +261,11 @@ async def _stream_audio(job_id: str): job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) audio_gcs_path = job.input_media_gcs_path if not audio_gcs_path: - raise HTTPException(status_code=404, detail="Audio file not found") + raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound")) try: transcoding = AudioTranscodingService() @@ -274,7 +275,7 @@ async def _stream_audio(job_id: str): except Exception as e: logger.error(f"Job {job_id}: Error generating audio signed URL: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=f"Error serving audio: {str(e)}") + raise HTTPException(status_code=500, detail=t("en", "review.audioServeError", error=str(e))) @router.post("/{job_id}/complete") @@ -298,12 +299,12 @@ async def complete_review( job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]: raise HTTPException( status_code=400, - detail=f"Job not in review state (current status: {job.status})" + detail=t("en", "review.reviewNotReady", status=job.status) ) # === Require instrumental selection === @@ -311,7 +312,7 @@ async def complete_review( if not instrumental_selection: raise HTTPException( status_code=400, - detail="instrumental_selection is required. Must be 'clean' or 'with_backing'." + detail=t("en", "review.instrumentalSelectionRequired") ) valid_selections = ["clean", "with_backing"] @@ -323,7 +324,7 @@ async def complete_review( if instrumental_selection not in valid_selections: raise HTTPException( status_code=400, - detail=f"Invalid instrumental_selection. Must be one of: {valid_selections}" + detail=t("en", "review.invalidInstrumentalSelection", valid_selections=valid_selections) ) try: @@ -384,7 +385,7 @@ async def complete_review( raise except Exception as e: logger.error(f"Job {job_id}: Error completing review: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=f"Error completing review: {str(e)}") + raise HTTPException(status_code=500, detail=t("en", "review.reviewCompletedError", error=str(e))) @router.post("/{job_id}/handlers") @@ -400,7 +401,7 @@ async def update_handlers( would require re-running correction. """ logger.info(f"Job {job_id}: Handler update requested (not implemented)") - return {"status": "success", "message": "Handler updates not yet implemented"} + return {"status": "success", "message": t("en", "review.handlersUpdateNotImplemented")} @router.post("/{job_id}/add-lyrics") @@ -420,13 +421,13 @@ async def add_lyrics( job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") - + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) + # Job must be in review state to add lyrics if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]: raise HTTPException( status_code=400, - detail=f"Job not in review state (current status: {job.status})" + detail=t("en", "review.reviewNotReady", status=job.status) ) source = data.get("source", "").strip() @@ -501,11 +502,11 @@ async def add_lyrics( # ValueError from CorrectionOperations (e.g., duplicate source name) logger.warning(f"Job {job_id}: Invalid add lyrics request: {e}") span.set_attribute("error", str(e)) - raise HTTPException(status_code=400, detail=str(e)) + raise HTTPException(status_code=400, detail=t("en", "review.lyricsAddInvalidRequest", error=str(e))) except Exception as e: logger.error(f"Job {job_id}: Failed to add lyrics: {e}", exc_info=True) span.set_attribute("error", str(e)) - raise HTTPException(status_code=500, detail=f"Failed to add lyrics: {str(e)}") + raise HTTPException(status_code=500, detail=t("en", "review.lyricsAddError", error=str(e))) @router.post("/{job_id}/search-lyrics") @@ -541,12 +542,12 @@ async def search_lyrics( job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]: raise HTTPException( status_code=400, - detail=f"Job not in review state (current status: {job.status})" + detail=t("en", "review.reviewNotReady", status=job.status) ) artist = (data.get("artist") or "").strip() @@ -606,7 +607,7 @@ async def search_lyrics( span.set_attribute("success", False) return { "status": "no_results", - "message": "No matching lyrics found from any provider", + "message": t("en", "review.lyricsSearchNoResults"), "sources_added": [], "sources_rejected": sources_rejected, "sources_not_found": sources_not_found, @@ -646,11 +647,11 @@ async def search_lyrics( except ValueError as e: logger.warning(f"Job {job_id}: Invalid search lyrics request: {e}") span.set_attribute("error", str(e)) - raise HTTPException(status_code=400, detail=str(e)) + raise HTTPException(status_code=400, detail=t("en", "review.lyricsSearchInvalidRequest", error=str(e))) except Exception as e: logger.error(f"Job {job_id}: Failed to search lyrics: {e}", exc_info=True) span.set_attribute("error", str(e)) - raise HTTPException(status_code=500, detail=f"Failed to search lyrics: {str(e)}") + raise HTTPException(status_code=500, detail=t("en", "review.lyricsSearchError", error=str(e))) @router.post("/{job_id}/preview-video") @@ -675,13 +676,13 @@ async def generate_preview_video( job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) # Job must be in review state to generate preview if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]: raise HTTPException( status_code=400, - detail=f"Job not in review state (current status: {job.status})" + detail=t("en", "review.reviewNotReady", status=job.status) ) # Check if GCE preview encoding is enabled @@ -855,7 +856,7 @@ async def generate_preview_video( span.set_attribute("error", str(e)) raise HTTPException( status_code=500, - detail=f"Failed to generate preview video: {e}" + detail=t("en", "review.previewVideoGenerationError", error=str(e)) ) from e @@ -876,7 +877,7 @@ async def get_preview_video( # Try standard path preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4" if not storage.file_exists(preview_gcs_path): - raise HTTPException(status_code=404, detail="Preview video not found") + raise HTTPException(status_code=404, detail=t("en", "review.previewVideoNotFound")) try: # Download to temp file and stream @@ -901,7 +902,7 @@ async def get_preview_video( except Exception as e: logger.error(f"Job {job_id}: Error streaming preview video: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=f"Error streaming preview video: {str(e)}") + raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e))) @router.post("/{job_id}/v1/annotations") @@ -941,7 +942,7 @@ async def submit_annotation( except Exception as e: logger.error(f"Job {job_id}: Error saving annotations: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=t("en", "review.annotationSaveError", error=str(e))) @router.get("/{job_id}/v1/annotations/stats") @@ -982,7 +983,7 @@ async def get_instrumental_analysis( job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) # Get backing vocals analysis from state_data backing_analysis = job.state_data.get('backing_vocals_analysis', {}) @@ -1050,7 +1051,7 @@ async def get_waveform_data( job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) # Get backing vocals path stems = job.file_urls.get('stems', {}) @@ -1061,7 +1062,7 @@ async def get_waveform_data( backing_vocals_path = job.input_media_gcs_path if not backing_vocals_path: - raise HTTPException(status_code=404, detail="No audio available for waveform") + raise HTTPException(status_code=404, detail=t("en", "review.waveformNoAudio")) try: analysis_service = AudioAnalysisService() @@ -1079,7 +1080,7 @@ async def get_waveform_data( } except Exception as e: logger.error(f"Job {job_id}: Error generating waveform data: {e}", exc_info=True) - raise HTTPException(status_code=500, detail=f"Error generating waveform: {str(e)}") + raise HTTPException(status_code=500, detail=t("en", "review.waveformGenerationError", error=str(e))) # ============================================ @@ -1111,11 +1112,11 @@ async def save_review_session( job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) correction_data = data.get("correction_data") if not correction_data: - raise HTTPException(status_code=400, detail="correction_data is required") + raise HTTPException(status_code=400, detail=t("en", "review.sessionSaveError")) # Compute hash for deduplication data_json = json.dumps(correction_data, sort_keys=True, default=str) @@ -1284,7 +1285,7 @@ async def save_audio_edit_session( job_manager = JobManager() job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) user_email = auth_info[0] if isinstance(auth_info, tuple) else "" edit_data = data.get("edit_data", {}) @@ -1477,7 +1478,7 @@ async def get_input_audio_info( job_manager = JobManager() job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) if not job.input_media_gcs_path: raise HTTPException(status_code=404, detail="No input audio available") @@ -1584,7 +1585,7 @@ async def apply_audio_edit( job_manager = JobManager() job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT): raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})") @@ -1681,7 +1682,7 @@ async def undo_audio_edit( job_manager = JobManager() job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT): raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})") @@ -1728,7 +1729,7 @@ async def redo_audio_edit( job_manager = JobManager() job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT): raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})") @@ -1784,7 +1785,7 @@ async def upload_audio_for_join( job_manager = JobManager() job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT): raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})") @@ -1877,7 +1878,7 @@ async def submit_audio_edit( job_manager = JobManager() job = job_manager.get_job(job_id) if not job: - raise HTTPException(status_code=404, detail="Job not found") + raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound")) if job.status not in (JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT): raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})") diff --git a/backend/api/routes/tenant.py b/backend/api/routes/tenant.py index 2f2a734f..2e6c4450 100644 --- a/backend/api/routes/tenant.py +++ b/backend/api/routes/tenant.py @@ -12,6 +12,7 @@ from fastapi import APIRouter, Query, Request from backend.models.tenant import TenantConfigResponse, TenantPublicConfig from backend.services.tenant_service import get_tenant_service +from backend.i18n import t, get_locale_from_request logger = logging.getLogger(__name__) @@ -115,6 +116,6 @@ async def get_tenant_asset(tenant_id: str, asset_name: str): if not url: from fastapi import HTTPException - raise HTTPException(status_code=404, detail="Asset not found") + raise HTTPException(status_code=404, detail=t("en", "tenant.assetNotFound")) return RedirectResponse(url=url) diff --git a/backend/api/routes/themes.py b/backend/api/routes/themes.py index 182dc72c..436a116d 100644 --- a/backend/api/routes/themes.py +++ b/backend/api/routes/themes.py @@ -9,10 +9,11 @@ before job creation. import logging from typing import Optional -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter, HTTPException, Request from backend.models.theme import ThemeDetailResponse, ThemesListResponse from backend.services.theme_service import get_theme_service +from backend.i18n import t, get_locale_from_request logger = logging.getLogger(__name__) @@ -20,7 +21,7 @@ router = APIRouter(prefix="/themes", tags=["themes"]) @router.get("", response_model=ThemesListResponse) -async def list_themes() -> ThemesListResponse: +async def list_themes(request: Request) -> ThemesListResponse: """ List all available themes. @@ -29,6 +30,7 @@ async def list_themes() -> ThemesListResponse: This endpoint is public and does not require authentication. """ + locale = get_locale_from_request(request) try: theme_service = get_theme_service() themes = theme_service.list_themes() @@ -37,12 +39,12 @@ async def list_themes() -> ThemesListResponse: logger.error(f"Error listing themes: {e}") raise HTTPException( status_code=500, - detail="Failed to load themes" + detail=t(locale, "themes.themesLoadError") ) @router.get("/{theme_id}", response_model=ThemeDetailResponse) -async def get_theme(theme_id: str) -> ThemeDetailResponse: +async def get_theme(theme_id: str, request: Request) -> ThemeDetailResponse: """ Get detailed information about a specific theme. @@ -58,6 +60,7 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse: Raises: 404: Theme not found """ + locale = get_locale_from_request(request) try: theme_service = get_theme_service() theme = theme_service.get_theme(theme_id) @@ -65,7 +68,7 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse: if theme is None: raise HTTPException( status_code=404, - detail=f"Theme not found: {theme_id}" + detail=t(locale, "themes.themeNotFound", theme_id=theme_id) ) return ThemeDetailResponse(theme=theme) @@ -75,12 +78,12 @@ async def get_theme(theme_id: str) -> ThemeDetailResponse: logger.error(f"Error getting theme {theme_id}: {e}") raise HTTPException( status_code=500, - detail="Failed to load theme" + detail=t(locale, "themes.themeLoadError") ) @router.get("/{theme_id}/preview") -async def get_theme_preview(theme_id: str) -> dict: +async def get_theme_preview(theme_id: str, request: Request) -> dict: """ Get a signed URL for the theme's preview image. @@ -96,20 +99,21 @@ async def get_theme_preview(theme_id: str) -> dict: Raises: 404: Theme not found or no preview available """ + locale = get_locale_from_request(request) try: theme_service = get_theme_service() if not theme_service.theme_exists(theme_id): raise HTTPException( status_code=404, - detail=f"Theme not found: {theme_id}" + detail=t(locale, "themes.themeNotFound", theme_id=theme_id) ) theme = theme_service.get_theme(theme_id) if theme is None or theme.preview_url is None: raise HTTPException( status_code=404, - detail=f"No preview available for theme: {theme_id}" + detail=t(locale, "themes.previewNotAvailable", theme_id=theme_id) ) return {"preview_url": theme.preview_url} @@ -119,12 +123,12 @@ async def get_theme_preview(theme_id: str) -> dict: logger.error(f"Error getting preview for theme {theme_id}: {e}") raise HTTPException( status_code=500, - detail="Failed to load theme preview" + detail=t(locale, "themes.previewLoadError") ) @router.get("/{theme_id}/youtube-description") -async def get_theme_youtube_description(theme_id: str) -> dict: +async def get_theme_youtube_description(theme_id: str, request: Request) -> dict: """ Get the YouTube description template for a theme. @@ -141,13 +145,14 @@ async def get_theme_youtube_description(theme_id: str) -> dict: Raises: 404: Theme not found """ + locale = get_locale_from_request(request) try: theme_service = get_theme_service() if not theme_service.theme_exists(theme_id): raise HTTPException( status_code=404, - detail=f"Theme not found: {theme_id}" + detail=t(locale, "themes.youtubeDescriptionNotFound", theme_id=theme_id) ) description = theme_service.get_youtube_description(theme_id) @@ -158,5 +163,5 @@ async def get_theme_youtube_description(theme_id: str) -> dict: logger.error(f"Error getting YouTube description for theme {theme_id}: {e}") raise HTTPException( status_code=500, - detail="Failed to load YouTube description" + detail=t(locale, "themes.youtubeDescriptionLoadError") ) diff --git a/backend/api/routes/users.py b/backend/api/routes/users.py index b2ff267a..d1830f42 100644 --- a/backend/api/routes/users.py +++ b/backend/api/routes/users.py @@ -35,6 +35,7 @@ def _mask_email(email: str) -> str: from fastapi import APIRouter, HTTPException, Depends, Request, Header from pydantic import BaseModel, EmailStr +from backend.i18n import t, get_locale_from_request from backend.services.email_validation_service import get_email_validation_service from backend.models.user import ( UserRole, @@ -182,18 +183,20 @@ async def send_magic_link( # (done before email service check so we can reject without needing email config) email_validation = get_email_validation_service() + locale = get_locale_from_request(http_request) + if email_validation.is_disposable_domain(email): logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}") raise HTTPException( status_code=422, - detail="disposable_email_not_allowed" + detail=t(locale, "users.disposableEmailBlocked") ) if email_validation.is_email_blocked(email): logger.warning(f"Blocked email signup attempt: {_mask_email(email)}") return SendMagicLinkResponse( status="success", - message="If this email is registered, you will receive a sign-in link shortly." + message=t(locale, "users.magicLinkSent") ) ip_address = get_client_ip(http_request) @@ -201,7 +204,7 @@ async def send_magic_link( logger.warning(f"Blocked IP signup attempt: {ip_address}") return SendMagicLinkResponse( status="success", - message="If this email is registered, you will receive a sign-in link shortly." + message=t(locale, "users.magicLinkSent") ) # Per-IP and per-fingerprint signup rate limit (only for new users) @@ -217,7 +220,7 @@ async def send_magic_link( # Silent reject (anti-enumeration) return SendMagicLinkResponse( status="success", - message="If this email is registered, you will receive a sign-in link shortly." + message=t(locale, "users.magicLinkSent") ) # Check if email service is configured @@ -225,7 +228,7 @@ async def send_magic_link( logger.error("Email service not configured - cannot send magic links") raise HTTPException( status_code=503, - detail="Email service is not available. Please contact support." + detail=t(locale, "users.emailServiceNotConfigured") ) # Get tenant context from middleware @@ -239,7 +242,7 @@ async def send_magic_link( # Return success anyway to prevent email enumeration return SendMagicLinkResponse( status="success", - message="If this email is registered, you will receive a sign-in link shortly." + message=t(locale, "users.magicLinkSent") ) # Get client info for security logging (ip_address already extracted above for blocklist check) @@ -291,7 +294,7 @@ async def send_magic_link( return SendMagicLinkResponse( status="success", - message="If this email is registered, you will receive a sign-in link shortly." + message=t(locale, "users.magicLinkSent") ) @@ -308,9 +311,11 @@ async def verify_magic_link( Returns a session token that should be stored and used for subsequent requests. The session will be associated with the tenant from the magic link. """ + locale = get_locale_from_request(http_request) + # Reject empty tokens early to avoid invalid Firestore document paths if not token or not token.strip(): - raise HTTPException(status_code=401, detail="Invalid token") + raise HTTPException(status_code=401, detail=t(locale, "users.invalidToken")) # Get client info ip_address = get_client_ip(http_request) @@ -334,7 +339,7 @@ async def verify_magic_link( success, user, message = user_service.verify_magic_link(token) if not success or not user: - raise HTTPException(status_code=401, detail=message) + raise HTTPException(status_code=401, detail=t(locale, "users.verifyError", message=message)) # Grant welcome credits on first verification (with AI abuse evaluation) # Use pre-computed evaluation from magic link if available (computed at send time) @@ -397,7 +402,7 @@ async def verify_magic_link( status="success", session_token=session.token, user=user_public, - message="Successfully signed in", + message=t(locale, "users.magicLinkSuccess"), tenant_subdomain=tenant_subdomain, credits_granted=credits_granted, credit_status=credit_status, @@ -406,21 +411,23 @@ async def verify_magic_link( @router.post("/auth/logout", response_model=LogoutResponse) async def logout( + request: Request, authorization: Optional[str] = Header(None), user_service: UserService = Depends(get_user_service), ): """ Logout and invalidate the current session. """ + locale = get_locale_from_request(request) if not authorization: - return LogoutResponse(status="success", message="Already logged out") + return LogoutResponse(status="success", message=t(locale, "users.logoutSuccess")) # Extract token from "Bearer " token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization user_service.revoke_session(token) - return LogoutResponse(status="success", message="Successfully logged out") + return LogoutResponse(status="success", message=t(locale, "users.logoutSuccess")) # ============================================================================= @@ -429,6 +436,7 @@ async def logout( @router.get("/me", response_model=UserProfileResponse) async def get_current_user( + request: Request, authorization: Optional[str] = Header(None), user_service: UserService = Depends(get_user_service), ): @@ -437,10 +445,11 @@ async def get_current_user( Requires a valid session token or admin token. """ + locale = get_locale_from_request(request) from backend.services.auth_service import get_auth_service if not authorization: - raise HTTPException(status_code=401, detail="Not authenticated") + raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound")) # Extract token token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization @@ -471,7 +480,7 @@ async def get_current_user( valid, user, message = user_service.validate_session(token) if not valid or not user: - raise HTTPException(status_code=401, detail=message) + raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound")) feedback_eligible = ( user.total_jobs_completed >= 2 @@ -1144,6 +1153,7 @@ async def stripe_webhook( @router.get("/feedback/eligibility", response_model=FeedbackEligibilityResponse) async def check_feedback_eligibility( + request: Request, authorization: Optional[str] = Header(None), user_service: UserService = Depends(get_user_service), ): @@ -1152,8 +1162,9 @@ async def check_feedback_eligibility( Eligible if: total_jobs_completed >= 2 AND has not already submitted feedback. """ + locale = get_locale_from_request(request) if not authorization: - raise HTTPException(status_code=401, detail="Authentication required") + raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound")) token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization @@ -1168,7 +1179,7 @@ async def check_feedback_eligibility( else: valid, user, message = user_service.validate_session(token) if not valid or not user: - raise HTTPException(status_code=401, detail=message) + raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound")) eligible = user.total_jobs_completed >= 2 and not user.has_submitted_feedback @@ -1182,6 +1193,7 @@ async def check_feedback_eligibility( @router.post("/feedback", response_model=UserFeedbackResponse) async def submit_user_feedback( + http_request: Request, request: UserFeedbackRequest, authorization: Optional[str] = Header(None), user_service: UserService = Depends(get_user_service), @@ -1193,8 +1205,9 @@ async def submit_user_feedback( not have already submitted feedback. At least one text field must have >50 characters. """ + locale = get_locale_from_request(http_request) if not authorization: - raise HTTPException(status_code=401, detail="Authentication required") + raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound")) token = authorization.replace("Bearer ", "") if authorization.startswith("Bearer ") else authorization @@ -1209,20 +1222,20 @@ async def submit_user_feedback( else: valid, user, message = user_service.validate_session(token) if not valid or not user: - raise HTTPException(status_code=401, detail=message) + raise HTTPException(status_code=401, detail=t(locale, "users.userNotFound")) # Check eligibility: must have completed 2+ jobs if user.total_jobs_completed < 2: raise HTTPException( status_code=400, - detail="You need to complete at least 2 karaoke videos before submitting feedback." + detail=t(locale, "users.feedbackNotEligible") ) # Check if already submitted if user.has_submitted_feedback: raise HTTPException( status_code=400, - detail="You have already submitted feedback. Thank you!" + detail=t(locale, "users.feedbackNotEligible") ) # Validate: at least one text field has >50 characters @@ -1495,12 +1508,14 @@ async def list_users( @router.get("/admin/users/{email}/detail", response_model=UserDetailResponse) async def get_user_detail( email: str, + request: Request, auth_data: Tuple[str, UserType, int] = Depends(require_admin), user_service: UserService = Depends(get_user_service), ): """ Get detailed user information including credit history and recent jobs (admin only). """ + locale = get_locale_from_request(request) from google.cloud import firestore from google.cloud.firestore_v1 import FieldFilter from urllib.parse import unquote @@ -1510,7 +1525,7 @@ async def get_user_detail( user = user_service.get_user(email) if not user: - raise HTTPException(status_code=404, detail="User not found") + raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound")) db = user_service.db @@ -1627,18 +1642,20 @@ async def add_credits_to_user( @router.post("/admin/users/{email}/disable") async def disable_user( email: str, + request: Request, auth_data: AuthResult = Depends(require_admin), user_service: UserService = Depends(get_user_service), ): """ Disable a user account (admin only). """ + locale = get_locale_from_request(request) admin_id = auth_data.user_email or "admin:unknown" success = user_service.disable_user(email, admin_email=admin_id) if not success: - raise HTTPException(status_code=404, detail="User not found") + raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound")) return {"status": "success", "message": f"User {email} has been disabled"} @@ -1646,18 +1663,20 @@ async def disable_user( @router.post("/admin/users/{email}/enable") async def enable_user( email: str, + request: Request, auth_data: AuthResult = Depends(require_admin), user_service: UserService = Depends(get_user_service), ): """ Enable a user account (admin only). """ + locale = get_locale_from_request(request) admin_id = auth_data.user_email or "admin:unknown" success = user_service.enable_user(email, admin_email=admin_id) if not success: - raise HTTPException(status_code=404, detail="User not found") + raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound")) return {"status": "success", "message": f"User {email} has been enabled"} @@ -1665,6 +1684,7 @@ async def enable_user( @router.delete("/admin/users/{email}") async def delete_user( email: str, + request: Request, auth_data: AuthResult = Depends(require_admin), user_service: UserService = Depends(get_user_service), ): @@ -1673,6 +1693,7 @@ async def delete_user( Jobs are NOT deleted - they remain as historical records. """ + locale = get_locale_from_request(request) admin_id = auth_data.user_email or "admin:unknown" try: @@ -1681,7 +1702,7 @@ async def delete_user( raise HTTPException(status_code=400, detail=str(e)) if not success: - raise HTTPException(status_code=404, detail="User not found") + raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound")) return {"status": "success", "message": f"User {email} has been deleted"} @@ -1690,18 +1711,20 @@ async def delete_user( async def set_user_role( email: str, role: UserRole, + request: Request, auth_data: AuthResult = Depends(require_admin), user_service: UserService = Depends(get_user_service), ): """ Set a user's role (admin only). """ + locale = get_locale_from_request(request) admin_id = auth_data.user_email or "admin:unknown" success = user_service.set_user_role(email, role, admin_email=admin_id) if not success: - raise HTTPException(status_code=404, detail="User not found") + raise HTTPException(status_code=404, detail=t(locale, "users.userNotFound")) return {"status": "success", "message": f"User {email} role set to {role.value}"} diff --git a/backend/i18n.py b/backend/i18n.py new file mode 100644 index 00000000..d963c41c --- /dev/null +++ b/backend/i18n.py @@ -0,0 +1,99 @@ +""" +Lightweight i18n utility for backend translations. + +Usage: + from backend.i18n import t, get_locale_from_request, SUPPORTED_LOCALES + + # In a route handler: + locale = get_locale_from_request(request) + message = t(locale, "auth.userNotFound") + message = t(locale, "jobs.notFound", job_id="abc123") +""" + +import json +from functools import lru_cache +from pathlib import Path +from typing import Any + +from starlette.requests import Request + +SUPPORTED_LOCALES = ("en", "es", "de") +DEFAULT_LOCALE = "en" +TRANSLATIONS_DIR = Path(__file__).parent / "translations" + + +@lru_cache(maxsize=len(SUPPORTED_LOCALES)) +def _load_translations(locale: str) -> dict[str, Any]: + """Load and cache translation file for a locale.""" + path = TRANSLATIONS_DIR / f"{locale}.json" + if not path.exists(): + if locale != DEFAULT_LOCALE: + return _load_translations(DEFAULT_LOCALE) + return {} + with open(path, encoding="utf-8") as f: + result: dict[str, Any] = json.load(f) + return result + + +def t(locale: str, key: str, **kwargs: Any) -> str: + """Get a translated string by dotted key path. + + Args: + locale: Language code (en, es, de) + key: Dotted path like "auth.userNotFound" or "emails.magicLink.subject" + **kwargs: Interpolation variables (e.g., job_id="abc123") + + Returns: + Translated string with variables interpolated, or the key itself if not found. + """ + if locale not in SUPPORTED_LOCALES: + locale = DEFAULT_LOCALE + + translations = _load_translations(locale) + + # Walk the dotted path + value: Any = translations + for part in key.split("."): + if isinstance(value, dict) and part in value: + value = value[part] + else: + # Key not found — fall back to English + if locale != DEFAULT_LOCALE: + return t(DEFAULT_LOCALE, key, **kwargs) + return key # Return the key itself as last resort + + if not isinstance(value, str): + return key + + result: str = value + # Interpolate variables + if kwargs: + try: + result = result.format(**kwargs) + except KeyError: + pass # Missing variable — return template as-is + + return result + + +def get_locale_from_request(request: Request) -> str: + """Extract locale from Accept-Language header. + + Returns the first supported locale found, or DEFAULT_LOCALE. + """ + accept_lang = request.headers.get("accept-language", "") + + # Simple parsing — Accept-Language can be "de", "de-DE", "en-US,en;q=0.9,de;q=0.8" + for part in accept_lang.split(","): + lang = part.split(";")[0].strip().split("-")[0].lower() + if lang in SUPPORTED_LOCALES: + return lang + + return DEFAULT_LOCALE + + +def get_locale_prefix(locale: str) -> str: + """Get URL locale prefix for frontend URLs (e.g., '/en', '/es').""" + if locale not in SUPPORTED_LOCALES: + locale = DEFAULT_LOCALE + return f"/{locale}" diff --git a/backend/main.py b/backend/main.py index 0362e74d..d46e67f2 100644 --- a/backend/main.py +++ b/backend/main.py @@ -170,18 +170,20 @@ app.include_router(tenant.router) # Tenant/white-label configuration (no /api p from fastapi import Request from fastapi.responses import JSONResponse from backend.exceptions import InsufficientCreditsError +from backend.i18n import t, get_locale_from_request @app.exception_handler(InsufficientCreditsError) async def insufficient_credits_exception_handler(request: Request, exc: InsufficientCreditsError): """Handle insufficient credits errors with 402 Payment Required status.""" + locale = get_locale_from_request(request) return JSONResponse( status_code=402, content={ - "detail": exc.message, + "detail": t(locale, "errors.insufficientCredits"), "credits_available": exc.credits_available, "credits_required": exc.credits_required, - "buy_url": "/#pricing", + "buy_url": t(locale, "errors.insufficientCreditsBuyUrl"), }, ) diff --git a/backend/models/user.py b/backend/models/user.py index 098f8b3c..81134504 100644 --- a/backend/models/user.py +++ b/backend/models/user.py @@ -91,6 +91,9 @@ class User(BaseModel): # Optional profile fields for future use display_name: Optional[str] = None + # i18n locale preference (set from Accept-Language on login, used for emails/push) + locale: Optional[str] = None + # Push notification subscriptions (Web Push API) # Users can subscribe from multiple devices/browsers push_subscriptions: List[PushSubscription] = Field(default_factory=list) diff --git a/backend/services/push_notification_service.py b/backend/services/push_notification_service.py index ec7add0e..e6e0479e 100644 --- a/backend/services/push_notification_service.py +++ b/backend/services/push_notification_service.py @@ -12,6 +12,7 @@ from pywebpush import webpush, WebPushException from backend.config import get_settings from backend.models.user import User, PushSubscription +from backend.i18n import t logger = logging.getLogger(__name__) @@ -239,15 +240,16 @@ class PushNotificationService: artist = job.get("artist", "Unknown Artist") title = job.get("title", "Unknown Title") tenant_id = job.get("tenant_id") or None + locale = job.get("locale", "en") if action_type == "lyrics": - notif_title = "Review Lyrics" - notif_body = f'"{title}" by {artist} needs lyrics review' + notif_title = t(locale, "pushNotifications.reviewLyricsTitle") + notif_body = t(locale, "pushNotifications.reviewLyricsBody", title=title, artist=artist) url = f"/app/jobs#/{job_id}/review" tag = f"lyrics-{job_id}" else: # instrumental - notif_title = "Select Instrumental" - notif_body = f'"{title}" by {artist} needs instrumental selection' + notif_title = t(locale, "pushNotifications.selectInstrumentalTitle") + notif_body = t(locale, "pushNotifications.selectInstrumentalBody", title=title, artist=artist) url = f"/app/jobs#/{job_id}/instrumental" tag = f"instrumental-{job_id}" @@ -278,11 +280,12 @@ class PushNotificationService: artist = job.get("artist", "Unknown Artist") title = job.get("title", "Unknown Title") tenant_id = job.get("tenant_id") or None + locale = job.get("locale", "en") return await self.send_push( user_email=user_email, - title="Video Ready!", - body=f'Your karaoke video for "{title}" by {artist} is ready to download', + title=t(locale, "pushNotifications.videoReadyTitle"), + body=t(locale, "pushNotifications.videoReadyBody", title=title, artist=artist), url=f"/app/?job={job_id}", tag=f"complete-{job_id}", tenant_id=tenant_id, diff --git a/backend/tests/test_admin_feedback.py b/backend/tests/test_admin_feedback.py index 1bc62adf..9eda85f2 100644 --- a/backend/tests/test_admin_feedback.py +++ b/backend/tests/test_admin_feedback.py @@ -282,7 +282,7 @@ class TestSubmitFeedbackEmailIntegration: with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"): result = asyncio.get_event_loop().run_until_complete( - submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc) + submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc) ) # Verify email notification was called with matching args @@ -339,7 +339,7 @@ class TestSubmitFeedbackEmailIntegration: with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"): result = asyncio.get_event_loop().run_until_complete( - submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc) + submit_user_feedback(http_request=MagicMock(headers={"accept-language": "en"}), request=request, authorization="Bearer test-token", user_service=mock_user_svc) ) # User still gets credits even though email failed diff --git a/backend/tests/test_i18n.py b/backend/tests/test_i18n.py new file mode 100644 index 00000000..f4620ae8 --- /dev/null +++ b/backend/tests/test_i18n.py @@ -0,0 +1,113 @@ +"""Tests for backend.i18n translation utility.""" + +import pytest +from unittest.mock import MagicMock + +from backend.i18n import t, get_locale_from_request, get_locale_prefix, SUPPORTED_LOCALES, DEFAULT_LOCALE, _load_translations + + +class TestTranslationFunction: + """Tests for t() function.""" + + def test_returns_english_string(self): + result = t("en", "jobs.notFound") + assert result == "Job not found" + + def test_dotted_key_path(self): + result = t("en", "pushNotifications.reviewLyricsTitle") + assert result == "Review Lyrics" + + def test_interpolation(self): + result = t("en", "jobs.notCompleted", status="downloading") + assert result == "Only completed jobs can be edited. Current status: downloading" + + def test_multiple_interpolation_vars(self): + result = t("en", "jobs.durationMismatch", upload_duration="120", original_duration="180") + assert "120s" in result + assert "180s" in result + + def test_fallback_to_english_for_missing_key_in_other_locale(self): + # es.json is a copy of en.json right now, but if a key were missing it should fall back + result = t("es", "jobs.notFound") + assert result == "Job not found" + + def test_returns_key_for_nonexistent_key(self): + result = t("en", "nonexistent.key.path") + assert result == "nonexistent.key.path" + + def test_unsupported_locale_falls_back_to_english(self): + result = t("fr", "jobs.notFound") + assert result == "Job not found" + + def test_empty_locale_falls_back_to_english(self): + result = t("", "jobs.notFound") + assert result == "Job not found" + + def test_missing_interpolation_var_returns_template(self): + # If kwargs are missing, return template string as-is + result = t("en", "jobs.notCompleted") + assert "{status}" in result + + def test_all_supported_locales_load(self): + for locale in SUPPORTED_LOCALES: + translations = _load_translations(locale) + assert isinstance(translations, dict) + assert len(translations) > 0 + + +class TestGetLocaleFromRequest: + """Tests for get_locale_from_request().""" + + def _make_request(self, accept_language: str = "") -> MagicMock: + request = MagicMock() + request.headers = {"accept-language": accept_language} + return request + + def test_simple_locale(self): + request = self._make_request("de") + assert get_locale_from_request(request) == "de" + + def test_locale_with_region(self): + request = self._make_request("es-MX") + assert get_locale_from_request(request) == "es" + + def test_quality_weighted_list(self): + request = self._make_request("fr;q=0.9,de;q=0.8,en;q=0.7") + # fr is not supported, de is next + assert get_locale_from_request(request) == "de" + + def test_complex_accept_language(self): + request = self._make_request("en-US,en;q=0.9,de;q=0.8") + assert get_locale_from_request(request) == "en" + + def test_unsupported_locale_returns_default(self): + request = self._make_request("ja") + assert get_locale_from_request(request) == DEFAULT_LOCALE + + def test_empty_header_returns_default(self): + request = self._make_request("") + assert get_locale_from_request(request) == DEFAULT_LOCALE + + def test_missing_header_returns_default(self): + request = MagicMock() + request.headers = {} + assert get_locale_from_request(request) == DEFAULT_LOCALE + + +class TestGetLocalePrefix: + """Tests for get_locale_prefix().""" + + def test_english(self): + assert get_locale_prefix("en") == "/en" + + def test_spanish(self): + assert get_locale_prefix("es") == "/es" + + def test_german(self): + assert get_locale_prefix("de") == "/de" + + def test_unsupported_returns_english(self): + assert get_locale_prefix("fr") == "/en" + + def test_empty_returns_english(self): + assert get_locale_prefix("") == "/en" diff --git a/backend/tests/test_main.py b/backend/tests/test_main.py index 5bf62331..f0efc927 100644 --- a/backend/tests/test_main.py +++ b/backend/tests/test_main.py @@ -90,12 +90,16 @@ class TestExceptionHandlers: credits_required=1, ) - response = await insufficient_credits_exception_handler(request=None, exc=exc) + from unittest.mock import MagicMock + mock_request = MagicMock() + mock_request.headers = {"accept-language": "en"} + + response = await insufficient_credits_exception_handler(request=mock_request, exc=exc) assert response.status_code == 402 import json body = json.loads(response.body) - assert body["detail"] == "No credits remaining" + assert body["detail"] == "Insufficient credits for this operation" assert body["credits_available"] == 0 assert body["credits_required"] == 1 assert body["buy_url"] == "/#pricing" diff --git a/backend/translations/de.json b/backend/translations/de.json new file mode 100644 index 00000000..47c3ef4e --- /dev/null +++ b/backend/translations/de.json @@ -0,0 +1,195 @@ +{ + "auth": { + "unknownService": "Unknown service: {service}", + "invalidCredentials": "The following services need re-authorization: {services}", + "validCredentials": "All requested credentials are valid", + "youtubeAuthInstructions": "Visit {verification_url} and enter code: {user_code}", + "youtubeAuthStartFailed": "Failed to start YouTube device auth: {error}", + "gdriveLinkInstructions": "Visit {verification_url} and enter code: {user_code}", + "gdriveAuthStartFailed": "Failed to start Google Drive device auth: {error}", + "discordAlertNotConfigured": "Discord alert webhook not configured" + }, + "jobs": { + "created": "Job created successfully. Processing started.", + "authError": "Authentication error: no user identity available", + "noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.", + "notFound": "Job not found", + "noPermissionAccess": "You don't have permission to access this job", + "noPermissionEdit": "You don't have permission to edit this job", + "noPermissionDelete": "You don't have permission to delete this job", + "noPermissionModify": "You don't have permission to modify this job", + "notCompleted": "Only completed jobs can be edited. Current status: {status}", + "alreadyBeingEdited": "This job is already being edited (outputs were already deleted)", + "cleanupFailed": "Cleanup failed for {services}. Job not modified. Please try again or contact support.", + "reopened": "Track reopened for editing. Previous outputs have been removed.", + "invalidDatetimeFormat": "Invalid {field} format: {value}", + "listError": "Error listing jobs: {error}", + "deleteError": "Error deleting job {job_id}: {error}", + "deletionPreview": "Add &confirm=true to execute deletion", + "deletionRequiresFilters": "At least one filter (environment, client_id, status, created_before) is required", + "bulkDeleteError": "Error bulk deleting jobs: {error}", + "reviewNotReady": "Job not ready for review (current status: {status})", + "correctionsUnavailable": "Corrections data not available", + "audioUnavailable": "Audio not available for review", + "reviewCannotStart": "Cannot start review", + "jobNotInReviewState": "Job not in review state (current status: {status})", + "correctionsProcessing": "Corrections saved. Call /complete-review when done.", + "editLogSaveFailed": "Error saving edit log for job {job_id}: {error}", + "stemsMissing": "Job missing required stems (instrumental_clean and/or backing_vocals)", + "customInstrumentalFailed": "Error creating custom instrumental for job {job_id}: {error}", + "audioProcessingFailed": "Failed to process audio file: {error}", + "durationMismatch": "Duration mismatch: uploaded file is {upload_duration}s but original audio is {original_duration}s. The instrumental must be exactly {original_duration}s (±0.5s).", + "reviewNotInState": "Job not in review state (current status: {status})", + "noLyricsDetected": "Cannot complete review: no lyrics were detected in the audio. This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). You can go back and paste lyrics manually using 'Replace All', or cancel this job and try again with an audio file that contains vocals.", + "reviewCompleteStartRendering": "Review complete. Video rendering started.", + "reviewCompleteError": "Error completing review for job {job_id}: {error}", + "instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.", + "invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}", + "instrumentalSelected": "Instrumental selected. Video generation started.", + "instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}", + "downloadUrlsError": "Error getting download URLs: {error}" + }, + "review": { + "jobNotFound": "Job not found", + "reviewNotReady": "Job not ready for review (current status: {status})", + "correctionsNotFound": "Corrections data not found. Lyrics processing may not be complete.", + "correctionsLoadFailed": "Error loading corrections: {error}", + "audioNotFound": "Audio file not found", + "audioServeError": "Error serving audio: {error}", + "instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.", + "invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}", + "reviewCompletedError": "Error completing review: {error}", + "handlersUpdateNotImplemented": "Handler updates not yet implemented", + "lyricsAddError": "Failed to add lyrics: {error}", + "lyricsAddInvalidRequest": "Invalid add lyrics request: {error}", + "lyricsSearchError": "Failed to search lyrics: {error}", + "lyricsSearchInvalidRequest": "Invalid search lyrics request: {error}", + "lyricsSearchNoResults": "No matching lyrics found from any provider", + "previewVideoGenerationError": "Failed to generate preview video: {error}", + "previewVideoNotFound": "Preview video not found", + "previewVideoStreamError": "Error streaming preview video: {error}", + "annotationSaveError": "Error saving annotations: {error}", + "waveformGenerationError": "Error generating waveform data: {error}", + "waveformNoAudio": "No audio available for waveform", + "sessionSaveError": "Correction data is required" + }, + "audioSearch": { + "notEnabled": "Audio search is not enabled for this tenant", + "disabled": "Audio search is not available", + "downloadError": "Download failed for job {job_id}: {error}", + "jobNotFound": "Job {job_id} not found", + "noSearchResults": "No search results available", + "invalidSelectionIndex": "Invalid selection index {selection_index}. Valid range: 0-{max}", + "selectionError": "Error during audio selection for job {job_id}: {error}", + "youtubeDownloadError": "YouTube download failed: {error}", + "torrentDownloadError": "Cannot download from {source} without remote flacfetch service. Configure FLACFETCH_API_URL.", + "remoteDownloadNoSearchId": "No source_id or remote_search_id available for {source} download", + "remoteDownloadCompleteNoPath": "Remote download completed but no file path returned", + "spotifyDownloadError": "Cannot download from Spotify without remote flacfetch service. Configure FLACFETCH_API_URL.", + "genericDownloadError": "Unknown source type: {source}, attempting generic download", + "jobNotFoundDuringDownload": "Job {job_id} not found during background download", + "selectAudioError": "Error selecting audio for job {job_id}: {error}", + "searchAudioError": "Error searching audio: {error}", + "searchCreatedSuccessfully": "Job created. Searching for audio...", + "autoDownloadStarted": "Best result selected automatically. Download starting..." + }, + "users": { + "disposableEmailBlocked": "disposable_email_not_allowed", + "magicLinkSent": "If this email is registered, you will receive a sign-in link shortly.", + "emailServiceNotConfigured": "Email service is not available. Please contact support.", + "emailDomainNotAllowed": "Email domain not allowed for this tenant", + "invalidToken": "Invalid token", + "verifyError": "Verification failed: {message}", + "magicLinkSuccess": "Successfully signed in", + "logoutSuccess": "Successfully logged out", + "userNotFound": "User not found", + "creditPackagesError": "Error loading credit packages: {error}", + "stripeSendError": "Error sending Stripe checkout link: {error}", + "stripeWebhookProcessingError": "Error processing Stripe webhook: {error}", + "feedbackSaveError": "Error saving feedback: {error}", + "feedbackNotEligible": "User not eligible for feedback" + }, + "fileUpload": { + "invalidTheme": "Theme not found: {theme_id}. Use GET /api/themes to list available themes.", + "uploadSuccess": "File uploaded successfully. Processing started.", + "uploadError": "Error uploading file: {error}", + "urlDownloadError": "Error downloading from URL: {error}", + "invalidContentType": "Invalid content type: {content_type}", + "fileSizeError": "File is too large: {size}. Maximum: {max_size}", + "invalidFileType": "Invalid file type: {file_type}", + "multipleAudioFilesNotAllowed": "Only one audio file can be uploaded", + "noAudioFileProvided": "No audio file provided", + "urlCreationSuccess": "Job created. Upload URLs generated.", + "urlCreationError": "Error creating job with upload URLs: {error}", + "uploadsCompleteSuccess": "Uploads complete. Processing started.", + "uploadsCompleteError": "Error completing uploads: {error}", + "noUploadedFiles": "No uploaded files specified", + "styleUploadUrlsSuccess": "Style upload URLs generated.", + "styleUploadsCompleteSuccess": "Style files updated. Processing restarted.", + "styleUploadsCompleteError": "Error completing style uploads: {error}" + }, + "catalog": { + "rateLimitExceeded": "Rate limit exceeded. Maximum {max_requests} catalog requests per minute.", + "catalogSearchError": "Error searching catalog: {error}", + "communityCheckError": "Error checking community versions: {error}" + }, + "themes": { + "themesLoadError": "Failed to load themes", + "themeNotFound": "Theme not found: {theme_id}", + "themeLoadError": "Failed to load theme", + "previewNotAvailable": "No preview available for theme: {theme_id}", + "previewLoadError": "Failed to load theme preview", + "youtubeDescriptionNotFound": "Theme not found: {theme_id}", + "youtubeDescriptionLoadError": "Failed to load YouTube description" + }, + "tenant": { + "assetNotFound": "Asset not found" + }, + "push": { + "disabled": "Push notifications are not enabled", + "userEmailNotAvailable": "User email not available", + "missingEncryptionKeys": "Missing required keys (p256dh, auth)", + "subscriptionSaveFailed": "Failed to save subscription", + "subscriptionRegistered": "Push subscription registered successfully", + "subscriptionNotFound": "Subscription removed (or was not found)", + "subscriptionRemoved": "Push subscription removed successfully", + "testNotificationSent": "Test notification sent to {sent_count} device(s)" + }, + "pushNotifications": { + "reviewLyricsTitle": "Review Lyrics", + "reviewLyricsBody": "\"{title}\" by {artist} needs lyrics review", + "selectInstrumentalTitle": "Select Instrumental", + "selectInstrumentalBody": "\"{title}\" by {artist} needs instrumental selection", + "videoReadyTitle": "Video Ready!", + "videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download" + }, + "admin": { + "invalidDomainFormat": "Invalid domain format", + "domainAddedToBl": "Domain '{domain}' added to disposable domains blocklist", + "domainNotFoundInBl": "Domain not found in blocklist", + "domainRemovedFromBl": "Domain '{domain}' removed from disposable domains blocklist", + "domainAddedToAllowlist": "Domain '{domain}' added to allowlist", + "domainNotFoundInAllowlist": "Domain not found in allowlist", + "domainRemovedFromAllowlist": "Domain '{domain}' removed from allowlist", + "syncComplete": "Synced {external_count} external domains ({added} added, {removed} removed)", + "invalidEmailFormat": "Invalid email format", + "emailAddedToBl": "Email '{email}' added to blocked emails list", + "emailNotFoundInBl": "Email not found in blocklist", + "emailRemovedFromBl": "Email '{email}' removed from blocked emails list", + "invalidIPAddress": "Invalid IP address", + "ipAddedToBl": "IP '{ip_address}' added to blocked IPs list", + "ipNotFoundInBl": "IP not found in blocklist", + "ipRemovedFromBl": "IP '{ip_address}' removed from blocked IPs list", + "youtubeUploadNotFound": "Upload not found or not in retryable state for job {job_id}", + "youtubeUploadQueuedForRetry": "YouTube upload for job {job_id} queued for retry", + "youtubeQueueProcessingStarted": "YouTube queue processing started in background" + }, + "rateLimits": { + "configNotFound": "Rate limit config not found: {config_id}", + "configUpdateError": "Error updating rate limit config: {error}" + }, + "errors": { + "insufficientCredits": "Insufficient credits for this operation", + "insufficientCreditsBuyUrl": "/#pricing" + } +} diff --git a/backend/translations/en.json b/backend/translations/en.json new file mode 100644 index 00000000..47c3ef4e --- /dev/null +++ b/backend/translations/en.json @@ -0,0 +1,195 @@ +{ + "auth": { + "unknownService": "Unknown service: {service}", + "invalidCredentials": "The following services need re-authorization: {services}", + "validCredentials": "All requested credentials are valid", + "youtubeAuthInstructions": "Visit {verification_url} and enter code: {user_code}", + "youtubeAuthStartFailed": "Failed to start YouTube device auth: {error}", + "gdriveLinkInstructions": "Visit {verification_url} and enter code: {user_code}", + "gdriveAuthStartFailed": "Failed to start Google Drive device auth: {error}", + "discordAlertNotConfigured": "Discord alert webhook not configured" + }, + "jobs": { + "created": "Job created successfully. Processing started.", + "authError": "Authentication error: no user identity available", + "noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.", + "notFound": "Job not found", + "noPermissionAccess": "You don't have permission to access this job", + "noPermissionEdit": "You don't have permission to edit this job", + "noPermissionDelete": "You don't have permission to delete this job", + "noPermissionModify": "You don't have permission to modify this job", + "notCompleted": "Only completed jobs can be edited. Current status: {status}", + "alreadyBeingEdited": "This job is already being edited (outputs were already deleted)", + "cleanupFailed": "Cleanup failed for {services}. Job not modified. Please try again or contact support.", + "reopened": "Track reopened for editing. Previous outputs have been removed.", + "invalidDatetimeFormat": "Invalid {field} format: {value}", + "listError": "Error listing jobs: {error}", + "deleteError": "Error deleting job {job_id}: {error}", + "deletionPreview": "Add &confirm=true to execute deletion", + "deletionRequiresFilters": "At least one filter (environment, client_id, status, created_before) is required", + "bulkDeleteError": "Error bulk deleting jobs: {error}", + "reviewNotReady": "Job not ready for review (current status: {status})", + "correctionsUnavailable": "Corrections data not available", + "audioUnavailable": "Audio not available for review", + "reviewCannotStart": "Cannot start review", + "jobNotInReviewState": "Job not in review state (current status: {status})", + "correctionsProcessing": "Corrections saved. Call /complete-review when done.", + "editLogSaveFailed": "Error saving edit log for job {job_id}: {error}", + "stemsMissing": "Job missing required stems (instrumental_clean and/or backing_vocals)", + "customInstrumentalFailed": "Error creating custom instrumental for job {job_id}: {error}", + "audioProcessingFailed": "Failed to process audio file: {error}", + "durationMismatch": "Duration mismatch: uploaded file is {upload_duration}s but original audio is {original_duration}s. The instrumental must be exactly {original_duration}s (±0.5s).", + "reviewNotInState": "Job not in review state (current status: {status})", + "noLyricsDetected": "Cannot complete review: no lyrics were detected in the audio. This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). You can go back and paste lyrics manually using 'Replace All', or cancel this job and try again with an audio file that contains vocals.", + "reviewCompleteStartRendering": "Review complete. Video rendering started.", + "reviewCompleteError": "Error completing review for job {job_id}: {error}", + "instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.", + "invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}", + "instrumentalSelected": "Instrumental selected. Video generation started.", + "instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}", + "downloadUrlsError": "Error getting download URLs: {error}" + }, + "review": { + "jobNotFound": "Job not found", + "reviewNotReady": "Job not ready for review (current status: {status})", + "correctionsNotFound": "Corrections data not found. Lyrics processing may not be complete.", + "correctionsLoadFailed": "Error loading corrections: {error}", + "audioNotFound": "Audio file not found", + "audioServeError": "Error serving audio: {error}", + "instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.", + "invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}", + "reviewCompletedError": "Error completing review: {error}", + "handlersUpdateNotImplemented": "Handler updates not yet implemented", + "lyricsAddError": "Failed to add lyrics: {error}", + "lyricsAddInvalidRequest": "Invalid add lyrics request: {error}", + "lyricsSearchError": "Failed to search lyrics: {error}", + "lyricsSearchInvalidRequest": "Invalid search lyrics request: {error}", + "lyricsSearchNoResults": "No matching lyrics found from any provider", + "previewVideoGenerationError": "Failed to generate preview video: {error}", + "previewVideoNotFound": "Preview video not found", + "previewVideoStreamError": "Error streaming preview video: {error}", + "annotationSaveError": "Error saving annotations: {error}", + "waveformGenerationError": "Error generating waveform data: {error}", + "waveformNoAudio": "No audio available for waveform", + "sessionSaveError": "Correction data is required" + }, + "audioSearch": { + "notEnabled": "Audio search is not enabled for this tenant", + "disabled": "Audio search is not available", + "downloadError": "Download failed for job {job_id}: {error}", + "jobNotFound": "Job {job_id} not found", + "noSearchResults": "No search results available", + "invalidSelectionIndex": "Invalid selection index {selection_index}. Valid range: 0-{max}", + "selectionError": "Error during audio selection for job {job_id}: {error}", + "youtubeDownloadError": "YouTube download failed: {error}", + "torrentDownloadError": "Cannot download from {source} without remote flacfetch service. Configure FLACFETCH_API_URL.", + "remoteDownloadNoSearchId": "No source_id or remote_search_id available for {source} download", + "remoteDownloadCompleteNoPath": "Remote download completed but no file path returned", + "spotifyDownloadError": "Cannot download from Spotify without remote flacfetch service. Configure FLACFETCH_API_URL.", + "genericDownloadError": "Unknown source type: {source}, attempting generic download", + "jobNotFoundDuringDownload": "Job {job_id} not found during background download", + "selectAudioError": "Error selecting audio for job {job_id}: {error}", + "searchAudioError": "Error searching audio: {error}", + "searchCreatedSuccessfully": "Job created. Searching for audio...", + "autoDownloadStarted": "Best result selected automatically. Download starting..." + }, + "users": { + "disposableEmailBlocked": "disposable_email_not_allowed", + "magicLinkSent": "If this email is registered, you will receive a sign-in link shortly.", + "emailServiceNotConfigured": "Email service is not available. Please contact support.", + "emailDomainNotAllowed": "Email domain not allowed for this tenant", + "invalidToken": "Invalid token", + "verifyError": "Verification failed: {message}", + "magicLinkSuccess": "Successfully signed in", + "logoutSuccess": "Successfully logged out", + "userNotFound": "User not found", + "creditPackagesError": "Error loading credit packages: {error}", + "stripeSendError": "Error sending Stripe checkout link: {error}", + "stripeWebhookProcessingError": "Error processing Stripe webhook: {error}", + "feedbackSaveError": "Error saving feedback: {error}", + "feedbackNotEligible": "User not eligible for feedback" + }, + "fileUpload": { + "invalidTheme": "Theme not found: {theme_id}. Use GET /api/themes to list available themes.", + "uploadSuccess": "File uploaded successfully. Processing started.", + "uploadError": "Error uploading file: {error}", + "urlDownloadError": "Error downloading from URL: {error}", + "invalidContentType": "Invalid content type: {content_type}", + "fileSizeError": "File is too large: {size}. Maximum: {max_size}", + "invalidFileType": "Invalid file type: {file_type}", + "multipleAudioFilesNotAllowed": "Only one audio file can be uploaded", + "noAudioFileProvided": "No audio file provided", + "urlCreationSuccess": "Job created. Upload URLs generated.", + "urlCreationError": "Error creating job with upload URLs: {error}", + "uploadsCompleteSuccess": "Uploads complete. Processing started.", + "uploadsCompleteError": "Error completing uploads: {error}", + "noUploadedFiles": "No uploaded files specified", + "styleUploadUrlsSuccess": "Style upload URLs generated.", + "styleUploadsCompleteSuccess": "Style files updated. Processing restarted.", + "styleUploadsCompleteError": "Error completing style uploads: {error}" + }, + "catalog": { + "rateLimitExceeded": "Rate limit exceeded. Maximum {max_requests} catalog requests per minute.", + "catalogSearchError": "Error searching catalog: {error}", + "communityCheckError": "Error checking community versions: {error}" + }, + "themes": { + "themesLoadError": "Failed to load themes", + "themeNotFound": "Theme not found: {theme_id}", + "themeLoadError": "Failed to load theme", + "previewNotAvailable": "No preview available for theme: {theme_id}", + "previewLoadError": "Failed to load theme preview", + "youtubeDescriptionNotFound": "Theme not found: {theme_id}", + "youtubeDescriptionLoadError": "Failed to load YouTube description" + }, + "tenant": { + "assetNotFound": "Asset not found" + }, + "push": { + "disabled": "Push notifications are not enabled", + "userEmailNotAvailable": "User email not available", + "missingEncryptionKeys": "Missing required keys (p256dh, auth)", + "subscriptionSaveFailed": "Failed to save subscription", + "subscriptionRegistered": "Push subscription registered successfully", + "subscriptionNotFound": "Subscription removed (or was not found)", + "subscriptionRemoved": "Push subscription removed successfully", + "testNotificationSent": "Test notification sent to {sent_count} device(s)" + }, + "pushNotifications": { + "reviewLyricsTitle": "Review Lyrics", + "reviewLyricsBody": "\"{title}\" by {artist} needs lyrics review", + "selectInstrumentalTitle": "Select Instrumental", + "selectInstrumentalBody": "\"{title}\" by {artist} needs instrumental selection", + "videoReadyTitle": "Video Ready!", + "videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download" + }, + "admin": { + "invalidDomainFormat": "Invalid domain format", + "domainAddedToBl": "Domain '{domain}' added to disposable domains blocklist", + "domainNotFoundInBl": "Domain not found in blocklist", + "domainRemovedFromBl": "Domain '{domain}' removed from disposable domains blocklist", + "domainAddedToAllowlist": "Domain '{domain}' added to allowlist", + "domainNotFoundInAllowlist": "Domain not found in allowlist", + "domainRemovedFromAllowlist": "Domain '{domain}' removed from allowlist", + "syncComplete": "Synced {external_count} external domains ({added} added, {removed} removed)", + "invalidEmailFormat": "Invalid email format", + "emailAddedToBl": "Email '{email}' added to blocked emails list", + "emailNotFoundInBl": "Email not found in blocklist", + "emailRemovedFromBl": "Email '{email}' removed from blocked emails list", + "invalidIPAddress": "Invalid IP address", + "ipAddedToBl": "IP '{ip_address}' added to blocked IPs list", + "ipNotFoundInBl": "IP not found in blocklist", + "ipRemovedFromBl": "IP '{ip_address}' removed from blocked IPs list", + "youtubeUploadNotFound": "Upload not found or not in retryable state for job {job_id}", + "youtubeUploadQueuedForRetry": "YouTube upload for job {job_id} queued for retry", + "youtubeQueueProcessingStarted": "YouTube queue processing started in background" + }, + "rateLimits": { + "configNotFound": "Rate limit config not found: {config_id}", + "configUpdateError": "Error updating rate limit config: {error}" + }, + "errors": { + "insufficientCredits": "Insufficient credits for this operation", + "insufficientCreditsBuyUrl": "/#pricing" + } +} diff --git a/backend/translations/es.json b/backend/translations/es.json new file mode 100644 index 00000000..47c3ef4e --- /dev/null +++ b/backend/translations/es.json @@ -0,0 +1,195 @@ +{ + "auth": { + "unknownService": "Unknown service: {service}", + "invalidCredentials": "The following services need re-authorization: {services}", + "validCredentials": "All requested credentials are valid", + "youtubeAuthInstructions": "Visit {verification_url} and enter code: {user_code}", + "youtubeAuthStartFailed": "Failed to start YouTube device auth: {error}", + "gdriveLinkInstructions": "Visit {verification_url} and enter code: {user_code}", + "gdriveAuthStartFailed": "Failed to start Google Drive device auth: {error}", + "discordAlertNotConfigured": "Discord alert webhook not configured" + }, + "jobs": { + "created": "Job created successfully. Processing started.", + "authError": "Authentication error: no user identity available", + "noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.", + "notFound": "Job not found", + "noPermissionAccess": "You don't have permission to access this job", + "noPermissionEdit": "You don't have permission to edit this job", + "noPermissionDelete": "You don't have permission to delete this job", + "noPermissionModify": "You don't have permission to modify this job", + "notCompleted": "Only completed jobs can be edited. Current status: {status}", + "alreadyBeingEdited": "This job is already being edited (outputs were already deleted)", + "cleanupFailed": "Cleanup failed for {services}. Job not modified. Please try again or contact support.", + "reopened": "Track reopened for editing. Previous outputs have been removed.", + "invalidDatetimeFormat": "Invalid {field} format: {value}", + "listError": "Error listing jobs: {error}", + "deleteError": "Error deleting job {job_id}: {error}", + "deletionPreview": "Add &confirm=true to execute deletion", + "deletionRequiresFilters": "At least one filter (environment, client_id, status, created_before) is required", + "bulkDeleteError": "Error bulk deleting jobs: {error}", + "reviewNotReady": "Job not ready for review (current status: {status})", + "correctionsUnavailable": "Corrections data not available", + "audioUnavailable": "Audio not available for review", + "reviewCannotStart": "Cannot start review", + "jobNotInReviewState": "Job not in review state (current status: {status})", + "correctionsProcessing": "Corrections saved. Call /complete-review when done.", + "editLogSaveFailed": "Error saving edit log for job {job_id}: {error}", + "stemsMissing": "Job missing required stems (instrumental_clean and/or backing_vocals)", + "customInstrumentalFailed": "Error creating custom instrumental for job {job_id}: {error}", + "audioProcessingFailed": "Failed to process audio file: {error}", + "durationMismatch": "Duration mismatch: uploaded file is {upload_duration}s but original audio is {original_duration}s. The instrumental must be exactly {original_duration}s (±0.5s).", + "reviewNotInState": "Job not in review state (current status: {status})", + "noLyricsDetected": "Cannot complete review: no lyrics were detected in the audio. This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). You can go back and paste lyrics manually using 'Replace All', or cancel this job and try again with an audio file that contains vocals.", + "reviewCompleteStartRendering": "Review complete. Video rendering started.", + "reviewCompleteError": "Error completing review for job {job_id}: {error}", + "instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.", + "invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}", + "instrumentalSelected": "Instrumental selected. Video generation started.", + "instrumentalSelectionError": "Error selecting instrumental for job {job_id}: {error}", + "downloadUrlsError": "Error getting download URLs: {error}" + }, + "review": { + "jobNotFound": "Job not found", + "reviewNotReady": "Job not ready for review (current status: {status})", + "correctionsNotFound": "Corrections data not found. Lyrics processing may not be complete.", + "correctionsLoadFailed": "Error loading corrections: {error}", + "audioNotFound": "Audio file not found", + "audioServeError": "Error serving audio: {error}", + "instrumentalSelectionRequired": "instrumental_selection is required. Must be 'clean' or 'with_backing'.", + "invalidInstrumentalSelection": "Invalid instrumental_selection. Must be one of: {valid_selections}", + "reviewCompletedError": "Error completing review: {error}", + "handlersUpdateNotImplemented": "Handler updates not yet implemented", + "lyricsAddError": "Failed to add lyrics: {error}", + "lyricsAddInvalidRequest": "Invalid add lyrics request: {error}", + "lyricsSearchError": "Failed to search lyrics: {error}", + "lyricsSearchInvalidRequest": "Invalid search lyrics request: {error}", + "lyricsSearchNoResults": "No matching lyrics found from any provider", + "previewVideoGenerationError": "Failed to generate preview video: {error}", + "previewVideoNotFound": "Preview video not found", + "previewVideoStreamError": "Error streaming preview video: {error}", + "annotationSaveError": "Error saving annotations: {error}", + "waveformGenerationError": "Error generating waveform data: {error}", + "waveformNoAudio": "No audio available for waveform", + "sessionSaveError": "Correction data is required" + }, + "audioSearch": { + "notEnabled": "Audio search is not enabled for this tenant", + "disabled": "Audio search is not available", + "downloadError": "Download failed for job {job_id}: {error}", + "jobNotFound": "Job {job_id} not found", + "noSearchResults": "No search results available", + "invalidSelectionIndex": "Invalid selection index {selection_index}. Valid range: 0-{max}", + "selectionError": "Error during audio selection for job {job_id}: {error}", + "youtubeDownloadError": "YouTube download failed: {error}", + "torrentDownloadError": "Cannot download from {source} without remote flacfetch service. Configure FLACFETCH_API_URL.", + "remoteDownloadNoSearchId": "No source_id or remote_search_id available for {source} download", + "remoteDownloadCompleteNoPath": "Remote download completed but no file path returned", + "spotifyDownloadError": "Cannot download from Spotify without remote flacfetch service. Configure FLACFETCH_API_URL.", + "genericDownloadError": "Unknown source type: {source}, attempting generic download", + "jobNotFoundDuringDownload": "Job {job_id} not found during background download", + "selectAudioError": "Error selecting audio for job {job_id}: {error}", + "searchAudioError": "Error searching audio: {error}", + "searchCreatedSuccessfully": "Job created. Searching for audio...", + "autoDownloadStarted": "Best result selected automatically. Download starting..." + }, + "users": { + "disposableEmailBlocked": "disposable_email_not_allowed", + "magicLinkSent": "If this email is registered, you will receive a sign-in link shortly.", + "emailServiceNotConfigured": "Email service is not available. Please contact support.", + "emailDomainNotAllowed": "Email domain not allowed for this tenant", + "invalidToken": "Invalid token", + "verifyError": "Verification failed: {message}", + "magicLinkSuccess": "Successfully signed in", + "logoutSuccess": "Successfully logged out", + "userNotFound": "User not found", + "creditPackagesError": "Error loading credit packages: {error}", + "stripeSendError": "Error sending Stripe checkout link: {error}", + "stripeWebhookProcessingError": "Error processing Stripe webhook: {error}", + "feedbackSaveError": "Error saving feedback: {error}", + "feedbackNotEligible": "User not eligible for feedback" + }, + "fileUpload": { + "invalidTheme": "Theme not found: {theme_id}. Use GET /api/themes to list available themes.", + "uploadSuccess": "File uploaded successfully. Processing started.", + "uploadError": "Error uploading file: {error}", + "urlDownloadError": "Error downloading from URL: {error}", + "invalidContentType": "Invalid content type: {content_type}", + "fileSizeError": "File is too large: {size}. Maximum: {max_size}", + "invalidFileType": "Invalid file type: {file_type}", + "multipleAudioFilesNotAllowed": "Only one audio file can be uploaded", + "noAudioFileProvided": "No audio file provided", + "urlCreationSuccess": "Job created. Upload URLs generated.", + "urlCreationError": "Error creating job with upload URLs: {error}", + "uploadsCompleteSuccess": "Uploads complete. Processing started.", + "uploadsCompleteError": "Error completing uploads: {error}", + "noUploadedFiles": "No uploaded files specified", + "styleUploadUrlsSuccess": "Style upload URLs generated.", + "styleUploadsCompleteSuccess": "Style files updated. Processing restarted.", + "styleUploadsCompleteError": "Error completing style uploads: {error}" + }, + "catalog": { + "rateLimitExceeded": "Rate limit exceeded. Maximum {max_requests} catalog requests per minute.", + "catalogSearchError": "Error searching catalog: {error}", + "communityCheckError": "Error checking community versions: {error}" + }, + "themes": { + "themesLoadError": "Failed to load themes", + "themeNotFound": "Theme not found: {theme_id}", + "themeLoadError": "Failed to load theme", + "previewNotAvailable": "No preview available for theme: {theme_id}", + "previewLoadError": "Failed to load theme preview", + "youtubeDescriptionNotFound": "Theme not found: {theme_id}", + "youtubeDescriptionLoadError": "Failed to load YouTube description" + }, + "tenant": { + "assetNotFound": "Asset not found" + }, + "push": { + "disabled": "Push notifications are not enabled", + "userEmailNotAvailable": "User email not available", + "missingEncryptionKeys": "Missing required keys (p256dh, auth)", + "subscriptionSaveFailed": "Failed to save subscription", + "subscriptionRegistered": "Push subscription registered successfully", + "subscriptionNotFound": "Subscription removed (or was not found)", + "subscriptionRemoved": "Push subscription removed successfully", + "testNotificationSent": "Test notification sent to {sent_count} device(s)" + }, + "pushNotifications": { + "reviewLyricsTitle": "Review Lyrics", + "reviewLyricsBody": "\"{title}\" by {artist} needs lyrics review", + "selectInstrumentalTitle": "Select Instrumental", + "selectInstrumentalBody": "\"{title}\" by {artist} needs instrumental selection", + "videoReadyTitle": "Video Ready!", + "videoReadyBody": "Your karaoke video for \"{title}\" by {artist} is ready to download" + }, + "admin": { + "invalidDomainFormat": "Invalid domain format", + "domainAddedToBl": "Domain '{domain}' added to disposable domains blocklist", + "domainNotFoundInBl": "Domain not found in blocklist", + "domainRemovedFromBl": "Domain '{domain}' removed from disposable domains blocklist", + "domainAddedToAllowlist": "Domain '{domain}' added to allowlist", + "domainNotFoundInAllowlist": "Domain not found in allowlist", + "domainRemovedFromAllowlist": "Domain '{domain}' removed from allowlist", + "syncComplete": "Synced {external_count} external domains ({added} added, {removed} removed)", + "invalidEmailFormat": "Invalid email format", + "emailAddedToBl": "Email '{email}' added to blocked emails list", + "emailNotFoundInBl": "Email not found in blocklist", + "emailRemovedFromBl": "Email '{email}' removed from blocked emails list", + "invalidIPAddress": "Invalid IP address", + "ipAddedToBl": "IP '{ip_address}' added to blocked IPs list", + "ipNotFoundInBl": "IP not found in blocklist", + "ipRemovedFromBl": "IP '{ip_address}' removed from blocked IPs list", + "youtubeUploadNotFound": "Upload not found or not in retryable state for job {job_id}", + "youtubeUploadQueuedForRetry": "YouTube upload for job {job_id} queued for retry", + "youtubeQueueProcessingStarted": "YouTube queue processing started in background" + }, + "rateLimits": { + "configNotFound": "Rate limit config not found: {config_id}", + "configUpdateError": "Error updating rate limit config: {error}" + }, + "errors": { + "insufficientCredits": "Insufficient credits for this operation", + "insufficientCreditsBuyUrl": "/#pricing" + } +} diff --git a/pyproject.toml b/pyproject.toml index b3f879dd..816ec65c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "karaoke-gen" -version = "0.158.0" +version = "0.159.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 "] license = "MIT"