mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-30 09:14:03 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80b8d9c5ae | ||
|
|
2337f70311 | ||
|
|
e2298c2b29 | ||
|
|
c898689fb6 | ||
|
|
04467fe856 |
No files matched your search
+184
-91
@@ -20,6 +20,7 @@ from backend.services.user_service import get_user_service, UserService, USERS_C
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
|
||||
from backend.models.job import JobStatus
|
||||
from backend.utils.test_data import is_test_email
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
|
||||
@@ -61,12 +62,17 @@ class AdminStatsOverview(BaseModel):
|
||||
|
||||
@router.get("/stats/overview", response_model=AdminStatsOverview)
|
||||
async def get_admin_stats_overview(
|
||||
exclude_test: bool = True,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Get overview statistics for admin dashboard.
|
||||
|
||||
Args:
|
||||
exclude_test: If True (default), exclude test data (users with @inbox.testmail.app emails
|
||||
and jobs created by test users) from all counts.
|
||||
|
||||
Includes:
|
||||
- User counts (total, active in 7d, active in 30d)
|
||||
- Job counts (total, by status, recent)
|
||||
@@ -81,48 +87,10 @@ async def get_admin_stats_overview(
|
||||
seven_days_ago = now - timedelta(days=7)
|
||||
thirty_days_ago = now - timedelta(days=30)
|
||||
|
||||
# Helper function to get count using aggregation
|
||||
def get_count(query) -> int:
|
||||
try:
|
||||
agg_query = aggregation.AggregationQuery(query)
|
||||
agg_query.count(alias="count")
|
||||
results = agg_query.get()
|
||||
return results[0][0].value if results else 0
|
||||
except Exception as e:
|
||||
logger.warning(f"Aggregation query failed: {e}")
|
||||
return 0
|
||||
|
||||
# User statistics
|
||||
users_collection = db.collection(USERS_COLLECTION)
|
||||
|
||||
total_users = get_count(users_collection)
|
||||
|
||||
active_users_7d = get_count(
|
||||
users_collection.where(filter=FieldFilter("last_login_at", ">=", seven_days_ago))
|
||||
)
|
||||
|
||||
active_users_30d = get_count(
|
||||
users_collection.where(filter=FieldFilter("last_login_at", ">=", thirty_days_ago))
|
||||
)
|
||||
|
||||
total_beta_testers = get_count(
|
||||
users_collection.where(filter=FieldFilter("is_beta_tester", "==", True))
|
||||
)
|
||||
|
||||
# Job statistics
|
||||
jobs_collection = db.collection("jobs")
|
||||
|
||||
total_jobs = get_count(jobs_collection)
|
||||
|
||||
jobs_last_7d = get_count(
|
||||
jobs_collection.where(filter=FieldFilter("created_at", ">=", seven_days_ago))
|
||||
)
|
||||
|
||||
jobs_last_30d = get_count(
|
||||
jobs_collection.where(filter=FieldFilter("created_at", ">=", thirty_days_ago))
|
||||
)
|
||||
|
||||
# Jobs by status - map multiple statuses to simplified categories
|
||||
# Jobs by status category mapping
|
||||
processing_statuses = [
|
||||
"downloading", "downloading_audio", "searching_audio", "awaiting_audio_selection",
|
||||
"separating_stage1", "separating_stage2", "transcribing", "correcting",
|
||||
@@ -131,63 +99,166 @@ async def get_admin_stats_overview(
|
||||
"uploading", "notifying"
|
||||
]
|
||||
|
||||
jobs_by_status = JobsByStatusResponse(
|
||||
pending=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "pending"))
|
||||
),
|
||||
processing=sum(
|
||||
get_count(jobs_collection.where(filter=FieldFilter("status", "==", status)))
|
||||
for status in processing_statuses
|
||||
),
|
||||
awaiting_review=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "awaiting_review"))
|
||||
) + get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "in_review"))
|
||||
),
|
||||
awaiting_instrumental=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "awaiting_instrumental_selection"))
|
||||
),
|
||||
complete=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "complete"))
|
||||
) + get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "prep_complete"))
|
||||
),
|
||||
failed=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "failed"))
|
||||
),
|
||||
cancelled=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "cancelled"))
|
||||
),
|
||||
)
|
||||
# Limits for streaming queries - these are safety limits to prevent memory issues
|
||||
# If hit, stats may be incomplete so we log a warning
|
||||
USERS_STREAM_LIMIT = 2000
|
||||
JOBS_STREAM_LIMIT = 10000
|
||||
|
||||
# Credit statistics - sum credits added in last 30 days
|
||||
# This is more expensive, so we'll just estimate from users
|
||||
total_credits_issued_30d = 0
|
||||
try:
|
||||
# Get all users and sum recent credit transactions
|
||||
users_docs = users_collection.limit(500).stream()
|
||||
for user_doc in users_docs:
|
||||
user_data = user_doc.to_dict()
|
||||
if exclude_test:
|
||||
# When excluding test data, we must stream and filter in Python
|
||||
# because Firestore doesn't support "not ends with" queries
|
||||
|
||||
# Stream all users and filter
|
||||
all_users = []
|
||||
users_fetched = 0
|
||||
for doc in users_collection.limit(USERS_STREAM_LIMIT).stream():
|
||||
users_fetched += 1
|
||||
user_data = doc.to_dict()
|
||||
email = user_data.get("email", "")
|
||||
if not is_test_email(email):
|
||||
all_users.append(user_data)
|
||||
|
||||
if users_fetched >= USERS_STREAM_LIMIT:
|
||||
logger.warning(f"Users stream hit limit ({USERS_STREAM_LIMIT}), stats may be incomplete")
|
||||
|
||||
# Calculate user stats from filtered list
|
||||
total_users = len(all_users)
|
||||
active_users_7d = sum(
|
||||
1 for u in all_users
|
||||
if u.get("last_login_at") and _normalize_datetime(u["last_login_at"]) >= seven_days_ago
|
||||
)
|
||||
active_users_30d = sum(
|
||||
1 for u in all_users
|
||||
if u.get("last_login_at") and _normalize_datetime(u["last_login_at"]) >= thirty_days_ago
|
||||
)
|
||||
total_beta_testers = sum(1 for u in all_users if u.get("is_beta_tester"))
|
||||
|
||||
# Calculate credits from filtered users
|
||||
total_credits_issued_30d = 0
|
||||
for user_data in all_users:
|
||||
transactions = user_data.get("credit_transactions", [])
|
||||
for txn in transactions:
|
||||
txn_date = txn.get("created_at")
|
||||
if txn_date:
|
||||
# Handle both datetime and string formats
|
||||
if isinstance(txn_date, str):
|
||||
try:
|
||||
txn_date = datetime.fromisoformat(txn_date.replace("Z", "+00:00"))
|
||||
except Exception:
|
||||
continue
|
||||
if isinstance(txn_date, datetime):
|
||||
txn_date = txn_date.replace(tzinfo=None)
|
||||
else:
|
||||
continue
|
||||
if txn_date >= thirty_days_ago:
|
||||
txn_date = _normalize_datetime(txn.get("created_at"))
|
||||
if txn_date and txn_date >= thirty_days_ago:
|
||||
amount = txn.get("amount", 0)
|
||||
if amount > 0:
|
||||
total_credits_issued_30d += amount
|
||||
|
||||
# Stream all jobs and filter by user_email
|
||||
all_jobs = []
|
||||
jobs_fetched = 0
|
||||
for doc in jobs_collection.limit(JOBS_STREAM_LIMIT).stream():
|
||||
jobs_fetched += 1
|
||||
job_data = doc.to_dict()
|
||||
user_email = job_data.get("user_email", "")
|
||||
if not is_test_email(user_email):
|
||||
all_jobs.append(job_data)
|
||||
|
||||
if jobs_fetched >= JOBS_STREAM_LIMIT:
|
||||
logger.warning(f"Jobs stream hit limit ({JOBS_STREAM_LIMIT}), stats may be incomplete")
|
||||
|
||||
# Calculate job stats from filtered list
|
||||
total_jobs = len(all_jobs)
|
||||
jobs_last_7d = sum(
|
||||
1 for j in all_jobs
|
||||
if j.get("created_at") and _normalize_datetime(j["created_at"]) >= seven_days_ago
|
||||
)
|
||||
jobs_last_30d = sum(
|
||||
1 for j in all_jobs
|
||||
if j.get("created_at") and _normalize_datetime(j["created_at"]) >= thirty_days_ago
|
||||
)
|
||||
|
||||
# Jobs by status
|
||||
jobs_by_status = JobsByStatusResponse(
|
||||
pending=sum(1 for j in all_jobs if j.get("status") == "pending"),
|
||||
processing=sum(1 for j in all_jobs if j.get("status") in processing_statuses),
|
||||
awaiting_review=sum(1 for j in all_jobs if j.get("status") in ["awaiting_review", "in_review"]),
|
||||
awaiting_instrumental=sum(1 for j in all_jobs if j.get("status") == "awaiting_instrumental_selection"),
|
||||
complete=sum(1 for j in all_jobs if j.get("status") in ["complete", "prep_complete"]),
|
||||
failed=sum(1 for j in all_jobs if j.get("status") == "failed"),
|
||||
cancelled=sum(1 for j in all_jobs if j.get("status") == "cancelled"),
|
||||
)
|
||||
else:
|
||||
# When including test data, use efficient aggregation queries
|
||||
def get_count(query) -> int:
|
||||
try:
|
||||
agg_query = aggregation.AggregationQuery(query)
|
||||
agg_query.count(alias="count")
|
||||
results = agg_query.get()
|
||||
return results[0][0].value if results else 0
|
||||
except Exception as e:
|
||||
logger.warning(f"Aggregation query failed: {e}")
|
||||
return 0
|
||||
|
||||
# User statistics
|
||||
total_users = get_count(users_collection)
|
||||
active_users_7d = get_count(
|
||||
users_collection.where(filter=FieldFilter("last_login_at", ">=", seven_days_ago))
|
||||
)
|
||||
active_users_30d = get_count(
|
||||
users_collection.where(filter=FieldFilter("last_login_at", ">=", thirty_days_ago))
|
||||
)
|
||||
total_beta_testers = get_count(
|
||||
users_collection.where(filter=FieldFilter("is_beta_tester", "==", True))
|
||||
)
|
||||
|
||||
# Job statistics
|
||||
total_jobs = get_count(jobs_collection)
|
||||
jobs_last_7d = get_count(
|
||||
jobs_collection.where(filter=FieldFilter("created_at", ">=", seven_days_ago))
|
||||
)
|
||||
jobs_last_30d = get_count(
|
||||
jobs_collection.where(filter=FieldFilter("created_at", ">=", thirty_days_ago))
|
||||
)
|
||||
|
||||
# Jobs by status
|
||||
jobs_by_status = JobsByStatusResponse(
|
||||
pending=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "pending"))
|
||||
),
|
||||
processing=sum(
|
||||
get_count(jobs_collection.where(filter=FieldFilter("status", "==", status)))
|
||||
for status in processing_statuses
|
||||
),
|
||||
awaiting_review=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "awaiting_review"))
|
||||
) + get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "in_review"))
|
||||
),
|
||||
awaiting_instrumental=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "awaiting_instrumental_selection"))
|
||||
),
|
||||
complete=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "complete"))
|
||||
) + get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "prep_complete"))
|
||||
),
|
||||
failed=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "failed"))
|
||||
),
|
||||
cancelled=get_count(
|
||||
jobs_collection.where(filter=FieldFilter("status", "==", "cancelled"))
|
||||
),
|
||||
)
|
||||
|
||||
# Credit statistics - sum credits added in last 30 days
|
||||
total_credits_issued_30d = 0
|
||||
try:
|
||||
users_fetched = 0
|
||||
for user_doc in users_collection.limit(USERS_STREAM_LIMIT).stream():
|
||||
users_fetched += 1
|
||||
user_data = user_doc.to_dict()
|
||||
transactions = user_data.get("credit_transactions", [])
|
||||
for txn in transactions:
|
||||
txn_date = _normalize_datetime(txn.get("created_at"))
|
||||
if txn_date and txn_date >= thirty_days_ago:
|
||||
amount = txn.get("amount", 0)
|
||||
if amount > 0: # Only count additions, not deductions
|
||||
if amount > 0:
|
||||
total_credits_issued_30d += amount
|
||||
except Exception as e:
|
||||
logger.warning(f"Error calculating credits: {e}")
|
||||
if users_fetched >= USERS_STREAM_LIMIT:
|
||||
logger.warning(f"Credit calculation hit user limit ({USERS_STREAM_LIMIT}), total may be incomplete")
|
||||
except Exception as e:
|
||||
logger.warning(f"Error calculating credits: {e}")
|
||||
|
||||
return AdminStatsOverview(
|
||||
total_users=total_users,
|
||||
@@ -202,6 +273,21 @@ async def get_admin_stats_overview(
|
||||
)
|
||||
|
||||
|
||||
def _normalize_datetime(dt_value) -> Optional[datetime]:
|
||||
"""Normalize datetime values from Firestore (can be datetime or ISO string)."""
|
||||
if dt_value is None:
|
||||
return None
|
||||
if isinstance(dt_value, datetime):
|
||||
return dt_value.replace(tzinfo=None)
|
||||
if isinstance(dt_value, str):
|
||||
try:
|
||||
parsed = datetime.fromisoformat(dt_value.replace("Z", "+00:00"))
|
||||
return parsed.replace(tzinfo=None)
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Audio Search Management Models
|
||||
# =============================================================================
|
||||
@@ -273,6 +359,7 @@ class CacheStatsResponse(BaseModel):
|
||||
async def list_audio_searches(
|
||||
limit: int = 50,
|
||||
status_filter: Optional[str] = None,
|
||||
exclude_test: bool = True,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -287,6 +374,7 @@ async def list_audio_searches(
|
||||
Args:
|
||||
limit: Maximum number of jobs to return (default 50)
|
||||
status_filter: Optional filter by job status (e.g., 'awaiting_audio_selection')
|
||||
exclude_test: If True (default), exclude jobs from test users
|
||||
"""
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
|
||||
@@ -306,6 +394,11 @@ async def list_audio_searches(
|
||||
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
|
||||
# Filter out test users if exclude_test is True
|
||||
if exclude_test and is_test_email(data.get("user_email", "")):
|
||||
continue
|
||||
|
||||
state_data = data.get("state_data", {})
|
||||
audio_results = state_data.get("audio_search_results", [])
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ from backend.services.flacfetch_client import get_flacfetch_client
|
||||
from backend.services.email_service import get_email_service
|
||||
from backend.services.stripe_service import get_stripe_service
|
||||
from backend.services.encoding_service import get_encoding_service
|
||||
from backend.services.spacy_preloader import get_preloaded_model, is_model_preloaded
|
||||
from backend.services.nltk_preloader import get_preloaded_cmudict, is_cmudict_preloaded
|
||||
from backend.services.langfuse_preloader import get_preloaded_langfuse_handler, is_langfuse_preloaded, is_langfuse_configured
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -334,6 +337,68 @@ async def detailed_health_check() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/preload-status")
|
||||
async def preload_status() -> Dict[str, Any]:
|
||||
"""
|
||||
Check status of preloaded resources for performance optimization.
|
||||
|
||||
Use this endpoint to verify that NLTK, SpaCy, and Langfuse resources
|
||||
were successfully preloaded at container startup. If any show as
|
||||
not preloaded, check Cloud Run startup logs for errors.
|
||||
|
||||
Expected state after successful deployment:
|
||||
- spacy.preloaded: true
|
||||
- nltk.preloaded: true
|
||||
- langfuse.preloaded: true (if configured) or configured: false
|
||||
"""
|
||||
# SpaCy status
|
||||
spacy_model = get_preloaded_model("en_core_web_sm")
|
||||
spacy_status = {
|
||||
"preloaded": is_model_preloaded("en_core_web_sm"),
|
||||
"model": "en_core_web_sm",
|
||||
}
|
||||
if spacy_model:
|
||||
spacy_status["vocab_size"] = len(spacy_model.vocab)
|
||||
|
||||
# NLTK status
|
||||
cmudict = get_preloaded_cmudict()
|
||||
nltk_status = {
|
||||
"preloaded": is_cmudict_preloaded(),
|
||||
"resource": "cmudict",
|
||||
}
|
||||
if cmudict:
|
||||
nltk_status["entries"] = len(cmudict)
|
||||
|
||||
# Langfuse status
|
||||
langfuse_handler = get_preloaded_langfuse_handler()
|
||||
langfuse_status = {
|
||||
"configured": is_langfuse_configured(),
|
||||
"preloaded": is_langfuse_preloaded(),
|
||||
}
|
||||
if langfuse_handler:
|
||||
langfuse_status["handler_type"] = type(langfuse_handler).__name__
|
||||
|
||||
# Overall status
|
||||
all_preloaded = (
|
||||
spacy_status["preloaded"]
|
||||
and nltk_status["preloaded"]
|
||||
and (langfuse_status["preloaded"] or not langfuse_status["configured"])
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "ok" if all_preloaded else "degraded",
|
||||
"message": "All resources preloaded" if all_preloaded else "Some resources not preloaded - check startup logs",
|
||||
"spacy": spacy_status,
|
||||
"nltk": nltk_status,
|
||||
"langfuse": langfuse_status,
|
||||
"performance_impact": {
|
||||
"spacy_preload": "Saves ~60s on first lyrics correction",
|
||||
"nltk_preload": "Saves ~100-150s on SyllablesMatchHandler init",
|
||||
"langfuse_preload": "Saves ~200s on AgenticCorrector init",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.get("/readiness")
|
||||
async def readiness_check() -> Dict[str, str]:
|
||||
"""Readiness check endpoint for Cloud Run."""
|
||||
|
||||
@@ -29,6 +29,7 @@ from backend.config import get_settings
|
||||
from backend.api.dependencies import require_admin, require_auth, require_instrumental_auth
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.services.metrics import metrics
|
||||
from backend.utils.test_data import is_test_email
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -182,6 +183,7 @@ async def list_jobs(
|
||||
client_id: Optional[str] = None,
|
||||
created_after: Optional[str] = None,
|
||||
created_before: Optional[str] = None,
|
||||
exclude_test: bool = True,
|
||||
limit: int = 100,
|
||||
auth_result: AuthResult = Depends(require_auth)
|
||||
) -> List[Job]:
|
||||
@@ -196,6 +198,7 @@ async def list_jobs(
|
||||
client_id: Filter by request_metadata.client_id (customer identifier)
|
||||
created_after: Filter jobs created after this ISO datetime (e.g., 2024-01-01T00:00:00Z)
|
||||
created_before: Filter jobs created before this ISO datetime
|
||||
exclude_test: If True (default), exclude jobs from test users (admin only)
|
||||
limit: Maximum number of jobs to return (default 100)
|
||||
|
||||
Returns:
|
||||
@@ -242,6 +245,10 @@ async def list_jobs(
|
||||
limit=limit
|
||||
)
|
||||
|
||||
# Filter out test user jobs if exclude_test is True (admin only)
|
||||
if exclude_test and auth_result.is_admin:
|
||||
jobs = [j for j in jobs if not is_test_email(j.user_email or "")]
|
||||
|
||||
logger.debug(f"Listed {len(jobs)} jobs for user={auth_result.user_email}, admin={auth_result.is_admin}")
|
||||
return jobs
|
||||
except HTTPException:
|
||||
|
||||
+515
-42
@@ -34,6 +34,7 @@ from backend.services.email_service import get_email_service, EmailService
|
||||
from backend.services.stripe_service import get_stripe_service, StripeService, CREDIT_PACKAGES
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.utils.test_data import is_test_email
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -57,6 +58,16 @@ class CreateCheckoutResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
class DoneForYouCheckoutRequest(BaseModel):
|
||||
"""Request to create a done-for-you karaoke video order."""
|
||||
email: EmailStr
|
||||
artist: str
|
||||
title: str
|
||||
source_type: str = "search" # search, youtube, or upload
|
||||
youtube_url: Optional[str] = None
|
||||
notes: Optional[str] = None
|
||||
|
||||
|
||||
class CreditPackage(BaseModel):
|
||||
"""Credit package information."""
|
||||
id: str
|
||||
@@ -327,10 +338,435 @@ async def create_checkout(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/done-for-you/checkout", response_model=CreateCheckoutResponse)
|
||||
async def create_done_for_you_checkout(
|
||||
request: DoneForYouCheckoutRequest,
|
||||
stripe_service: StripeService = Depends(get_stripe_service),
|
||||
):
|
||||
"""
|
||||
Create a Stripe checkout session for a done-for-you karaoke video order.
|
||||
|
||||
This is the full-service option where Nomad Karaoke handles everything:
|
||||
- Finding or processing the audio
|
||||
- Reviewing and correcting lyrics
|
||||
- Selecting the best instrumental
|
||||
- Generating the final video
|
||||
|
||||
$15 with 24-hour delivery guarantee.
|
||||
No authentication required - customer email is provided in the request.
|
||||
"""
|
||||
if not stripe_service.is_configured():
|
||||
raise HTTPException(status_code=503, detail="Payment processing is not available")
|
||||
|
||||
success, checkout_url, message = stripe_service.create_done_for_you_checkout_session(
|
||||
customer_email=request.email,
|
||||
artist=request.artist,
|
||||
title=request.title,
|
||||
source_type=request.source_type,
|
||||
youtube_url=request.youtube_url,
|
||||
notes=request.notes,
|
||||
)
|
||||
|
||||
if not success or not checkout_url:
|
||||
raise HTTPException(status_code=400, detail=message)
|
||||
|
||||
return CreateCheckoutResponse(
|
||||
status="success",
|
||||
checkout_url=checkout_url,
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Stripe Webhooks
|
||||
# =============================================================================
|
||||
|
||||
# Admin email for done-for-you order notifications
|
||||
ADMIN_EMAIL = "andrew@nomadkaraoke.com"
|
||||
|
||||
|
||||
async def _handle_done_for_you_order(
|
||||
session_id: str,
|
||||
metadata: dict,
|
||||
user_service: UserService,
|
||||
email_service: EmailService,
|
||||
) -> None:
|
||||
"""
|
||||
Handle a completed done-for-you order by creating a job and notifying Andrew.
|
||||
|
||||
For orders with a YouTube URL, the job is created and workers are triggered immediately.
|
||||
For orders without a URL (search mode), the audio search flow is used to find and
|
||||
download the best matching audio source automatically.
|
||||
|
||||
Args:
|
||||
session_id: Stripe checkout session ID
|
||||
metadata: Order metadata from Stripe session
|
||||
user_service: User service for marking session processed
|
||||
email_service: Email service for notifications
|
||||
"""
|
||||
from backend.models.job import JobCreate, JobStatus
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.services.audio_search_service import (
|
||||
get_audio_search_service,
|
||||
NoResultsError,
|
||||
AudioSearchError,
|
||||
)
|
||||
from backend.services.storage_service import StorageService
|
||||
import asyncio
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
customer_email = metadata.get("customer_email", "")
|
||||
artist = metadata.get("artist", "Unknown Artist")
|
||||
title = metadata.get("title", "Unknown Title")
|
||||
source_type = metadata.get("source_type", "search")
|
||||
youtube_url = metadata.get("youtube_url")
|
||||
notes = metadata.get("notes", "")
|
||||
|
||||
logger.info(
|
||||
f"Processing done-for-you order: {artist} - {title} for {customer_email} "
|
||||
f"(session: {session_id}, source_type: {source_type})"
|
||||
)
|
||||
|
||||
try:
|
||||
job_manager = JobManager()
|
||||
worker_service = get_worker_service()
|
||||
storage_service = StorageService()
|
||||
|
||||
# Create job for the customer
|
||||
# Note: done-for-you jobs should NOT be non_interactive - Andrew needs to review
|
||||
job_create = JobCreate(
|
||||
url=youtube_url if youtube_url else None,
|
||||
artist=artist,
|
||||
title=title,
|
||||
user_email=customer_email, # Customer owns the job
|
||||
non_interactive=False, # Andrew will review lyrics/instrumental
|
||||
# Set audio search fields for search-based orders
|
||||
audio_search_artist=artist if not youtube_url else None,
|
||||
audio_search_title=title if not youtube_url else None,
|
||||
auto_download=True, # Auto-select best audio source
|
||||
)
|
||||
job = job_manager.create_job(job_create)
|
||||
job_id = job.job_id
|
||||
|
||||
logger.info(f"Created done-for-you job {job_id} for {customer_email}")
|
||||
|
||||
# Mark session as processed for idempotency
|
||||
# Note: Using internal method since this isn't a credit transaction
|
||||
user_service._mark_stripe_session_processed(
|
||||
stripe_session_id=session_id,
|
||||
email=customer_email,
|
||||
amount=0 # No credits, just tracking the session
|
||||
)
|
||||
|
||||
# Handle based on whether we have a YouTube URL or need to search
|
||||
if youtube_url:
|
||||
# URL provided - trigger workers directly
|
||||
logger.info(f"Job {job_id}: YouTube URL provided, triggering workers")
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
else:
|
||||
# No URL - use audio search flow with auto_download
|
||||
logger.info(f"Job {job_id}: No URL, using audio search for '{artist} - {title}'")
|
||||
|
||||
# Update job with audio search fields
|
||||
job_manager.update_job(job_id, {
|
||||
'audio_search_artist': artist,
|
||||
'audio_search_title': title,
|
||||
'auto_download': True,
|
||||
})
|
||||
|
||||
# Transition to searching state
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.SEARCHING_AUDIO,
|
||||
progress=5,
|
||||
message=f"Searching for audio: {artist} - {title}"
|
||||
)
|
||||
|
||||
# Perform audio search
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
try:
|
||||
search_results = audio_search_service.search(artist, title)
|
||||
except NoResultsError as e:
|
||||
# No results found - transition to AWAITING_AUDIO_SELECTION so Andrew can handle manually
|
||||
logger.warning(f"Job {job_id}: No audio sources found for '{artist} - {title}'")
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message=f"No automatic audio sources found. Manual intervention required."
|
||||
)
|
||||
# Don't fail the job - Andrew can manually provide audio
|
||||
search_results = None
|
||||
except AudioSearchError as e:
|
||||
logger.error(f"Job {job_id}: Audio search failed: {e}")
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message=f"Audio search error. Manual intervention required."
|
||||
)
|
||||
search_results = None
|
||||
|
||||
if search_results:
|
||||
# Store search results in state_data
|
||||
results_dicts = [r.to_dict() for r in search_results]
|
||||
state_data_update = {
|
||||
'audio_search_results': results_dicts,
|
||||
'audio_search_count': len(results_dicts),
|
||||
}
|
||||
if audio_search_service.last_remote_search_id:
|
||||
state_data_update['remote_search_id'] = audio_search_service.last_remote_search_id
|
||||
job_manager.update_job(job_id, {'state_data': state_data_update})
|
||||
|
||||
# Auto-select best result and download
|
||||
best_index = audio_search_service.select_best(search_results)
|
||||
selected = results_dicts[best_index]
|
||||
|
||||
logger.info(f"Job {job_id}: Auto-selected result {best_index}: {selected.get('provider')} - {selected.get('title')}")
|
||||
|
||||
# Transition to downloading state
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING_AUDIO,
|
||||
progress=10,
|
||||
message=f"Downloading from {selected.get('provider')}: {selected.get('artist')} - {selected.get('title')}",
|
||||
state_data_updates={
|
||||
'selected_audio_index': best_index,
|
||||
'selected_audio_provider': selected.get('provider'),
|
||||
}
|
||||
)
|
||||
|
||||
# Download audio
|
||||
try:
|
||||
is_torrent_source = selected.get('provider') in ['RED', 'OPS']
|
||||
is_remote_enabled = audio_search_service.is_remote_enabled()
|
||||
source_id = selected.get('source_id')
|
||||
source_name = selected.get('provider')
|
||||
target_file = selected.get('target_file')
|
||||
download_url = selected.get('url')
|
||||
remote_search_id = state_data_update.get('remote_search_id')
|
||||
|
||||
if is_torrent_source and is_remote_enabled:
|
||||
# Remote torrent download - upload directly to GCS
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
|
||||
if source_id and source_name:
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir="",
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
else:
|
||||
result = audio_search_service.download(
|
||||
result_index=best_index,
|
||||
output_dir="",
|
||||
gcs_path=gcs_destination,
|
||||
remote_search_id=remote_search_id,
|
||||
)
|
||||
|
||||
# Extract GCS path
|
||||
if result.filepath.startswith("gs://"):
|
||||
parts = result.filepath.replace("gs://", "").split("/", 1)
|
||||
audio_gcs_path = parts[1] if len(parts) == 2 else result.filepath
|
||||
filename = os.path.basename(result.filepath)
|
||||
else:
|
||||
filename = os.path.basename(result.filepath)
|
||||
audio_gcs_path = f"uploads/{job_id}/audio/{filename}"
|
||||
else:
|
||||
# Local download (YouTube or local torrent)
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"audio_download_{job_id}_")
|
||||
import shutil
|
||||
|
||||
try:
|
||||
if source_id and source_name and is_remote_enabled:
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir=temp_dir,
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
)
|
||||
elif source_name == 'YouTube' and download_url:
|
||||
# YouTube download
|
||||
from backend.workers.audio_worker import download_from_url
|
||||
local_path = await download_from_url(
|
||||
download_url,
|
||||
temp_dir,
|
||||
selected.get('artist'),
|
||||
selected.get('title')
|
||||
)
|
||||
if not local_path or not os.path.exists(local_path):
|
||||
raise Exception(f"Failed to download from YouTube: {download_url}")
|
||||
|
||||
class DownloadResult:
|
||||
def __init__(self, filepath):
|
||||
self.filepath = filepath
|
||||
result = DownloadResult(local_path)
|
||||
else:
|
||||
result = audio_search_service.download(
|
||||
result_index=best_index,
|
||||
output_dir=temp_dir,
|
||||
remote_search_id=remote_search_id,
|
||||
)
|
||||
|
||||
# Upload to GCS
|
||||
filename = os.path.basename(result.filepath)
|
||||
audio_gcs_path = f"uploads/{job_id}/audio/{filename}"
|
||||
|
||||
with open(result.filepath, 'rb') as f:
|
||||
storage_service.upload_fileobj(f, audio_gcs_path, content_type='audio/flac')
|
||||
finally:
|
||||
# Always cleanup temp directory
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
|
||||
# Update job with GCS path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
'filename': filename,
|
||||
})
|
||||
|
||||
# Transition to DOWNLOADING and trigger workers
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=15,
|
||||
message="Audio downloaded, starting processing"
|
||||
)
|
||||
|
||||
# Trigger workers
|
||||
await asyncio.gather(
|
||||
worker_service.trigger_audio_worker(job_id),
|
||||
worker_service.trigger_lyrics_worker(job_id)
|
||||
)
|
||||
|
||||
logger.info(f"Job {job_id}: Audio downloaded and workers triggered")
|
||||
|
||||
except Exception as download_error:
|
||||
logger.error(f"Job {job_id}: Audio download failed: {download_error}")
|
||||
# Don't fail job - transition to awaiting selection so Andrew can handle
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
|
||||
progress=10,
|
||||
message=f"Auto-download failed: {download_error}. Manual intervention required."
|
||||
)
|
||||
|
||||
# Send confirmation email to customer
|
||||
email_service.send_email(
|
||||
to_email=customer_email,
|
||||
subject=f"Your Karaoke Video Order: {artist} - {title}",
|
||||
html_content=f"""
|
||||
<h2>Thank you for your order!</h2>
|
||||
<p>We've received your request for a karaoke video:</p>
|
||||
<ul>
|
||||
<li><strong>Artist:</strong> {artist}</li>
|
||||
<li><strong>Title:</strong> {title}</li>
|
||||
{f'<li><strong>Notes:</strong> {notes}</li>' if notes else ''}
|
||||
</ul>
|
||||
<p>Our team will review and create your video within <strong>24 hours</strong>.</p>
|
||||
<p>You'll receive another email with download links when your video is ready.</p>
|
||||
<p>If you have any questions, reply to this email or contact us at support@nomadkaraoke.com</p>
|
||||
<p>Thanks for using Nomad Karaoke!</p>
|
||||
""",
|
||||
text_content=f"""
|
||||
Thank you for your order!
|
||||
|
||||
We've received your request for a karaoke video:
|
||||
- Artist: {artist}
|
||||
- Title: {title}
|
||||
{f'- Notes: {notes}' if notes else ''}
|
||||
|
||||
Our team will review and create your video within 24 hours.
|
||||
You'll receive another email with download links when your video is ready.
|
||||
|
||||
If you have any questions, reply to this email or contact us at support@nomadkaraoke.com
|
||||
|
||||
Thanks for using Nomad Karaoke!
|
||||
""".strip(),
|
||||
)
|
||||
|
||||
# Send notification email to Andrew
|
||||
email_service.send_email(
|
||||
to_email=ADMIN_EMAIL,
|
||||
subject=f"[Done For You Order] {artist} - {title}",
|
||||
html_content=f"""
|
||||
<h2>New Done-For-You Order</h2>
|
||||
<p>A customer has ordered a karaoke video:</p>
|
||||
<ul>
|
||||
<li><strong>Customer:</strong> {customer_email}</li>
|
||||
<li><strong>Artist:</strong> {artist}</li>
|
||||
<li><strong>Title:</strong> {title}</li>
|
||||
<li><strong>Source:</strong> {source_type}</li>
|
||||
{f'<li><strong>YouTube URL:</strong> <a href="{youtube_url}">{youtube_url}</a></li>' if youtube_url else ''}
|
||||
{f'<li><strong>Notes:</strong> {notes}</li>' if notes else ''}
|
||||
</ul>
|
||||
<p><strong>Job ID:</strong> {job_id}</p>
|
||||
<p>View job in admin: <a href="https://gen.nomadkaraoke.com/admin/jobs/{job_id}">Admin Link</a></p>
|
||||
<p>View job as customer: <a href="https://gen.nomadkaraoke.com/jobs/{job_id}">Customer Link</a></p>
|
||||
<p><strong>Deadline:</strong> 24 hours from now</p>
|
||||
""",
|
||||
text_content=f"""
|
||||
New Done-For-You Order
|
||||
|
||||
Customer: {customer_email}
|
||||
Artist: {artist}
|
||||
Title: {title}
|
||||
Source: {source_type}
|
||||
{f'YouTube URL: {youtube_url}' if youtube_url else ''}
|
||||
{f'Notes: {notes}' if notes else ''}
|
||||
|
||||
Job ID: {job_id}
|
||||
Admin: https://gen.nomadkaraoke.com/admin/jobs/{job_id}
|
||||
Customer: https://gen.nomadkaraoke.com/jobs/{job_id}
|
||||
|
||||
Deadline: 24 hours from now
|
||||
""".strip(),
|
||||
)
|
||||
|
||||
logger.info(f"Sent done-for-you order notifications for job {job_id}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing done-for-you order: {e}", exc_info=True)
|
||||
# Still try to notify Andrew of the failure
|
||||
try:
|
||||
email_service.send_email(
|
||||
to_email=ADMIN_EMAIL,
|
||||
subject=f"[FAILED] Done For You Order: {artist} - {title}",
|
||||
html_content=f"""
|
||||
<h2>Done-For-You Order Failed</h2>
|
||||
<p>An error occurred processing this order:</p>
|
||||
<ul>
|
||||
<li><strong>Customer:</strong> {customer_email}</li>
|
||||
<li><strong>Artist:</strong> {artist}</li>
|
||||
<li><strong>Title:</strong> {title}</li>
|
||||
<li><strong>Error:</strong> {str(e)}</li>
|
||||
</ul>
|
||||
<p>Please manually create this job and notify the customer.</p>
|
||||
""",
|
||||
text_content=f"""
|
||||
Done-For-You Order Failed
|
||||
|
||||
Customer: {customer_email}
|
||||
Artist: {artist}
|
||||
Title: {title}
|
||||
Error: {str(e)}
|
||||
|
||||
Please manually create this job and notify the customer.
|
||||
""".strip(),
|
||||
)
|
||||
except Exception as email_error:
|
||||
logger.error(f"Failed to send error notification: {email_error}")
|
||||
|
||||
|
||||
@router.post("/webhooks/stripe")
|
||||
async def stripe_webhook(
|
||||
request: Request,
|
||||
@@ -365,30 +801,41 @@ async def stripe_webhook(
|
||||
if event_type == "checkout.session.completed":
|
||||
session = event["data"]["object"]
|
||||
session_id = session.get("id")
|
||||
metadata = session.get("metadata", {})
|
||||
|
||||
# Idempotency check: Skip if this session was already processed
|
||||
if session_id and user_service.is_stripe_session_processed(session_id):
|
||||
logger.info(f"Skipping already processed session: {session_id}")
|
||||
return {"status": "received", "type": event_type, "note": "already_processed"}
|
||||
|
||||
# Process the completed checkout
|
||||
success, user_email, credits, _ = stripe_service.handle_checkout_completed(session)
|
||||
|
||||
if success and user_email and credits > 0:
|
||||
# Add credits to user account
|
||||
ok, new_balance, credit_msg = user_service.add_credits(
|
||||
email=user_email,
|
||||
amount=credits,
|
||||
reason="stripe_purchase",
|
||||
stripe_session_id=session_id,
|
||||
# Check if this is a done-for-you order
|
||||
if metadata.get("order_type") == "done_for_you":
|
||||
# Handle done-for-you order - create a job
|
||||
await _handle_done_for_you_order(
|
||||
session_id=session_id,
|
||||
metadata=metadata,
|
||||
user_service=user_service,
|
||||
email_service=email_service,
|
||||
)
|
||||
else:
|
||||
# Handle regular credit purchase
|
||||
success, user_email, credits, _ = stripe_service.handle_checkout_completed(session)
|
||||
|
||||
if ok:
|
||||
# Send confirmation email
|
||||
email_service.send_credits_added(user_email, credits, new_balance)
|
||||
logger.info(f"Added {credits} credits to {user_email}, new balance: {new_balance}")
|
||||
else:
|
||||
logger.error(f"Failed to add credits: {credit_msg}")
|
||||
if success and user_email and credits > 0:
|
||||
# Add credits to user account
|
||||
ok, new_balance, credit_msg = user_service.add_credits(
|
||||
email=user_email,
|
||||
amount=credits,
|
||||
reason="stripe_purchase",
|
||||
stripe_session_id=session_id,
|
||||
)
|
||||
|
||||
if ok:
|
||||
# Send confirmation email
|
||||
email_service.send_credits_added(user_email, credits, new_balance)
|
||||
logger.info(f"Added {credits} credits to {user_email}, new balance: {new_balance}")
|
||||
else:
|
||||
logger.error(f"Failed to add credits: {credit_msg}")
|
||||
|
||||
elif event_type == "checkout.session.expired":
|
||||
logger.info(f"Checkout session expired: {event['data']['object'].get('id')}")
|
||||
@@ -663,6 +1110,7 @@ async def list_users(
|
||||
sort_by: str = "created_at",
|
||||
sort_order: str = "desc",
|
||||
include_inactive: bool = False,
|
||||
exclude_test: bool = True,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
@@ -676,6 +1124,7 @@ async def list_users(
|
||||
sort_by: Field to sort by (created_at, last_login_at, credits, email)
|
||||
sort_order: Sort direction (asc, desc)
|
||||
include_inactive: Include disabled users
|
||||
exclude_test: If True (default), exclude test users (e.g., @inbox.testmail.app)
|
||||
"""
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
@@ -704,9 +1153,14 @@ async def list_users(
|
||||
else:
|
||||
query = query.order_by("created_at", direction=direction)
|
||||
|
||||
# Get total count (without pagination) for has_more calculation
|
||||
# Get all docs and filter in Python
|
||||
# Note: This is expensive for large datasets, consider caching
|
||||
all_docs = list(query.stream())
|
||||
|
||||
# Filter out test users if exclude_test is True
|
||||
if exclude_test:
|
||||
all_docs = [d for d in all_docs if not is_test_email(d.to_dict().get('email', ''))]
|
||||
|
||||
total_count = len(all_docs)
|
||||
|
||||
# Apply pagination manually (Firestore doesn't support offset well)
|
||||
@@ -942,44 +1396,64 @@ async def list_beta_feedback(
|
||||
|
||||
@router.get("/admin/beta/stats")
|
||||
async def get_beta_stats(
|
||||
exclude_test: bool = True,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Get beta tester program statistics (admin only).
|
||||
|
||||
Args:
|
||||
exclude_test: If True (default), exclude test users from beta stats
|
||||
"""
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from google.cloud.firestore_v1 import aggregation
|
||||
|
||||
# Count beta testers by status using efficient aggregation queries
|
||||
users_collection = user_service.db.collection(USERS_COLLECTION)
|
||||
|
||||
# Helper function to get count using aggregation
|
||||
def get_count(query) -> int:
|
||||
agg_query = aggregation.AggregationQuery(query)
|
||||
agg_query.count(alias="count")
|
||||
results = agg_query.get()
|
||||
return results[0][0].value if results else 0
|
||||
if exclude_test:
|
||||
# Stream and filter in Python since Firestore doesn't support "not ends with"
|
||||
all_beta_users = []
|
||||
for doc in users_collection.where(filter=FieldFilter("is_beta_tester", "==", True)).stream():
|
||||
data = doc.to_dict()
|
||||
if not is_test_email(data.get("email", "")):
|
||||
all_beta_users.append(data)
|
||||
|
||||
total_beta_testers = get_count(
|
||||
users_collection.where(filter=FieldFilter("is_beta_tester", "==", True))
|
||||
)
|
||||
total_beta_testers = len(all_beta_users)
|
||||
active_testers = sum(1 for u in all_beta_users if u.get("beta_tester_status") == "active")
|
||||
pending_feedback = sum(1 for u in all_beta_users if u.get("beta_tester_status") == "pending_feedback")
|
||||
completed_feedback = sum(1 for u in all_beta_users if u.get("beta_tester_status") == "completed")
|
||||
|
||||
active_testers = get_count(
|
||||
users_collection.where(filter=FieldFilter("beta_tester_status", "==", "active"))
|
||||
)
|
||||
# Filter feedback by non-test users
|
||||
all_feedback = []
|
||||
for doc in user_service.db.collection("beta_feedback").stream():
|
||||
data = doc.to_dict()
|
||||
if not is_test_email(data.get("user_email", "")):
|
||||
all_feedback.append(data)
|
||||
feedback_docs = all_feedback
|
||||
else:
|
||||
# Use efficient aggregation queries when including test data
|
||||
def get_count(query) -> int:
|
||||
agg_query = aggregation.AggregationQuery(query)
|
||||
agg_query.count(alias="count")
|
||||
results = agg_query.get()
|
||||
return results[0][0].value if results else 0
|
||||
|
||||
pending_feedback = get_count(
|
||||
users_collection.where(filter=FieldFilter("beta_tester_status", "==", "pending_feedback"))
|
||||
)
|
||||
|
||||
completed_feedback = get_count(
|
||||
users_collection.where(filter=FieldFilter("beta_tester_status", "==", "completed"))
|
||||
)
|
||||
|
||||
# Get average ratings from feedback
|
||||
feedback_docs = list(user_service.db.collection("beta_feedback").stream())
|
||||
total_beta_testers = get_count(
|
||||
users_collection.where(filter=FieldFilter("is_beta_tester", "==", True))
|
||||
)
|
||||
active_testers = get_count(
|
||||
users_collection.where(filter=FieldFilter("beta_tester_status", "==", "active"))
|
||||
)
|
||||
pending_feedback = get_count(
|
||||
users_collection.where(filter=FieldFilter("beta_tester_status", "==", "pending_feedback"))
|
||||
)
|
||||
completed_feedback = get_count(
|
||||
users_collection.where(filter=FieldFilter("beta_tester_status", "==", "completed"))
|
||||
)
|
||||
feedback_docs = [doc.to_dict() for doc in user_service.db.collection("beta_feedback").stream()]
|
||||
|
||||
# Calculate average ratings from feedback
|
||||
avg_overall = 0
|
||||
avg_ease = 0
|
||||
avg_accuracy = 0
|
||||
@@ -987,8 +1461,7 @@ async def get_beta_stats(
|
||||
|
||||
if feedback_docs:
|
||||
total = len(feedback_docs)
|
||||
for doc in feedback_docs:
|
||||
data = doc.to_dict()
|
||||
for data in feedback_docs:
|
||||
avg_overall += data.get("overall_rating", 0)
|
||||
avg_ease += data.get("ease_of_use_rating", 0)
|
||||
avg_accuracy += data.get("lyrics_accuracy_rating", 0)
|
||||
|
||||
+18
-2
@@ -11,6 +11,8 @@ from backend.api.routes import health, jobs, internal, file_upload, review, auth
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
from backend.services.spacy_preloader import preload_spacy_model
|
||||
from backend.services.nltk_preloader import preload_all_nltk_resources
|
||||
from backend.services.langfuse_preloader import preload_langfuse_handler
|
||||
from backend.middleware.audit_logging import AuditLoggingMiddleware
|
||||
|
||||
|
||||
@@ -69,13 +71,27 @@ async def lifespan(app: FastAPI):
|
||||
logger.info(f"GCS Bucket: {settings.gcs_bucket_name}")
|
||||
logger.info(f"Tracing enabled: {tracing_enabled}")
|
||||
|
||||
# Preload SpaCy model to avoid 60+ second delay on first request
|
||||
# See docs/archive/2026-01-08-spacy-preload-plan.md for background
|
||||
# Preload NLP models and resources to avoid cold start delays
|
||||
# See docs/archive/2026-01-08-performance-investigation.md for background
|
||||
|
||||
# 1. SpaCy model (60+ second delay without preload)
|
||||
try:
|
||||
preload_spacy_model("en_core_web_sm")
|
||||
except Exception as e:
|
||||
logger.warning(f"SpaCy preload failed (will load lazily): {e}")
|
||||
|
||||
# 2. NLTK cmudict (50-100+ second delay without preload)
|
||||
try:
|
||||
preload_all_nltk_resources()
|
||||
except Exception as e:
|
||||
logger.warning(f"NLTK preload failed (will load lazily): {e}")
|
||||
|
||||
# 3. Langfuse callback handler (200+ second delay without preload)
|
||||
try:
|
||||
preload_langfuse_handler()
|
||||
except Exception as e:
|
||||
logger.warning(f"Langfuse preload failed (will initialize lazily): {e}")
|
||||
|
||||
# Validate OAuth credentials (non-blocking)
|
||||
try:
|
||||
await validate_credentials_on_startup()
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Langfuse callback handler preloader for container startup.
|
||||
|
||||
Initializes the Langfuse callback handler at container startup to avoid
|
||||
slow initialization during request processing. The CallbackHandler()
|
||||
constructor makes blocking network calls to the Langfuse API, which can
|
||||
take 3+ minutes on Cloud Run cold starts.
|
||||
|
||||
See docs/archive/2026-01-08-performance-investigation.md for background.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Optional, Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Singleton storage for preloaded handler
|
||||
_preloaded_handler: Optional[Any] = None
|
||||
_initialization_attempted: bool = False
|
||||
|
||||
|
||||
def preload_langfuse_handler() -> Optional[Any]:
|
||||
"""Preload Langfuse callback handler at startup.
|
||||
|
||||
Only initializes if LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY
|
||||
environment variables are set.
|
||||
|
||||
Returns:
|
||||
The preloaded CallbackHandler, or None if not configured
|
||||
"""
|
||||
global _preloaded_handler, _initialization_attempted
|
||||
|
||||
if _initialization_attempted:
|
||||
logger.debug("Langfuse initialization already attempted")
|
||||
return _preloaded_handler
|
||||
|
||||
_initialization_attempted = True
|
||||
|
||||
# Check if Langfuse is configured
|
||||
public_key = os.getenv("LANGFUSE_PUBLIC_KEY")
|
||||
secret_key = os.getenv("LANGFUSE_SECRET_KEY")
|
||||
|
||||
if not (public_key and secret_key):
|
||||
logger.info("Langfuse not configured (missing keys), skipping preload")
|
||||
return None
|
||||
|
||||
logger.info("Preloading Langfuse callback handler...")
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
from langfuse.langchain import CallbackHandler
|
||||
|
||||
# Initialize the handler - this is the slow part that makes network calls
|
||||
_preloaded_handler = CallbackHandler()
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
host = os.getenv("LANGFUSE_HOST", "cloud.langfuse.com")
|
||||
logger.info(f"Langfuse handler preloaded in {elapsed:.2f}s (host: {host})")
|
||||
|
||||
return _preloaded_handler
|
||||
|
||||
except ImportError:
|
||||
logger.warning("langfuse package not installed, skipping preload")
|
||||
return None
|
||||
except Exception as e:
|
||||
elapsed = time.time() - start_time
|
||||
logger.error(f"Failed to preload Langfuse handler after {elapsed:.2f}s: {e}")
|
||||
# Don't raise - Langfuse is optional
|
||||
return None
|
||||
|
||||
|
||||
def get_preloaded_langfuse_handler() -> Optional[Any]:
|
||||
"""Get the preloaded Langfuse callback handler if available.
|
||||
|
||||
Returns:
|
||||
The preloaded CallbackHandler, or None if not preloaded/configured
|
||||
"""
|
||||
return _preloaded_handler
|
||||
|
||||
|
||||
def is_langfuse_preloaded() -> bool:
|
||||
"""Check if Langfuse handler has been preloaded."""
|
||||
return _preloaded_handler is not None
|
||||
|
||||
|
||||
def is_langfuse_configured() -> bool:
|
||||
"""Check if Langfuse environment variables are configured."""
|
||||
return bool(
|
||||
os.getenv("LANGFUSE_PUBLIC_KEY") and os.getenv("LANGFUSE_SECRET_KEY")
|
||||
)
|
||||
|
||||
|
||||
def clear_preloaded_handler() -> None:
|
||||
"""Clear preloaded handler. Useful for testing."""
|
||||
global _preloaded_handler, _initialization_attempted
|
||||
_preloaded_handler = None
|
||||
_initialization_attempted = False
|
||||
@@ -0,0 +1,122 @@
|
||||
"""NLTK resource preloader for container startup.
|
||||
|
||||
Loads NLTK data at container startup to avoid slow downloads during request processing.
|
||||
Cloud Run's ephemeral filesystem means NLTK data must be re-downloaded on each cold start,
|
||||
which can take 30-100+ seconds for cmudict.
|
||||
|
||||
See docs/archive/2026-01-08-performance-investigation.md for background.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Singleton storage for preloaded resources
|
||||
_preloaded_resources: Dict[str, Any] = {}
|
||||
|
||||
|
||||
def preload_nltk_cmudict() -> None:
|
||||
"""Preload NLTK's CMU Pronouncing Dictionary at startup.
|
||||
|
||||
The cmudict is used by SyllablesMatchHandler for syllable counting.
|
||||
Without preloading, each SyllablesMatchHandler init downloads ~30MB,
|
||||
which took 50-100+ seconds in Cloud Run.
|
||||
"""
|
||||
global _preloaded_resources
|
||||
|
||||
if "cmudict" in _preloaded_resources:
|
||||
logger.info("NLTK cmudict already preloaded")
|
||||
return
|
||||
|
||||
logger.info("Preloading NLTK cmudict...")
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
import nltk
|
||||
|
||||
# Ensure the data is downloaded
|
||||
try:
|
||||
from nltk.corpus import cmudict
|
||||
|
||||
# Try to access it - will raise LookupError if not downloaded
|
||||
_ = cmudict.dict()
|
||||
except LookupError:
|
||||
logger.info("Downloading NLTK cmudict data...")
|
||||
nltk.download("cmudict", quiet=True)
|
||||
from nltk.corpus import cmudict
|
||||
|
||||
# Load into memory
|
||||
cmu_dict = cmudict.dict()
|
||||
_preloaded_resources["cmudict"] = cmu_dict
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
logger.info(f"NLTK cmudict preloaded in {elapsed:.2f}s ({len(cmu_dict)} entries)")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to preload NLTK cmudict: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def get_preloaded_cmudict() -> Optional[Dict]:
|
||||
"""Get the preloaded CMU dictionary if available.
|
||||
|
||||
Returns:
|
||||
The preloaded cmudict dictionary, or None if not preloaded
|
||||
"""
|
||||
return _preloaded_resources.get("cmudict")
|
||||
|
||||
|
||||
def is_cmudict_preloaded() -> bool:
|
||||
"""Check if cmudict has been preloaded."""
|
||||
return "cmudict" in _preloaded_resources
|
||||
|
||||
|
||||
def preload_nltk_punkt() -> None:
|
||||
"""Preload NLTK's punkt tokenizer (optional, used for sentence tokenization)."""
|
||||
global _preloaded_resources
|
||||
|
||||
if "punkt" in _preloaded_resources:
|
||||
logger.info("NLTK punkt already preloaded")
|
||||
return
|
||||
|
||||
logger.info("Preloading NLTK punkt tokenizer...")
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
import nltk
|
||||
|
||||
try:
|
||||
from nltk.tokenize import word_tokenize
|
||||
|
||||
# Test it works
|
||||
_ = word_tokenize("test")
|
||||
except LookupError:
|
||||
logger.info("Downloading NLTK punkt data...")
|
||||
nltk.download("punkt", quiet=True)
|
||||
nltk.download("punkt_tab", quiet=True)
|
||||
|
||||
_preloaded_resources["punkt"] = True
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
logger.info(f"NLTK punkt preloaded in {elapsed:.2f}s")
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to preload NLTK punkt (non-critical): {e}")
|
||||
|
||||
|
||||
def preload_all_nltk_resources() -> None:
|
||||
"""Preload all NLTK resources used by the application."""
|
||||
preload_nltk_cmudict()
|
||||
# punkt is optional and less critical
|
||||
try:
|
||||
preload_nltk_punkt()
|
||||
except Exception:
|
||||
pass # Non-critical
|
||||
|
||||
|
||||
def clear_preloaded_resources() -> None:
|
||||
"""Clear all preloaded resources. Useful for testing."""
|
||||
global _preloaded_resources
|
||||
_preloaded_resources.clear()
|
||||
@@ -46,6 +46,13 @@ CREDIT_PACKAGES = {
|
||||
},
|
||||
}
|
||||
|
||||
# Done-for-you service package (not a credit package - creates a job directly)
|
||||
DONE_FOR_YOU_PACKAGE = {
|
||||
"price_cents": 1500, # $15.00
|
||||
"name": "Done For You Karaoke Video",
|
||||
"description": "Full-service karaoke video creation with 24-hour delivery",
|
||||
}
|
||||
|
||||
|
||||
class StripeService:
|
||||
"""Service for Stripe payment processing."""
|
||||
@@ -143,6 +150,95 @@ class StripeService:
|
||||
logger.error(f"Error creating checkout session: {e}")
|
||||
return False, None, "Failed to create checkout session"
|
||||
|
||||
def create_done_for_you_checkout_session(
|
||||
self,
|
||||
customer_email: str,
|
||||
artist: str,
|
||||
title: str,
|
||||
source_type: str = "search",
|
||||
youtube_url: Optional[str] = None,
|
||||
notes: Optional[str] = None,
|
||||
success_url: Optional[str] = None,
|
||||
cancel_url: Optional[str] = None,
|
||||
) -> Tuple[bool, Optional[str], str]:
|
||||
"""
|
||||
Create a Stripe Checkout session for a done-for-you order.
|
||||
|
||||
This is for the full-service karaoke video creation where Nomad Karaoke
|
||||
handles all the work (lyrics review, instrumental selection, etc.).
|
||||
|
||||
Args:
|
||||
customer_email: Customer's email for delivery
|
||||
artist: Song artist
|
||||
title: Song title
|
||||
source_type: Audio source type (search, youtube, upload)
|
||||
youtube_url: YouTube URL if source_type is youtube
|
||||
notes: Any special requests from customer
|
||||
success_url: URL to redirect to on success (optional)
|
||||
cancel_url: URL to redirect to on cancel (optional)
|
||||
|
||||
Returns:
|
||||
(success, checkout_url, message)
|
||||
"""
|
||||
if not self.is_configured():
|
||||
return False, None, "Payment processing is not configured"
|
||||
|
||||
try:
|
||||
# Default URLs - redirect to homepage success page
|
||||
if not success_url:
|
||||
success_url = "https://nomadkaraoke.com/order/success/?session_id={CHECKOUT_SESSION_ID}"
|
||||
if not cancel_url:
|
||||
cancel_url = "https://nomadkaraoke.com/#do-it-for-me"
|
||||
|
||||
# Build metadata for job creation after payment
|
||||
metadata = {
|
||||
'order_type': 'done_for_you',
|
||||
'customer_email': customer_email,
|
||||
'artist': artist,
|
||||
'title': title,
|
||||
'source_type': source_type,
|
||||
}
|
||||
if youtube_url:
|
||||
metadata['youtube_url'] = youtube_url
|
||||
if notes:
|
||||
# Truncate notes to fit Stripe's 500 char limit per metadata value
|
||||
metadata['notes'] = notes[:500] if len(notes) > 500 else notes
|
||||
|
||||
# Create checkout session
|
||||
session = stripe.checkout.Session.create(
|
||||
payment_method_types=['card'],
|
||||
line_items=[{
|
||||
'price_data': {
|
||||
'currency': 'usd',
|
||||
'product_data': {
|
||||
'name': DONE_FOR_YOU_PACKAGE['name'],
|
||||
'description': f"{artist} - {title}",
|
||||
},
|
||||
'unit_amount': DONE_FOR_YOU_PACKAGE['price_cents'],
|
||||
},
|
||||
'quantity': 1,
|
||||
}],
|
||||
mode='payment',
|
||||
success_url=success_url,
|
||||
cancel_url=cancel_url,
|
||||
customer_email=customer_email,
|
||||
metadata=metadata,
|
||||
allow_promotion_codes=True,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Created done-for-you checkout session {session.id} for {customer_email}, "
|
||||
f"song: {artist} - {title}"
|
||||
)
|
||||
return True, session.url, "Checkout session created"
|
||||
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Stripe error creating done-for-you checkout session: {e}")
|
||||
return False, None, f"Payment error: {str(e)}"
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating done-for-you checkout session: {e}")
|
||||
return False, None, "Failed to create checkout session"
|
||||
|
||||
def verify_webhook_signature(self, payload: bytes, signature: str) -> Tuple[bool, Optional[Dict], str]:
|
||||
"""
|
||||
Verify a Stripe webhook signature.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
Utilities for identifying test data.
|
||||
|
||||
Test data is generated by automated E2E tests and should be filterable
|
||||
in admin dashboards to show only real user data by default.
|
||||
"""
|
||||
|
||||
# Email domains used by automated testing frameworks
|
||||
TEST_EMAIL_DOMAINS = [
|
||||
"inbox.testmail.app", # Used by E2E happy path tests
|
||||
]
|
||||
|
||||
|
||||
def is_test_email(email: str) -> bool:
|
||||
"""
|
||||
Check if an email address belongs to automated test data.
|
||||
|
||||
Args:
|
||||
email: Email address to check
|
||||
|
||||
Returns:
|
||||
True if the email matches a test email domain pattern
|
||||
"""
|
||||
if not email:
|
||||
return False
|
||||
email_lower = email.lower()
|
||||
return any(email_lower.endswith(f"@{domain}") for domain in TEST_EMAIL_DOMAINS)
|
||||
+37
@@ -77,8 +77,14 @@ Response includes:
|
||||
GET /api/jobs
|
||||
GET /api/jobs?status=complete
|
||||
GET /api/jobs?limit=10&offset=0
|
||||
GET /api/jobs?exclude_test=false
|
||||
```
|
||||
|
||||
Query parameters:
|
||||
- `exclude_test` (bool, default: true) - Admin only: filter out jobs from test users
|
||||
- `status` - Filter by job status
|
||||
- `limit` / `offset` - Pagination
|
||||
|
||||
#### Delete Job
|
||||
|
||||
```http
|
||||
@@ -341,10 +347,24 @@ Bonus credit for detailed feedback (50+ chars).
|
||||
|
||||
All admin endpoints require an admin-role session token.
|
||||
|
||||
### Test Data Filtering
|
||||
|
||||
Most admin list/stats endpoints support an `exclude_test` query parameter (default: `true`) to filter out E2E test data:
|
||||
- Test users: email addresses ending in `@inbox.testmail.app`
|
||||
- Test jobs: jobs created by test users
|
||||
|
||||
```http
|
||||
GET /api/admin/stats/overview?exclude_test=true # Default - hide test data
|
||||
GET /api/admin/stats/overview?exclude_test=false # Show all data including tests
|
||||
```
|
||||
|
||||
The frontend admin dashboard includes a "Show test data" toggle that controls this filter globally.
|
||||
|
||||
### Admin Dashboard Stats
|
||||
|
||||
```http
|
||||
GET /api/admin/stats/overview
|
||||
GET /api/admin/stats/overview?exclude_test=false
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
@@ -375,9 +395,16 @@ Returns platform statistics:
|
||||
GET /api/users/admin/users
|
||||
GET /api/users/admin/users?search=user@example.com
|
||||
GET /api/users/admin/users?limit=20&offset=0&sort_by=created_at&sort_order=desc
|
||||
GET /api/users/admin/users?exclude_test=false
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Query parameters:
|
||||
- `exclude_test` (bool, default: true) - Filter out test users
|
||||
- `limit` / `offset` - Pagination
|
||||
- `search` - Email prefix search
|
||||
- `sort_by` / `sort_order` - Sorting
|
||||
|
||||
Returns paginated user list with total count.
|
||||
|
||||
### User Detail (Admin)
|
||||
@@ -429,9 +456,13 @@ Authorization: Bearer ADMIN_TOKEN
|
||||
|
||||
```http
|
||||
GET /api/users/admin/beta/stats
|
||||
GET /api/users/admin/beta/stats?exclude_test=false
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Query parameters:
|
||||
- `exclude_test` (bool, default: true) - Filter out test users from beta statistics
|
||||
|
||||
### Beta Feedback List (Admin)
|
||||
|
||||
```http
|
||||
@@ -455,9 +486,15 @@ Admins can delete any job. Regular users can only delete their own jobs.
|
||||
```http
|
||||
GET /api/admin/audio-searches
|
||||
GET /api/admin/audio-searches?limit=50&status_filter=awaiting_audio_selection
|
||||
GET /api/admin/audio-searches?exclude_test=false
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Query parameters:
|
||||
- `exclude_test` (bool, default: true) - Filter out searches from test users
|
||||
- `limit` - Max results to return
|
||||
- `status_filter` - Filter by job status
|
||||
|
||||
Returns jobs with cached audio search results. Useful for:
|
||||
- Monitoring search activity
|
||||
- Identifying stale cached results (YouTube-only when lossless should be available)
|
||||
|
||||
+99
-28
@@ -435,6 +435,31 @@ Example: `youtube_description` vs `youtube_description_template`
|
||||
|
||||
See `docs/archive/2025-12-30-cloud-output-structure-fix.md` for full details.
|
||||
|
||||
### Jobs Without URLs Must Use Audio Search Flow
|
||||
|
||||
**Problem**: Done-for-you orders submitted without a YouTube URL immediately failed because the audio worker was triggered directly, but it had no audio source to process (no URL, no uploaded file, no GCS path).
|
||||
|
||||
**Root cause**: The webhook handler created a job with `url=None` and immediately triggered audio/lyrics workers, bypassing the audio search flow that handles artist+title-only jobs.
|
||||
|
||||
**Symptoms**:
|
||||
- Job transitions to FAILED status within seconds
|
||||
- Error: "No input source found (no GCS path, file_urls, or URL)"
|
||||
- Works fine when customer provides YouTube URL
|
||||
|
||||
**Solution**: When creating jobs without a URL or uploaded file:
|
||||
1. Set `audio_search_artist` and `audio_search_title` fields on the job
|
||||
2. Transition to `SEARCHING_AUDIO` status
|
||||
3. Use `audio_search_service.search()` to find sources
|
||||
4. Auto-select best result with `select_best()`
|
||||
5. Download and upload to GCS
|
||||
6. THEN trigger audio/lyrics workers
|
||||
|
||||
**Key insight**: There are two distinct audio acquisition paths:
|
||||
- **URL/Upload path**: Audio source is known → trigger workers directly
|
||||
- **Search path**: Only artist+title known → must search, download, then trigger workers
|
||||
|
||||
The audio search flow (`SEARCHING_AUDIO` → `AWAITING_AUDIO_SELECTION` → `DOWNLOADING_AUDIO` → `DOWNLOADING`) exists specifically for jobs where we need to find audio. Don't bypass it by triggering workers on jobs with no audio source.
|
||||
|
||||
## Testing Insights
|
||||
|
||||
### E2E Mock Responses Must Match API Types Exactly
|
||||
@@ -1055,53 +1080,82 @@ class LangChainBridge:
|
||||
|
||||
### Preloading Heavy Resources at Container Startup
|
||||
|
||||
**Problem**: Lazy-loading heavy resources (like SpaCy NLP models) during request processing can cause 60+ second delays on Cloud Run due to slow filesystem I/O during cold starts. The first request after deployment/scaling pays the full load penalty.
|
||||
**Problem**: Lazy-loading heavy resources (like SpaCy NLP models, NLTK data, or external service clients) during request processing can cause 60-200+ second delays on Cloud Run due to slow filesystem I/O and network latency during cold starts. The first request after deployment/scaling pays the full load penalty.
|
||||
|
||||
**Example bug**: `PhraseAnalyzer` loaded SpaCy's `en_core_web_sm` model lazily on first use during agentic lyrics correction. On Cloud Run, this took 63 seconds due to container filesystem being slower than local SSD. Job `2ccbdf6b` showed 73-second gap between "Initializing PhraseAnalyzer" and "Initialized AnchorSequenceFinder" logs.
|
||||
**Example bugs**:
|
||||
- `PhraseAnalyzer` loaded SpaCy's `en_core_web_sm` lazily → 63 seconds on Cloud Run
|
||||
- `SyllablesMatchHandler` downloaded NLTK cmudict lazily → 100-150 seconds (30MB download)
|
||||
- `ModelFactory` initialized Langfuse CallbackHandler lazily → 201 seconds (network calls to `us.cloud.langfuse.com`)
|
||||
|
||||
Job `36c21ece` (ABBA - Waterloo) had lyrics processing take **16 minutes 28 seconds**, with over 10 minutes wasted on initialization that could have been preloaded.
|
||||
|
||||
**Symptoms**:
|
||||
- First job after deployment is extremely slow
|
||||
- Large time gaps in logs between "loading X" and "using X"
|
||||
- Same code runs much faster locally (where filesystem is faster)
|
||||
- Same code runs much faster locally (where filesystem is faster and network is lower latency)
|
||||
- Subsequent requests (warm container) are fast
|
||||
|
||||
**Solution**: Preload heavy resources at container startup using FastAPI's lifespan handler:
|
||||
|
||||
```python
|
||||
# backend/services/spacy_preloader.py - singleton storage
|
||||
_preloaded_models: dict = {}
|
||||
|
||||
def preload_spacy_model(model_name: str = "en_core_web_sm") -> None:
|
||||
if model_name not in _preloaded_models:
|
||||
_preloaded_models[model_name] = spacy.load(model_name)
|
||||
|
||||
def get_preloaded_model(model_name: str) -> Optional[object]:
|
||||
return _preloaded_models.get(model_name)
|
||||
|
||||
# backend/main.py - load at startup
|
||||
# backend/main.py - load ALL heavy resources at startup
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
preload_spacy_model("en_core_web_sm") # Pay cost once at startup
|
||||
# SpaCy model (~60s → ~2s)
|
||||
preload_spacy_model("en_core_web_sm")
|
||||
|
||||
# NLTK cmudict (~100-150s → ~2s)
|
||||
preload_all_nltk_resources()
|
||||
|
||||
# Langfuse callback handler (~200s → ~2s)
|
||||
preload_langfuse_handler()
|
||||
|
||||
yield
|
||||
```
|
||||
|
||||
Then modify consumers to check for preloaded model:
|
||||
**Pattern for each preloader**:
|
||||
|
||||
```python
|
||||
class PhraseAnalyzer:
|
||||
def __init__(self):
|
||||
preloaded = get_preloaded_model("en_core_web_sm")
|
||||
# backend/services/nltk_preloader.py
|
||||
_preloaded_resources: Dict[str, Any] = {}
|
||||
|
||||
def preload_nltk_cmudict() -> None:
|
||||
"""Preload NLTK cmudict at container startup."""
|
||||
global _preloaded_resources
|
||||
if "cmudict" in _preloaded_resources:
|
||||
return
|
||||
try:
|
||||
from nltk.corpus import cmudict
|
||||
_ = cmudict.dict() # Trigger download if needed
|
||||
except LookupError:
|
||||
nltk.download("cmudict", quiet=True)
|
||||
_preloaded_resources["cmudict"] = cmudict.dict()
|
||||
|
||||
def get_preloaded_cmudict() -> Optional[Dict]:
|
||||
return _preloaded_resources.get("cmudict")
|
||||
|
||||
def is_cmudict_preloaded() -> bool:
|
||||
return "cmudict" in _preloaded_resources
|
||||
```
|
||||
|
||||
Then modify consumers to check for preloaded resource:
|
||||
```python
|
||||
class SyllablesMatchHandler:
|
||||
def _init_nltk_resources(self):
|
||||
preloaded = get_preloaded_cmudict()
|
||||
if preloaded:
|
||||
self.nlp = preloaded # Fast path
|
||||
self.cmudict = preloaded # Fast path
|
||||
else:
|
||||
self.nlp = spacy.load("en_core_web_sm") # Fallback
|
||||
self.cmudict = cmudict.dict() # Fallback for local dev
|
||||
```
|
||||
|
||||
**Key insight**: On Cloud Run, container startup time doesn't directly impact users (they don't see the startup delay), but request processing time does. Moving heavy initialization from request-time to startup-time improves user experience even if total work is the same.
|
||||
|
||||
**Good candidates for preloading**:
|
||||
- ML model files (SpaCy, transformers, etc.)
|
||||
- ML model files (SpaCy, transformers, etc.) - saved **60s**
|
||||
- NLTK data downloads (cmudict, wordnet, etc.) - saved **100-150s**
|
||||
- External service clients that make network calls during init (Langfuse) - saved **200s**
|
||||
- Large data files
|
||||
- Expensive-to-initialize clients
|
||||
- Anything that touches the filesystem heavily
|
||||
|
||||
**Not worth preloading**:
|
||||
@@ -1109,13 +1163,30 @@ class PhraseAnalyzer:
|
||||
- Resources that vary per-request
|
||||
- Rarely-used code paths
|
||||
|
||||
**Logging**: Add timing logs to both startup preload and usage paths so you can verify the optimization is working:
|
||||
```
|
||||
# At startup: "SpaCy model 'en_core_web_sm' preloaded in 2.34s"
|
||||
# During request: "Using preloaded SpaCy model: en_core_web_sm"
|
||||
**Verification endpoint**: Add a `/health/preload-status` endpoint to verify preloading works:
|
||||
```python
|
||||
@router.get("/health/preload-status")
|
||||
async def preload_status():
|
||||
return {
|
||||
"status": "ok" if all_preloaded else "degraded",
|
||||
"spacy": {"preloaded": is_model_preloaded("en_core_web_sm")},
|
||||
"nltk": {"preloaded": is_cmudict_preloaded()},
|
||||
"langfuse": {"preloaded": is_langfuse_preloaded()},
|
||||
"performance_impact": {
|
||||
"spacy_preload": "Saves ~60s on first lyrics correction",
|
||||
"nltk_preload": "Saves ~100-150s on SyllablesMatchHandler init",
|
||||
"langfuse_preload": "Saves ~200s on AgenticCorrector init",
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See `docs/archive/2026-01-08-spacy-preload-plan.md` for full implementation details.
|
||||
**Logging**: Add timing logs to both startup preload and usage paths:
|
||||
```
|
||||
# At startup: "NLTK cmudict preloaded in 2.34s (133906 entries)"
|
||||
# During request: "Using preloaded NLTK cmudict"
|
||||
```
|
||||
|
||||
See `docs/archive/2026-01-08-performance-investigation.md` for full analysis and implementation details.
|
||||
|
||||
## Performance Observations
|
||||
|
||||
|
||||
@@ -40,6 +40,8 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Comprehensive Performance Optimization** (2026-01-08): Reduced lyrics processing from **16+ minutes to ~5 minutes** through multiple optimizations. Key changes: (1) NLTK cmudict preloading at startup saves 100-150s, (2) Langfuse callback handler preloading saves 200s, (3) Model warmup in `AgenticCorrector.from_model()` prevents parallel initialization race, (4) Parallel anchor sequence search (4 workers) reduces n-gram processing from 38s to ~10s. Added `/health/preload-status` endpoint for deployment verification. PR #236. See [archive/2026-01-08-performance-investigation.md](archive/2026-01-08-performance-investigation.md) and [LESSONS-LEARNED.md](LESSONS-LEARNED.md#preloading-heavy-resources-at-container-startup).
|
||||
|
||||
- **UI Simplification & Brand Accessibility** (2026-01-08): Simplified the "Create Karaoke Video" form by hiding advanced options (theme settings now admin-only, "Display As" behind toggle). Improved audio search dialog UX by hiding technical tracker names and showing user-friendly availability badges. Fixed brand pink color contrast for accessibility - swapped default/hover values so white text on pink buttons meets WCAG contrast ratio. See [BRAND-STYLE-GUIDE.md](BRAND-STYLE-GUIDE.md) v1.2.
|
||||
|
||||
- **SpaCy Preloading** (2026-01-08): Implemented SpaCy model preloading at container startup to eliminate 60+ second delay during agentic correction. The `en_core_web_sm` model is now loaded during FastAPI lifespan startup, and `PhraseAnalyzer`/`SyllablesMatchHandler` reuse the preloaded model. Added timing logs to verify performance. See [archive/2026-01-08-spacy-preload-plan.md](archive/2026-01-08-spacy-preload-plan.md).
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
# Performance Investigation: Karaoke Generation Pipeline
|
||||
|
||||
**Date**: 2026-01-08
|
||||
**Status**: Phase 1 Complete, Validated in Production
|
||||
**Goal**: Reduce total karaoke generation time from ~30 minutes to ~10 minutes
|
||||
|
||||
## Executive Summary
|
||||
|
||||
We achieved a **~50% reduction in lyrics processing time** (from ~13 min to ~6.5 min) through preloading optimizations. However, the overall pipeline still takes ~25-30 minutes. Further optimization is needed to reach the 10-minute target.
|
||||
|
||||
### Key Achievements (PR #236)
|
||||
|
||||
| Optimization | Before | After | Savings |
|
||||
|-------------|--------|-------|---------|
|
||||
| NLTK cmudict preloading | 100-150s lazy load | ~2s at startup | **~150s** |
|
||||
| Langfuse handler preloading | 201s lazy load | ~2s at startup | **~200s** |
|
||||
| Model warmup (eager init) | 300s+ parallel timeout | 0s (pre-warmed) | **~300s** |
|
||||
| Parallel anchor search | 38s sequential | ~10s parallel | **~28s** |
|
||||
| **Total Lyrics Stage** | ~13 min | **~6.5 min** | **~50%** |
|
||||
|
||||
### Remaining Bottlenecks
|
||||
|
||||
| Stage | Current Duration | Target | Gap |
|
||||
|-------|-----------------|--------|-----|
|
||||
| Audio separation (Modal) | ~3 min | 2 min | 1 min |
|
||||
| Lyrics processing | ~6.5 min | 3 min | 3.5 min |
|
||||
| Video rendering | ~6 min | 3 min | 3 min |
|
||||
| Final encoding (GCE) | ~9 min | 2 min | 7 min |
|
||||
| **Total (excl. human review)** | **~25 min** | **10 min** | **15 min** |
|
||||
|
||||
---
|
||||
|
||||
## Empirical Data: E2E Test Comparison
|
||||
|
||||
### Before Optimization (Job 6b5a354e - 09:17 UTC)
|
||||
|
||||
```
|
||||
Test song: piri - dog
|
||||
Total E2E test time: 31.4 minutes
|
||||
|
||||
Stage Breakdown:
|
||||
├─ Steps 1-5 (Setup/Audio selection): 25 seconds
|
||||
├─ Step 6 (Lyrics processing): 12 min 53 sec ← PRIMARY BOTTLENECK
|
||||
├─ Step 7 (Lyrics review UI): 2 min 12 sec
|
||||
├─ Step 8 (Video render + instrumental): 6 min 3 sec
|
||||
└─ Step 9 (Final encoding): 9 min 28 sec
|
||||
```
|
||||
|
||||
### After Optimization (Job b099c91b - 10:02 UTC)
|
||||
|
||||
```
|
||||
Test song: piri - dog
|
||||
Total E2E test time: ~19 min (encoding failed, unrelated bug)
|
||||
|
||||
Stage Breakdown:
|
||||
├─ Steps 1-5 (Setup/Audio selection): 32 seconds
|
||||
├─ Step 6 (Lyrics processing): 6 min 28 sec ← 50% FASTER!
|
||||
├─ Step 7 (Lyrics review UI): 2 min 20 sec
|
||||
├─ Step 8 (Video render + instrumental): 6 min 10 sec
|
||||
└─ Step 9 (Final encoding): FAILED (MOV→MP4 bug, unrelated)
|
||||
```
|
||||
|
||||
### Improvement Summary
|
||||
|
||||
| Stage | Before | After | Change |
|
||||
|-------|--------|-------|--------|
|
||||
| Lyrics Processing | 12m 53s | **6m 28s** | **-50%** |
|
||||
| Video Rendering | 6m 3s | 6m 10s | ~same |
|
||||
| Encoding | 9m 28s | N/A (failed) | expected same |
|
||||
|
||||
---
|
||||
|
||||
## Complete Pipeline Timing Breakdown
|
||||
|
||||
Based on analysis of multiple jobs, here's the detailed breakdown of each stage:
|
||||
|
||||
### Stage 1: Audio Worker (~3 minutes)
|
||||
|
||||
| Sub-stage | Duration | Notes |
|
||||
|-----------|----------|-------|
|
||||
| Job creation → Worker start | 13s | Cloud Tasks dispatch |
|
||||
| Modal audio separation | 72s | GPU-accelerated, fast |
|
||||
| Stems download from Modal | 47s | 8 files from Modal storage |
|
||||
| Stage 2 local separation | 23s | CPU-bound on Cloud Run |
|
||||
| **Total Audio Worker** | **~3 min** | Acceptable |
|
||||
|
||||
**Optimization opportunities**:
|
||||
- [ ] Faster Modal model (research needed)
|
||||
- [ ] Parallel stem downloads
|
||||
- [ ] Skip Stage 2 separation for some use cases
|
||||
|
||||
### Stage 2: Lyrics Worker (~6.5 minutes after optimization)
|
||||
|
||||
| Sub-stage | Before | After | Notes |
|
||||
|-----------|--------|-------|-------|
|
||||
| AudioShake API call | 78s | 78s | External API, hard to optimize |
|
||||
| NLTK cmudict load | 106s | **~0s** | Preloaded at startup |
|
||||
| SpaCy model load | 63s | **~0s** | Preloaded at startup |
|
||||
| Langfuse init | 201s | **~0s** | Preloaded at startup |
|
||||
| Anchor sequence search | 38s | **~10s** | Parallelized |
|
||||
| Agentic correction | 300s+ | **~60s** | Model pre-warmed |
|
||||
| Output generation | ~30s | ~30s | - |
|
||||
| **Total Lyrics Worker** | **~16 min** | **~6.5 min** | **-60%** |
|
||||
|
||||
**Optimization opportunities**:
|
||||
- [ ] Local Whisper transcription (eliminates AudioShake 78s)
|
||||
- [ ] GCE-based lyrics worker (eliminates all cold start overhead)
|
||||
- [ ] Faster agentic model (smaller model, fewer gaps)
|
||||
- [ ] Skip agentic correction for simple songs
|
||||
|
||||
### Stage 3: Video Rendering (~6 minutes)
|
||||
|
||||
| Sub-stage | Duration | Notes |
|
||||
|-----------|----------|-------|
|
||||
| ASS subtitle generation | ~5s | Fast, CPU-only |
|
||||
| FFmpeg video render | ~5-6 min | CPU-bound, single-threaded |
|
||||
| Upload to GCS | ~10s | - |
|
||||
|
||||
**Optimization opportunities**:
|
||||
- [ ] GPU-accelerated FFmpeg (NVENC on GCE)
|
||||
- [ ] Lower resolution preview during render stage
|
||||
- [ ] Parallel encoding of segments
|
||||
|
||||
### Stage 4: Final Encoding (~9 minutes)
|
||||
|
||||
| Sub-stage | Duration | Notes |
|
||||
|-----------|----------|-------|
|
||||
| GCE job dispatch | ~5s | - |
|
||||
| File downloads from GCS | ~30s | Videos + stems |
|
||||
| Title/karaoke/end concatenation | ~2 min | FFmpeg concat |
|
||||
| Multi-format encoding | ~6 min | 4K lossless + 720p |
|
||||
| Upload results to GCS | ~30s | - |
|
||||
|
||||
**Optimization opportunities**:
|
||||
- [ ] GPU encoding (NVENC) - would reduce 6 min → ~1-2 min
|
||||
- [ ] Skip 4K lossless for most users
|
||||
- [ ] Parallel format encoding
|
||||
- [ ] Pre-rendered title/end screens
|
||||
|
||||
---
|
||||
|
||||
## Optimization Ideas: Not Yet Implemented
|
||||
|
||||
### High Impact, Medium Effort
|
||||
|
||||
#### 1. GPU-Accelerated Encoding on GCE
|
||||
**Current**: GCE worker uses CPU encoding (libx264)
|
||||
**Proposed**: Add NVIDIA GPU to GCE VM, use NVENC
|
||||
**Expected savings**: 6 min → 1-2 min (~4-5 min saved)
|
||||
**Effort**: 1-2 days (Pulumi changes, FFmpeg flags)
|
||||
|
||||
```python
|
||||
# Current (CPU)
|
||||
ffmpeg -i input.mkv -c:v libx264 -preset medium output.mp4
|
||||
|
||||
# With GPU (NVENC)
|
||||
ffmpeg -hwaccel cuda -i input.mkv -c:v h264_nvenc -preset p4 output.mp4
|
||||
```
|
||||
|
||||
#### 2. Local Whisper Transcription
|
||||
**Current**: AudioShake API call takes 78 seconds
|
||||
**Proposed**: Run Whisper locally on Modal GPU or GCE
|
||||
**Expected savings**: 78s → ~30s (API overhead eliminated)
|
||||
**Effort**: 1 week (integration, testing, fallback logic)
|
||||
|
||||
#### 3. GCE Lyrics Worker
|
||||
**Current**: Lyrics processing on Cloud Run (cold starts, ephemeral filesystem)
|
||||
**Proposed**: Dedicated GCE VM with persistent cache
|
||||
**Expected savings**: Additional 1-2 min (no remaining init overhead)
|
||||
**Effort**: 2-3 days (infrastructure + integration)
|
||||
|
||||
### Medium Impact, Low Effort
|
||||
|
||||
#### 4. Skip 4K Lossless for Web Users
|
||||
**Current**: Always encode 4K lossless + 720p
|
||||
**Proposed**: Only encode 720p by default, 4K on request
|
||||
**Expected savings**: ~3 min per job
|
||||
**Effort**: 1 day (API flag, conditional encoding)
|
||||
|
||||
#### 5. Pre-rendered Title/End Screens
|
||||
**Current**: Title screens rendered per-job
|
||||
**Proposed**: Pre-render common templates, composite at encode time
|
||||
**Expected savings**: ~1 min
|
||||
**Effort**: 2 days
|
||||
|
||||
#### 6. Parallel Multi-Format Encoding
|
||||
**Current**: Formats encoded sequentially (4K then 720p)
|
||||
**Proposed**: Encode both formats in parallel
|
||||
**Expected savings**: ~2-3 min (depends on CPU cores)
|
||||
**Effort**: 1 day
|
||||
|
||||
### Lower Impact, Research Needed
|
||||
|
||||
#### 7. Faster Audio Separation Model
|
||||
**Current**: Modal uses bs_roformer model
|
||||
**Proposed**: Research faster models with acceptable quality
|
||||
**Expected savings**: Unknown
|
||||
**Effort**: Research project
|
||||
|
||||
#### 8. Smart Agentic Correction Skipping
|
||||
**Current**: Always run agentic correction
|
||||
**Proposed**: Skip for songs with high-confidence transcription
|
||||
**Expected savings**: ~60s for some songs
|
||||
**Effort**: 2 days (confidence scoring, threshold tuning)
|
||||
|
||||
#### 9. Cached Lyrics from Previous Jobs
|
||||
**Current**: Each job fetches/transcribes fresh
|
||||
**Proposed**: Cache lyrics by audio hash, reuse if available
|
||||
**Expected savings**: Up to 5+ min for repeat songs
|
||||
**Effort**: 1 day
|
||||
|
||||
---
|
||||
|
||||
## Implementation Status
|
||||
|
||||
### Completed (PR #236)
|
||||
|
||||
| Fix | File | Status |
|
||||
|-----|------|--------|
|
||||
| NLTK cmudict preloading | `backend/services/nltk_preloader.py` | ✅ Deployed |
|
||||
| Langfuse handler preloading | `backend/services/langfuse_preloader.py` | ✅ Deployed |
|
||||
| SpaCy model preloading | `backend/services/spacy_preloader.py` | ✅ Deployed |
|
||||
| Model warmup method | `langchain_bridge.py` | ✅ Deployed |
|
||||
| Parallel anchor search | `anchor_sequence.py` | ✅ Deployed |
|
||||
| Preload status endpoint | `/health/preload-status` | ✅ Deployed |
|
||||
|
||||
### Verification
|
||||
|
||||
Production endpoint confirms all preloaders working:
|
||||
```bash
|
||||
curl https://api.nomadkaraoke.com/api/health/preload-status
|
||||
```
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"message": "All resources preloaded",
|
||||
"spacy": {"preloaded": true, "vocab_size": 764},
|
||||
"nltk": {"preloaded": true, "entries": 123455},
|
||||
"langfuse": {"preloaded": true, "handler_type": "LangchainCallbackHandler"}
|
||||
}
|
||||
```
|
||||
|
||||
### Not Started
|
||||
|
||||
| Optimization | Priority | Effort | Expected Impact |
|
||||
|-------------|----------|--------|-----------------|
|
||||
| GPU encoding (NVENC) | High | 2 days | -4 min |
|
||||
| Skip 4K lossless | High | 1 day | -3 min |
|
||||
| Local Whisper | Medium | 1 week | -1 min |
|
||||
| GCE lyrics worker | Medium | 3 days | -2 min |
|
||||
| Parallel format encoding | Medium | 1 day | -2 min |
|
||||
|
||||
---
|
||||
|
||||
## Target Timeline to 10-Minute Goal
|
||||
|
||||
| Phase | Optimization | Cumulative Time |
|
||||
|-------|-------------|-----------------|
|
||||
| Baseline | Current state | ~25 min |
|
||||
| Done | NLTK/Langfuse/SpaCy preload | ~19 min |
|
||||
| Next | GPU encoding (NVENC) | ~15 min |
|
||||
| Next | Skip 4K lossless | ~12 min |
|
||||
| Next | Local Whisper | ~11 min |
|
||||
| Stretch | GCE lyrics worker | ~10 min |
|
||||
|
||||
---
|
||||
|
||||
## Debugging Tips
|
||||
|
||||
### Check Preload Status
|
||||
```bash
|
||||
curl https://api.nomadkaraoke.com/api/health/preload-status | jq
|
||||
```
|
||||
|
||||
### Check GCE Encoding Worker Logs
|
||||
```bash
|
||||
gcloud compute ssh encoding-worker --zone=us-central1-a --project=nomadkaraoke \
|
||||
--command="journalctl -u encoding-worker --since '30 min ago' | tail -100"
|
||||
```
|
||||
|
||||
### Monitor E2E Test Progress
|
||||
```bash
|
||||
gh run view <run_id> --log 2>&1 | grep -E 'STEP.*COMPLETE'
|
||||
```
|
||||
|
||||
### Check FFmpeg Hardware Acceleration
|
||||
```bash
|
||||
curl https://api.nomadkaraoke.com/api/health/detailed | jq '.ffmpeg'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
- PR #232: Thread-safe locking for LangChainBridge
|
||||
- PR #233: SpaCy model preloading
|
||||
- PR #236: Comprehensive performance optimization (this work)
|
||||
- [LESSONS-LEARNED.md - Preloading Heavy Resources](../LESSONS-LEARNED.md#preloading-heavy-resources-at-container-startup)
|
||||
- [LESSONS-LEARNED.md - Thread-Safe Lazy Initialization](../LESSONS-LEARNED.md#thread-safe-lazy-initialization-in-shared-components)
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { adminApi, AdminBetaStats, AdminBetaFeedback } from "@/lib/api"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { StatsCard, StatsGrid } from "@/components/admin/stats-card"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
@@ -27,6 +28,7 @@ import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
export default function AdminBetaPage() {
|
||||
const { toast } = useToast()
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [stats, setStats] = useState<AdminBetaStats | null>(null)
|
||||
const [feedback, setFeedback] = useState<AdminBetaFeedback[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
@@ -35,7 +37,7 @@ export default function AdminBetaPage() {
|
||||
try {
|
||||
setLoading(true)
|
||||
const [statsData, feedbackData] = await Promise.all([
|
||||
adminApi.getBetaStats(),
|
||||
adminApi.getBetaStats({ exclude_test: !showTestData }),
|
||||
adminApi.getBetaFeedback(50),
|
||||
])
|
||||
setStats(statsData)
|
||||
@@ -54,7 +56,7 @@ export default function AdminBetaPage() {
|
||||
|
||||
useEffect(() => {
|
||||
loadData()
|
||||
}, [])
|
||||
}, [showTestData])
|
||||
|
||||
const renderStars = (rating?: number) => {
|
||||
if (!rating) return "—"
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { adminApi, Job } from "@/lib/api"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
@@ -62,6 +63,7 @@ const statusOptions = [
|
||||
export default function AdminJobsPage() {
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [jobs, setJobs] = useState<Job[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [statusFilter, setStatusFilter] = useState("all")
|
||||
@@ -80,6 +82,7 @@ export default function AdminJobsPage() {
|
||||
status: statusFilter !== "all" ? statusFilter : undefined,
|
||||
user_email: userEmailFilter || undefined,
|
||||
limit: 100,
|
||||
exclude_test: !showTestData,
|
||||
})
|
||||
setJobs(data)
|
||||
} catch (err: any) {
|
||||
@@ -92,7 +95,7 @@ export default function AdminJobsPage() {
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [statusFilter, userEmailFilter, toast])
|
||||
}, [statusFilter, userEmailFilter, showTestData, toast])
|
||||
|
||||
useEffect(() => {
|
||||
loadJobs()
|
||||
|
||||
@@ -4,10 +4,13 @@ import React, { useEffect, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { getAccessToken } from "@/lib/api"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { SidebarProvider, SidebarInset, SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import { AdminSidebar } from "@/components/admin/admin-sidebar"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
@@ -124,6 +127,8 @@ export default function AdminLayout({
|
||||
)
|
||||
}
|
||||
|
||||
const { showTestData, setShowTestData } = useAdminSettings()
|
||||
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<AdminSidebar />
|
||||
@@ -132,6 +137,16 @@ export default function AdminLayout({
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator orientation="vertical" className="mr-2 h-4" />
|
||||
<AdminBreadcrumb />
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<Switch
|
||||
id="show-test-data"
|
||||
checked={showTestData}
|
||||
onCheckedChange={setShowTestData}
|
||||
/>
|
||||
<Label htmlFor="show-test-data" className="text-sm text-muted-foreground cursor-pointer">
|
||||
Show test data
|
||||
</Label>
|
||||
</div>
|
||||
</header>
|
||||
<main className="flex-1 p-4 md:p-6">{children}</main>
|
||||
</SidebarInset>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { adminApi, AdminStatsOverview } from "@/lib/api"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { StatsCard, StatsGrid } from "@/components/admin/stats-card"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
@@ -23,12 +24,13 @@ export default function AdminDashboardPage() {
|
||||
const [stats, setStats] = useState<AdminStatsOverview | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const { showTestData } = useAdminSettings()
|
||||
|
||||
const loadStats = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
const data = await adminApi.getStats()
|
||||
const data = await adminApi.getStats({ exclude_test: !showTestData })
|
||||
setStats(data)
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : "Failed to load statistics"
|
||||
@@ -41,7 +43,7 @@ export default function AdminDashboardPage() {
|
||||
|
||||
useEffect(() => {
|
||||
loadStats()
|
||||
}, [])
|
||||
}, [showTestData])
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import { adminApi, AudioSearchJobSummary, CacheStatsResponse } from "@/lib/api"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import {
|
||||
@@ -58,6 +59,7 @@ const statusOptions = [
|
||||
|
||||
export default function AdminSearchesPage() {
|
||||
const { toast } = useToast()
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [searches, setSearches] = useState<AudioSearchJobSummary[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [statusFilter, setStatusFilter] = useState("all")
|
||||
@@ -81,6 +83,7 @@ export default function AdminSearchesPage() {
|
||||
const data = await adminApi.listAudioSearches({
|
||||
limit: 100,
|
||||
status_filter: statusFilter !== "all" ? statusFilter : undefined,
|
||||
exclude_test: !showTestData,
|
||||
})
|
||||
setSearches(data.jobs)
|
||||
} catch (err: any) {
|
||||
@@ -93,7 +96,7 @@ export default function AdminSearchesPage() {
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [statusFilter, toast])
|
||||
}, [statusFilter, showTestData, toast])
|
||||
|
||||
const loadCacheStats = useCallback(async () => {
|
||||
try {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { adminApi, AdminUser, AdminUserListResponse } from "@/lib/api"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
@@ -49,6 +50,7 @@ import { useToast } from "@/hooks/use-toast"
|
||||
export default function AdminUsersPage() {
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [users, setUsers] = useState<AdminUser[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [total, setTotal] = useState(0)
|
||||
@@ -76,6 +78,7 @@ export default function AdminUsersPage() {
|
||||
search: search || undefined,
|
||||
sort_by: sortBy,
|
||||
sort_order: sortOrder,
|
||||
exclude_test: !showTestData,
|
||||
})
|
||||
setUsers(data.users)
|
||||
setTotal(data.total)
|
||||
@@ -90,7 +93,7 @@ export default function AdminUsersPage() {
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [limit, offset, search, sortBy, sortOrder, toast])
|
||||
}, [limit, offset, search, sortBy, sortOrder, showTestData, toast])
|
||||
|
||||
useEffect(() => {
|
||||
loadUsers()
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Admin settings store for persisting admin dashboard preferences.
|
||||
*
|
||||
* Uses zustand with localStorage persistence for settings like
|
||||
* whether to show test data in admin views.
|
||||
*/
|
||||
import { create } from 'zustand'
|
||||
import { persist } from 'zustand/middleware'
|
||||
|
||||
interface AdminSettings {
|
||||
/**
|
||||
* When false (default), test data (e.g., @inbox.testmail.app users) is hidden.
|
||||
* When true, all data including test data is shown.
|
||||
*/
|
||||
showTestData: boolean
|
||||
setShowTestData: (show: boolean) => void
|
||||
}
|
||||
|
||||
export const useAdminSettings = create<AdminSettings>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
showTestData: false,
|
||||
setShowTestData: (show) => set({ showTestData: show }),
|
||||
}),
|
||||
{
|
||||
name: 'admin-settings',
|
||||
}
|
||||
)
|
||||
)
|
||||
+20
-5
@@ -866,8 +866,13 @@ export const adminApi = {
|
||||
/**
|
||||
* Get admin dashboard statistics
|
||||
*/
|
||||
async getStats(): Promise<AdminStatsOverview> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/admin/stats/overview`, {
|
||||
async getStats(params?: { exclude_test?: boolean }): Promise<AdminStatsOverview> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.exclude_test !== undefined) {
|
||||
searchParams.set('exclude_test', String(params.exclude_test));
|
||||
}
|
||||
const url = `${API_BASE_URL}/api/admin/stats/overview${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
return handleResponse(response);
|
||||
@@ -883,6 +888,7 @@ export const adminApi = {
|
||||
sort_by?: 'created_at' | 'last_login_at' | 'credits' | 'email';
|
||||
sort_order?: 'asc' | 'desc';
|
||||
include_inactive?: boolean;
|
||||
exclude_test?: boolean;
|
||||
}): Promise<AdminUserListResponse> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.limit) searchParams.set('limit', String(params.limit));
|
||||
@@ -891,6 +897,7 @@ export const adminApi = {
|
||||
if (params?.sort_by) searchParams.set('sort_by', params.sort_by);
|
||||
if (params?.sort_order) searchParams.set('sort_order', params.sort_order);
|
||||
if (params?.include_inactive) searchParams.set('include_inactive', 'true');
|
||||
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
|
||||
|
||||
const url = `${API_BASE_URL}/api/users/admin/users${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, {
|
||||
@@ -966,7 +973,7 @@ export const adminApi = {
|
||||
/**
|
||||
* List all jobs (admin view)
|
||||
*/
|
||||
async listAllJobs(params?: AdminJobListParams): Promise<Job[]> {
|
||||
async listAllJobs(params?: AdminJobListParams & { exclude_test?: boolean }): Promise<Job[]> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.status) searchParams.set('status', params.status);
|
||||
if (params?.user_email) searchParams.set('user_email', params.user_email);
|
||||
@@ -974,6 +981,7 @@ export const adminApi = {
|
||||
if (params?.created_after) searchParams.set('created_after', params.created_after);
|
||||
if (params?.created_before) searchParams.set('created_before', params.created_before);
|
||||
if (params?.limit) searchParams.set('limit', String(params.limit));
|
||||
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
|
||||
|
||||
const url = `${API_BASE_URL}/api/jobs${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, {
|
||||
@@ -985,8 +993,13 @@ export const adminApi = {
|
||||
/**
|
||||
* Get beta program statistics
|
||||
*/
|
||||
async getBetaStats(): Promise<AdminBetaStats> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/users/admin/beta/stats`, {
|
||||
async getBetaStats(params?: { exclude_test?: boolean }): Promise<AdminBetaStats> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.exclude_test !== undefined) {
|
||||
searchParams.set('exclude_test', String(params.exclude_test));
|
||||
}
|
||||
const url = `${API_BASE_URL}/api/users/admin/beta/stats${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
return handleResponse(response);
|
||||
@@ -1019,10 +1032,12 @@ export const adminApi = {
|
||||
async listAudioSearches(params?: {
|
||||
limit?: number;
|
||||
status_filter?: string;
|
||||
exclude_test?: boolean;
|
||||
}): Promise<AudioSearchListResponse> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.limit) searchParams.set('limit', String(params.limit));
|
||||
if (params?.status_filter) searchParams.set('status_filter', params.status_filter);
|
||||
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
|
||||
|
||||
const url = `${API_BASE_URL}/api/admin/audio-searches${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "karaoke-gen-frontend",
|
||||
"version": "0.81.0",
|
||||
"version": "0.82.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "next build",
|
||||
|
||||
@@ -86,28 +86,39 @@ class AgenticCorrector:
|
||||
|
||||
@classmethod
|
||||
def from_model(
|
||||
cls,
|
||||
model: str,
|
||||
cls,
|
||||
model: str,
|
||||
config: ProviderConfig | None = None,
|
||||
session_id: Optional[str] = None,
|
||||
cache_dir: Optional[str] = None
|
||||
cache_dir: Optional[str] = None,
|
||||
warmup: bool = True
|
||||
) -> "AgenticCorrector":
|
||||
"""Factory method to create corrector from model specification.
|
||||
|
||||
|
||||
This is a convenience method for the common case where you want
|
||||
to use LangChainBridge with a model spec string.
|
||||
|
||||
|
||||
Args:
|
||||
model: Model identifier in format "provider/model"
|
||||
config: Optional provider configuration
|
||||
session_id: Optional Langfuse session ID to group related traces
|
||||
cache_dir: Optional cache directory (uses default if not provided)
|
||||
|
||||
warmup: If True, eagerly initialize the model to avoid delays when
|
||||
multiple threads call classify_gap() simultaneously (default: True)
|
||||
|
||||
Returns:
|
||||
AgenticCorrector instance with LangChainBridge provider
|
||||
"""
|
||||
config = config or ProviderConfig.from_env(cache_dir=cache_dir)
|
||||
provider = LangChainBridge(model=model, config=config)
|
||||
|
||||
# Eagerly initialize the model to avoid lazy initialization delays
|
||||
# when multiple threads call classify_gap() simultaneously
|
||||
if warmup:
|
||||
logger.info(f"🤖 Warming up model {model} before parallel processing...")
|
||||
if not provider.warmup():
|
||||
logger.warning(f"🤖 Model warmup failed for {model}, will retry on first use")
|
||||
|
||||
return cls(provider=provider, session_id=session_id)
|
||||
|
||||
def classify_gap(
|
||||
|
||||
+87
-43
@@ -100,7 +100,75 @@ class LangChainBridge(BaseAIProvider):
|
||||
# Lock prevents race condition where multiple threads try to initialize simultaneously
|
||||
self._chat_model: Optional[Any] = None
|
||||
self._model_init_lock = threading.Lock()
|
||||
|
||||
|
||||
def warmup(self) -> bool:
|
||||
"""Eagerly initialize the chat model.
|
||||
|
||||
Call this after creating the bridge to avoid lazy initialization delays
|
||||
when multiple threads call generate_correction_proposals() simultaneously.
|
||||
|
||||
Returns:
|
||||
True if model was initialized successfully, False otherwise
|
||||
"""
|
||||
if self._chat_model is not None:
|
||||
logger.debug(f"🤖 Model {self._model} already initialized")
|
||||
return True
|
||||
|
||||
logger.info(f"🤖 Warming up model {self._model}...")
|
||||
# Trigger initialization by calling the initialization logic directly
|
||||
try:
|
||||
self._ensure_model_initialized()
|
||||
return self._chat_model is not None
|
||||
except Exception as e:
|
||||
logger.error(f"🤖 Warmup failed for {self._model}: {e}")
|
||||
return False
|
||||
|
||||
def _ensure_model_initialized(self) -> None:
|
||||
"""Ensure the chat model is initialized (thread-safe).
|
||||
|
||||
This method handles the lazy initialization with proper locking.
|
||||
It's separated out so it can be called from both warmup() and
|
||||
generate_correction_proposals().
|
||||
"""
|
||||
if self._chat_model is not None:
|
||||
return
|
||||
|
||||
with self._model_init_lock:
|
||||
# Double-check after acquiring lock
|
||||
if self._chat_model is not None:
|
||||
return
|
||||
|
||||
timeout = self._config.initialization_timeout_seconds
|
||||
logger.info(f"🤖 Initializing model {self._model} with {timeout}s timeout...")
|
||||
init_start = time.time()
|
||||
|
||||
try:
|
||||
# Use ThreadPoolExecutor for cross-platform timeout
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
future = executor.submit(
|
||||
self._factory.create_chat_model,
|
||||
self._model,
|
||||
self._config
|
||||
)
|
||||
try:
|
||||
self._chat_model = future.result(timeout=timeout)
|
||||
except FuturesTimeoutError:
|
||||
raise InitializationTimeoutError(
|
||||
f"Model initialization timed out after {timeout}s. "
|
||||
f"This may indicate network issues or service unavailability."
|
||||
) from None
|
||||
|
||||
init_elapsed = time.time() - init_start
|
||||
logger.info(f"🤖 Model initialized in {init_elapsed:.2f}s")
|
||||
|
||||
except InitializationTimeoutError:
|
||||
self._circuit_breaker.record_failure(self._model)
|
||||
raise
|
||||
except Exception as e:
|
||||
self._circuit_breaker.record_failure(self._model)
|
||||
logger.error(f"🤖 Failed to initialize chat model: {e}")
|
||||
raise
|
||||
|
||||
def name(self) -> str:
|
||||
"""Return provider name for logging."""
|
||||
return f"langchain:{self._model}"
|
||||
@@ -147,48 +215,24 @@ class LangChainBridge(BaseAIProvider):
|
||||
# Use double-checked locking to avoid race condition where multiple threads
|
||||
# all try to initialize the model simultaneously (which caused job 2ccbdf6b
|
||||
# to have 5 concurrent model initializations and 6+ minute delays)
|
||||
if not self._chat_model:
|
||||
with self._model_init_lock:
|
||||
# Double-check after acquiring lock - another thread may have initialized
|
||||
if not self._chat_model:
|
||||
timeout = self._config.initialization_timeout_seconds
|
||||
logger.info(f"🤖 Initializing model {self._model} with {timeout}s timeout...")
|
||||
init_start = time.time()
|
||||
|
||||
try:
|
||||
# Use ThreadPoolExecutor for cross-platform timeout
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
future = executor.submit(
|
||||
self._factory.create_chat_model,
|
||||
self._model,
|
||||
self._config
|
||||
)
|
||||
try:
|
||||
self._chat_model = future.result(timeout=timeout)
|
||||
except FuturesTimeoutError:
|
||||
raise InitializationTimeoutError(
|
||||
f"Model initialization timed out after {timeout}s. "
|
||||
f"This may indicate network issues or service unavailability."
|
||||
) from None
|
||||
|
||||
init_elapsed = time.time() - init_start
|
||||
logger.info(f"🤖 Model initialized in {init_elapsed:.2f}s")
|
||||
|
||||
except InitializationTimeoutError as e:
|
||||
self._circuit_breaker.record_failure(self._model)
|
||||
logger.exception("🤖 Model initialization timeout")
|
||||
return [{
|
||||
"error": INIT_TIMEOUT_ERROR,
|
||||
"message": str(e),
|
||||
"timeout_seconds": timeout
|
||||
}]
|
||||
except Exception as e:
|
||||
self._circuit_breaker.record_failure(self._model)
|
||||
logger.error(f"🤖 Failed to initialize chat model: {e}")
|
||||
return [{
|
||||
"error": MODEL_INIT_ERROR,
|
||||
"message": str(e)
|
||||
}]
|
||||
#
|
||||
# NOTE: For best performance, call warmup() after creating the bridge to
|
||||
# eagerly initialize the model before parallel processing begins.
|
||||
try:
|
||||
self._ensure_model_initialized()
|
||||
except InitializationTimeoutError as e:
|
||||
logger.exception("🤖 Model initialization timeout")
|
||||
return [{
|
||||
"error": INIT_TIMEOUT_ERROR,
|
||||
"message": str(e),
|
||||
"timeout_seconds": self._config.initialization_timeout_seconds
|
||||
}]
|
||||
except Exception as e:
|
||||
logger.error(f"🤖 Failed to initialize chat model: {e}")
|
||||
return [{
|
||||
"error": MODEL_INIT_ERROR,
|
||||
"message": str(e)
|
||||
}]
|
||||
|
||||
# Step 3: Execute with retry logic
|
||||
logger.info(
|
||||
|
||||
+27
-6
@@ -10,6 +10,14 @@ from .config import ProviderConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Try to import Langfuse preloader (may not exist in standalone library usage)
|
||||
try:
|
||||
from backend.services.langfuse_preloader import get_preloaded_langfuse_handler
|
||||
|
||||
_HAS_LANGFUSE_PRELOADER = True
|
||||
except ImportError:
|
||||
_HAS_LANGFUSE_PRELOADER = False
|
||||
|
||||
# Error message constant for TRY003 compliance
|
||||
GOOGLE_API_KEY_MISSING_ERROR = (
|
||||
"GOOGLE_API_KEY environment variable is required for Google/Gemini models. "
|
||||
@@ -87,25 +95,38 @@ class ModelFactory:
|
||||
|
||||
def _initialize_langfuse(self, model_spec: str) -> None:
|
||||
"""Initialize Langfuse callback handler if keys are present.
|
||||
|
||||
|
||||
First tries to use a preloaded handler (to avoid 200+ second init delay
|
||||
on Cloud Run cold starts), then falls back to creating a new one.
|
||||
|
||||
Langfuse reads credentials from environment variables automatically:
|
||||
- LANGFUSE_PUBLIC_KEY
|
||||
- LANGFUSE_SECRET_KEY
|
||||
- LANGFUSE_SECRET_KEY
|
||||
- LANGFUSE_HOST (optional)
|
||||
|
||||
|
||||
Args:
|
||||
model_spec: Model specification for logging
|
||||
|
||||
|
||||
Raises:
|
||||
RuntimeError: If Langfuse keys are set but initialization fails
|
||||
"""
|
||||
public_key = os.getenv("LANGFUSE_PUBLIC_KEY")
|
||||
secret_key = os.getenv("LANGFUSE_SECRET_KEY")
|
||||
|
||||
|
||||
if not (public_key and secret_key):
|
||||
logger.debug("🤖 Langfuse keys not found, tracing disabled")
|
||||
return
|
||||
|
||||
|
||||
# Try to use preloaded handler first (avoids 200+ second delay on Cloud Run)
|
||||
if _HAS_LANGFUSE_PRELOADER:
|
||||
preloaded = get_preloaded_langfuse_handler()
|
||||
if preloaded is not None:
|
||||
logger.info(f"🤖 Using preloaded Langfuse handler for {model_spec}")
|
||||
self._langfuse_handler = preloaded
|
||||
return
|
||||
|
||||
# Fall back to creating new handler
|
||||
logger.info(f"🤖 Initializing Langfuse handler (not preloaded) for {model_spec}...")
|
||||
try:
|
||||
from langfuse.langchain import CallbackHandler
|
||||
|
||||
|
||||
@@ -250,6 +250,65 @@ class AnchorSequenceFinder:
|
||||
self.logger.error(f"Unexpected error loading cache: {type(e).__name__}: {e}")
|
||||
return None
|
||||
|
||||
def _process_ngram_length_no_state(
|
||||
self,
|
||||
n: int,
|
||||
trans_words: List[str],
|
||||
all_words: List[Word],
|
||||
ref_texts_clean: Dict[str, List[str]],
|
||||
ref_words: Dict[str, List[Word]],
|
||||
min_sources: int,
|
||||
) -> List[AnchorSequence]:
|
||||
"""Process a single n-gram length without modifying shared state (thread-safe).
|
||||
|
||||
This version doesn't track used positions - overlap filtering happens later
|
||||
in _remove_overlapping_sequences. This allows parallel processing of different
|
||||
n-gram lengths.
|
||||
"""
|
||||
candidate_anchors = []
|
||||
|
||||
# Build hash-based index for O(1) lookups
|
||||
ngram_index = self._build_ngram_index(ref_texts_clean, n)
|
||||
|
||||
# Generate n-grams from transcribed text
|
||||
trans_ngrams = self._find_ngrams(trans_words, n)
|
||||
|
||||
# Single pass through all transcription n-grams
|
||||
for ngram, trans_pos in trans_ngrams:
|
||||
# Use indexed lookup (O(1) instead of O(n))
|
||||
ngram_tuple = tuple(ngram)
|
||||
if ngram_tuple not in ngram_index:
|
||||
continue
|
||||
|
||||
# Find matches in all sources (no used_positions check - handled later)
|
||||
matches = {}
|
||||
source_positions = ngram_index[ngram_tuple]
|
||||
for source, positions in source_positions.items():
|
||||
if positions:
|
||||
matches[source] = positions[0] # Take first position
|
||||
|
||||
if len(matches) >= min_sources:
|
||||
# Get Word IDs for transcribed words
|
||||
transcribed_word_ids = [w.id for w in all_words[trans_pos : trans_pos + n]]
|
||||
|
||||
# Get Word IDs for reference words
|
||||
reference_word_ids = {
|
||||
source: [w.id for w in ref_words[source][pos : pos + n]]
|
||||
for source, pos in matches.items()
|
||||
}
|
||||
|
||||
anchor = AnchorSequence(
|
||||
id=WordUtils.generate_id(),
|
||||
transcribed_word_ids=transcribed_word_ids,
|
||||
transcription_position=trans_pos,
|
||||
reference_positions=matches,
|
||||
reference_word_ids=reference_word_ids,
|
||||
confidence=len(matches) / len(ref_texts_clean),
|
||||
)
|
||||
candidate_anchors.append(anchor)
|
||||
|
||||
return candidate_anchors
|
||||
|
||||
def _process_ngram_length(
|
||||
self,
|
||||
n: int,
|
||||
@@ -413,45 +472,95 @@ class AnchorSequenceFinder:
|
||||
min_sources=self.min_sources,
|
||||
)
|
||||
|
||||
# Process n-gram lengths sequentially (single-threaded for cloud compatibility)
|
||||
# Process n-gram lengths in parallel for better performance
|
||||
# The overlap filtering at the end handles deduplication, so we don't
|
||||
# need to track used_positions during processing
|
||||
candidate_anchors = []
|
||||
|
||||
|
||||
# Check timeout before processing
|
||||
self._check_timeout(start_time, "n-gram processing start")
|
||||
self.logger.info(f"🔍 ANCHOR SEARCH: Starting sequential n-gram processing ({len(n_gram_lengths)} lengths)")
|
||||
|
||||
batch_size = 10
|
||||
batch_results = []
|
||||
|
||||
for i, n in enumerate(n_gram_lengths):
|
||||
try:
|
||||
# Check timeout periodically
|
||||
if self.timeout_seconds > 0:
|
||||
elapsed_time = time.time() - start_time
|
||||
if elapsed_time > self.timeout_seconds:
|
||||
self.logger.warning(f"🔍 ANCHOR SEARCH: ⏰ Timeout reached at n-gram {n}, stopping")
|
||||
break
|
||||
|
||||
anchors = self._process_ngram_length(
|
||||
n, trans_words, all_words, ref_texts_clean, ref_words, self.min_sources
|
||||
)
|
||||
candidate_anchors.extend(anchors)
|
||||
|
||||
# Batch logging
|
||||
batch_results.append((n, len(anchors)))
|
||||
|
||||
# Log progress every batch_size results or on the last result
|
||||
if (i + 1) % batch_size == 0 or (i + 1) == len(n_gram_lengths):
|
||||
total_anchors_in_batch = sum(anchor_count for _, anchor_count in batch_results)
|
||||
n_gram_ranges = [str(ng) for ng, _ in batch_results]
|
||||
range_str = f"{n_gram_ranges[0]}-{n_gram_ranges[-1]}" if len(n_gram_ranges) > 1 else n_gram_ranges[0]
|
||||
self.logger.debug(f"🔍 ANCHOR SEARCH: Completed n-gram lengths {range_str} - found {total_anchors_in_batch} anchors")
|
||||
batch_results = []
|
||||
|
||||
except Exception as e:
|
||||
self.logger.warning(f"🔍 ANCHOR SEARCH: ⚠️ n-gram length {n} failed: {str(e)}")
|
||||
batch_results.append((n, 0))
|
||||
continue
|
||||
|
||||
# Determine parallelization strategy
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
# Use parallel processing by default, can be disabled via env var
|
||||
use_parallel = os.getenv("ANCHOR_SEARCH_SEQUENTIAL", "0").lower() not in {"1", "true", "yes"}
|
||||
max_workers = int(os.getenv("ANCHOR_SEARCH_WORKERS", "4"))
|
||||
|
||||
if use_parallel and len(n_gram_lengths) > 1:
|
||||
self.logger.info(f"🔍 ANCHOR SEARCH: Starting PARALLEL n-gram processing ({len(n_gram_lengths)} lengths, {max_workers} workers)")
|
||||
|
||||
# Process in parallel - each n-gram length is independent
|
||||
# since we don't track used_positions during processing
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
||||
# Submit all tasks
|
||||
future_to_n = {
|
||||
executor.submit(
|
||||
self._process_ngram_length_no_state,
|
||||
n, trans_words, all_words, ref_texts_clean, ref_words, self.min_sources
|
||||
): n
|
||||
for n in n_gram_lengths
|
||||
}
|
||||
|
||||
completed = 0
|
||||
for future in as_completed(future_to_n):
|
||||
n = future_to_n[future]
|
||||
completed += 1
|
||||
|
||||
# Check timeout periodically
|
||||
if self.timeout_seconds > 0:
|
||||
elapsed_time = time.time() - start_time
|
||||
if elapsed_time > self.timeout_seconds:
|
||||
self.logger.warning(f"🔍 ANCHOR SEARCH: ⏰ Timeout reached, stopping ({completed}/{len(n_gram_lengths)} completed)")
|
||||
# Cancel remaining futures
|
||||
for f in future_to_n.keys():
|
||||
f.cancel()
|
||||
break
|
||||
|
||||
try:
|
||||
anchors = future.result()
|
||||
candidate_anchors.extend(anchors)
|
||||
if completed % 20 == 0:
|
||||
self.logger.debug(f"🔍 ANCHOR SEARCH: Progress {completed}/{len(n_gram_lengths)} lengths processed")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"🔍 ANCHOR SEARCH: ⚠️ n-gram length {n} failed: {str(e)}")
|
||||
else:
|
||||
# Sequential fallback
|
||||
self.logger.info(f"🔍 ANCHOR SEARCH: Starting sequential n-gram processing ({len(n_gram_lengths)} lengths)")
|
||||
|
||||
batch_size = 10
|
||||
batch_results = []
|
||||
|
||||
for i, n in enumerate(n_gram_lengths):
|
||||
try:
|
||||
# Check timeout periodically
|
||||
if self.timeout_seconds > 0:
|
||||
elapsed_time = time.time() - start_time
|
||||
if elapsed_time > self.timeout_seconds:
|
||||
self.logger.warning(f"🔍 ANCHOR SEARCH: ⏰ Timeout reached at n-gram {n}, stopping")
|
||||
break
|
||||
|
||||
anchors = self._process_ngram_length(
|
||||
n, trans_words, all_words, ref_texts_clean, ref_words, self.min_sources
|
||||
)
|
||||
candidate_anchors.extend(anchors)
|
||||
|
||||
# Batch logging
|
||||
batch_results.append((n, len(anchors)))
|
||||
|
||||
# Log progress every batch_size results or on the last result
|
||||
if (i + 1) % batch_size == 0 or (i + 1) == len(n_gram_lengths):
|
||||
total_anchors_in_batch = sum(anchor_count for _, anchor_count in batch_results)
|
||||
n_gram_ranges = [str(ng) for ng, _ in batch_results]
|
||||
range_str = f"{n_gram_ranges[0]}-{n_gram_ranges[-1]}" if len(n_gram_ranges) > 1 else n_gram_ranges[0]
|
||||
self.logger.debug(f"🔍 ANCHOR SEARCH: Completed n-gram lengths {range_str} - found {total_anchors_in_batch} anchors")
|
||||
batch_results = []
|
||||
|
||||
except Exception as e:
|
||||
self.logger.warning(f"🔍 ANCHOR SEARCH: ⚠️ n-gram length {n} failed: {str(e)}")
|
||||
batch_results.append((n, 0))
|
||||
continue
|
||||
|
||||
self.logger.info(f"🔍 ANCHOR SEARCH: ✅ Found {len(candidate_anchors)} candidate anchors in {time.time() - start_time:.1f}s")
|
||||
|
||||
|
||||
@@ -12,9 +12,10 @@ from lyrics_transcriber.types import GapSequence, WordCorrection
|
||||
from lyrics_transcriber.correction.handlers.base import GapCorrectionHandler
|
||||
from lyrics_transcriber.correction.handlers.word_operations import WordOperations
|
||||
|
||||
# Try to import preloader (may not exist in standalone library usage)
|
||||
# Try to import preloaders (may not exist in standalone library usage)
|
||||
try:
|
||||
from backend.services.spacy_preloader import get_preloaded_model
|
||||
from backend.services.nltk_preloader import get_preloaded_cmudict
|
||||
|
||||
_HAS_PRELOADER = True
|
||||
except ImportError:
|
||||
@@ -78,7 +79,16 @@ class SyllablesMatchHandler(GapCorrectionHandler):
|
||||
# Initialize Pyphen for English
|
||||
self.dic = pyphen.Pyphen(lang="en_US")
|
||||
|
||||
# Initialize NLTK's CMU dictionary
|
||||
# Try to use preloaded cmudict first (avoids 50-100+ second download on Cloud Run)
|
||||
if _HAS_PRELOADER:
|
||||
preloaded_cmudict = get_preloaded_cmudict()
|
||||
if preloaded_cmudict is not None:
|
||||
self.logger.debug("Using preloaded NLTK cmudict")
|
||||
self.cmudict = preloaded_cmudict
|
||||
return
|
||||
|
||||
# Fall back to loading directly
|
||||
self.logger.info("Loading NLTK cmudict (not preloaded)...")
|
||||
try:
|
||||
self.cmudict = cmudict.dict()
|
||||
except LookupError:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.97.1"
|
||||
version = "0.99.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
Reference in new issue
Block a user