mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-21 05:18:08 +09:00
Compare commits
202
Commits
No files matched your search
@@ -0,0 +1,74 @@
|
||||
---
|
||||
description: Periodic documentation maintenance and organization check
|
||||
allowed-tools: Read, Glob, Grep, Edit, Write, Bash
|
||||
---
|
||||
|
||||
# Documentation Maintenance Check
|
||||
|
||||
You are performing periodic maintenance on the project documentation.
|
||||
|
||||
## Checks to Perform
|
||||
|
||||
### 1. Structure Compliance
|
||||
Verify docs/ follows the correct structure:
|
||||
```
|
||||
docs/
|
||||
├── README.md # Current status + navigation
|
||||
├── ARCHITECTURE.md # System design
|
||||
├── DEVELOPMENT.md # Dev setup, testing, deployment
|
||||
├── API.md # Backend API reference
|
||||
├── LESSONS-LEARNED.md # Accumulated wisdom
|
||||
└── archive/ # Historical docs (YYYY-MM-DD-topic.md)
|
||||
```
|
||||
|
||||
Report any files that don't belong or are misplaced.
|
||||
|
||||
### 2. Freshness Check
|
||||
- Read `docs/README.md` - is the status section current?
|
||||
- Check recent git commits - do they suggest docs should be updated?
|
||||
- Look for stale information that contradicts current code
|
||||
|
||||
### 3. Archive Organization
|
||||
- Verify all archive files have YYYY-MM-DD prefix
|
||||
- Check for any docs that should be archived (completed work, old plans)
|
||||
- Remove truly obsolete content (empty files, duplicate info)
|
||||
|
||||
### 4. Cross-Reference Check
|
||||
- Verify CLAUDE.md points to current doc locations
|
||||
- Check that docs reference each other correctly
|
||||
- Ensure no broken internal links
|
||||
|
||||
### 5. Content Quality
|
||||
- Flag any docs over 500 lines (may need splitting)
|
||||
- Identify duplicate information across docs
|
||||
- Note sections that seem outdated
|
||||
|
||||
## Actions to Take
|
||||
|
||||
1. **Fix structural issues** - Move/rename misplaced files
|
||||
2. **Update stale content** - Refresh outdated information
|
||||
3. **Archive completed work** - Move old docs to archive/
|
||||
4. **Report findings** - Summarize what was found and fixed
|
||||
|
||||
## Output Format
|
||||
|
||||
Provide a maintenance report:
|
||||
```
|
||||
## Documentation Maintenance Report - YYYY-MM-DD
|
||||
|
||||
### Issues Found
|
||||
- [list of issues]
|
||||
|
||||
### Actions Taken
|
||||
- [list of fixes made]
|
||||
|
||||
### Recommendations
|
||||
- [suggestions for future attention]
|
||||
|
||||
### Status
|
||||
- [ ] Structure: OK/Fixed
|
||||
- [ ] Freshness: OK/Updated
|
||||
- [ ] Archive: OK/Organized
|
||||
- [ ] Cross-refs: OK/Fixed
|
||||
- [ ] Quality: OK/Flagged
|
||||
```
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
description: Review current session for documentation updates before merging PR
|
||||
allowed-tools: Read, Glob, Grep, Edit, Write
|
||||
---
|
||||
|
||||
# Pre-Merge Documentation Review
|
||||
|
||||
You are reviewing this chat session to identify documentation updates needed before merging the current PR.
|
||||
|
||||
## Your Task
|
||||
|
||||
1. **Analyze the current session** - What work was done? What was learned? What changed?
|
||||
|
||||
2. **Check if docs need updates:**
|
||||
- Does `docs/README.md` status section need updating?
|
||||
- Should anything be added to `docs/LESSONS-LEARNED.md`?
|
||||
- Does `docs/ARCHITECTURE.md` need changes (if architecture changed)?
|
||||
- Does `docs/DEVELOPMENT.md` need changes (if dev workflow changed)?
|
||||
- Does `docs/API.md` need changes (if API changed)?
|
||||
|
||||
3. **For significant completed work:**
|
||||
- Create `docs/archive/YYYY-MM-DD-topic.md` summarizing the work
|
||||
- Use today's date and a descriptive topic name
|
||||
|
||||
4. **Update docs/README.md** with:
|
||||
- Current status if it changed
|
||||
- Any new known issues discovered
|
||||
- Link to new archive doc if created
|
||||
|
||||
## Guidelines
|
||||
|
||||
- Keep updates concise and factual
|
||||
- Focus on information useful for future AI agents
|
||||
- Don't duplicate information that's in the code
|
||||
- Archive docs should capture "what was done and why" not implementation details
|
||||
|
||||
## Output
|
||||
|
||||
After reviewing, either:
|
||||
- Make the necessary documentation updates
|
||||
- Report "No documentation updates needed" with brief explanation why
|
||||
|
||||
Remember: Good documentation helps the next agent continue where you left off.
|
||||
@@ -1,21 +0,0 @@
|
||||
---
|
||||
description: Git branching and PR workflow
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Branching Workflow
|
||||
|
||||
**Never commit directly to `main`.** Always work on a feature branch.
|
||||
|
||||
Create descriptive branch names like `feature/add-discord-notifications`, `fix/audio-sync-issue`, or `refactor/cleanup-api-routes`.
|
||||
|
||||
# Creating a Pull Request
|
||||
|
||||
Once all changes are complete, tests pass, and commits are pushed, create a PR with:
|
||||
|
||||
1. **Summary** - Brief overview of the changes
|
||||
2. **Changes Made** - List of specific modifications
|
||||
3. **Testing** - How changes were tested (unit tests, manual testing)
|
||||
4. **Related Issues** - Reference any GitHub issues (e.g., "Fixes #123")
|
||||
|
||||
Only merge after review and CI checks pass.
|
||||
@@ -1,14 +0,0 @@
|
||||
# Infrastructure Changes
|
||||
|
||||
All Google Cloud infrastructure (IAM, Cloud Storage, Cloud Run, Secret Manager, Artifact Registry, etc.) must be managed via Pulumi in the `infrastructure/` folder.
|
||||
|
||||
## Rules
|
||||
|
||||
- **Reading/querying** with `gcloud` CLI is fine
|
||||
- **Creating or modifying** resources must go through IaC — never use `gcloud` or the Console to make changes
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Make changes in `infrastructure/`
|
||||
2. Run `pulumi preview` and verify the output
|
||||
3. Run `pulumi up` to apply
|
||||
@@ -1,27 +0,0 @@
|
||||
---
|
||||
description: Version bumping rule for commits
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Version Management
|
||||
|
||||
When committing and pushing changes, always bump the patch version in `pyproject.toml`.
|
||||
|
||||
The version is located at `tool.poetry.version` in `pyproject.toml`. For example, if the current version is `0.70.3`, bump it to `0.70.4`.
|
||||
|
||||
This ensures every commit pushed to the repository has a unique version number for tracking and deployment purposes.
|
||||
|
||||
# Testing Requirements
|
||||
|
||||
Before committing and pushing changes, ensure all tests pass:
|
||||
|
||||
```bash
|
||||
python -m pytest tests/ backend/tests/ -v -x --ignore=tests/integration
|
||||
```
|
||||
|
||||
Ensure all code touched is thoroughly covered by unit tests, we have a 70% coverage minimum in CI:
|
||||
```bash
|
||||
poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=xml --cov-report=term-missing --cov-fail-under=70
|
||||
```
|
||||
|
||||
Do not commit or push code that fails tests. Fix any test failures before proceeding.
|
||||
@@ -0,0 +1,83 @@
|
||||
# .dockerignore - Reduce Docker build context size
|
||||
# This is critical for fast builds as it reduces upload time and cache invalidation
|
||||
|
||||
# Git
|
||||
.git/
|
||||
.gitignore
|
||||
.gitmodules
|
||||
|
||||
# Node.js / Frontend (not needed for backend image)
|
||||
node_modules/
|
||||
frontend/
|
||||
frontend-react/
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Python virtual environments (use Docker's Python instead)
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
.venv/
|
||||
venv/
|
||||
backend/venv/
|
||||
ENV/
|
||||
env/
|
||||
*.egg-info/
|
||||
.eggs/
|
||||
dist/
|
||||
build/
|
||||
*.egg
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.DS_Store
|
||||
|
||||
# Testing (not needed in production image)
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
coverage.xml
|
||||
*.cover
|
||||
tests/
|
||||
backend/tests/
|
||||
|
||||
# Documentation (not needed in Docker image)
|
||||
docs/
|
||||
*.md
|
||||
!README.md
|
||||
|
||||
# Infrastructure (not needed for Docker build)
|
||||
infrastructure/
|
||||
|
||||
# CI/CD configs
|
||||
.github/
|
||||
|
||||
# Cloud Build configs (keep for reference but not in image)
|
||||
cloudbuild*.yaml
|
||||
|
||||
# Local development files
|
||||
lyrics_transcriber_local/
|
||||
*.local
|
||||
.env
|
||||
.env.*
|
||||
*.bak
|
||||
*.tmp
|
||||
Thumbs.db
|
||||
|
||||
# Large test/sample files
|
||||
tests/data/
|
||||
*.mp3
|
||||
*.wav
|
||||
*.mp4
|
||||
*.mkv
|
||||
*.flac
|
||||
+409
-155
@@ -17,14 +17,124 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
# ============================================
|
||||
# PACKAGE TESTS (karaoke-gen Python CLI)
|
||||
# PATH FILTERING - Determine what changed
|
||||
# Only needed for PRs (main branch skips tests)
|
||||
# ============================================
|
||||
|
||||
changes:
|
||||
name: "Detect Changes"
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref != 'refs/heads/main'
|
||||
outputs:
|
||||
frontend: ${{ steps.filter.outputs.frontend }}
|
||||
backend: ${{ steps.filter.outputs.backend }}
|
||||
package: ${{ steps.filter.outputs.package }}
|
||||
infra: ${{ steps.filter.outputs.infra }}
|
||||
deps: ${{ steps.filter.outputs.deps }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: dorny/paths-filter@v3
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
frontend:
|
||||
- 'frontend/**'
|
||||
backend:
|
||||
- 'backend/**'
|
||||
package:
|
||||
- 'karaoke_gen/**'
|
||||
- 'lyrics_transcriber_temp/**'
|
||||
- 'tests/**'
|
||||
infra:
|
||||
- 'infrastructure/**'
|
||||
deps:
|
||||
- 'poetry.lock'
|
||||
|
||||
- name: Summary
|
||||
run: |
|
||||
echo "### Change Detection Results" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Area | Changed |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|------|---------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Frontend | ${{ steps.filter.outputs.frontend }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Backend | ${{ steps.filter.outputs.backend }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Package | ${{ steps.filter.outputs.package }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Infrastructure | ${{ steps.filter.outputs.infra }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Dependencies | ${{ steps.filter.outputs.deps }} |" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
# ============================================
|
||||
# FRONTEND TESTS (PRs only - main skips tests)
|
||||
# ============================================
|
||||
|
||||
frontend-unit-tests:
|
||||
name: "Frontend - Unit Tests"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && needs.changes.outputs.frontend == 'true'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js with caching
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Run unit tests with coverage
|
||||
working-directory: frontend
|
||||
run: npm run test:ci
|
||||
|
||||
- name: Upload coverage report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: frontend-coverage
|
||||
path: frontend/coverage/
|
||||
retention-days: 7
|
||||
|
||||
frontend-build:
|
||||
name: "Frontend - Build"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && needs.changes.outputs.frontend == 'true'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js with caching
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Build frontend
|
||||
working-directory: frontend
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
run: npm run build
|
||||
|
||||
# ============================================
|
||||
# PACKAGE TESTS (PRs only - main skips tests)
|
||||
# ============================================
|
||||
|
||||
package-unit-tests:
|
||||
name: "Package - Unit Tests (70% coverage)"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
@@ -37,6 +147,14 @@ jobs:
|
||||
virtualenvs-create: true
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Cache Poetry dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-package-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install --with dev
|
||||
|
||||
@@ -45,12 +163,18 @@ jobs:
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y ffmpeg
|
||||
|
||||
- name: Cache spaCy model
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/spacy
|
||||
key: spacy-en_core_web_sm-${{ runner.os }}
|
||||
|
||||
- name: Install spaCy language models
|
||||
run: poetry run python -m spacy download en_core_web_sm
|
||||
|
||||
- name: Run unit tests
|
||||
run: |
|
||||
poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=xml --cov-report=term-missing --cov-fail-under=70
|
||||
poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=xml --cov-report=term-missing --cov-fail-under=69
|
||||
|
||||
- name: Upload coverage reports
|
||||
uses: codecov/codecov-action@v5
|
||||
@@ -63,8 +187,12 @@ jobs:
|
||||
package-integration-tests:
|
||||
name: "Package - Integration Tests"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
@@ -77,6 +205,14 @@ jobs:
|
||||
virtualenvs-create: true
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Cache Poetry dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-package-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install --with dev
|
||||
|
||||
@@ -85,18 +221,31 @@ jobs:
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y ffmpeg
|
||||
|
||||
- name: Cache spaCy model
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/spacy
|
||||
key: spacy-en_core_web_sm-${{ runner.os }}
|
||||
|
||||
- name: Install spaCy language models
|
||||
run: poetry run python -m spacy download en_core_web_sm
|
||||
|
||||
- name: Run integration tests
|
||||
run: poetry run pytest tests/integration/ -v
|
||||
|
||||
package-build:
|
||||
name: "Package - Build & Install"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [package-unit-tests, package-integration-tests]
|
||||
package-build-test:
|
||||
name: "Package - Build & Install (Test)"
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
needs: [changes, package-unit-tests, package-integration-tests]
|
||||
if: >-
|
||||
github.ref != 'refs/heads/main' && always() &&
|
||||
(needs.package-unit-tests.result == 'success' || needs.package-unit-tests.result == 'skipped') &&
|
||||
(needs.package-integration-tests.result == 'success' || needs.package-integration-tests.result == 'skipped') &&
|
||||
(needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
@@ -112,36 +261,20 @@ jobs:
|
||||
- name: Build package
|
||||
run: poetry build
|
||||
|
||||
- name: Free disk space
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
with:
|
||||
tool-cache: false
|
||||
android: true
|
||||
haskell: true
|
||||
dotnet: false
|
||||
large-packages: false
|
||||
docker-images: false
|
||||
swap-storage: false
|
||||
|
||||
- name: Test package installation
|
||||
run: |
|
||||
pip install dist/*.whl
|
||||
python -m karaoke_gen.utils.gen_cli --help
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: package-dist
|
||||
path: dist/
|
||||
retention-days: 1
|
||||
|
||||
# ============================================
|
||||
# BACKEND TESTS (Cloud Run API service)
|
||||
# BACKEND TESTS (PRs only - main skips tests)
|
||||
# ============================================
|
||||
|
||||
backend-unit-tests:
|
||||
name: "Backend - Unit Tests"
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
@@ -162,7 +295,7 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
|
||||
- name: Run unit tests
|
||||
- name: Run all backend unit tests
|
||||
env:
|
||||
GOOGLE_CLOUD_PROJECT: test-project
|
||||
GCS_BUCKET_NAME: test-bucket
|
||||
@@ -170,23 +303,16 @@ jobs:
|
||||
ENVIRONMENT: test
|
||||
run: |
|
||||
poetry run pytest \
|
||||
backend/tests/test_models.py \
|
||||
backend/tests/test_job_manager.py \
|
||||
backend/tests/test_file_upload.py \
|
||||
backend/tests/test_services.py \
|
||||
backend/tests/ \
|
||||
--ignore=backend/tests/emulator \
|
||||
-v --tb=short
|
||||
|
||||
backend-emulator-tests:
|
||||
name: "Backend - Emulator Integration Tests"
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- name: Free disk space
|
||||
run: |
|
||||
sudo rm -rf /usr/share/dotnet
|
||||
sudo rm -rf /opt/ghc
|
||||
sudo rm -rf /usr/local/share/boost
|
||||
df -h
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -209,14 +335,6 @@ jobs:
|
||||
distribution: "temurin"
|
||||
java-version: "21"
|
||||
|
||||
- name: Set up Cloud SDK
|
||||
uses: google-github-actions/setup-gcloud@v2
|
||||
with:
|
||||
version: "latest"
|
||||
|
||||
- name: Install Firestore emulator
|
||||
run: gcloud components install beta cloud-firestore-emulator --quiet
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
|
||||
@@ -239,6 +357,8 @@ jobs:
|
||||
backend-lint:
|
||||
name: "Backend - Code Quality"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true')
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
@@ -256,6 +376,14 @@ jobs:
|
||||
virtualenvs-create: true
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Cache Poetry dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-lint-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-lint-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Install dependencies
|
||||
run: poetry install
|
||||
|
||||
@@ -265,9 +393,78 @@ jobs:
|
||||
echo "✅ Basic syntax validation passed"
|
||||
|
||||
# ============================================
|
||||
# DEPLOYMENTS (main branch only)
|
||||
# CI GATE - Required status check for PRs
|
||||
# Only runs on PRs, not on main
|
||||
# ============================================
|
||||
|
||||
ci-gate:
|
||||
name: "CI Gate"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [frontend-unit-tests, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint]
|
||||
if: github.ref != 'refs/heads/main' && always()
|
||||
steps:
|
||||
- name: Check results
|
||||
run: |
|
||||
results=(
|
||||
"${{ needs.frontend-unit-tests.result }}"
|
||||
"${{ needs.frontend-build.result }}"
|
||||
"${{ needs.package-unit-tests.result }}"
|
||||
"${{ needs.package-integration-tests.result }}"
|
||||
"${{ needs.backend-unit-tests.result }}"
|
||||
"${{ needs.backend-emulator-tests.result }}"
|
||||
"${{ needs.backend-lint.result }}"
|
||||
)
|
||||
for result in "${results[@]}"; do
|
||||
if [[ "$result" == "failure" || "$result" == "cancelled" ]]; then
|
||||
echo "❌ CI failed"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo "✅ CI passed"
|
||||
|
||||
# ============================================
|
||||
# DEPLOYMENTS (main branch only)
|
||||
# Tests already passed on PR, so we skip them here
|
||||
# ============================================
|
||||
|
||||
package-build:
|
||||
name: "Package - Build"
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.13"
|
||||
|
||||
- name: Install Poetry
|
||||
uses: snok/install-poetry@v1
|
||||
with:
|
||||
virtualenvs-create: true
|
||||
virtualenvs-in-project: true
|
||||
|
||||
- name: Cache Poetry dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: .venv
|
||||
key: venv-package-${{ runner.os }}-py3.13-${{ hashFiles('poetry.lock') }}
|
||||
restore-keys: |
|
||||
venv-package-${{ runner.os }}-py3.13-
|
||||
|
||||
- name: Build package
|
||||
run: poetry build
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: package-dist
|
||||
path: dist/
|
||||
retention-days: 1
|
||||
|
||||
package-publish:
|
||||
name: "Deploy - Publish to PyPI"
|
||||
runs-on: ubuntu-latest
|
||||
@@ -275,6 +472,8 @@ jobs:
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
@@ -357,28 +556,69 @@ jobs:
|
||||
name: "Deploy - Frontend (GitHub Pages)"
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js with caching
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Enable Yarn (for lyrics frontend)
|
||||
run: corepack enable
|
||||
|
||||
# ===== Build Main Frontend (Next.js) =====
|
||||
- name: Install main frontend dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Build main frontend (Next.js static export)
|
||||
working-directory: frontend
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
|
||||
run: npm run build
|
||||
|
||||
# ===== Build Lyrics Review Frontend (Vite) =====
|
||||
- name: Cache Yarn dependencies (lyrics frontend)
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: lyrics_transcriber_temp/lyrics_transcriber/frontend/node_modules
|
||||
key: yarn-lyrics-${{ runner.os }}-${{ hashFiles('lyrics_transcriber_temp/lyrics_transcriber/frontend/yarn.lock') }}
|
||||
restore-keys: |
|
||||
yarn-lyrics-${{ runner.os }}-
|
||||
|
||||
- name: Install lyrics frontend dependencies
|
||||
working-directory: lyrics_transcriber_temp/lyrics_transcriber/frontend
|
||||
run: yarn install --frozen-lockfile
|
||||
|
||||
- name: Build lyrics frontend (Vite)
|
||||
working-directory: lyrics_transcriber_temp/lyrics_transcriber/frontend
|
||||
env:
|
||||
# Set base path for subpath deployment
|
||||
VITE_BASE_PATH: /lyrics/
|
||||
run: yarn build --base=/lyrics/
|
||||
|
||||
- name: Copy lyrics frontend to main output
|
||||
run: |
|
||||
mkdir -p frontend/out/lyrics
|
||||
cp -r lyrics_transcriber_temp/lyrics_transcriber/frontend/dist/* frontend/out/lyrics/
|
||||
|
||||
# ===== Copy Instrumental Review UI (Static HTML) =====
|
||||
- name: Copy instrumental review UI to main output
|
||||
run: |
|
||||
mkdir -p frontend/out/instrumental
|
||||
cp karaoke_gen/instrumental_review/static/index.html frontend/out/instrumental/
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v4
|
||||
|
||||
- name: Prepare frontend files
|
||||
run: |
|
||||
echo "📁 Preparing frontend files for deployment..."
|
||||
mkdir -p _site
|
||||
cp -r frontend/* _site/
|
||||
echo "✅ Frontend files copied to _site/"
|
||||
ls -la _site/
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: "_site"
|
||||
path: "frontend/out"
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
@@ -386,20 +626,28 @@ jobs:
|
||||
|
||||
deploy-backend:
|
||||
name: "Deploy - Backend (Cloud Run)"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [backend-unit-tests, backend-emulator-tests, backend-lint]
|
||||
runs-on: [self-hosted, linux, gcp]
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
env:
|
||||
REGISTRY: us-central1-docker.pkg.dev
|
||||
PROJECT_ID: nomadkaraoke
|
||||
REPOSITORY: karaoke-repo
|
||||
BASE_IMAGE_NAME: karaoke-backend-base
|
||||
APP_IMAGE_NAME: karaoke-backend
|
||||
steps:
|
||||
# ============================================
|
||||
# Check if deployment is needed FIRST
|
||||
# ============================================
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: false
|
||||
fetch-depth: 0 # Need full history for tag check
|
||||
|
||||
- name: Set up Python (for version extraction)
|
||||
- name: Set up Python 3.13
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.13"
|
||||
@@ -413,7 +661,7 @@ jobs:
|
||||
VERSION=$(poetry version --short)
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "📋 Current version: $VERSION"
|
||||
|
||||
|
||||
if git ls-remote --tags origin | grep -q "refs/tags/v$VERSION$"; then
|
||||
echo "needs_deploy=false" >> $GITHUB_OUTPUT
|
||||
echo "⏭️ Tag v$VERSION already exists - skipping backend deployment"
|
||||
@@ -423,6 +671,8 @@ jobs:
|
||||
echo "✨ Tag v$VERSION does not exist - proceeding with deployment"
|
||||
fi
|
||||
|
||||
# No disk cleanup needed - self-hosted runner has 200GB SSD
|
||||
|
||||
- name: Authenticate to Google Cloud (Workload Identity)
|
||||
if: steps.version_check.outputs.needs_deploy == 'true'
|
||||
id: auth
|
||||
@@ -437,21 +687,37 @@ jobs:
|
||||
with:
|
||||
version: "latest"
|
||||
|
||||
- name: Check if base image needs rebuild
|
||||
- name: Configure Docker for Artifact Registry
|
||||
if: steps.version_check.outputs.needs_deploy == 'true'
|
||||
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
|
||||
|
||||
# ============================================
|
||||
# Docker Build with BuildKit + Registry Cache
|
||||
# This replaces expensive Cloud Build with free GitHub Actions
|
||||
# Registry cache persists between builds for fast rebuilds
|
||||
# ============================================
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
if: steps.version_check.outputs.needs_deploy == 'true'
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Calculate base image hash
|
||||
if: steps.version_check.outputs.needs_deploy == 'true'
|
||||
id: base-hash
|
||||
run: |
|
||||
# Hash both poetry.lock AND Dockerfile.base - rebuild if either changes
|
||||
CURRENT_HASH=$(cat poetry.lock backend/Dockerfile.base | sha256sum | cut -d' ' -f1)
|
||||
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
|
||||
echo "📋 Base content hash: $CURRENT_HASH"
|
||||
|
||||
- name: Check if base image exists and is current
|
||||
if: steps.version_check.outputs.needs_deploy == 'true'
|
||||
id: check-base
|
||||
run: |
|
||||
echo "🔍 Checking if base image needs rebuild..."
|
||||
BASE_IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest"
|
||||
|
||||
# Hash both poetry.lock AND Dockerfile.base - rebuild if either changes
|
||||
CURRENT_HASH=$(cat poetry.lock backend/Dockerfile.base | sha256sum | cut -d' ' -f1)
|
||||
echo "Current combined hash (poetry.lock + Dockerfile.base): $CURRENT_HASH"
|
||||
|
||||
gcloud auth configure-docker us-central1-docker.pkg.dev --quiet
|
||||
|
||||
BASE_IMAGE="us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend-base:latest"
|
||||
# Try to get the existing base image's hash label
|
||||
EXISTING_HASH=""
|
||||
|
||||
if docker pull $BASE_IMAGE 2>/dev/null; then
|
||||
EXISTING_HASH=$(docker inspect $BASE_IMAGE --format='{{index .Config.Labels "base.content.hash"}}' 2>/dev/null || echo "")
|
||||
# Fallback to old label name for backwards compatibility
|
||||
@@ -460,10 +726,10 @@ jobs:
|
||||
fi
|
||||
echo "Existing base image hash: $EXISTING_HASH"
|
||||
else
|
||||
echo "⚠️ No existing base image found"
|
||||
echo "⚠️ No existing base image found - will build"
|
||||
fi
|
||||
|
||||
if [ "$CURRENT_HASH" != "$EXISTING_HASH" ]; then
|
||||
if [ "${{ steps.base-hash.outputs.hash }}" != "$EXISTING_HASH" ]; then
|
||||
echo "🔄 Base image needs rebuild (poetry.lock or Dockerfile.base changed)"
|
||||
echo "needs_rebuild=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
@@ -471,88 +737,73 @@ jobs:
|
||||
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Rebuild base image (if needed)
|
||||
- name: Build and push base image (if needed)
|
||||
if: steps.version_check.outputs.needs_deploy == 'true' && steps.check-base.outputs.needs_rebuild == 'true'
|
||||
run: |
|
||||
echo "🏗️ Rebuilding base image with updated dependencies..."
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile.base
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:latest
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:${{ github.sha }}
|
||||
# Registry cache for ALL layers (mode=max) - persists between builds
|
||||
# ignore-error=true allows build to continue if cache doesn't exist yet
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
build-args: |
|
||||
BUILD_DATE=${{ github.run_id }}
|
||||
BUILD_ID=${{ github.sha }}
|
||||
BASE_CONTENT_HASH=${{ steps.base-hash.outputs.hash }}
|
||||
# Provenance disabled for smaller image and faster push
|
||||
provenance: false
|
||||
|
||||
BASE_BUILD_ID=$(gcloud builds submit \
|
||||
--config=cloudbuild-base.yaml \
|
||||
--project=nomadkaraoke \
|
||||
--format='value(id)' \
|
||||
--async \
|
||||
.)
|
||||
- name: Build and push app image
|
||||
if: steps.version_check.outputs.needs_deploy == 'true'
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: backend/Dockerfile
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:latest
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}
|
||||
${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
|
||||
# Registry cache for app layers
|
||||
# ignore-error=true allows build to continue if cache doesn't exist yet
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,ignore-error=true
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
|
||||
provenance: false
|
||||
|
||||
echo "Base Build ID: $BASE_BUILD_ID"
|
||||
echo "Build URL: https://console.cloud.google.com/cloud-build/builds/$BASE_BUILD_ID?project=nomadkaraoke"
|
||||
# ============================================
|
||||
# Deploy to Cloud Run
|
||||
# ============================================
|
||||
|
||||
echo "Waiting for base image build to complete..."
|
||||
while true; do
|
||||
BUILD_STATUS=$(gcloud builds describe $BASE_BUILD_ID --project=nomadkaraoke --format='value(status)')
|
||||
echo "Base build status: $BUILD_STATUS"
|
||||
|
||||
if [ "$BUILD_STATUS" = "SUCCESS" ]; then
|
||||
echo "✅ Base image build completed successfully"
|
||||
break
|
||||
elif [ "$BUILD_STATUS" = "FAILURE" ] || [ "$BUILD_STATUS" = "CANCELLED" ] || [ "$BUILD_STATUS" = "TIMEOUT" ]; then
|
||||
echo "❌ Base image build failed with status: $BUILD_STATUS"
|
||||
echo ""
|
||||
echo "==================== BUILD LOGS ===================="
|
||||
gcloud logging read "resource.type=build AND resource.labels.build_id=$BASE_BUILD_ID" \
|
||||
--project=nomadkaraoke \
|
||||
--format="value(textPayload)" \
|
||||
--limit=200 \
|
||||
--order=asc || echo "Failed to retrieve logs from Cloud Logging"
|
||||
echo "===================================================="
|
||||
gcloud builds log $BASE_BUILD_ID --project=nomadkaraoke 2>&1 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sleep 30
|
||||
done
|
||||
|
||||
- name: Trigger Cloud Build
|
||||
- name: Deploy to Cloud Run
|
||||
if: steps.version_check.outputs.needs_deploy == 'true'
|
||||
run: |
|
||||
echo "🚀 Triggering Cloud Build for deployment..."
|
||||
echo "Commit: ${{ github.sha }}"
|
||||
echo "Version: ${{ steps.version_check.outputs.version }}"
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
|
||||
|
||||
BUILD_ID=$(gcloud builds submit \
|
||||
--config=cloudbuild.yaml \
|
||||
--project=nomadkaraoke \
|
||||
--format='value(id)' \
|
||||
--async \
|
||||
.)
|
||||
echo "🚀 Deploying to Cloud Run..."
|
||||
echo "Image: $IMAGE"
|
||||
echo "Version: $VERSION"
|
||||
|
||||
echo "Build ID: $BUILD_ID"
|
||||
echo "Build URL: https://console.cloud.google.com/cloud-build/builds/$BUILD_ID?project=nomadkaraoke"
|
||||
|
||||
echo "Waiting for build to complete..."
|
||||
while true; do
|
||||
BUILD_STATUS=$(gcloud builds describe $BUILD_ID --project=nomadkaraoke --format='value(status)')
|
||||
echo "Build status: $BUILD_STATUS"
|
||||
|
||||
if [ "$BUILD_STATUS" = "SUCCESS" ]; then
|
||||
echo "✅ Build completed successfully"
|
||||
break
|
||||
elif [ "$BUILD_STATUS" = "FAILURE" ] || [ "$BUILD_STATUS" = "CANCELLED" ] || [ "$BUILD_STATUS" = "TIMEOUT" ]; then
|
||||
echo "❌ Build failed with status: $BUILD_STATUS"
|
||||
echo ""
|
||||
echo "==================== BUILD LOGS ===================="
|
||||
gcloud logging read "resource.type=build AND resource.labels.build_id=$BUILD_ID" \
|
||||
--project=nomadkaraoke \
|
||||
--format="value(textPayload)" \
|
||||
--limit=200 \
|
||||
--order=asc || echo "Failed to retrieve logs from Cloud Logging"
|
||||
echo "===================================================="
|
||||
echo ""
|
||||
gcloud builds log $BUILD_ID --project=nomadkaraoke 2>&1 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sleep 30
|
||||
done
|
||||
gcloud run deploy karaoke-backend \
|
||||
--image $IMAGE \
|
||||
--region us-central1 \
|
||||
--platform managed \
|
||||
--allow-unauthenticated \
|
||||
--memory 16Gi \
|
||||
--cpu 8 \
|
||||
--cpu-boost \
|
||||
--execution-environment gen2 \
|
||||
--timeout 1800 \
|
||||
--concurrency 1 \
|
||||
--max-instances 50 \
|
||||
--min-instances 0 \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest"
|
||||
|
||||
- name: Verify deployment and version
|
||||
if: steps.version_check.outputs.needs_deploy == 'true'
|
||||
@@ -564,22 +815,22 @@ jobs:
|
||||
|
||||
echo "Service URL: $SERVICE_URL"
|
||||
echo "Expected version: $EXPECTED_VERSION"
|
||||
|
||||
|
||||
# Wait for new revision to be ready
|
||||
echo "Waiting for new revision to be ready..."
|
||||
sleep 15
|
||||
|
||||
|
||||
# Basic health check
|
||||
curl -f "$SERVICE_URL/api/health" || exit 1
|
||||
echo "✅ Service is healthy"
|
||||
|
||||
|
||||
# Version verification with retries (Cloud Run may take time to route to new revision)
|
||||
MAX_RETRIES=6
|
||||
RETRY_DELAY=10
|
||||
for i in $(seq 1 $MAX_RETRIES); do
|
||||
echo "Checking deployed version (attempt $i/$MAX_RETRIES)..."
|
||||
DEPLOYED_VERSION=$(curl -sf "$SERVICE_URL/api/health/detailed" | jq -r '.version // empty')
|
||||
|
||||
|
||||
if [ "$DEPLOYED_VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo "✅ Version verified: $DEPLOYED_VERSION"
|
||||
break
|
||||
@@ -603,7 +854,10 @@ jobs:
|
||||
echo "Commit: ${{ github.sha }}"
|
||||
echo "Branch: ${{ github.ref_name }}"
|
||||
echo "Run: ${{ github.run_number }}"
|
||||
|
||||
echo ""
|
||||
echo "📊 Built on self-hosted GCP runner (200GB SSD, no disk space issues)"
|
||||
echo " Runner: gcp-runner with 4 vCPU, 16GB RAM"
|
||||
|
||||
- name: Skipped deployment summary
|
||||
if: steps.version_check.outputs.needs_deploy == 'false'
|
||||
run: |
|
||||
|
||||
+13
@@ -12,6 +12,9 @@ tests/outputs
|
||||
/input
|
||||
/output/
|
||||
|
||||
# Cloud Infra
|
||||
.emulator-logs
|
||||
|
||||
# Next.js / React Frontend (./frontend)
|
||||
node_modules/
|
||||
frontend/node_modules/
|
||||
@@ -41,6 +44,9 @@ frontend/.pnpm-debug.log*
|
||||
|
||||
# Testing
|
||||
frontend/coverage/
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
frontend/playwright/.cache/
|
||||
|
||||
# TypeScript
|
||||
frontend/*.tsbuildinfo
|
||||
@@ -73,8 +79,11 @@ dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
# Python lib directories (not frontend)
|
||||
lib/
|
||||
lib64/
|
||||
# But allow frontend lib
|
||||
!frontend/lib/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
@@ -217,3 +226,7 @@ cython_debug/
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
flacfetch
|
||||
|
||||
# Test output directories
|
||||
Rick Astley*/
|
||||
@@ -0,0 +1,97 @@
|
||||
# Karaoke-Gen AI Assistant Guidelines
|
||||
|
||||
## Project Overview
|
||||
|
||||
**Karaoke video generation platform** - CLI tool and web service that creates professional karaoke videos with synchronized lyrics.
|
||||
|
||||
- **Production**: <https://gen.nomadkaraoke.com> (frontend), <https://api.nomadkaraoke.com> (backend)
|
||||
- **CLI**: `karaoke-gen` (local), `karaoke-gen-remote` (cloud)
|
||||
- **Repo**: <https://github.com/nomadkaraoke/karaoke-gen>
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| What | Where |
|
||||
|------|-------|
|
||||
| Current status | `docs/README.md` |
|
||||
| Architecture | `docs/ARCHITECTURE.md` |
|
||||
| Dev setup & testing | `docs/DEVELOPMENT.md` |
|
||||
| API reference | `docs/API.md` |
|
||||
| Past learnings | `docs/LESSONS-LEARNED.md` |
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Backend**: FastAPI on Cloud Run, Firestore, GCS, Secret Manager
|
||||
- **Frontend**: Next.js on Cloudflare Pages
|
||||
- **Processing**: Modal (GPU audio separation), AudioShake/Whisper (transcription)
|
||||
- **Infra**: Pulumi IaC, GitHub Actions CI/CD
|
||||
|
||||
## Essential Rules
|
||||
|
||||
### Git Workflow
|
||||
- **Never commit directly to `main`** - always use feature branches
|
||||
- **Use git worktrees** for all changes:
|
||||
```bash
|
||||
git worktree add -b feature/xyz ../karaoke-gen-feat-xyz main
|
||||
```
|
||||
- Create PR with summary, changes, testing info
|
||||
- Merge only after CI passes
|
||||
|
||||
### Testing (Required Before Commit)
|
||||
```bash
|
||||
# Backend (10 min timeout, limit output)
|
||||
make test 2>&1 | tail -n 500
|
||||
|
||||
# Frontend
|
||||
cd frontend && npm run test:all 2>&1 | tail -n 200
|
||||
```
|
||||
|
||||
### Version Bumping
|
||||
- Bump `tool.poetry.version` in `pyproject.toml` for code changes
|
||||
- Skip for docs-only changes
|
||||
|
||||
### Infrastructure
|
||||
- All GCP changes via Pulumi in `infrastructure/`
|
||||
- `gcloud` CLI for reading/debugging only
|
||||
- Stop and notify user on auth issues
|
||||
|
||||
## Documentation Maintenance
|
||||
|
||||
### Structure
|
||||
```text
|
||||
docs/
|
||||
├── README.md # Current status + navigation (UPDATE THIS)
|
||||
├── ARCHITECTURE.md # System design
|
||||
├── DEVELOPMENT.md # Dev setup, testing, deployment
|
||||
├── API.md # Backend API reference
|
||||
├── LESSONS-LEARNED.md # Key insights for future agents
|
||||
└── archive/ # Historical docs (YYYY-MM-DD-topic.md)
|
||||
```
|
||||
|
||||
### Rules
|
||||
1. **Before merging PRs**: Run `/docs-review` to check if docs need updating
|
||||
2. **Periodically**: Run `/docs-maintain` to verify docs are organized
|
||||
3. **For significant work**: Create `docs/archive/YYYY-MM-DD-topic.md`
|
||||
4. **Add learnings**: Update `docs/LESSONS-LEARNED.md` with insights
|
||||
5. **Keep status current**: Update `docs/README.md` when project state changes
|
||||
|
||||
### What Goes Where
|
||||
- **README.md**: Current status, known issues, quick links
|
||||
- **ARCHITECTURE.md**: System design, data flow, tech decisions
|
||||
- **DEVELOPMENT.md**: Setup, testing, deployment, CI/CD
|
||||
- **API.md**: Endpoints, request/response formats
|
||||
- **LESSONS-LEARNED.md**: What worked, what didn't, gotchas
|
||||
- **archive/**: Completed work, session summaries, old plans
|
||||
|
||||
## Related Projects
|
||||
|
||||
### flacfetch
|
||||
Location: `/Users/andrew/Projects/flacfetch`
|
||||
|
||||
Workflow: Make changes on `main`, bump version, push, wait for CI, then `poetry update flacfetch` in karaoke-gen.
|
||||
|
||||
## Pre-Commit Checklist
|
||||
|
||||
- [ ] Tests pass (`make test` / `npm run test:all`)
|
||||
- [ ] Version bumped (if code changed)
|
||||
- [ ] `/docs-review` run (check for doc updates)
|
||||
- [ ] PR created with clear description
|
||||
@@ -0,0 +1,77 @@
|
||||
# Makefile for karaoke-gen project
|
||||
# Run `make help` to see available commands
|
||||
|
||||
.PHONY: help test test-unit test-backend test-integration test-e2e test-all lint clean emulators-start emulators-stop
|
||||
|
||||
# Default target
|
||||
help:
|
||||
@echo "Available commands:"
|
||||
@echo " make test - Run all tests (unit + backend + emulator-based)"
|
||||
@echo " make test-unit - Run unit tests only (karaoke_gen)"
|
||||
@echo " make test-backend - Run backend unit tests only"
|
||||
@echo " make test-e2e - Run E2E tests with emulators (starts/stops automatically)"
|
||||
@echo " make test-all - Alias for 'make test'"
|
||||
@echo " make lint - Run linter checks"
|
||||
@echo " make emulators-start - Start GCP emulators for local development"
|
||||
@echo " make emulators-stop - Stop GCP emulators"
|
||||
@echo ""
|
||||
@echo "Before committing, run: make test"
|
||||
|
||||
# Run unit tests for karaoke_gen package
|
||||
test-unit:
|
||||
@echo "=== Running karaoke_gen unit tests ==="
|
||||
poetry run pytest tests/unit/ -v --cov=karaoke_gen --cov-report=term-missing --cov-fail-under=69
|
||||
|
||||
# Run backend unit tests
|
||||
test-backend:
|
||||
@echo "=== Running backend unit tests ==="
|
||||
poetry run pytest backend/tests/ --ignore=backend/tests/emulator -v
|
||||
|
||||
# Run E2E integration tests with emulators
|
||||
test-e2e:
|
||||
@echo "=== Running E2E integration tests with emulators ==="
|
||||
@./scripts/start-emulators.sh || (echo "Failed to start emulators" && exit 1)
|
||||
@export FIRESTORE_EMULATOR_HOST=127.0.0.1:8080 && \
|
||||
export STORAGE_EMULATOR_HOST=http://127.0.0.1:4443 && \
|
||||
export GOOGLE_CLOUD_PROJECT=test-project && \
|
||||
export GCS_BUCKET_NAME=test-bucket && \
|
||||
export ADMIN_TOKENS=test-admin-token && \
|
||||
export ENVIRONMENT=test && \
|
||||
poetry run pytest backend/tests/emulator/ -v; \
|
||||
TEST_RESULT=$$?; \
|
||||
./scripts/stop-emulators.sh; \
|
||||
exit $$TEST_RESULT
|
||||
|
||||
# Run all tests (use this before committing!)
|
||||
test: test-unit test-backend test-e2e
|
||||
@echo ""
|
||||
@echo "✅ All tests passed! Ready to commit."
|
||||
|
||||
# Alias for test
|
||||
test-all: test
|
||||
|
||||
# Lint checks
|
||||
lint:
|
||||
@echo "=== Running lint checks ==="
|
||||
poetry run ruff check karaoke_gen/ backend/
|
||||
poetry run ruff format --check karaoke_gen/ backend/
|
||||
|
||||
# Start emulators for local development
|
||||
emulators-start:
|
||||
@echo "=== Starting GCP emulators ==="
|
||||
./scripts/start-emulators.sh
|
||||
|
||||
# Stop emulators
|
||||
emulators-stop:
|
||||
@echo "=== Stopping GCP emulators ==="
|
||||
./scripts/stop-emulators.sh
|
||||
|
||||
# Clean up temporary files
|
||||
clean:
|
||||
find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
|
||||
find . -type d -name ".pytest_cache" -exec rm -rf {} + 2>/dev/null || true
|
||||
find . -type d -name ".coverage" -exec rm -rf {} + 2>/dev/null || true
|
||||
find . -type f -name "*.pyc" -delete 2>/dev/null || true
|
||||
rm -rf htmlcov/ .coverage coverage.xml 2>/dev/null || true
|
||||
@echo "Cleaned up temporary files"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Karaoke Generator 🎶 🎥 🚀
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
@@ -54,10 +54,76 @@ pip install karaoke-gen
|
||||
This installs both `karaoke-gen` (local) and `karaoke-gen-remote` (cloud) CLIs.
|
||||
|
||||
### Requirements
|
||||
- Python 3.10+
|
||||
- Python 3.10-3.13
|
||||
- FFmpeg
|
||||
- For local processing: CUDA-capable GPU or Apple Silicon CPU recommended
|
||||
|
||||
### Transcription Provider Setup
|
||||
|
||||
**Transcription is required** for creating karaoke videos with synchronized lyrics. The system needs word-level timing data to display lyrics in sync with the music.
|
||||
|
||||
#### Option 1: AudioShake (Recommended)
|
||||
Commercial service with high-quality transcription. Best for production use.
|
||||
|
||||
```bash
|
||||
export AUDIOSHAKE_API_TOKEN="your_audioshake_token"
|
||||
```
|
||||
|
||||
Get an API key at [https://www.audioshake.ai/](https://www.audioshake.ai/) - business only, at time of writing this.
|
||||
|
||||
#### Option 2: Local Whisper (No Cloud Required)
|
||||
Run Whisper directly on your local machine using whisper-timestamped. Works on CPU, NVIDIA GPU (CUDA), or Apple Silicon.
|
||||
|
||||
```bash
|
||||
# Install with local Whisper support
|
||||
pip install "karaoke-gen[local-whisper]"
|
||||
|
||||
# Optional: Configure model size (tiny, base, small, medium, large)
|
||||
export WHISPER_MODEL_SIZE="medium"
|
||||
|
||||
# Optional: Force specific device (cpu, cuda, mps)
|
||||
export WHISPER_DEVICE="cpu"
|
||||
```
|
||||
|
||||
**Model Size Guide:**
|
||||
| Model | VRAM | Speed | Quality |
|
||||
|-------|------|-------|---------|
|
||||
| tiny | ~1GB | Fast | Lower |
|
||||
| base | ~1GB | Fast | Basic |
|
||||
| small | ~2GB | Medium | Good |
|
||||
| medium | ~5GB | Slower | Better |
|
||||
| large | ~10GB | Slowest | Best |
|
||||
|
||||
**CPU-Only Installation** (no GPU required):
|
||||
```bash
|
||||
# Pre-install CPU-only PyTorch first
|
||||
pip install torch torchaudio --index-url https://download.pytorch.org/whl/cpu
|
||||
pip install "karaoke-gen[local-whisper]"
|
||||
```
|
||||
|
||||
Local Whisper runs automatically as a fallback when no cloud transcription services are configured.
|
||||
|
||||
#### Option 3: Whisper via RunPod
|
||||
Cloud-based alternative using OpenAI's Whisper model on RunPod infrastructure.
|
||||
|
||||
```bash
|
||||
export RUNPOD_API_KEY="your_runpod_key"
|
||||
export WHISPER_RUNPOD_ID="your_whisper_endpoint_id"
|
||||
```
|
||||
|
||||
Set up a Whisper endpoint at [https://www.runpod.io/](https://www.runpod.io/)
|
||||
|
||||
#### Without Transcription (Instrumental Only)
|
||||
If you don't need synchronized lyrics, use the `--skip-lyrics` flag:
|
||||
|
||||
```bash
|
||||
karaoke-gen --skip-lyrics "Artist" "Title"
|
||||
```
|
||||
|
||||
This creates an instrumental-only karaoke video without lyrics overlay.
|
||||
|
||||
> **Note:** See `lyrics_transcriber_temp/README.md` for detailed transcription provider configuration options.
|
||||
|
||||
---
|
||||
|
||||
## 🖥️ Local CLI (`karaoke-gen`)
|
||||
@@ -180,9 +246,11 @@ karaoke-gen-remote \
|
||||
|----------|-------------|---------|
|
||||
| `KARAOKE_GEN_URL` | Backend service URL | Required |
|
||||
| `KARAOKE_GEN_AUTH_TOKEN` | Admin auth token (for protected endpoints) | Optional |
|
||||
| `REVIEW_UI_URL` | Lyrics review UI URL | `https://lyrics.nomadkaraoke.com` |
|
||||
| `REVIEW_UI_URL` | Lyrics review UI URL | `https://gen.nomadkaraoke.com/lyrics/` |
|
||||
| `POLL_INTERVAL` | Seconds between status polls | `5` |
|
||||
|
||||
**Note:** The `REVIEW_UI_URL` defaults to the hosted lyrics review UI. For local development, set it to `http://localhost:5173` if you're running the frontend dev server.
|
||||
|
||||
### Authentication
|
||||
|
||||
The backend uses token-based authentication for admin operations (bulk delete, internal worker triggers). For basic job submission and monitoring, authentication is optional.
|
||||
@@ -473,6 +541,111 @@ Check backend health status.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Troubleshooting
|
||||
|
||||
### "No suitable files found for processing"
|
||||
|
||||
This error occurs during the finalisation step when the `(With Vocals).mkv` file is missing. This file is created during lyrics transcription.
|
||||
|
||||
**Most common cause:** No transcription provider configured.
|
||||
|
||||
**Quick fix:**
|
||||
1. Check if transcription providers are configured:
|
||||
```bash
|
||||
echo $AUDIOSHAKE_API_TOKEN
|
||||
echo $RUNPOD_API_KEY
|
||||
```
|
||||
|
||||
2. If both are empty, set up a provider (see [Transcription Provider Setup](#transcription-provider-setup))
|
||||
|
||||
3. Or use `--skip-lyrics` for instrumental-only karaoke:
|
||||
```bash
|
||||
karaoke-gen --skip-lyrics "Artist" "Title"
|
||||
```
|
||||
|
||||
**Other causes:**
|
||||
- Invalid API credentials - verify your tokens are correct and active
|
||||
- API service unavailable - check service status pages
|
||||
- Network connectivity issues - ensure you can reach the API endpoints
|
||||
- Transcription timeout - try again or use a different provider
|
||||
|
||||
### Transcription Fails Silently
|
||||
|
||||
If karaoke-gen runs without errors but produces no synchronized lyrics:
|
||||
|
||||
1. **Check logs** - Run with `--log_level debug` for detailed output:
|
||||
```bash
|
||||
karaoke-gen --log_level debug "Artist" "Title"
|
||||
```
|
||||
|
||||
2. **Verify environment variables** - Ensure API tokens are exported in your shell:
|
||||
```bash
|
||||
# Check if set
|
||||
printenv | grep -E "(AUDIOSHAKE|RUNPOD|WHISPER)"
|
||||
|
||||
# Set in current session
|
||||
export AUDIOSHAKE_API_TOKEN="your_token"
|
||||
```
|
||||
|
||||
3. **Test API connectivity** - Verify you can reach the transcription service
|
||||
|
||||
### "No lyrics found from any source"
|
||||
|
||||
This warning means no reference lyrics were fetched from online sources (Genius, Spotify, Musixmatch). The transcription will still work, but auto-correction may be less accurate.
|
||||
|
||||
**To fix:**
|
||||
- Set `GENIUS_API_TOKEN` for Genius lyrics
|
||||
- Set `SPOTIFY_COOKIE_SP_DC` for Spotify lyrics
|
||||
- Set `RAPIDAPI_KEY` for Musixmatch lyrics
|
||||
- Or provide lyrics manually with `--lyrics_file /path/to/lyrics.txt`
|
||||
|
||||
### Video Quality Issues
|
||||
|
||||
If the output video has quality problems:
|
||||
- Ensure FFmpeg is properly installed: `ffmpeg -version`
|
||||
- Check available codecs: `ffmpeg -codecs`
|
||||
- For 4K output, ensure sufficient disk space (10GB+ per track)
|
||||
|
||||
### Local Whisper Issues
|
||||
|
||||
#### GPU Out of Memory
|
||||
If you get CUDA out of memory errors:
|
||||
```bash
|
||||
# Use a smaller model
|
||||
export WHISPER_MODEL_SIZE="small" # or "tiny"
|
||||
|
||||
# Or force CPU mode
|
||||
export WHISPER_DEVICE="cpu"
|
||||
```
|
||||
|
||||
#### Slow Transcription on CPU
|
||||
CPU transcription is significantly slower than GPU. For faster processing:
|
||||
- Use a smaller model (`tiny` or `base`)
|
||||
- Consider using cloud transcription (AudioShake or RunPod)
|
||||
- On Apple Silicon, the `small` model offers good speed/quality balance
|
||||
|
||||
#### Model Download Issues
|
||||
Whisper models are downloaded on first use (~1-3GB depending on size). If downloads fail:
|
||||
- Check your internet connection
|
||||
- Set a custom cache directory: `export WHISPER_CACHE_DIR="/path/with/space"`
|
||||
- Models are cached in `~/.cache/whisper/` by default
|
||||
|
||||
#### whisper-timestamped Not Found
|
||||
If you get "whisper-timestamped is not installed":
|
||||
```bash
|
||||
pip install "karaoke-gen[local-whisper]"
|
||||
# Or install directly:
|
||||
pip install whisper-timestamped
|
||||
```
|
||||
|
||||
#### Disabling Local Whisper
|
||||
If you want to disable local Whisper (e.g., to force cloud transcription):
|
||||
```bash
|
||||
export ENABLE_LOCAL_WHISPER="false"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Development
|
||||
|
||||
### Running Tests
|
||||
|
||||
+205
-6
@@ -2,8 +2,10 @@
|
||||
FastAPI dependencies for authentication and authorization.
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional, Tuple
|
||||
from fastapi import Depends, HTTPException, Header, Query, Request
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, UTC
|
||||
from typing import Optional, Tuple, Callable
|
||||
from fastapi import Depends, HTTPException, Header, Query, Request, Path
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
|
||||
from backend.services.auth_service import get_auth_service, UserType, AuthService
|
||||
@@ -12,6 +14,16 @@ from backend.services.auth_service import get_auth_service, UserType, AuthServic
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def generate_review_token() -> str:
|
||||
"""Generate a cryptographically secure review token."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def get_review_token_expiry(hours: int = 24) -> datetime:
|
||||
"""Get expiry time for a review token."""
|
||||
return datetime.now(UTC) + timedelta(hours=hours)
|
||||
|
||||
|
||||
# HTTP Bearer security scheme (Authorization: Bearer <token>)
|
||||
security = HTTPBearer(auto_error=False)
|
||||
|
||||
@@ -24,14 +36,21 @@ async def get_token_from_request(
|
||||
"""
|
||||
Extract access token from request.
|
||||
|
||||
Supports two methods:
|
||||
1. Authorization header: Authorization: Bearer <token>
|
||||
2. Query parameter: ?token=<token> (for download links)
|
||||
Supports three methods (in priority order):
|
||||
1. X-Admin-Token header: Used by Cloud Tasks (since OIDC overwrites Authorization)
|
||||
2. Authorization header: Authorization: Bearer <token>
|
||||
3. Query parameter: ?token=<token> (for download links)
|
||||
|
||||
Returns:
|
||||
Token string or None
|
||||
"""
|
||||
# Try Authorization header first
|
||||
# Check X-Admin-Token header first (used by Cloud Tasks)
|
||||
# Cloud Tasks OIDC token overwrites Authorization header, so we use a custom header
|
||||
admin_token = request.headers.get("X-Admin-Token")
|
||||
if admin_token:
|
||||
return admin_token
|
||||
|
||||
# Try Authorization header
|
||||
if credentials:
|
||||
return credentials.credentials
|
||||
|
||||
@@ -144,3 +163,183 @@ def optional_auth(
|
||||
return None
|
||||
|
||||
return token_str, user_type, remaining_uses
|
||||
|
||||
|
||||
def require_review_auth_factory(job_id_param: str = "job_id"):
|
||||
"""
|
||||
Factory to create a review authentication dependency.
|
||||
|
||||
Accepts either:
|
||||
1. Full user authentication (admin/user token)
|
||||
2. Job-specific review token (only valid for the specific job)
|
||||
|
||||
Args:
|
||||
job_id_param: Name of the path parameter containing the job ID
|
||||
|
||||
Returns:
|
||||
Dependency function that validates review access
|
||||
"""
|
||||
async def require_review_auth(
|
||||
request: Request,
|
||||
job_id: str = Path(...),
|
||||
review_token: Optional[str] = Query(None, description="Job-specific review token"),
|
||||
auth_service: AuthService = Depends(get_auth_service),
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
|
||||
token: Optional[str] = Query(None, alias="token", description="Full access token")
|
||||
) -> Tuple[str, str]:
|
||||
"""
|
||||
Validate review access for a job.
|
||||
|
||||
Returns:
|
||||
(job_id, auth_type) where auth_type is "full" or "review_token"
|
||||
|
||||
Raises:
|
||||
HTTPException: 401 if authentication fails
|
||||
"""
|
||||
# Import here to avoid circular dependency
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
# Try full authentication first
|
||||
full_token = None
|
||||
if credentials:
|
||||
full_token = credentials.credentials
|
||||
elif token:
|
||||
full_token = token
|
||||
|
||||
if full_token:
|
||||
is_valid, user_type, remaining_uses, message = auth_service.validate_token(full_token)
|
||||
if is_valid:
|
||||
logger.info(f"Review access granted via full auth ({user_type}) for job {job_id}")
|
||||
return job_id, "full"
|
||||
|
||||
# Try review token
|
||||
if review_token:
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Validate review token matches
|
||||
if job.review_token and secrets.compare_digest(job.review_token, review_token):
|
||||
# Check expiry if set
|
||||
if job.review_token_expires_at:
|
||||
now = datetime.now(UTC)
|
||||
# Handle timezone-naive datetimes from Firestore
|
||||
expiry = job.review_token_expires_at
|
||||
if expiry.tzinfo is None:
|
||||
expiry = expiry.replace(tzinfo=UTC)
|
||||
|
||||
if now > expiry:
|
||||
logger.warning(f"Review token expired for job {job_id}")
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Review token has expired. Please request a new review link."
|
||||
)
|
||||
|
||||
logger.info(f"Review access granted via review_token for job {job_id}")
|
||||
return job_id, "review_token"
|
||||
else:
|
||||
logger.warning(f"Invalid review token for job {job_id}")
|
||||
|
||||
# No valid authentication
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Authentication required. Provide either a full access token or a valid review_token for this job."
|
||||
)
|
||||
|
||||
return require_review_auth
|
||||
|
||||
|
||||
# Default instance for most review endpoints
|
||||
require_review_auth = require_review_auth_factory()
|
||||
|
||||
|
||||
def require_instrumental_auth_factory(job_id_param: str = "job_id"):
|
||||
"""
|
||||
Factory to create an instrumental review authentication dependency.
|
||||
|
||||
Accepts either:
|
||||
1. Full user authentication (admin/user token)
|
||||
2. Job-specific instrumental token (only valid for the specific job)
|
||||
|
||||
Args:
|
||||
job_id_param: Name of the path parameter containing the job ID
|
||||
|
||||
Returns:
|
||||
Dependency function that validates instrumental review access
|
||||
"""
|
||||
async def require_instrumental_auth(
|
||||
request: Request,
|
||||
job_id: str = Path(...),
|
||||
instrumental_token: Optional[str] = Query(None, description="Job-specific instrumental review token"),
|
||||
auth_service: AuthService = Depends(get_auth_service),
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
|
||||
token: Optional[str] = Query(None, alias="token", description="Full access token")
|
||||
) -> Tuple[str, str]:
|
||||
"""
|
||||
Validate instrumental review access for a job.
|
||||
|
||||
Returns:
|
||||
(job_id, auth_type) where auth_type is "full" or "instrumental_token"
|
||||
|
||||
Raises:
|
||||
HTTPException: 401 if authentication fails
|
||||
"""
|
||||
# Import here to avoid circular dependency
|
||||
from backend.services.job_manager import JobManager
|
||||
|
||||
# Try full authentication first
|
||||
full_token = None
|
||||
if credentials:
|
||||
full_token = credentials.credentials
|
||||
elif token:
|
||||
full_token = token
|
||||
|
||||
if full_token:
|
||||
is_valid, user_type, remaining_uses, message = auth_service.validate_token(full_token)
|
||||
if is_valid:
|
||||
logger.info(f"Instrumental access granted via full auth ({user_type}) for job {job_id}")
|
||||
return job_id, "full"
|
||||
|
||||
# Try instrumental token
|
||||
if instrumental_token:
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Validate instrumental token matches
|
||||
if job.instrumental_token and secrets.compare_digest(job.instrumental_token, instrumental_token):
|
||||
# Check expiry if set
|
||||
if job.instrumental_token_expires_at:
|
||||
now = datetime.now(UTC)
|
||||
# Handle timezone-naive datetimes from Firestore
|
||||
expiry = job.instrumental_token_expires_at
|
||||
if expiry.tzinfo is None:
|
||||
expiry = expiry.replace(tzinfo=UTC)
|
||||
|
||||
if now > expiry:
|
||||
logger.warning(f"Instrumental token expired for job {job_id}")
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Instrumental review token has expired. Please request a new review link."
|
||||
)
|
||||
|
||||
logger.info(f"Instrumental access granted via instrumental_token for job {job_id}")
|
||||
return job_id, "instrumental_token"
|
||||
else:
|
||||
logger.warning(f"Invalid instrumental token for job {job_id}")
|
||||
|
||||
# No valid authentication
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Authentication required. Provide either a full access token or a valid instrumental_token for this job."
|
||||
)
|
||||
|
||||
return require_instrumental_auth
|
||||
|
||||
|
||||
# Default instance for most instrumental review endpoints
|
||||
require_instrumental_auth = require_instrumental_auth_factory()
|
||||
@@ -15,9 +15,9 @@ import asyncio
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
from typing import Optional, List, Dict, Any
|
||||
from typing import Optional, List, Dict, Any, Tuple
|
||||
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Request, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.models.job import JobCreate, JobStatus
|
||||
@@ -34,8 +34,23 @@ from backend.services.audio_search_service import (
|
||||
)
|
||||
from backend.config import get_settings
|
||||
from backend.version import VERSION
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import UserType
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Valid style file types (from file_upload.py)
|
||||
STYLE_FILE_TYPES = {
|
||||
'style_params': {'.json'},
|
||||
'style_intro_background': {'.jpg', '.jpeg', '.png'},
|
||||
'style_karaoke_background': {'.jpg', '.jpeg', '.png'},
|
||||
'style_end_background': {'.jpg', '.jpeg', '.png'},
|
||||
'style_font': {'.ttf', '.otf'},
|
||||
'style_cdg_instrumental_background': {'.jpg', '.jpeg', '.png'},
|
||||
'style_cdg_title_background': {'.jpg', '.jpeg', '.png'},
|
||||
'style_cdg_outro_background': {'.jpg', '.jpeg', '.png'},
|
||||
}
|
||||
router = APIRouter(tags=["audio-search"])
|
||||
|
||||
# Initialize services
|
||||
@@ -48,17 +63,35 @@ worker_service = get_worker_service()
|
||||
# Pydantic models
|
||||
# ============================================================================
|
||||
|
||||
class StyleFileRequest(BaseModel):
|
||||
"""Information about a style file to be uploaded."""
|
||||
filename: str = Field(..., description="Original filename with extension")
|
||||
content_type: str = Field(..., description="MIME type of the file")
|
||||
file_type: str = Field(..., description="Type of file: 'style_params', 'style_intro_background', 'style_karaoke_background', 'style_end_background', 'style_font', 'style_cdg_instrumental_background', 'style_cdg_title_background', 'style_cdg_outro_background'")
|
||||
|
||||
|
||||
class StyleUploadUrl(BaseModel):
|
||||
"""Signed URL for uploading a style file."""
|
||||
file_type: str = Field(..., description="Type of file being uploaded")
|
||||
gcs_path: str = Field(..., description="Destination path in GCS")
|
||||
upload_url: str = Field(..., description="Signed URL to PUT the file to")
|
||||
|
||||
|
||||
class AudioSearchRequest(BaseModel):
|
||||
"""Request to search for audio by artist and title."""
|
||||
artist: str = Field(..., description="Artist name to search for")
|
||||
title: str = Field(..., description="Song title to search for")
|
||||
|
||||
|
||||
# Auto-download mode
|
||||
auto_download: bool = Field(False, description="Automatically select best result and download")
|
||||
|
||||
# Processing options
|
||||
enable_cdg: bool = Field(True, description="Generate CDG+MP3 package")
|
||||
enable_txt: bool = Field(True, description="Generate TXT+MP3 package")
|
||||
|
||||
# Theme configuration
|
||||
theme_id: Optional[str] = Field(None, description="Theme ID to use (e.g., 'nomad', 'default'). If set, CDG/TXT are enabled by default.")
|
||||
color_overrides: Optional[Dict[str, str]] = Field(None, description="Color overrides: artist_color, title_color, sung_lyrics_color, unsung_lyrics_color (hex #RRGGBB)")
|
||||
|
||||
# Processing options (CDG/TXT require style config or theme, disabled by default unless theme is set)
|
||||
enable_cdg: Optional[bool] = Field(None, description="Generate CDG+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
enable_txt: Optional[bool] = Field(None, description="Generate TXT+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Field(None, description="Brand code prefix (e.g., NOMAD)")
|
||||
@@ -79,6 +112,10 @@ class AudioSearchRequest(BaseModel):
|
||||
clean_instrumental_model: Optional[str] = Field(None, description="Model for clean instrumental separation")
|
||||
backing_vocals_models: Optional[List[str]] = Field(None, description="Models for backing vocals separation")
|
||||
other_stems_models: Optional[List[str]] = Field(None, description="Models for other stems")
|
||||
|
||||
# Style file uploads (optional)
|
||||
# Style params JSON and related assets (background images, fonts)
|
||||
style_files: Optional[List[StyleFileRequest]] = Field(None, description="Style files to upload (style_params JSON, backgrounds, fonts)")
|
||||
|
||||
|
||||
class AudioSearchResultResponse(BaseModel):
|
||||
@@ -127,6 +164,8 @@ class AudioSearchResponse(BaseModel):
|
||||
results_count: int = 0
|
||||
auto_download: bool = False
|
||||
server_version: str
|
||||
# Style file upload URLs (when style_files are specified in request)
|
||||
style_upload_urls: Optional[List[StyleUploadUrl]] = None
|
||||
|
||||
|
||||
class AudioSelectRequest(BaseModel):
|
||||
@@ -145,6 +184,35 @@ class AudioSelectResponse(BaseModel):
|
||||
selected_provider: str
|
||||
|
||||
|
||||
def _resolve_cdg_txt_defaults(
|
||||
theme_id: Optional[str],
|
||||
enable_cdg: Optional[bool],
|
||||
enable_txt: Optional[bool]
|
||||
) -> Tuple[bool, bool]:
|
||||
"""
|
||||
Resolve CDG/TXT settings based on theme and explicit settings.
|
||||
|
||||
When a theme is selected, CDG and TXT are enabled by default.
|
||||
Explicit True/False values always override the default.
|
||||
|
||||
Args:
|
||||
theme_id: Theme identifier (if any)
|
||||
enable_cdg: Explicit CDG setting (None means use default)
|
||||
enable_txt: Explicit TXT setting (None means use default)
|
||||
|
||||
Returns:
|
||||
Tuple of (resolved_enable_cdg, resolved_enable_txt)
|
||||
"""
|
||||
# Default based on whether theme is set
|
||||
default_enabled = theme_id is not None
|
||||
|
||||
# Explicit values override defaults, None uses default
|
||||
resolved_cdg = enable_cdg if enable_cdg is not None else default_enabled
|
||||
resolved_txt = enable_txt if enable_txt is not None else default_enabled
|
||||
|
||||
return resolved_cdg, resolved_txt
|
||||
|
||||
|
||||
def extract_request_metadata(request: Request, created_from: str = "audio_search") -> Dict[str, Any]:
|
||||
"""Extract metadata from request for job tracking."""
|
||||
headers = dict(request.headers)
|
||||
@@ -206,14 +274,17 @@ async def _download_and_start_processing(
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
if not search_results:
|
||||
raise HTTPException(status_code=400, detail="No search results available")
|
||||
|
||||
|
||||
if selection_index < 0 or selection_index >= len(search_results):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid selection index {selection_index}. Valid range: 0-{len(search_results)-1}"
|
||||
)
|
||||
|
||||
|
||||
selected = search_results[selection_index]
|
||||
|
||||
# Get remote_search_id from state_data (stored during initial search)
|
||||
remote_search_id = job.state_data.get('remote_search_id')
|
||||
|
||||
# Transition to downloading state
|
||||
job_manager.transition_to_state(
|
||||
@@ -229,22 +300,43 @@ async def _download_and_start_processing(
|
||||
|
||||
try:
|
||||
# Determine if this is a remote torrent download
|
||||
is_torrent_source = selected.get('provider') in ['Redacted', 'OPS']
|
||||
is_torrent_source = selected.get('provider') in ['RED', 'OPS']
|
||||
is_remote_enabled = audio_search_service.is_remote_enabled()
|
||||
|
||||
|
||||
# Check if we can use download_by_id (preferred - avoids re-searching)
|
||||
source_id = selected.get('source_id')
|
||||
source_name = selected.get('provider')
|
||||
target_file = selected.get('target_file')
|
||||
download_url = selected.get('url')
|
||||
|
||||
# For remote torrent downloads, have flacfetch VM upload directly to GCS
|
||||
if is_torrent_source and is_remote_enabled:
|
||||
# Generate GCS path for remote upload
|
||||
gcs_destination = f"uploads/{job_id}/audio/"
|
||||
|
||||
logger.info(f"Using remote download with GCS upload to: {gcs_destination}")
|
||||
|
||||
result = audio_search_service.download(
|
||||
result_index=selection_index,
|
||||
output_dir="", # Not used for remote
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
|
||||
|
||||
# Use download_by_id if we have source_id (preferred - no re-search needed)
|
||||
if source_id and source_name:
|
||||
logger.info(f"Using download_by_id for {source_name} ID={source_id} with GCS upload to: {gcs_destination}")
|
||||
|
||||
result = audio_search_service.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir="", # Not used for remote
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_destination,
|
||||
)
|
||||
else:
|
||||
# Fallback to search-based download (requires re-search)
|
||||
logger.info(f"No source_id available, falling back to search-based download to: {gcs_destination}")
|
||||
|
||||
result = audio_search_service.download(
|
||||
result_index=selection_index,
|
||||
output_dir="", # Not used for remote
|
||||
gcs_path=gcs_destination,
|
||||
remote_search_id=remote_search_id,
|
||||
)
|
||||
|
||||
# For remote downloads, filepath is already the GCS path
|
||||
if result.filepath.startswith("gs://"):
|
||||
# Extract the path portion after the bucket name
|
||||
@@ -259,34 +351,48 @@ async def _download_and_start_processing(
|
||||
# Fallback: treat as local path (shouldn't happen for remote)
|
||||
filename = os.path.basename(result.filepath)
|
||||
audio_gcs_path = f"uploads/{job_id}/audio/{filename}"
|
||||
|
||||
|
||||
logger.warning(f"Remote download returned local path: {result.filepath}, uploading manually")
|
||||
with open(result.filepath, 'rb') as f:
|
||||
storage_service.upload_fileobj(f, audio_gcs_path, content_type='audio/flac')
|
||||
|
||||
|
||||
logger.info(f"Remote download complete, GCS path: {audio_gcs_path}")
|
||||
else:
|
||||
# Local download (YouTube or fallback)
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"audio_download_{job_id}_")
|
||||
|
||||
result = audio_search_service.download(
|
||||
result_index=selection_index,
|
||||
output_dir=temp_dir,
|
||||
)
|
||||
|
||||
|
||||
# Use download_by_id if we have source_id and remote is enabled
|
||||
if source_id and source_name and is_remote_enabled:
|
||||
logger.info(f"Using download_by_id for local download: {source_name} ID={source_id}")
|
||||
|
||||
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,
|
||||
)
|
||||
else:
|
||||
# Fallback to search-based download
|
||||
result = audio_search_service.download(
|
||||
result_index=selection_index,
|
||||
output_dir=temp_dir,
|
||||
remote_search_id=remote_search_id, # Pass for potential fallback scenarios
|
||||
)
|
||||
|
||||
# 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' # flacfetch typically returns FLAC
|
||||
)
|
||||
|
||||
|
||||
logger.info(f"Uploaded audio to GCS: {audio_gcs_path}")
|
||||
|
||||
|
||||
# Clean up temp file
|
||||
try:
|
||||
os.remove(result.filepath)
|
||||
@@ -330,6 +436,7 @@ async def search_audio(
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: AudioSearchRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Search for audio by artist and title, creating a new job.
|
||||
@@ -350,12 +457,17 @@ async def search_audio(
|
||||
effective_dropbox_path = body.dropbox_path or settings.default_dropbox_path
|
||||
effective_gdrive_folder_id = body.gdrive_folder_id or settings.default_gdrive_folder_id
|
||||
effective_discord_webhook_url = body.discord_webhook_url or settings.default_discord_webhook_url
|
||||
|
||||
|
||||
# Apply defaults for YouTube/Dropbox distribution (for web service)
|
||||
effective_enable_youtube_upload = body.enable_youtube_upload or settings.default_enable_youtube_upload
|
||||
effective_brand_prefix = body.brand_prefix or settings.default_brand_prefix
|
||||
effective_youtube_description = body.youtube_description or settings.default_youtube_description
|
||||
|
||||
# Validate credentials if distribution services are requested
|
||||
invalid_services = []
|
||||
credential_manager = get_credential_manager()
|
||||
|
||||
if body.enable_youtube_upload:
|
||||
|
||||
if effective_enable_youtube_upload:
|
||||
result = credential_manager.check_youtube_credentials()
|
||||
if result.status != CredentialStatus.VALID:
|
||||
invalid_services.append(f"youtube ({result.message})")
|
||||
@@ -382,16 +494,24 @@ async def search_audio(
|
||||
|
||||
# Extract request metadata
|
||||
request_metadata = extract_request_metadata(request, created_from="audio_search")
|
||||
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
body.theme_id, body.enable_cdg, body.enable_txt
|
||||
)
|
||||
|
||||
# Create job
|
||||
job_create = JobCreate(
|
||||
artist=body.artist,
|
||||
title=body.title,
|
||||
enable_cdg=body.enable_cdg,
|
||||
enable_txt=body.enable_txt,
|
||||
brand_prefix=body.brand_prefix,
|
||||
enable_youtube_upload=body.enable_youtube_upload,
|
||||
youtube_description=body.youtube_description,
|
||||
theme_id=body.theme_id,
|
||||
color_overrides=body.color_overrides or {},
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
brand_prefix=effective_brand_prefix,
|
||||
enable_youtube_upload=effective_enable_youtube_upload,
|
||||
youtube_description=effective_youtube_description,
|
||||
youtube_description_template=effective_youtube_description, # video_worker reads this field
|
||||
discord_webhook_url=effective_discord_webhook_url,
|
||||
dropbox_path=effective_dropbox_path,
|
||||
gdrive_folder_id=effective_gdrive_folder_id,
|
||||
@@ -417,6 +537,87 @@ async def search_audio(
|
||||
'audio_search_title': body.title,
|
||||
'auto_download': body.auto_download,
|
||||
})
|
||||
|
||||
# If theme is set and no custom style files are being uploaded, prepare theme style now
|
||||
# This copies the theme's style_params.json to the job folder so LyricsTranscriber
|
||||
# can access the style configuration for preview videos
|
||||
if body.theme_id and not body.style_files:
|
||||
from backend.api.routes.file_upload import _prepare_theme_for_job
|
||||
try:
|
||||
style_params_path, theme_style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, body.theme_id, body.color_overrides
|
||||
)
|
||||
theme_update = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
'style_assets': theme_style_assets,
|
||||
}
|
||||
if youtube_desc and not effective_youtube_description:
|
||||
theme_update['youtube_description_template'] = youtube_desc
|
||||
job_manager.update_job(job_id, theme_update)
|
||||
logger.info(f"Applied theme '{body.theme_id}' to job {job_id}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to prepare theme '{body.theme_id}' for job {job_id}: {e}")
|
||||
# Continue without theme - job can still be processed with defaults
|
||||
|
||||
# Handle style file uploads if provided
|
||||
style_upload_urls: List[StyleUploadUrl] = []
|
||||
style_assets = {}
|
||||
|
||||
if body.style_files:
|
||||
logger.info(f"Processing {len(body.style_files)} style file uploads for job {job_id}")
|
||||
|
||||
for file_info in body.style_files:
|
||||
# Validate file type
|
||||
if file_info.file_type not in STYLE_FILE_TYPES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid file type '{file_info.file_type}'. Must be one of: {', '.join(STYLE_FILE_TYPES.keys())}"
|
||||
)
|
||||
|
||||
# Validate extension
|
||||
ext = Path(file_info.filename).suffix.lower()
|
||||
allowed_exts = STYLE_FILE_TYPES[file_info.file_type]
|
||||
if ext not in allowed_exts:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid extension '{ext}' for {file_info.file_type}. Allowed: {', '.join(allowed_exts)}"
|
||||
)
|
||||
|
||||
# Generate GCS path
|
||||
if file_info.file_type == 'style_params':
|
||||
gcs_path = f"uploads/{job_id}/style/style_params.json"
|
||||
else:
|
||||
# style_intro_background -> intro_background, etc.
|
||||
asset_key = file_info.file_type.replace('style_', '')
|
||||
gcs_path = f"uploads/{job_id}/style/{asset_key}{ext}"
|
||||
|
||||
# Generate signed upload URL
|
||||
signed_url = storage_service.generate_signed_upload_url(
|
||||
gcs_path,
|
||||
content_type=file_info.content_type,
|
||||
expiration_minutes=60
|
||||
)
|
||||
|
||||
style_upload_urls.append(StyleUploadUrl(
|
||||
file_type=file_info.file_type,
|
||||
gcs_path=gcs_path,
|
||||
upload_url=signed_url
|
||||
))
|
||||
|
||||
# Track the expected asset paths
|
||||
if file_info.file_type == 'style_params':
|
||||
style_assets['style_params'] = gcs_path
|
||||
else:
|
||||
asset_key = file_info.file_type.replace('style_', '')
|
||||
style_assets[asset_key] = gcs_path
|
||||
|
||||
# Update job with style asset expectations
|
||||
style_update = {'style_assets': style_assets}
|
||||
if 'style_params' in style_assets:
|
||||
style_update['style_params_gcs_path'] = style_assets['style_params']
|
||||
job_manager.update_job(job_id, style_update)
|
||||
|
||||
logger.info(f"Generated {len(style_upload_urls)} style upload URLs for job {job_id}")
|
||||
|
||||
# Transition to searching state
|
||||
job_manager.transition_to_state(
|
||||
@@ -445,13 +646,17 @@ async def search_audio(
|
||||
job_manager.fail_job(job_id, f"Audio search failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Search failed: {e}")
|
||||
|
||||
# Store results in job state_data
|
||||
# Store results in job state_data, including remote_search_id if available
|
||||
results_dicts = [r.to_dict() for r in search_results]
|
||||
state_data_update = {
|
||||
'audio_search_results': results_dicts,
|
||||
'audio_search_count': len(results_dicts),
|
||||
}
|
||||
# Store remote_search_id for use during download (important for concurrent requests)
|
||||
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': {
|
||||
'audio_search_results': results_dicts,
|
||||
'audio_search_count': len(results_dicts),
|
||||
}
|
||||
'state_data': state_data_update
|
||||
})
|
||||
|
||||
# If auto_download, select best and start processing
|
||||
@@ -475,6 +680,7 @@ async def search_audio(
|
||||
results_count=len(search_results),
|
||||
auto_download=True,
|
||||
server_version=VERSION,
|
||||
style_upload_urls=style_upload_urls if style_upload_urls else None,
|
||||
)
|
||||
|
||||
# Interactive mode: return results for user selection
|
||||
@@ -489,12 +695,20 @@ async def search_audio(
|
||||
result_responses = []
|
||||
for r in search_results:
|
||||
# Get full serialized data from raw_result if available
|
||||
# raw_result can be either:
|
||||
# - A dict (from remote flacfetch API)
|
||||
# - A Release object (from local flacfetch)
|
||||
raw_dict = {}
|
||||
if r.raw_result:
|
||||
try:
|
||||
raw_dict = r.raw_result.to_dict()
|
||||
except AttributeError:
|
||||
pass # Not a Release object
|
||||
if isinstance(r.raw_result, dict):
|
||||
# Remote flacfetch API returns dicts directly
|
||||
raw_dict = r.raw_result
|
||||
else:
|
||||
# Local flacfetch returns Release objects
|
||||
try:
|
||||
raw_dict = r.raw_result.to_dict()
|
||||
except AttributeError:
|
||||
pass # Not a Release object
|
||||
|
||||
result_responses.append(
|
||||
AudioSearchResultResponse(
|
||||
@@ -526,7 +740,8 @@ async def search_audio(
|
||||
is_lossless=raw_dict.get('is_lossless'),
|
||||
quality_str=raw_dict.get('quality_str'),
|
||||
# Full quality object for Release.from_dict()
|
||||
quality_data=raw_dict.get('quality'),
|
||||
# Remote API uses 'quality_data', local uses 'quality' for the dict
|
||||
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -538,6 +753,7 @@ async def search_audio(
|
||||
results_count=len(search_results),
|
||||
auto_download=False,
|
||||
server_version=VERSION,
|
||||
style_upload_urls=style_upload_urls if style_upload_urls else None,
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
@@ -548,7 +764,10 @@ async def search_audio(
|
||||
|
||||
|
||||
@router.get("/audio-search/{job_id}/results")
|
||||
async def get_audio_search_results(job_id: str):
|
||||
async def get_audio_search_results(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Get audio search results for a job.
|
||||
|
||||
@@ -582,6 +801,7 @@ async def select_audio_source(
|
||||
job_id: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: AudioSelectRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Select an audio source and start job processing.
|
||||
@@ -603,25 +823,16 @@ async def select_audio_source(
|
||||
detail=f"Job is not awaiting audio selection (status: {job.status})"
|
||||
)
|
||||
|
||||
# Re-instantiate the audio search service (it caches raw results from search)
|
||||
# For production, we'd need to re-search or store raw results differently
|
||||
# Get search service instance
|
||||
# Note: With download_by_id, we no longer need to re-search to populate the cache.
|
||||
# The source_id stored in job.state_data['audio_search_results'] is sufficient.
|
||||
audio_search_service = get_audio_search_service()
|
||||
|
||||
# Re-run search to populate the cache
|
||||
# This is necessary because the service caches raw results in memory
|
||||
|
||||
# Validate search results exist in job state_data
|
||||
search_results = job.state_data.get('audio_search_results', [])
|
||||
if not search_results:
|
||||
raise HTTPException(status_code=400, detail="No search results cached for this job")
|
||||
|
||||
artist = job.audio_search_artist or job.artist
|
||||
title = job.audio_search_title or job.title
|
||||
|
||||
try:
|
||||
# Re-search to populate cache
|
||||
audio_search_service.search(artist, title)
|
||||
except Exception as e:
|
||||
logger.warning(f"Re-search failed, trying direct download: {e}")
|
||||
|
||||
selection_info = await _download_and_start_processing(
|
||||
job_id=job_id,
|
||||
selection_index=body.selection_index,
|
||||
|
||||
@@ -15,20 +15,24 @@ import json
|
||||
import logging
|
||||
import tempfile
|
||||
import os
|
||||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body
|
||||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body, Depends
|
||||
from pathlib import Path
|
||||
from typing import Optional, List, Dict, Any, Tuple
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.models.job import JobCreate, JobStatus
|
||||
from backend.models.theme import ColorOverrides
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.services.credential_manager import get_credential_manager, CredentialStatus
|
||||
from backend.services.theme_service import get_theme_service
|
||||
from backend.config import get_settings
|
||||
from backend.version import VERSION
|
||||
from backend.services.metrics import metrics
|
||||
from backend.api.dependencies import require_auth
|
||||
from backend.services.auth_service import UserType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(tags=["jobs"])
|
||||
@@ -49,15 +53,19 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
"""Request to create a job from a YouTube/online URL."""
|
||||
# Required fields
|
||||
url: str = Field(..., description="YouTube or other video URL to download audio from")
|
||||
|
||||
|
||||
# Optional fields - will be auto-detected from URL if not provided
|
||||
artist: Optional[str] = Field(None, description="Artist name (auto-detected from URL if not provided)")
|
||||
title: Optional[str] = Field(None, description="Song title (auto-detected from URL if not provided)")
|
||||
|
||||
# Processing options
|
||||
enable_cdg: bool = Field(True, description="Generate CDG+MP3 package")
|
||||
enable_txt: bool = Field(True, description="Generate TXT+MP3 package")
|
||||
|
||||
|
||||
# Theme configuration (use pre-made theme from GCS)
|
||||
theme_id: Optional[str] = Field(None, description="Theme ID to use (e.g., 'nomad', 'default'). If set, CDG/TXT are enabled by default.")
|
||||
color_overrides: Optional[Dict[str, str]] = Field(None, description="Color overrides: artist_color, title_color, sung_lyrics_color, unsung_lyrics_color (hex #RRGGBB)")
|
||||
|
||||
# Processing options (CDG/TXT require style config or theme, disabled by default unless theme is set)
|
||||
enable_cdg: Optional[bool] = Field(None, description="Generate CDG+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
enable_txt: Optional[bool] = Field(None, description="Generate TXT+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Field(None, description="Brand code prefix (e.g., NOMAD)")
|
||||
enable_youtube_upload: bool = Field(False, description="Upload to YouTube")
|
||||
@@ -65,19 +73,19 @@ class CreateJobFromUrlRequest(BaseModel):
|
||||
discord_webhook_url: Optional[str] = Field(None, description="Discord webhook URL for notifications")
|
||||
webhook_url: Optional[str] = Field(None, description="Generic webhook URL")
|
||||
user_email: Optional[str] = Field(None, description="User email for notifications")
|
||||
|
||||
|
||||
# Distribution options (native API - preferred for remote CLI)
|
||||
dropbox_path: Optional[str] = Field(None, description="Dropbox folder path for organized output")
|
||||
gdrive_folder_id: Optional[str] = Field(None, description="Google Drive folder ID for public share uploads")
|
||||
|
||||
|
||||
# Legacy distribution options (rclone - deprecated)
|
||||
organised_dir_rclone_root: Optional[str] = Field(None, description="[Deprecated] rclone remote path")
|
||||
|
||||
|
||||
# Lyrics configuration
|
||||
lyrics_artist: Optional[str] = Field(None, description="Override artist name for lyrics search")
|
||||
lyrics_title: Optional[str] = Field(None, description="Override title for lyrics search")
|
||||
subtitle_offset_ms: int = Field(0, description="Subtitle timing offset in milliseconds")
|
||||
|
||||
|
||||
# Audio separation model configuration
|
||||
clean_instrumental_model: Optional[str] = Field(None, description="Model for clean instrumental separation")
|
||||
backing_vocals_models: Optional[List[str]] = Field(None, description="Models for backing vocals separation")
|
||||
@@ -100,10 +108,14 @@ class CreateJobWithUploadUrlsRequest(BaseModel):
|
||||
artist: str = Field(..., description="Artist name")
|
||||
title: str = Field(..., description="Song title")
|
||||
files: List[FileUploadRequest] = Field(..., description="List of files to upload")
|
||||
|
||||
# Processing options
|
||||
enable_cdg: bool = Field(True, description="Generate CDG+MP3 package")
|
||||
enable_txt: bool = Field(True, description="Generate TXT+MP3 package")
|
||||
|
||||
# Theme configuration (use pre-made theme from GCS)
|
||||
theme_id: Optional[str] = Field(None, description="Theme ID to use (e.g., 'nomad', 'default'). If set, CDG/TXT are enabled by default.")
|
||||
color_overrides: Optional[Dict[str, str]] = Field(None, description="Color overrides: artist_color, title_color, sung_lyrics_color, unsung_lyrics_color (hex #RRGGBB)")
|
||||
|
||||
# Processing options (CDG/TXT require style config or theme, disabled by default unless theme is set)
|
||||
enable_cdg: Optional[bool] = Field(None, description="Generate CDG+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
enable_txt: Optional[bool] = Field(None, description="Generate TXT+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Field(None, description="Brand code prefix (e.g., NOMAD)")
|
||||
@@ -224,7 +236,7 @@ ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
|
||||
async def _trigger_workers_parallel(job_id: str) -> None:
|
||||
"""
|
||||
Trigger both audio and lyrics workers in parallel.
|
||||
|
||||
|
||||
FastAPI's BackgroundTasks runs async tasks sequentially, so we use
|
||||
asyncio.gather to ensure both workers start at the same time.
|
||||
"""
|
||||
@@ -234,10 +246,88 @@ async def _trigger_workers_parallel(job_id: str) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _resolve_cdg_txt_defaults(
|
||||
theme_id: Optional[str],
|
||||
enable_cdg: Optional[bool],
|
||||
enable_txt: Optional[bool]
|
||||
) -> Tuple[bool, bool]:
|
||||
"""
|
||||
Resolve CDG/TXT settings based on theme and explicit settings.
|
||||
|
||||
When a theme is selected, CDG and TXT are enabled by default.
|
||||
Explicit True/False values always override the default.
|
||||
|
||||
Args:
|
||||
theme_id: Theme identifier (if any)
|
||||
enable_cdg: Explicit CDG setting (None means use default)
|
||||
enable_txt: Explicit TXT setting (None means use default)
|
||||
|
||||
Returns:
|
||||
Tuple of (resolved_enable_cdg, resolved_enable_txt)
|
||||
"""
|
||||
# Default based on whether theme is set
|
||||
default_enabled = theme_id is not None
|
||||
|
||||
# Resolve with explicit override taking precedence
|
||||
resolved_cdg = enable_cdg if enable_cdg is not None else default_enabled
|
||||
resolved_txt = enable_txt if enable_txt is not None else default_enabled
|
||||
|
||||
return resolved_cdg, resolved_txt
|
||||
|
||||
|
||||
def _prepare_theme_for_job(
|
||||
job_id: str,
|
||||
theme_id: str,
|
||||
color_overrides: Optional[Dict[str, str]] = None
|
||||
) -> Tuple[str, Dict[str, str], Optional[str]]:
|
||||
"""
|
||||
Prepare theme style files for a job.
|
||||
|
||||
Args:
|
||||
job_id: The job ID
|
||||
theme_id: Theme identifier
|
||||
color_overrides: Optional color override dict
|
||||
|
||||
Returns:
|
||||
Tuple of (style_params_gcs_path, style_assets, youtube_description)
|
||||
|
||||
Raises:
|
||||
HTTPException: If theme not found
|
||||
"""
|
||||
theme_service = get_theme_service()
|
||||
|
||||
# Verify theme exists
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Theme not found: {theme_id}. Use GET /api/themes to list available themes."
|
||||
)
|
||||
|
||||
# Convert dict to ColorOverrides model if provided
|
||||
color_overrides_model = None
|
||||
if color_overrides:
|
||||
color_overrides_model = ColorOverrides(**color_overrides)
|
||||
|
||||
# Prepare job style from theme
|
||||
style_params_path, style_assets = theme_service.prepare_job_style(
|
||||
job_id=job_id,
|
||||
theme_id=theme_id,
|
||||
color_overrides=color_overrides_model
|
||||
)
|
||||
|
||||
# Get YouTube description template if available
|
||||
youtube_desc = theme_service.get_youtube_description(theme_id)
|
||||
|
||||
logger.info(f"Prepared theme '{theme_id}' for job {job_id}")
|
||||
|
||||
return style_params_path, style_assets, youtube_desc
|
||||
|
||||
|
||||
@router.post("/jobs/upload")
|
||||
async def upload_and_create_job(
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth),
|
||||
# Required fields
|
||||
file: UploadFile = File(..., description="Audio file to process"),
|
||||
artist: str = Form(..., description="Artist name"),
|
||||
@@ -251,9 +341,9 @@ async def upload_and_create_job(
|
||||
style_cdg_instrumental_background: Optional[UploadFile] = File(None, description="CDG instrumental background"),
|
||||
style_cdg_title_background: Optional[UploadFile] = File(None, description="CDG title screen background"),
|
||||
style_cdg_outro_background: Optional[UploadFile] = File(None, description="CDG outro screen background"),
|
||||
# Processing options
|
||||
enable_cdg: bool = Form(True, description="Generate CDG+MP3 package"),
|
||||
enable_txt: bool = Form(True, description="Generate TXT+MP3 package"),
|
||||
# Processing options (CDG/TXT require style config, disabled by default)
|
||||
enable_cdg: bool = Form(False, description="Generate CDG+MP3 package (requires style config)"),
|
||||
enable_txt: bool = Form(False, description="Generate TXT+MP3 package (requires style config)"),
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Form(None, description="Brand code prefix (e.g., NOMAD)"),
|
||||
enable_youtube_upload: bool = Form(False, description="Upload to YouTube"),
|
||||
@@ -678,10 +768,14 @@ class CreateFinaliseOnlyJobRequest(BaseModel):
|
||||
artist: str = Field(..., description="Artist name")
|
||||
title: str = Field(..., description="Song title")
|
||||
files: List[FinaliseOnlyFileRequest] = Field(..., description="List of prep output files to upload")
|
||||
|
||||
# Processing options
|
||||
enable_cdg: bool = Field(True, description="Generate CDG+MP3 package")
|
||||
enable_txt: bool = Field(True, description="Generate TXT+MP3 package")
|
||||
|
||||
# Theme configuration (use pre-made theme from GCS)
|
||||
theme_id: Optional[str] = Field(None, description="Theme ID to use (e.g., 'nomad', 'default'). If set, CDG/TXT are enabled by default.")
|
||||
color_overrides: Optional[Dict[str, str]] = Field(None, description="Color overrides: artist_color, title_color, sung_lyrics_color, unsung_lyrics_color (hex #RRGGBB)")
|
||||
|
||||
# Processing options (CDG/TXT require style config or theme, disabled by default unless theme is set)
|
||||
enable_cdg: Optional[bool] = Field(None, description="Generate CDG+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
enable_txt: Optional[bool] = Field(None, description="Generate TXT+MP3 package. Default: True if theme_id set, False otherwise")
|
||||
|
||||
# Finalisation options
|
||||
brand_prefix: Optional[str] = Field(None, description="Brand code prefix (e.g., NOMAD)")
|
||||
@@ -774,6 +868,7 @@ def _get_gcs_path_for_file(job_id: str, file_type: str, filename: str) -> str:
|
||||
async def create_job_with_upload_urls(
|
||||
request: Request,
|
||||
body: CreateJobWithUploadUrlsRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Create a karaoke generation job and return signed URLs for direct file upload to GCS.
|
||||
@@ -855,17 +950,27 @@ async def create_job_with_upload_urls(
|
||||
|
||||
# Extract request metadata for tracking
|
||||
request_metadata = extract_request_metadata(request, created_from="signed_url_upload")
|
||||
|
||||
|
||||
# Get original audio filename
|
||||
audio_file = audio_files[0]
|
||||
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
body.theme_id, body.enable_cdg, body.enable_txt
|
||||
)
|
||||
|
||||
# Check if style_params is being uploaded (overrides theme)
|
||||
has_style_params_upload = any(f.file_type == 'style_params' for f in body.files)
|
||||
|
||||
# Create job
|
||||
job_create = JobCreate(
|
||||
artist=body.artist,
|
||||
title=body.title,
|
||||
filename=audio_file.filename,
|
||||
enable_cdg=body.enable_cdg,
|
||||
enable_txt=body.enable_txt,
|
||||
theme_id=body.theme_id,
|
||||
color_overrides=body.color_overrides or {},
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
brand_prefix=body.brand_prefix,
|
||||
enable_youtube_upload=body.enable_youtube_upload,
|
||||
youtube_description=body.youtube_description,
|
||||
@@ -885,11 +990,26 @@ async def create_job_with_upload_urls(
|
||||
)
|
||||
job = job_manager.create_job(job_create)
|
||||
job_id = job.job_id
|
||||
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="upload")
|
||||
|
||||
|
||||
logger.info(f"Created job {job_id} for {body.artist} - {body.title} (signed URL upload flow)")
|
||||
|
||||
# If theme is set and no style_params uploaded, prepare theme style now
|
||||
if body.theme_id and not has_style_params_upload:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, body.theme_id, body.color_overrides
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
'style_assets': style_assets,
|
||||
}
|
||||
if youtube_desc and not body.youtube_description:
|
||||
update_data['youtube_description_template'] = youtube_desc
|
||||
job_manager.update_job(job_id, update_data)
|
||||
logger.info(f"Applied theme '{body.theme_id}' to job {job_id}")
|
||||
|
||||
# Generate signed upload URLs for each file
|
||||
upload_urls = []
|
||||
@@ -932,6 +1052,7 @@ async def mark_uploads_complete(
|
||||
job_id: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: UploadsCompleteRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Mark file uploads as complete and start job processing.
|
||||
@@ -1177,6 +1298,7 @@ async def create_job_from_url(
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: CreateJobFromUrlRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Create a karaoke generation job from a YouTube or other online video URL.
|
||||
@@ -1239,19 +1361,26 @@ async def create_job_from_url(
|
||||
|
||||
# Extract request metadata for tracking
|
||||
request_metadata = extract_request_metadata(request, created_from="url")
|
||||
|
||||
|
||||
# Use provided artist/title or leave as None (will be auto-detected by audio worker)
|
||||
artist = body.artist
|
||||
title = body.title
|
||||
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
body.theme_id, body.enable_cdg, body.enable_txt
|
||||
)
|
||||
|
||||
# Create job with URL
|
||||
job_create = JobCreate(
|
||||
url=body.url,
|
||||
artist=artist,
|
||||
title=title,
|
||||
filename=None, # No file uploaded
|
||||
enable_cdg=body.enable_cdg,
|
||||
enable_txt=body.enable_txt,
|
||||
theme_id=body.theme_id,
|
||||
color_overrides=body.color_overrides or {},
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
brand_prefix=body.brand_prefix,
|
||||
enable_youtube_upload=body.enable_youtube_upload,
|
||||
youtube_description=body.youtube_description,
|
||||
@@ -1271,9 +1400,24 @@ async def create_job_from_url(
|
||||
)
|
||||
job = job_manager.create_job(job_create)
|
||||
job_id = job.job_id
|
||||
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="url")
|
||||
|
||||
# If theme is set, prepare theme style now
|
||||
if body.theme_id:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, body.theme_id, body.color_overrides
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
'style_assets': style_assets,
|
||||
}
|
||||
if youtube_desc and not body.youtube_description:
|
||||
update_data['youtube_description_template'] = youtube_desc
|
||||
job_manager.update_job(job_id, update_data)
|
||||
logger.info(f"Applied theme '{body.theme_id}' to job {job_id}")
|
||||
|
||||
logger.info(f"Created URL-based job {job_id} for URL: {body.url}")
|
||||
if artist:
|
||||
@@ -1354,6 +1498,7 @@ def _get_gcs_path_for_finalise_file(job_id: str, file_type: str, filename: str)
|
||||
async def create_finalise_only_job(
|
||||
request: Request,
|
||||
body: CreateFinaliseOnlyJobRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Create a finalise-only job for continuing from a local prep phase.
|
||||
@@ -1455,14 +1600,24 @@ async def create_finalise_only_job(
|
||||
|
||||
# Extract request metadata
|
||||
request_metadata = extract_request_metadata(request, created_from="finalise_only_upload")
|
||||
|
||||
|
||||
# Resolve CDG/TXT defaults based on theme
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
body.theme_id, body.enable_cdg, body.enable_txt
|
||||
)
|
||||
|
||||
# Check if style_params is being uploaded (overrides theme)
|
||||
has_style_params_upload = any(f.file_type == 'style_params' for f in body.files)
|
||||
|
||||
# Create job with finalise_only=True
|
||||
job_create = JobCreate(
|
||||
artist=body.artist,
|
||||
title=body.title,
|
||||
filename="finalise_only", # No single audio file - using prep outputs
|
||||
enable_cdg=body.enable_cdg,
|
||||
enable_txt=body.enable_txt,
|
||||
theme_id=body.theme_id,
|
||||
color_overrides=body.color_overrides or {},
|
||||
enable_cdg=resolved_cdg,
|
||||
enable_txt=resolved_txt,
|
||||
brand_prefix=body.brand_prefix,
|
||||
enable_youtube_upload=body.enable_youtube_upload,
|
||||
youtube_description=body.youtube_description,
|
||||
@@ -1475,11 +1630,26 @@ async def create_finalise_only_job(
|
||||
)
|
||||
job = job_manager.create_job(job_create)
|
||||
job_id = job.job_id
|
||||
|
||||
|
||||
# Record job creation metric
|
||||
metrics.record_job_created(job_id, source="finalise")
|
||||
|
||||
|
||||
logger.info(f"Created finalise-only job {job_id} for {body.artist} - {body.title}")
|
||||
|
||||
# If theme is set and no style_params uploaded, prepare theme style now
|
||||
if body.theme_id and not has_style_params_upload:
|
||||
style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(
|
||||
job_id, body.theme_id, body.color_overrides
|
||||
)
|
||||
# Update job with theme style data
|
||||
update_data = {
|
||||
'style_params_gcs_path': style_params_path,
|
||||
'style_assets': style_assets,
|
||||
}
|
||||
if youtube_desc and not body.youtube_description:
|
||||
update_data['youtube_description_template'] = youtube_desc
|
||||
job_manager.update_job(job_id, update_data)
|
||||
logger.info(f"Applied theme '{body.theme_id}' to job {job_id}")
|
||||
|
||||
# Generate signed upload URLs for each file
|
||||
upload_urls = []
|
||||
@@ -1522,6 +1692,7 @@ async def mark_finalise_uploads_complete(
|
||||
job_id: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
body: UploadsCompleteRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Mark finalise-only file uploads as complete and start video generation.
|
||||
|
||||
+146
-34
@@ -26,7 +26,7 @@ from backend.services.job_manager import JobManager
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.config import get_settings
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.api.dependencies import require_admin, require_auth, require_instrumental_auth
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.services.metrics import metrics
|
||||
|
||||
@@ -56,7 +56,8 @@ async def _trigger_workers_parallel(job_id: str) -> None:
|
||||
@router.post("", response_model=JobResponse)
|
||||
async def create_job(
|
||||
request: URLSubmissionRequest,
|
||||
background_tasks: BackgroundTasks
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> JobResponse:
|
||||
"""
|
||||
Create a new karaoke generation job from a URL.
|
||||
@@ -106,7 +107,10 @@ async def create_job(
|
||||
|
||||
|
||||
@router.get("/{job_id}", response_model=Job)
|
||||
async def get_job(job_id: str) -> Job:
|
||||
async def get_job(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> Job:
|
||||
"""Get job status and details."""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
@@ -126,7 +130,8 @@ async def list_jobs(
|
||||
client_id: Optional[str] = None,
|
||||
created_after: Optional[str] = None,
|
||||
created_before: Optional[str] = None,
|
||||
limit: int = 100
|
||||
limit: int = 100,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> List[Job]:
|
||||
"""
|
||||
List jobs with optional filters.
|
||||
@@ -178,7 +183,11 @@ async def list_jobs(
|
||||
|
||||
|
||||
@router.delete("/{job_id}")
|
||||
async def delete_job(job_id: str, delete_files: bool = True) -> dict:
|
||||
async def delete_job(
|
||||
job_id: str,
|
||||
delete_files: bool = True,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""Delete a job and optionally its output files."""
|
||||
try:
|
||||
job = job_manager.get_job(job_id)
|
||||
@@ -305,7 +314,10 @@ async def bulk_delete_jobs(
|
||||
# ============================================================================
|
||||
|
||||
@router.get("/{job_id}/review-data")
|
||||
async def get_review_data(job_id: str) -> Dict[str, Any]:
|
||||
async def get_review_data(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get data needed for lyrics review interface.
|
||||
|
||||
@@ -324,12 +336,27 @@ async def get_review_data(job_id: str) -> Dict[str, Any]:
|
||||
|
||||
# Get URLs from file_urls
|
||||
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
audio_url = job.file_urls.get('lyrics', {}).get('audio')
|
||||
|
||||
if not corrections_url or not audio_url:
|
||||
|
||||
# For audio, try multiple sources in order of preference:
|
||||
# 1. Explicit lyrics audio (if worker uploaded it)
|
||||
# 2. Lead vocals stem (best for reviewing lyrics sync)
|
||||
# 3. Input media (original audio)
|
||||
audio_url = (
|
||||
job.file_urls.get('lyrics', {}).get('audio') or
|
||||
job.file_urls.get('stems', {}).get('lead_vocals') or
|
||||
job.input_media_gcs_path
|
||||
)
|
||||
|
||||
if not corrections_url:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Review data not available"
|
||||
detail="Corrections data not available"
|
||||
)
|
||||
|
||||
if not audio_url:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Audio not available for review"
|
||||
)
|
||||
|
||||
# Generate signed URLs for direct access
|
||||
@@ -346,7 +373,11 @@ async def get_review_data(job_id: str) -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.post("/{job_id}/start-review")
|
||||
async def start_review(job_id: str, request: StartReviewRequest) -> dict:
|
||||
async def start_review(
|
||||
job_id: str,
|
||||
request: StartReviewRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Mark job as IN_REVIEW (user opened review interface).
|
||||
|
||||
@@ -368,7 +399,8 @@ async def start_review(job_id: str, request: StartReviewRequest) -> dict:
|
||||
async def submit_corrections(
|
||||
job_id: str,
|
||||
submission: CorrectionsSubmission,
|
||||
background_tasks: BackgroundTasks
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Save corrected lyrics during human review.
|
||||
@@ -426,7 +458,8 @@ async def submit_corrections(
|
||||
@router.post("/{job_id}/complete-review")
|
||||
async def complete_review(
|
||||
job_id: str,
|
||||
background_tasks: BackgroundTasks
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Complete the human review and trigger video rendering.
|
||||
@@ -474,13 +507,18 @@ async def complete_review(
|
||||
|
||||
|
||||
@router.get("/{job_id}/instrumental-options")
|
||||
async def get_instrumental_options(job_id: str) -> Dict[str, Any]:
|
||||
async def get_instrumental_options(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get instrumental audio options for user selection.
|
||||
|
||||
Returns signed URLs for both options:
|
||||
1. Clean instrumental (no backing vocals)
|
||||
2. Instrumental with backing vocals
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
@@ -529,7 +567,10 @@ async def get_instrumental_options(job_id: str) -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/{job_id}/instrumental-analysis")
|
||||
async def get_instrumental_analysis(job_id: str) -> Dict[str, Any]:
|
||||
async def get_instrumental_analysis(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get audio analysis data for instrumental selection.
|
||||
|
||||
@@ -540,6 +581,8 @@ async def get_instrumental_analysis(job_id: str) -> Dict[str, Any]:
|
||||
|
||||
This endpoint enables intelligent instrumental selection by providing
|
||||
detailed analysis of the backing vocals track.
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
@@ -603,7 +646,11 @@ async def get_instrumental_analysis(job_id: str) -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio-stream/{stem_type}")
|
||||
async def stream_audio(job_id: str, stem_type: str):
|
||||
async def stream_audio(
|
||||
job_id: str,
|
||||
stem_type: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
):
|
||||
"""
|
||||
Stream an audio file for playback in the browser.
|
||||
|
||||
@@ -615,6 +662,8 @@ async def stream_audio(job_id: str, stem_type: str):
|
||||
|
||||
Returns audio as a streaming response with proper headers for
|
||||
browser audio playback.
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
from fastapi.responses import StreamingResponse
|
||||
import tempfile
|
||||
@@ -691,6 +740,7 @@ async def stream_audio(job_id: str, stem_type: str):
|
||||
async def create_custom_instrumental(
|
||||
job_id: str,
|
||||
request: CreateCustomInstrumentalRequest,
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Create a custom instrumental by muting regions of backing vocals.
|
||||
@@ -702,6 +752,8 @@ async def create_custom_instrumental(
|
||||
|
||||
After calling this endpoint, the user can select "custom" in the
|
||||
select-instrumental endpoint.
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
from backend.services.audio_editing_service import AudioEditingService
|
||||
from karaoke_gen.instrumental_review import MuteRegion
|
||||
@@ -780,7 +832,11 @@ async def create_custom_instrumental(
|
||||
|
||||
|
||||
@router.get("/{job_id}/waveform-data")
|
||||
async def get_waveform_data(job_id: str, num_points: int = 500) -> Dict[str, Any]:
|
||||
async def get_waveform_data(
|
||||
job_id: str,
|
||||
num_points: int = 500,
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get waveform amplitude data for client-side rendering.
|
||||
|
||||
@@ -797,6 +853,8 @@ async def get_waveform_data(job_id: str, num_points: int = 500) -> Dict[str, Any
|
||||
"duration_seconds": 180.5,
|
||||
"num_points": 500
|
||||
}
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
@@ -837,13 +895,16 @@ async def get_waveform_data(job_id: str, num_points: int = 500) -> Dict[str, Any
|
||||
async def select_instrumental(
|
||||
job_id: str,
|
||||
selection: InstrumentalSelection,
|
||||
background_tasks: BackgroundTasks
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_info: Tuple[str, str] = Depends(require_instrumental_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Submit instrumental selection.
|
||||
|
||||
This is the SECOND critical human-in-the-loop interaction point.
|
||||
After selection, the job proceeds to video generation.
|
||||
|
||||
Accepts either full auth token or job-specific instrumental_token.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
@@ -885,7 +946,10 @@ async def select_instrumental(
|
||||
|
||||
|
||||
@router.get("/{job_id}/download-urls")
|
||||
async def get_download_urls(job_id: str) -> dict:
|
||||
async def get_download_urls(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Get download URLs for all job output files.
|
||||
|
||||
@@ -927,7 +991,12 @@ async def get_download_urls(job_id: str) -> dict:
|
||||
|
||||
|
||||
@router.get("/{job_id}/download/{category}/{file_key}")
|
||||
async def download_file(job_id: str, category: str, file_key: str):
|
||||
async def download_file(
|
||||
job_id: str,
|
||||
category: str,
|
||||
file_key: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Stream download a specific file from a completed job.
|
||||
|
||||
@@ -1014,7 +1083,11 @@ async def download_file(job_id: str, category: str, file_key: str):
|
||||
|
||||
|
||||
@router.post("/{job_id}/cancel")
|
||||
async def cancel_job(job_id: str, request: CancelJobRequest) -> dict:
|
||||
async def cancel_job(
|
||||
job_id: str,
|
||||
request: CancelJobRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Cancel a job.
|
||||
|
||||
@@ -1035,35 +1108,38 @@ async def cancel_job(job_id: str, request: CancelJobRequest) -> dict:
|
||||
@router.post("/{job_id}/retry")
|
||||
async def retry_job(
|
||||
job_id: str,
|
||||
background_tasks: BackgroundTasks
|
||||
background_tasks: BackgroundTasks,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> dict:
|
||||
"""
|
||||
Retry a failed job from the last successful checkpoint.
|
||||
|
||||
This endpoint allows resuming jobs that failed during:
|
||||
Retry a failed or cancelled job from the last successful checkpoint.
|
||||
|
||||
This endpoint allows resuming jobs that failed or were cancelled during:
|
||||
- Audio processing (re-runs from beginning if input audio exists)
|
||||
- Video generation (re-runs video worker)
|
||||
- Encoding (re-runs video worker)
|
||||
- Packaging (re-runs video worker)
|
||||
|
||||
|
||||
The retry logic determines the appropriate stage to resume from
|
||||
based on what files/state already exist.
|
||||
"""
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
if job.status != JobStatus.FAILED:
|
||||
|
||||
if job.status not in [JobStatus.FAILED, JobStatus.CANCELLED]:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Only failed jobs can be retried (current status: {job.status})"
|
||||
detail=f"Only failed or cancelled jobs can be retried (current status: {job.status})"
|
||||
)
|
||||
|
||||
try:
|
||||
# Determine retry point based on what's already complete
|
||||
error_details = job.error_details or {}
|
||||
error_stage = error_details.get('stage', 'unknown')
|
||||
|
||||
logger.info(f"Job {job_id}: Retrying from failed stage '{error_stage}'")
|
||||
original_status = job.status
|
||||
|
||||
logger.info(f"Job {job_id}: Retrying from {original_status} state (error stage: '{error_stage}')")
|
||||
|
||||
# Check what state exists to determine retry point
|
||||
file_urls = job.file_urls or {}
|
||||
@@ -1171,11 +1247,46 @@ async def retry_job(
|
||||
"retry_stage": "screens_generation"
|
||||
}
|
||||
|
||||
# If we have input audio (uploaded or from URL), restart from beginning
|
||||
elif job.input_media_gcs_path or job.url:
|
||||
logger.info(f"Job {job_id}: Has input audio, restarting from beginning")
|
||||
|
||||
# Clear error state and any partial progress
|
||||
job_manager.update_job(job_id, {
|
||||
'error_message': None,
|
||||
'error_details': None,
|
||||
'state_data': {}, # Clear parallel worker progress
|
||||
})
|
||||
|
||||
# Reset to DOWNLOADING and trigger audio worker
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=5,
|
||||
message=f"Restarting job from {original_status} state"
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to transition job status for retry"
|
||||
)
|
||||
|
||||
# Trigger audio worker (which kicks off parallel audio + lyrics processing)
|
||||
background_tasks.add_task(worker_service.trigger_audio_worker, job_id)
|
||||
background_tasks.add_task(worker_service.trigger_lyrics_worker, job_id)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"job_id": job_id,
|
||||
"job_status": "downloading",
|
||||
"message": f"Job restarted from {original_status} state",
|
||||
"retry_stage": "from_beginning"
|
||||
}
|
||||
|
||||
else:
|
||||
# Can't determine a safe retry point, need to restart from beginning
|
||||
# No input audio available - job needs to be resubmitted
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Cannot determine safe retry point. Job may need to be resubmitted."
|
||||
detail="Cannot retry: no input audio available. Job must be resubmitted."
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
@@ -1189,7 +1300,8 @@ async def retry_job(
|
||||
async def get_worker_logs(
|
||||
job_id: str,
|
||||
since_index: int = 0,
|
||||
worker: Optional[str] = None
|
||||
worker: Optional[str] = None,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_auth)
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get worker logs for debugging.
|
||||
|
||||
@@ -16,9 +16,9 @@ import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, Set
|
||||
from typing import Dict, Any, Set, Tuple
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi import APIRouter, HTTPException, Request, Depends
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
@@ -27,6 +27,8 @@ from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.job_logging import job_log_context, JobLogger
|
||||
from backend.services.tracing import create_span, add_span_attribute, add_span_event
|
||||
from backend.api.dependencies import require_auth, require_review_auth
|
||||
from backend.services.auth_service import UserType
|
||||
|
||||
# LyricsTranscriber imports for preview generation
|
||||
from lyrics_transcriber.types import CorrectionResult
|
||||
@@ -63,7 +65,10 @@ async def ping(job_id: str):
|
||||
|
||||
|
||||
@router.get("/{job_id}/correction-data")
|
||||
async def get_correction_data(job_id: str):
|
||||
async def get_correction_data(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Get correction data for the review interface.
|
||||
|
||||
@@ -129,14 +134,21 @@ async def get_correction_data(job_id: str):
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/{audio_hash}")
|
||||
async def get_audio_with_hash(job_id: str, audio_hash: str):
|
||||
async def get_audio_with_hash(
|
||||
job_id: str,
|
||||
audio_hash: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the audio file for playback (with hash parameter)."""
|
||||
return await _stream_audio(job_id)
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/")
|
||||
@router.get("/{job_id}/audio")
|
||||
async def get_audio_no_hash(job_id: str):
|
||||
async def get_audio_no_hash(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the audio file for playback (without hash parameter)."""
|
||||
return await _stream_audio(job_id)
|
||||
|
||||
@@ -189,7 +201,11 @@ async def _stream_audio(job_id: str):
|
||||
|
||||
|
||||
@router.post("/{job_id}/complete")
|
||||
async def complete_review(job_id: str, updated_data: Dict[str, Any]):
|
||||
async def complete_review(
|
||||
job_id: str,
|
||||
updated_data: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Complete the review and save corrected lyrics.
|
||||
|
||||
@@ -244,7 +260,11 @@ async def complete_review(job_id: str, updated_data: Dict[str, Any]):
|
||||
|
||||
|
||||
@router.post("/{job_id}/handlers")
|
||||
async def update_handlers(job_id: str, enabled_handlers: list):
|
||||
async def update_handlers(
|
||||
job_id: str,
|
||||
enabled_handlers: list,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Update enabled correction handlers (optional feature).
|
||||
|
||||
@@ -256,7 +276,11 @@ async def update_handlers(job_id: str, enabled_handlers: list):
|
||||
|
||||
|
||||
@router.post("/{job_id}/add-lyrics")
|
||||
async def add_lyrics(job_id: str, data: Dict[str, str]):
|
||||
async def add_lyrics(
|
||||
job_id: str,
|
||||
data: Dict[str, str],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Add custom lyrics source and rerun correction.
|
||||
|
||||
@@ -354,7 +378,11 @@ async def add_lyrics(job_id: str, data: Dict[str, str]):
|
||||
|
||||
|
||||
@router.post("/{job_id}/preview-video")
|
||||
async def generate_preview_video(job_id: str, updated_data: Dict[str, Any]):
|
||||
async def generate_preview_video(
|
||||
job_id: str,
|
||||
updated_data: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Generate a preview video with the current corrections.
|
||||
|
||||
@@ -469,7 +497,11 @@ async def generate_preview_video(job_id: str, updated_data: Dict[str, Any]):
|
||||
|
||||
|
||||
@router.get("/{job_id}/preview-video/{preview_hash}")
|
||||
async def get_preview_video(job_id: str, preview_hash: str):
|
||||
async def get_preview_video(
|
||||
job_id: str,
|
||||
preview_hash: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the generated preview video."""
|
||||
storage = StorageService()
|
||||
|
||||
@@ -510,7 +542,11 @@ async def get_preview_video(job_id: str, preview_hash: str):
|
||||
|
||||
|
||||
@router.post("/{job_id}/v1/annotations")
|
||||
async def submit_annotation(job_id: str, annotation: Dict[str, Any]):
|
||||
async def submit_annotation(
|
||||
job_id: str,
|
||||
annotation: Dict[str, Any],
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Submit a correction annotation for ML training data.
|
||||
|
||||
@@ -522,7 +558,10 @@ async def submit_annotation(job_id: str, annotation: Dict[str, Any]):
|
||||
|
||||
|
||||
@router.get("/{job_id}/v1/annotations/stats")
|
||||
async def get_annotation_stats(job_id: str):
|
||||
async def get_annotation_stats(
|
||||
job_id: str,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Get annotation statistics."""
|
||||
return {
|
||||
"total_annotations": 0,
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
Theme API routes for listing and retrieving theme information.
|
||||
|
||||
Themes are pre-created style configurations that users can select when creating jobs.
|
||||
These endpoints are public (no authentication required) to allow theme selection
|
||||
before job creation.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from backend.models.theme import ThemeDetailResponse, ThemesListResponse
|
||||
from backend.services.theme_service import get_theme_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/themes", tags=["themes"])
|
||||
|
||||
|
||||
@router.get("", response_model=ThemesListResponse)
|
||||
async def list_themes() -> ThemesListResponse:
|
||||
"""
|
||||
List all available themes.
|
||||
|
||||
Returns a list of themes with their metadata and preview image URLs.
|
||||
Preview URLs are signed and valid for 60 minutes.
|
||||
|
||||
This endpoint is public and does not require authentication.
|
||||
"""
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
themes = theme_service.list_themes()
|
||||
return ThemesListResponse(themes=themes)
|
||||
except Exception as e:
|
||||
logger.error(f"Error listing themes: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load themes"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}", response_model=ThemeDetailResponse)
|
||||
async def get_theme(theme_id: str) -> ThemeDetailResponse:
|
||||
"""
|
||||
Get detailed information about a specific theme.
|
||||
|
||||
Returns the full theme details including style parameters.
|
||||
This can be used to preview theme settings or inspect configuration.
|
||||
|
||||
Args:
|
||||
theme_id: The unique identifier of the theme
|
||||
|
||||
Returns:
|
||||
ThemeDetailResponse with full theme details
|
||||
|
||||
Raises:
|
||||
404: Theme not found
|
||||
"""
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
theme = theme_service.get_theme(theme_id)
|
||||
|
||||
if theme is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
)
|
||||
|
||||
return ThemeDetailResponse(theme=theme)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load theme"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}/preview")
|
||||
async def get_theme_preview(theme_id: str) -> dict:
|
||||
"""
|
||||
Get a signed URL for the theme's preview image.
|
||||
|
||||
This endpoint is useful when you need just the preview URL
|
||||
without loading the full theme details.
|
||||
|
||||
Args:
|
||||
theme_id: The unique identifier of the theme
|
||||
|
||||
Returns:
|
||||
Object with preview_url field
|
||||
|
||||
Raises:
|
||||
404: Theme not found or no preview available
|
||||
"""
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
)
|
||||
|
||||
theme = theme_service.get_theme(theme_id)
|
||||
if theme is None or theme.preview_url is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"No preview available for theme: {theme_id}"
|
||||
)
|
||||
|
||||
return {"preview_url": theme.preview_url}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting preview for theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load theme preview"
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{theme_id}/youtube-description")
|
||||
async def get_theme_youtube_description(theme_id: str) -> dict:
|
||||
"""
|
||||
Get the YouTube description template for a theme.
|
||||
|
||||
Some themes include a default YouTube video description template
|
||||
that can be used when uploading videos.
|
||||
|
||||
Args:
|
||||
theme_id: The unique identifier of the theme
|
||||
|
||||
Returns:
|
||||
Object with description field containing the template text,
|
||||
or null if no template is available
|
||||
|
||||
Raises:
|
||||
404: Theme not found
|
||||
"""
|
||||
try:
|
||||
theme_service = get_theme_service()
|
||||
|
||||
if not theme_service.theme_exists(theme_id):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Theme not found: {theme_id}"
|
||||
)
|
||||
|
||||
description = theme_service.get_youtube_description(theme_id)
|
||||
return {"description": description}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting YouTube description for theme {theme_id}: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to load YouTube description"
|
||||
)
|
||||
@@ -69,6 +69,16 @@ class Settings(BaseSettings):
|
||||
default_discord_webhook_url: Optional[str] = (
|
||||
os.getenv("DEFAULT_DISCORD_WEBHOOK_URL", "").strip() or None
|
||||
)
|
||||
|
||||
# Default values for web service jobs (YouTube/Dropbox distribution)
|
||||
default_enable_youtube_upload: bool = os.getenv("DEFAULT_ENABLE_YOUTUBE_UPLOAD", "false").lower() in ("true", "1", "yes")
|
||||
default_brand_prefix: Optional[str] = os.getenv("DEFAULT_BRAND_PREFIX")
|
||||
default_youtube_description: str = os.getenv(
|
||||
"DEFAULT_YOUTUBE_DESCRIPTION",
|
||||
"Karaoke video created with Nomad Karaoke (https://nomadkaraoke.com)\n\n"
|
||||
"AI-powered vocal separation and synchronized lyrics.\n\n"
|
||||
"#karaoke #music #singing #instrumental #lyrics"
|
||||
)
|
||||
|
||||
# Secret Manager cache
|
||||
_secret_cache: Dict[str, str] = {}
|
||||
|
||||
+2
-1
@@ -7,7 +7,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
|
||||
@@ -108,6 +108,7 @@ app.include_router(internal.router, prefix="/api") # Internal worker endpoints
|
||||
app.include_router(review.router, prefix="/api") # Review UI compatibility endpoints
|
||||
app.include_router(auth.router, prefix="/api") # OAuth credential management
|
||||
app.include_router(audio_search.router, prefix="/api") # Audio search (artist+title mode)
|
||||
app.include_router(themes.router, prefix="/api") # Theme selection for styles
|
||||
|
||||
|
||||
@app.get("/")
|
||||
|
||||
+44
-10
@@ -134,17 +134,23 @@ STATE_TRANSITIONS = {
|
||||
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
|
||||
|
||||
# Terminal states - COMPLETE, PREP_COMPLETE, and CANCELLED have no transitions
|
||||
# FAILED allows retry transitions to resume from checkpoints
|
||||
# Terminal states - COMPLETE, PREP_COMPLETE have no transitions
|
||||
# FAILED and CANCELLED allow retry transitions to resume from checkpoints
|
||||
# PREP_COMPLETE allows finalise-only continuation
|
||||
JobStatus.COMPLETE: [],
|
||||
JobStatus.PREP_COMPLETE: [JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.FAILED], # Finalise-only continues from here
|
||||
JobStatus.FAILED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
],
|
||||
JobStatus.CANCELLED: [
|
||||
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
|
||||
JobStatus.INSTRUMENTAL_SELECTED, # Retry from video generation
|
||||
JobStatus.REVIEW_COMPLETE, # Retry from render stage
|
||||
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
|
||||
],
|
||||
JobStatus.CANCELLED: [],
|
||||
|
||||
# Legacy states (for backward compatibility)
|
||||
JobStatus.QUEUED: [JobStatus.PENDING],
|
||||
@@ -192,14 +198,25 @@ class Job(BaseModel):
|
||||
input_media_gcs_path: Optional[str] = None # GCS path to uploaded file
|
||||
|
||||
# User preferences
|
||||
enable_cdg: bool = True # Generate CDG+MP3 package
|
||||
enable_txt: bool = True # Generate TXT+MP3 package
|
||||
enable_cdg: bool = False # Generate CDG+MP3 package (requires style config)
|
||||
enable_txt: bool = False # Generate TXT+MP3 package (requires style config)
|
||||
enable_youtube_upload: bool = False # Upload to YouTube
|
||||
youtube_description: Optional[str] = None # YouTube video description
|
||||
webhook_url: Optional[str] = None # Webhook for notifications
|
||||
user_email: Optional[str] = None # Email for notifications
|
||||
|
||||
# Style configuration (uploaded files)
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
color_overrides: Dict[str, str] = Field(default_factory=dict)
|
||||
"""
|
||||
User color overrides applied on top of theme. Keys:
|
||||
- artist_color: Hex color for artist name (#RRGGBB)
|
||||
- title_color: Hex color for song title
|
||||
- sung_lyrics_color: Hex color for highlighted lyrics
|
||||
- unsung_lyrics_color: Hex color for unhighlighted lyrics
|
||||
"""
|
||||
|
||||
# Style configuration (uploaded files - used when theme_id is not set)
|
||||
style_params_gcs_path: Optional[str] = None # GCS path to style_params.json
|
||||
style_assets: Dict[str, str] = Field(default_factory=dict)
|
||||
"""
|
||||
@@ -251,6 +268,12 @@ class Job(BaseModel):
|
||||
finalise_only: bool = False # Skip prep, run only finalisation (requires uploaded prep outputs)
|
||||
keep_brand_code: Optional[str] = None # Preserve existing brand code instead of generating new one
|
||||
|
||||
# Review authentication (Batch 7)
|
||||
review_token: Optional[str] = None # Job-scoped token for lyrics review UI access (generated when entering AWAITING_REVIEW)
|
||||
review_token_expires_at: Optional[datetime] = None # Token expiry time (optional, for extra security)
|
||||
instrumental_token: Optional[str] = None # Job-scoped token for instrumental review UI access (generated when entering AWAITING_INSTRUMENTAL_SELECTION)
|
||||
instrumental_token_expires_at: Optional[datetime] = None # Token expiry time
|
||||
|
||||
# Processing state
|
||||
track_output_dir: Optional[str] = None # Local output directory (temp)
|
||||
audio_hash: Optional[str] = None # Hash for deduplication
|
||||
@@ -388,16 +411,27 @@ class JobCreate(BaseModel):
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
filename: Optional[str] = None # Original uploaded filename
|
||||
|
||||
|
||||
# Optional preferences
|
||||
enable_cdg: bool = True
|
||||
enable_txt: bool = True
|
||||
enable_cdg: bool = False # Requires style config
|
||||
enable_txt: bool = False # Requires style config
|
||||
enable_youtube_upload: bool = False
|
||||
youtube_description: Optional[str] = None
|
||||
webhook_url: Optional[str] = None
|
||||
user_email: Optional[str] = None
|
||||
|
||||
# Style configuration (will be populated after file upload)
|
||||
# Theme configuration (pre-made themes from GCS)
|
||||
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
|
||||
color_overrides: Dict[str, str] = Field(default_factory=dict)
|
||||
"""
|
||||
User color overrides applied on top of theme. Keys:
|
||||
- artist_color: Hex color for artist name (#RRGGBB)
|
||||
- title_color: Hex color for song title
|
||||
- sung_lyrics_color: Hex color for highlighted lyrics
|
||||
- unsung_lyrics_color: Hex color for unhighlighted lyrics
|
||||
"""
|
||||
|
||||
# Style configuration (will be populated after file upload, or from theme)
|
||||
style_params_gcs_path: Optional[str] = None
|
||||
style_assets: Dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ class URLSubmissionRequest(BaseModel):
|
||||
title: Optional[str] = None # Auto-detected if not provided
|
||||
|
||||
# Optional preferences
|
||||
enable_cdg: bool = True
|
||||
enable_txt: bool = True
|
||||
enable_cdg: bool = False # Requires style config
|
||||
enable_txt: bool = False # Requires style config
|
||||
enable_youtube_upload: bool = False
|
||||
youtube_description: Optional[str] = None
|
||||
webhook_url: Optional[str] = None
|
||||
@@ -24,10 +24,10 @@ class UploadSubmissionRequest(BaseModel):
|
||||
"""Request to submit a job from an uploaded file."""
|
||||
artist: str
|
||||
title: str
|
||||
|
||||
|
||||
# Optional preferences
|
||||
enable_cdg: bool = True
|
||||
enable_txt: bool = True
|
||||
enable_cdg: bool = False # Requires style config
|
||||
enable_txt: bool = False # Requires style config
|
||||
enable_youtube_upload: bool = False
|
||||
youtube_description: Optional[str] = None
|
||||
webhook_url: Optional[str] = None
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""
|
||||
Theme data models for karaoke-gen.
|
||||
|
||||
Themes are pre-created style configurations stored in GCS that users can select
|
||||
when creating karaoke jobs. Each theme includes:
|
||||
- Style parameters (fonts, colors, backgrounds, layouts)
|
||||
- Asset files (images, fonts)
|
||||
- Preview images
|
||||
- Optional YouTube description template
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ThemeSummary(BaseModel):
|
||||
"""Summary of a theme for listing purposes."""
|
||||
|
||||
id: str = Field(..., description="Unique theme identifier (e.g., 'nomad', 'default')")
|
||||
name: str = Field(..., description="Human-readable theme name")
|
||||
description: str = Field(..., description="Brief description of the theme style")
|
||||
preview_url: Optional[str] = Field(None, description="Signed URL for preview image")
|
||||
thumbnail_url: Optional[str] = Field(None, description="Signed URL for smaller thumbnail")
|
||||
is_default: bool = Field(False, description="Whether this is the default theme")
|
||||
|
||||
|
||||
class ThemeMetadata(BaseModel):
|
||||
"""Metadata for a single theme in the registry."""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
description: str
|
||||
is_default: bool = False
|
||||
created_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class ThemeRegistry(BaseModel):
|
||||
"""Registry of all available themes, stored as _metadata.json in GCS."""
|
||||
|
||||
version: int = 1
|
||||
themes: List[ThemeMetadata] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ThemeDetail(BaseModel):
|
||||
"""Full theme details including style parameters."""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
description: str
|
||||
preview_url: Optional[str] = None
|
||||
is_default: bool = False
|
||||
style_params: Dict[str, Any] = Field(default_factory=dict)
|
||||
has_youtube_description: bool = False
|
||||
|
||||
|
||||
class ColorOverrides(BaseModel):
|
||||
"""
|
||||
User-customizable color overrides that can be applied on top of a theme.
|
||||
|
||||
All colors are hex format (#RRGGBB). When applied:
|
||||
- artist_color: Applied to intro.artist_color, end.artist_color, cdg.artist_color
|
||||
- title_color: Applied to intro.title_color, end.title_color, cdg.title_color
|
||||
- sung_lyrics_color: Applied to karaoke.primary_color (converted to RGBA), cdg.active_fill
|
||||
- unsung_lyrics_color: Applied to karaoke.secondary_color (converted to RGBA), cdg.inactive_fill
|
||||
"""
|
||||
|
||||
artist_color: Optional[str] = Field(
|
||||
None,
|
||||
pattern=r"^#[0-9A-Fa-f]{6}$",
|
||||
description="Hex color for artist name on intro/end screens",
|
||||
)
|
||||
title_color: Optional[str] = Field(
|
||||
None,
|
||||
pattern=r"^#[0-9A-Fa-f]{6}$",
|
||||
description="Hex color for song title on intro/end screens",
|
||||
)
|
||||
sung_lyrics_color: Optional[str] = Field(
|
||||
None,
|
||||
pattern=r"^#[0-9A-Fa-f]{6}$",
|
||||
description="Hex color for lyrics being sung (highlighted)",
|
||||
)
|
||||
unsung_lyrics_color: Optional[str] = Field(
|
||||
None,
|
||||
pattern=r"^#[0-9A-Fa-f]{6}$",
|
||||
description="Hex color for lyrics not yet sung",
|
||||
)
|
||||
|
||||
def has_overrides(self) -> bool:
|
||||
"""Check if any color overrides are set."""
|
||||
return any(
|
||||
[
|
||||
self.artist_color,
|
||||
self.title_color,
|
||||
self.sung_lyrics_color,
|
||||
self.unsung_lyrics_color,
|
||||
]
|
||||
)
|
||||
|
||||
def to_dict(self) -> Dict[str, str]:
|
||||
"""Convert to dict, excluding None values."""
|
||||
return {k: v for k, v in self.model_dump().items() if v is not None}
|
||||
|
||||
|
||||
class ThemesListResponse(BaseModel):
|
||||
"""Response from GET /api/themes endpoint."""
|
||||
|
||||
themes: List[ThemeSummary]
|
||||
|
||||
|
||||
class ThemeDetailResponse(BaseModel):
|
||||
"""Response from GET /api/themes/{theme_id} endpoint."""
|
||||
|
||||
theme: ThemeDetail
|
||||
|
||||
|
||||
# Utility functions for color conversion
|
||||
|
||||
|
||||
def hex_to_rgba(hex_color: str, alpha: int = 255) -> str:
|
||||
"""
|
||||
Convert hex color (#RRGGBB) to RGBA format for ASS subtitles.
|
||||
|
||||
ASS subtitle format uses "R, G, B, A" string format.
|
||||
|
||||
Args:
|
||||
hex_color: Hex color string like "#7070F7"
|
||||
alpha: Alpha value 0-255 (default 255 = opaque)
|
||||
|
||||
Returns:
|
||||
RGBA string like "112, 112, 247, 255"
|
||||
"""
|
||||
hex_color = hex_color.lstrip("#")
|
||||
r = int(hex_color[0:2], 16)
|
||||
g = int(hex_color[2:4], 16)
|
||||
b = int(hex_color[4:6], 16)
|
||||
return f"{r}, {g}, {b}, {alpha}"
|
||||
|
||||
|
||||
def rgba_to_hex(rgba_str: str) -> str:
|
||||
"""
|
||||
Convert RGBA format to hex color.
|
||||
|
||||
Args:
|
||||
rgba_str: RGBA string like "112, 112, 247, 255"
|
||||
|
||||
Returns:
|
||||
Hex color string like "#7070F7"
|
||||
"""
|
||||
parts = [int(x.strip()) for x in rgba_str.split(",")]
|
||||
r, g, b = parts[0], parts[1], parts[2]
|
||||
return f"#{r:02x}{g:02x}{b:02x}"
|
||||
@@ -71,22 +71,30 @@ class AudioSearchService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
redacted_api_key: Optional[str] = _USE_ENV,
|
||||
red_api_key: Optional[str] = _USE_ENV,
|
||||
red_api_url: Optional[str] = _USE_ENV,
|
||||
ops_api_key: Optional[str] = _USE_ENV,
|
||||
ops_api_url: Optional[str] = _USE_ENV,
|
||||
):
|
||||
"""
|
||||
Initialize the audio search service.
|
||||
|
||||
Args:
|
||||
redacted_api_key: API key for Redacted tracker (optional, uses env if not provided)
|
||||
red_api_key: API key for RED tracker (optional, uses env if not provided)
|
||||
red_api_url: Base URL for RED tracker API (optional, uses env if not provided)
|
||||
ops_api_key: API key for OPS tracker (optional, uses env if not provided)
|
||||
ops_api_url: Base URL for OPS tracker API (optional, uses env if not provided)
|
||||
"""
|
||||
# Use environment variables if not explicitly provided
|
||||
if redacted_api_key is self._USE_ENV:
|
||||
redacted_api_key = os.environ.get("REDACTED_API_KEY")
|
||||
if red_api_key is self._USE_ENV:
|
||||
red_api_key = os.environ.get("RED_API_KEY")
|
||||
if red_api_url is self._USE_ENV:
|
||||
red_api_url = os.environ.get("RED_API_URL")
|
||||
|
||||
if ops_api_key is self._USE_ENV:
|
||||
ops_api_key = os.environ.get("OPS_API_KEY")
|
||||
if ops_api_url is self._USE_ENV:
|
||||
ops_api_url = os.environ.get("OPS_API_URL")
|
||||
|
||||
# Check for remote flacfetch client
|
||||
self._remote_client = get_flacfetch_client()
|
||||
@@ -99,8 +107,10 @@ class AudioSearchService:
|
||||
|
||||
# Delegate to shared FlacFetcher implementation (for local mode or fallback)
|
||||
self._fetcher = FlacFetcher(
|
||||
redacted_api_key=redacted_api_key,
|
||||
red_api_key=red_api_key,
|
||||
red_api_url=red_api_url,
|
||||
ops_api_key=ops_api_key,
|
||||
ops_api_url=ops_api_url,
|
||||
)
|
||||
|
||||
# Cache search results for API-based selection flow
|
||||
@@ -237,28 +247,32 @@ class AudioSearchService:
|
||||
output_dir: str,
|
||||
output_filename: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
remote_search_id: Optional[str] = None,
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Download audio from a cached search result.
|
||||
|
||||
|
||||
This method uses the cached results from the last search() call.
|
||||
The API flow is:
|
||||
1. Client calls search() -> gets list of results
|
||||
2. Client picks an index
|
||||
3. Client calls download(index) -> gets downloaded file
|
||||
|
||||
|
||||
If a remote flacfetch service is configured and the search was performed
|
||||
remotely (for torrent sources), uses the remote service for download.
|
||||
|
||||
|
||||
Args:
|
||||
result_index: Index of the result to download (from search results)
|
||||
output_dir: Directory to save the downloaded file
|
||||
output_filename: Optional filename (without extension)
|
||||
gcs_path: Optional GCS path for remote uploads (e.g., "uploads/job123/audio/")
|
||||
|
||||
remote_search_id: Optional search_id for remote downloads. If provided,
|
||||
uses this instead of the cached _remote_search_id. This is important
|
||||
for concurrent requests where the service-level cache may be stale.
|
||||
|
||||
Returns:
|
||||
AudioDownloadResult with the downloaded file path
|
||||
|
||||
|
||||
Raises:
|
||||
DownloadError: If download fails or no cached result for index
|
||||
"""
|
||||
@@ -268,18 +282,21 @@ class AudioSearchService:
|
||||
f"Available indices: 0-{len(self._cached_results) - 1}. "
|
||||
"Run search() first."
|
||||
)
|
||||
|
||||
|
||||
result = self._cached_results[result_index]
|
||||
|
||||
|
||||
logger.info(f"Downloading: {result.artist} - {result.title} from {result.provider}")
|
||||
|
||||
|
||||
# Use provided search_id or fall back to service-level cache
|
||||
effective_search_id = remote_search_id or self._remote_search_id
|
||||
|
||||
# Check if this was a remote search (torrent sources need remote download)
|
||||
if self._remote_search_id and self._remote_client:
|
||||
if effective_search_id and self._remote_client:
|
||||
# Check if this is a torrent source that needs remote handling
|
||||
is_torrent = result.provider in ["Redacted", "OPS"]
|
||||
|
||||
is_torrent = result.provider in ["RED", "OPS"]
|
||||
|
||||
if is_torrent:
|
||||
return self._download_remote(result_index, output_dir, output_filename, gcs_path)
|
||||
return self._download_remote(result_index, output_dir, output_filename, gcs_path, effective_search_id)
|
||||
|
||||
# Delegate to shared FlacFetcher (local download)
|
||||
fetch_result = self._fetcher.download(result, output_dir, output_filename)
|
||||
@@ -288,21 +305,182 @@ class AudioSearchService:
|
||||
|
||||
return fetch_result
|
||||
|
||||
def download_by_id(
|
||||
self,
|
||||
source_name: str,
|
||||
source_id: str,
|
||||
output_dir: str,
|
||||
output_filename: Optional[str] = None,
|
||||
target_file: Optional[str] = None,
|
||||
download_url: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Download audio directly by source ID (no prior search required).
|
||||
|
||||
This is the preferred method when you have stored the source_id from a
|
||||
previous search and want to download later without re-searching. This
|
||||
avoids unnecessary API calls to private trackers.
|
||||
|
||||
Args:
|
||||
source_name: Provider name (RED, OPS, YouTube, Spotify)
|
||||
source_id: Source-specific ID (torrent ID, video ID, track ID)
|
||||
output_dir: Directory to save the downloaded file
|
||||
output_filename: Optional filename (without extension)
|
||||
target_file: For torrents, specific file to extract from the torrent
|
||||
download_url: For YouTube/Spotify, direct URL (optional)
|
||||
gcs_path: Optional GCS path for remote uploads
|
||||
|
||||
Returns:
|
||||
AudioDownloadResult with the downloaded file path
|
||||
|
||||
Raises:
|
||||
DownloadError: If download fails
|
||||
"""
|
||||
logger.info(f"Download by ID: {source_name} ID={source_id}")
|
||||
|
||||
# For torrent sources, must use remote client
|
||||
if source_name in ["RED", "OPS"]:
|
||||
if not self._remote_client:
|
||||
raise DownloadError(
|
||||
f"Cannot download from {source_name} without remote flacfetch service"
|
||||
)
|
||||
return self._download_by_id_remote(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir=output_dir,
|
||||
output_filename=output_filename,
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_path,
|
||||
)
|
||||
|
||||
# For YouTube/Spotify, can use local flacfetch via FetchManager.download_by_id
|
||||
# But we currently only have remote support, so use remote if available
|
||||
if self._remote_client:
|
||||
return self._download_by_id_remote(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_dir=output_dir,
|
||||
output_filename=output_filename,
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_path,
|
||||
)
|
||||
|
||||
# Local download for YouTube/Spotify (fallback)
|
||||
# Use the local fetcher's download_by_id if available
|
||||
raise DownloadError(
|
||||
f"Local download_by_id not yet implemented for {source_name}. "
|
||||
"Configure FLACFETCH_API_URL for remote downloads."
|
||||
)
|
||||
|
||||
def _download_by_id_remote(
|
||||
self,
|
||||
source_name: str,
|
||||
source_id: str,
|
||||
output_dir: str, # Not used for remote downloads (files go to GCS or remote server)
|
||||
output_filename: Optional[str] = None,
|
||||
target_file: Optional[str] = None,
|
||||
download_url: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Download by ID using the remote flacfetch service.
|
||||
|
||||
Note: output_dir is accepted for API compatibility but ignored for remote
|
||||
downloads. Remote downloads either go to GCS (if gcs_path is set) or to
|
||||
the remote server's download directory.
|
||||
"""
|
||||
# output_dir is intentionally unused - remote downloads don't use local paths
|
||||
_ = output_dir
|
||||
try:
|
||||
# Enable nested event loops
|
||||
try:
|
||||
running_loop = asyncio.get_running_loop()
|
||||
nest_asyncio.apply(running_loop)
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
try:
|
||||
# Start download
|
||||
download_id = loop.run_until_complete(
|
||||
self._remote_client.download_by_id(
|
||||
source_name=source_name,
|
||||
source_id=source_id,
|
||||
output_filename=output_filename,
|
||||
target_file=target_file,
|
||||
download_url=download_url,
|
||||
gcs_path=gcs_path,
|
||||
)
|
||||
)
|
||||
|
||||
logger.info(f"Remote download by ID started: {download_id}")
|
||||
|
||||
# Wait for completion
|
||||
def log_progress(status):
|
||||
progress = status.get("progress", 0)
|
||||
speed = status.get("download_speed_kbps", 0)
|
||||
logger.debug(f"Download progress: {progress:.1f}% ({speed:.1f} KB/s)")
|
||||
|
||||
final_status = loop.run_until_complete(
|
||||
self._remote_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
progress_callback=log_progress,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
# Determine file path
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
|
||||
if not filepath:
|
||||
raise DownloadError("Remote download completed but no file path returned")
|
||||
|
||||
logger.info(f"Remote download by ID complete: {filepath}")
|
||||
|
||||
return AudioDownloadResult(
|
||||
filepath=filepath,
|
||||
artist="", # Not available without search
|
||||
title="", # Not available without search
|
||||
provider=source_name,
|
||||
quality="", # Not available without search
|
||||
)
|
||||
|
||||
except FlacfetchServiceError as e:
|
||||
raise DownloadError(f"Remote download by ID failed: {e}") from e
|
||||
except Exception as e:
|
||||
logger.error(f"Remote download by ID error: {e}")
|
||||
raise DownloadError(f"Remote download by ID failed: {e}") from e
|
||||
|
||||
def _download_remote(
|
||||
self,
|
||||
result_index: int,
|
||||
output_dir: str,
|
||||
output_filename: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
search_id: Optional[str] = None,
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Download using the remote flacfetch service.
|
||||
|
||||
|
||||
The remote service downloads via torrent and optionally uploads to GCS.
|
||||
|
||||
Args:
|
||||
result_index: Index of the result to download
|
||||
output_dir: Directory to save downloaded file
|
||||
output_filename: Optional filename
|
||||
gcs_path: Optional GCS path for remote uploads
|
||||
search_id: Remote search ID to use (overrides self._remote_search_id)
|
||||
"""
|
||||
if not self._remote_search_id:
|
||||
effective_search_id = search_id or self._remote_search_id
|
||||
if not effective_search_id:
|
||||
raise DownloadError("No remote search ID - run search() first")
|
||||
|
||||
|
||||
result = self._cached_results[result_index]
|
||||
|
||||
try:
|
||||
@@ -319,7 +497,7 @@ class AudioSearchService:
|
||||
# Start download
|
||||
download_id = loop.run_until_complete(
|
||||
self._remote_client.download(
|
||||
search_id=self._remote_search_id,
|
||||
search_id=effective_search_id,
|
||||
result_index=result_index,
|
||||
output_filename=output_filename,
|
||||
gcs_path=gcs_path,
|
||||
@@ -424,22 +602,54 @@ class AudioSearchService:
|
||||
output_dir: str,
|
||||
output_filename: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
remote_search_id: Optional[str] = None,
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Async version of download for use in async routes.
|
||||
|
||||
|
||||
Note: Currently wraps sync download in executor. Future optimization
|
||||
could make this fully async.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self.download(result_index, output_dir, output_filename, gcs_path)
|
||||
None,
|
||||
lambda: self.download(result_index, output_dir, output_filename, gcs_path, remote_search_id)
|
||||
)
|
||||
|
||||
async def download_by_id_async(
|
||||
self,
|
||||
source_name: str,
|
||||
source_id: str,
|
||||
output_dir: str,
|
||||
output_filename: Optional[str] = None,
|
||||
target_file: Optional[str] = None,
|
||||
download_url: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
) -> AudioDownloadResult:
|
||||
"""
|
||||
Async version of download_by_id for use in async routes.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self.download_by_id(
|
||||
source_name, source_id, output_dir, output_filename,
|
||||
target_file, download_url, gcs_path
|
||||
)
|
||||
)
|
||||
|
||||
def is_remote_enabled(self) -> bool:
|
||||
"""Check if remote flacfetch service is configured."""
|
||||
return self._remote_client is not None
|
||||
|
||||
@property
|
||||
def last_remote_search_id(self) -> Optional[str]:
|
||||
"""Get the search_id from the last remote search.
|
||||
|
||||
This should be stored in job state_data after search and passed
|
||||
back to download() to ensure correct remote download handling.
|
||||
"""
|
||||
return self._remote_search_id
|
||||
|
||||
async def check_remote_health(self) -> Optional[dict]:
|
||||
"""
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Client for the remote flacfetch HTTP API service.
|
||||
|
||||
This client communicates with a dedicated flacfetch VM that handles:
|
||||
- BitTorrent downloads from private trackers (Redacted, OPS)
|
||||
- BitTorrent downloads from private trackers (RED, OPS)
|
||||
- YouTube downloads
|
||||
- GCS uploads of downloaded files
|
||||
|
||||
@@ -199,6 +199,67 @@ class FlacfetchClient:
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Download start failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
async def download_by_id(
|
||||
self,
|
||||
source_name: str,
|
||||
source_id: str,
|
||||
output_filename: Optional[str] = None,
|
||||
target_file: Optional[str] = None,
|
||||
download_url: Optional[str] = None,
|
||||
gcs_path: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Start downloading directly by source ID (no prior search required).
|
||||
|
||||
This is useful when you have stored the source_id from a previous search
|
||||
and want to download later without re-searching.
|
||||
|
||||
Args:
|
||||
source_name: Provider name (RED, OPS, YouTube, Spotify)
|
||||
source_id: Source-specific ID (torrent ID, video ID, track ID)
|
||||
output_filename: Optional custom filename (without extension)
|
||||
target_file: For torrents, specific file to extract
|
||||
download_url: For YouTube/Spotify, direct URL (optional)
|
||||
gcs_path: GCS path for upload (e.g., "uploads/job123/audio/")
|
||||
|
||||
Returns:
|
||||
Download ID for tracking progress
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On download start failure
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
payload = {
|
||||
"source_name": source_name,
|
||||
"source_id": source_id,
|
||||
}
|
||||
if output_filename:
|
||||
payload["output_filename"] = output_filename
|
||||
if target_file:
|
||||
payload["target_file"] = target_file
|
||||
if download_url:
|
||||
payload["download_url"] = download_url
|
||||
if gcs_path:
|
||||
payload["upload_to_gcs"] = True
|
||||
payload["gcs_path"] = gcs_path
|
||||
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/download-by-id",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
data = resp.json()
|
||||
return data["download_id"]
|
||||
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Download by ID request failed: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Download by ID failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
async def get_download_status(self, download_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get the current status of a download.
|
||||
|
||||
@@ -53,8 +53,19 @@ class JobManager:
|
||||
enable_txt=job_create.enable_txt,
|
||||
enable_youtube_upload=job_create.enable_youtube_upload,
|
||||
youtube_description=job_create.youtube_description,
|
||||
youtube_description_template=job_create.youtube_description_template, # video_worker reads this
|
||||
webhook_url=job_create.webhook_url,
|
||||
user_email=job_create.user_email,
|
||||
# Distribution settings
|
||||
brand_prefix=job_create.brand_prefix,
|
||||
discord_webhook_url=job_create.discord_webhook_url,
|
||||
dropbox_path=job_create.dropbox_path,
|
||||
gdrive_folder_id=job_create.gdrive_folder_id,
|
||||
# Theme configuration
|
||||
theme_id=job_create.theme_id,
|
||||
color_overrides=job_create.color_overrides,
|
||||
style_params_gcs_path=job_create.style_params_gcs_path,
|
||||
style_assets=job_create.style_assets,
|
||||
# Two-phase workflow (Batch 6)
|
||||
prep_only=job_create.prep_only,
|
||||
finalise_only=job_create.finalise_only,
|
||||
@@ -280,6 +291,24 @@ class JobManager:
|
||||
if progress is not None:
|
||||
updates['progress'] = progress
|
||||
|
||||
# Generate review token when entering AWAITING_REVIEW state
|
||||
if new_status == JobStatus.AWAITING_REVIEW:
|
||||
from backend.api.dependencies import generate_review_token, get_review_token_expiry
|
||||
review_token = generate_review_token()
|
||||
review_token_expires = get_review_token_expiry(hours=48) # 48 hour expiry
|
||||
updates['review_token'] = review_token
|
||||
updates['review_token_expires_at'] = review_token_expires
|
||||
logger.info(f"Generated review token for job {job_id}, expires in 48 hours")
|
||||
|
||||
# Generate instrumental token when entering AWAITING_INSTRUMENTAL_SELECTION state
|
||||
if new_status == JobStatus.AWAITING_INSTRUMENTAL_SELECTION:
|
||||
from backend.api.dependencies import generate_review_token, get_review_token_expiry
|
||||
instrumental_token = generate_review_token() # Reuse same token generator
|
||||
instrumental_token_expires = get_review_token_expiry(hours=48) # 48 hour expiry
|
||||
updates['instrumental_token'] = instrumental_token
|
||||
updates['instrumental_token_expires_at'] = instrumental_token_expires
|
||||
logger.info(f"Generated instrumental token for job {job_id}, expires in 48 hours")
|
||||
|
||||
# If we have state_data_updates, merge them with existing state_data
|
||||
merged_state_data = None
|
||||
if state_data_updates:
|
||||
@@ -304,6 +333,20 @@ class JobManager:
|
||||
message=message
|
||||
)
|
||||
|
||||
# Apply review token update separately if generated
|
||||
if new_status == JobStatus.AWAITING_REVIEW and 'review_token' in updates:
|
||||
self.firestore.update_job(job_id, {
|
||||
'review_token': updates['review_token'],
|
||||
'review_token_expires_at': updates['review_token_expires_at']
|
||||
})
|
||||
|
||||
# Apply instrumental token update separately if generated
|
||||
if new_status == JobStatus.AWAITING_INSTRUMENTAL_SELECTION and 'instrumental_token' in updates:
|
||||
self.firestore.update_job(job_id, {
|
||||
'instrumental_token': updates['instrumental_token'],
|
||||
'instrumental_token_expires_at': updates['instrumental_token_expires_at']
|
||||
})
|
||||
|
||||
logger.info(f"Job {job_id} transitioned to {new_status}")
|
||||
return True
|
||||
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
"""
|
||||
Theme service for managing pre-created style themes.
|
||||
|
||||
Themes are stored in GCS at themes/{theme_id}/ with:
|
||||
- style_params.json: Complete style configuration
|
||||
- preview.png: Preview image for theme selection UI
|
||||
- youtube_description.txt: Optional YouTube description template
|
||||
- assets/: Fonts, backgrounds, and other assets
|
||||
|
||||
The service provides:
|
||||
- Theme listing with signed preview URLs
|
||||
- Theme detail retrieval
|
||||
- Color override application
|
||||
- Job style preparation (copying theme to job folder)
|
||||
"""
|
||||
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from backend.models.theme import (
|
||||
ColorOverrides,
|
||||
ThemeDetail,
|
||||
ThemeMetadata,
|
||||
ThemeRegistry,
|
||||
ThemeSummary,
|
||||
hex_to_rgba,
|
||||
)
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# GCS paths for themes
|
||||
THEMES_PREFIX = "themes"
|
||||
METADATA_FILE = f"{THEMES_PREFIX}/_metadata.json"
|
||||
|
||||
|
||||
class ThemeService:
|
||||
"""Service for managing themes from GCS."""
|
||||
|
||||
def __init__(self, storage: Optional[StorageService] = None):
|
||||
"""
|
||||
Initialize the theme service.
|
||||
|
||||
Args:
|
||||
storage: StorageService instance (creates new one if not provided)
|
||||
"""
|
||||
self.storage = storage or StorageService()
|
||||
self._metadata_cache: Optional[ThemeRegistry] = None
|
||||
self._cache_time: Optional[datetime] = None
|
||||
self.CACHE_TTL_SECONDS = 300 # 5 minute cache for theme metadata
|
||||
|
||||
def _get_theme_path(self, theme_id: str, filename: str = "") -> str:
|
||||
"""Get the GCS path for a theme file."""
|
||||
if filename:
|
||||
return f"{THEMES_PREFIX}/{theme_id}/{filename}"
|
||||
return f"{THEMES_PREFIX}/{theme_id}"
|
||||
|
||||
def _is_cache_valid(self) -> bool:
|
||||
"""Check if the metadata cache is still valid."""
|
||||
if self._metadata_cache is None or self._cache_time is None:
|
||||
return False
|
||||
age = datetime.now() - self._cache_time
|
||||
return age.total_seconds() < self.CACHE_TTL_SECONDS
|
||||
|
||||
def _load_metadata(self, force_refresh: bool = False) -> ThemeRegistry:
|
||||
"""
|
||||
Load theme metadata from GCS with caching.
|
||||
|
||||
Args:
|
||||
force_refresh: Force reload from GCS even if cache is valid
|
||||
|
||||
Returns:
|
||||
ThemeRegistry containing all theme metadata
|
||||
"""
|
||||
if not force_refresh and self._is_cache_valid():
|
||||
return self._metadata_cache # type: ignore
|
||||
|
||||
try:
|
||||
data = self.storage.download_json(METADATA_FILE)
|
||||
self._metadata_cache = ThemeRegistry(**data)
|
||||
self._cache_time = datetime.now()
|
||||
logger.info(f"Loaded theme metadata: {len(self._metadata_cache.themes)} themes")
|
||||
return self._metadata_cache
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load theme metadata: {e}")
|
||||
# Return empty registry on error
|
||||
return ThemeRegistry(version=1, themes=[])
|
||||
|
||||
def list_themes(self) -> List[ThemeSummary]:
|
||||
"""
|
||||
List all available themes with signed preview URLs.
|
||||
|
||||
Returns:
|
||||
List of ThemeSummary objects with preview URLs
|
||||
"""
|
||||
metadata = self._load_metadata()
|
||||
summaries = []
|
||||
|
||||
for theme in metadata.themes:
|
||||
try:
|
||||
# Generate signed URLs for preview images
|
||||
preview_path = self._get_theme_path(theme.id, "preview.png")
|
||||
thumbnail_path = self._get_theme_path(theme.id, "preview_thumbnail.png")
|
||||
|
||||
preview_url = None
|
||||
thumbnail_url = None
|
||||
|
||||
if self.storage.file_exists(preview_path):
|
||||
preview_url = self.storage.generate_signed_url(preview_path, expiration_minutes=60)
|
||||
|
||||
# Try thumbnail, fall back to main preview
|
||||
if self.storage.file_exists(thumbnail_path):
|
||||
thumbnail_url = self.storage.generate_signed_url(thumbnail_path, expiration_minutes=60)
|
||||
elif preview_url:
|
||||
thumbnail_url = preview_url
|
||||
|
||||
summaries.append(
|
||||
ThemeSummary(
|
||||
id=theme.id,
|
||||
name=theme.name,
|
||||
description=theme.description,
|
||||
preview_url=preview_url,
|
||||
thumbnail_url=thumbnail_url,
|
||||
is_default=theme.is_default,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Error processing theme {theme.id}: {e}")
|
||||
# Still include theme but without preview URLs
|
||||
summaries.append(
|
||||
ThemeSummary(
|
||||
id=theme.id,
|
||||
name=theme.name,
|
||||
description=theme.description,
|
||||
is_default=theme.is_default,
|
||||
)
|
||||
)
|
||||
|
||||
return summaries
|
||||
|
||||
def get_theme(self, theme_id: str) -> Optional[ThemeDetail]:
|
||||
"""
|
||||
Get full theme details including style parameters.
|
||||
|
||||
Args:
|
||||
theme_id: The theme identifier
|
||||
|
||||
Returns:
|
||||
ThemeDetail if found, None otherwise
|
||||
"""
|
||||
metadata = self._load_metadata()
|
||||
|
||||
# Find theme in metadata
|
||||
theme_meta = next((t for t in metadata.themes if t.id == theme_id), None)
|
||||
if not theme_meta:
|
||||
logger.warning(f"Theme not found: {theme_id}")
|
||||
return None
|
||||
|
||||
try:
|
||||
# Load style_params.json
|
||||
style_params_path = self._get_theme_path(theme_id, "style_params.json")
|
||||
style_params = self.storage.download_json(style_params_path)
|
||||
|
||||
# Check for YouTube description
|
||||
youtube_desc_path = self._get_theme_path(theme_id, "youtube_description.txt")
|
||||
has_youtube_desc = self.storage.file_exists(youtube_desc_path)
|
||||
|
||||
# Generate preview URL
|
||||
preview_path = self._get_theme_path(theme_id, "preview.png")
|
||||
preview_url = None
|
||||
if self.storage.file_exists(preview_path):
|
||||
preview_url = self.storage.generate_signed_url(preview_path, expiration_minutes=60)
|
||||
|
||||
return ThemeDetail(
|
||||
id=theme_id,
|
||||
name=theme_meta.name,
|
||||
description=theme_meta.description,
|
||||
preview_url=preview_url,
|
||||
is_default=theme_meta.is_default,
|
||||
style_params=style_params,
|
||||
has_youtube_description=has_youtube_desc,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error loading theme {theme_id}: {e}")
|
||||
return None
|
||||
|
||||
def get_theme_style_params(self, theme_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Get just the style_params.json for a theme.
|
||||
|
||||
Args:
|
||||
theme_id: The theme identifier
|
||||
|
||||
Returns:
|
||||
Style parameters dict if found, None otherwise
|
||||
"""
|
||||
try:
|
||||
style_params_path = self._get_theme_path(theme_id, "style_params.json")
|
||||
return self.storage.download_json(style_params_path)
|
||||
except Exception as e:
|
||||
logger.error(f"Error loading style params for theme {theme_id}: {e}")
|
||||
return None
|
||||
|
||||
def get_youtube_description(self, theme_id: str) -> Optional[str]:
|
||||
"""
|
||||
Get the YouTube description template for a theme.
|
||||
|
||||
Args:
|
||||
theme_id: The theme identifier
|
||||
|
||||
Returns:
|
||||
YouTube description text if found, None otherwise
|
||||
"""
|
||||
try:
|
||||
youtube_desc_path = self._get_theme_path(theme_id, "youtube_description.txt")
|
||||
if not self.storage.file_exists(youtube_desc_path):
|
||||
return None
|
||||
|
||||
# Download to temp file and read
|
||||
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as tmp:
|
||||
tmp_path = tmp.name
|
||||
|
||||
try:
|
||||
self.storage.download_file(youtube_desc_path, tmp_path)
|
||||
with open(tmp_path, "r") as f:
|
||||
return f.read()
|
||||
finally:
|
||||
if os.path.exists(tmp_path):
|
||||
os.remove(tmp_path)
|
||||
except Exception as e:
|
||||
logger.error(f"Error loading YouTube description for theme {theme_id}: {e}")
|
||||
return None
|
||||
|
||||
def apply_color_overrides(
|
||||
self, style_params: Dict[str, Any], overrides: ColorOverrides
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Apply user color overrides to theme style parameters.
|
||||
|
||||
Args:
|
||||
style_params: Base style parameters from theme
|
||||
overrides: User color overrides
|
||||
|
||||
Returns:
|
||||
Modified style parameters with overrides applied
|
||||
"""
|
||||
if not overrides.has_overrides():
|
||||
return style_params
|
||||
|
||||
# Deep copy to avoid modifying original
|
||||
result = copy.deepcopy(style_params)
|
||||
|
||||
# Apply artist_color to intro, end, and CDG sections
|
||||
if overrides.artist_color:
|
||||
if "intro" in result:
|
||||
result["intro"]["artist_color"] = overrides.artist_color
|
||||
if "end" in result:
|
||||
result["end"]["artist_color"] = overrides.artist_color
|
||||
if "cdg" in result:
|
||||
result["cdg"]["artist_color"] = overrides.artist_color
|
||||
|
||||
# Apply title_color to intro, end, and CDG sections
|
||||
if overrides.title_color:
|
||||
if "intro" in result:
|
||||
result["intro"]["title_color"] = overrides.title_color
|
||||
if "end" in result:
|
||||
result["end"]["title_color"] = overrides.title_color
|
||||
if "cdg" in result:
|
||||
result["cdg"]["title_color"] = overrides.title_color
|
||||
|
||||
# Apply sung_lyrics_color (karaoke uses RGBA, CDG uses hex)
|
||||
if overrides.sung_lyrics_color:
|
||||
if "karaoke" in result:
|
||||
result["karaoke"]["primary_color"] = hex_to_rgba(overrides.sung_lyrics_color)
|
||||
if "cdg" in result:
|
||||
result["cdg"]["active_fill"] = overrides.sung_lyrics_color
|
||||
|
||||
# Apply unsung_lyrics_color (karaoke uses RGBA, CDG uses hex)
|
||||
if overrides.unsung_lyrics_color:
|
||||
if "karaoke" in result:
|
||||
result["karaoke"]["secondary_color"] = hex_to_rgba(overrides.unsung_lyrics_color)
|
||||
if "cdg" in result:
|
||||
result["cdg"]["inactive_fill"] = overrides.unsung_lyrics_color
|
||||
|
||||
return result
|
||||
|
||||
def prepare_job_style(
|
||||
self,
|
||||
job_id: str,
|
||||
theme_id: str,
|
||||
color_overrides: Optional[ColorOverrides] = None,
|
||||
) -> Tuple[str, Dict[str, str]]:
|
||||
"""
|
||||
Prepare style files for a job by copying theme to job folder.
|
||||
|
||||
This method:
|
||||
1. Loads the theme's style_params.json
|
||||
2. Applies any color overrides
|
||||
3. Updates asset paths to point to theme assets (shared, not copied)
|
||||
4. Uploads modified style_params.json to job folder
|
||||
5. Returns the GCS path and style_assets mapping
|
||||
|
||||
Args:
|
||||
job_id: The job ID
|
||||
theme_id: The theme to use
|
||||
color_overrides: Optional color overrides
|
||||
|
||||
Returns:
|
||||
Tuple of (style_params_gcs_path, style_assets dict)
|
||||
|
||||
Raises:
|
||||
ValueError: If theme not found
|
||||
"""
|
||||
# Load theme style params
|
||||
style_params = self.get_theme_style_params(theme_id)
|
||||
if style_params is None:
|
||||
raise ValueError(f"Theme not found: {theme_id}")
|
||||
|
||||
# Apply color overrides if provided
|
||||
if color_overrides:
|
||||
style_params = self.apply_color_overrides(style_params, color_overrides)
|
||||
|
||||
# Update asset paths to point to theme's shared assets
|
||||
# Theme assets stay in themes/{theme_id}/assets/ - they're shared
|
||||
style_assets = self._build_style_assets_mapping(theme_id, style_params)
|
||||
|
||||
# Update style_params to use theme asset paths (not job-specific)
|
||||
style_params = self._update_asset_paths_in_style(theme_id, style_params)
|
||||
|
||||
# Upload modified style_params.json to job's style folder
|
||||
job_style_path = f"uploads/{job_id}/style/style_params.json"
|
||||
self.storage.upload_json(job_style_path, style_params)
|
||||
|
||||
logger.info(f"Prepared job {job_id} style from theme {theme_id}")
|
||||
|
||||
return job_style_path, style_assets
|
||||
|
||||
def _build_style_assets_mapping(
|
||||
self, theme_id: str, style_params: Dict[str, Any]
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
Build the style_assets mapping for a theme.
|
||||
|
||||
Maps asset keys to their GCS paths in the theme folder.
|
||||
"""
|
||||
style_assets = {}
|
||||
theme_assets_prefix = f"{THEMES_PREFIX}/{theme_id}/assets"
|
||||
|
||||
# Check each potential asset type
|
||||
asset_checks = [
|
||||
("intro_background", "intro", "background_image"),
|
||||
("karaoke_background", "karaoke", "background_image"),
|
||||
("end_background", "end", "background_image"),
|
||||
("font", "intro", "font"), # Font is typically shared across sections
|
||||
("cdg_instrumental_background", "cdg", "instrumental_background"),
|
||||
("cdg_title_background", "cdg", "title_screen_background"),
|
||||
("cdg_outro_background", "cdg", "outro_background"),
|
||||
]
|
||||
|
||||
for asset_key, section, field in asset_checks:
|
||||
if section in style_params and field in style_params[section]:
|
||||
value = style_params[section][field]
|
||||
if value and isinstance(value, str):
|
||||
# Check if it's a theme asset path or already has the full path
|
||||
if value.startswith(f"{THEMES_PREFIX}/"):
|
||||
# Already a full theme path
|
||||
style_assets[asset_key] = value
|
||||
elif not value.startswith("/") and not value.startswith("gs://"):
|
||||
# Relative path - prepend theme assets prefix
|
||||
asset_path = f"{theme_assets_prefix}/{os.path.basename(value)}"
|
||||
if self.storage.file_exists(asset_path):
|
||||
style_assets[asset_key] = asset_path
|
||||
|
||||
return style_assets
|
||||
|
||||
def _update_asset_paths_in_style(
|
||||
self, theme_id: str, style_params: Dict[str, Any]
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Update asset paths in style_params to use full GCS theme paths.
|
||||
|
||||
This ensures the style_loader can find assets when processing.
|
||||
"""
|
||||
result = copy.deepcopy(style_params)
|
||||
theme_assets_prefix = f"{THEMES_PREFIX}/{theme_id}/assets"
|
||||
|
||||
# Fields that contain asset paths
|
||||
path_fields = {
|
||||
"intro": ["background_image", "font"],
|
||||
"end": ["background_image", "font"],
|
||||
"karaoke": ["background_image", "font_path"],
|
||||
"cdg": [
|
||||
"font_path",
|
||||
"instrumental_background",
|
||||
"title_screen_background",
|
||||
"outro_background",
|
||||
],
|
||||
}
|
||||
|
||||
for section, fields in path_fields.items():
|
||||
if section not in result:
|
||||
continue
|
||||
for field in fields:
|
||||
if field not in result[section]:
|
||||
continue
|
||||
value = result[section][field]
|
||||
if value and isinstance(value, str):
|
||||
# Skip if already a full path or URL
|
||||
if value.startswith(f"{THEMES_PREFIX}/") or value.startswith("gs://"):
|
||||
continue
|
||||
# Skip absolute local paths (shouldn't happen but be safe)
|
||||
if value.startswith("/"):
|
||||
continue
|
||||
# Update to full theme asset path
|
||||
result[section][field] = f"{theme_assets_prefix}/{os.path.basename(value)}"
|
||||
|
||||
return result
|
||||
|
||||
def theme_exists(self, theme_id: str) -> bool:
|
||||
"""
|
||||
Check if a theme exists.
|
||||
|
||||
Args:
|
||||
theme_id: The theme identifier
|
||||
|
||||
Returns:
|
||||
True if theme exists, False otherwise
|
||||
"""
|
||||
metadata = self._load_metadata()
|
||||
return any(t.id == theme_id for t in metadata.themes)
|
||||
|
||||
def get_default_theme_id(self) -> Optional[str]:
|
||||
"""
|
||||
Get the ID of the default theme.
|
||||
|
||||
Returns:
|
||||
Default theme ID if one exists, None otherwise
|
||||
"""
|
||||
metadata = self._load_metadata()
|
||||
default_theme = next((t for t in metadata.themes if t.is_default), None)
|
||||
return default_theme.id if default_theme else None
|
||||
|
||||
def invalidate_cache(self) -> None:
|
||||
"""Force invalidation of the metadata cache."""
|
||||
self._metadata_cache = None
|
||||
self._cache_time = None
|
||||
logger.info("Theme metadata cache invalidated")
|
||||
|
||||
|
||||
# Singleton instance with thread-safe initialization
|
||||
_theme_service: Optional[ThemeService] = None
|
||||
_theme_service_lock = threading.Lock()
|
||||
|
||||
|
||||
def get_theme_service() -> ThemeService:
|
||||
"""Get or create the singleton ThemeService instance (thread-safe)."""
|
||||
global _theme_service
|
||||
if _theme_service is None:
|
||||
with _theme_service_lock:
|
||||
# Double-check after acquiring lock
|
||||
if _theme_service is None:
|
||||
_theme_service = ThemeService()
|
||||
return _theme_service
|
||||
@@ -218,12 +218,15 @@ class WorkerService:
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
# Add admin auth header if available
|
||||
# This is needed for the internal endpoint's require_admin dependency
|
||||
# Add admin auth via custom header
|
||||
# NOTE: We use X-Admin-Token instead of Authorization because Cloud Tasks
|
||||
# OIDC token overwrites the Authorization header when oidc_token is specified.
|
||||
# The OIDC token handles Cloud Run authentication (allows Cloud Tasks to invoke
|
||||
# the service), while X-Admin-Token handles application-level authentication.
|
||||
if self._admin_token:
|
||||
headers["Authorization"] = f"Bearer {self._admin_token}"
|
||||
headers["X-Admin-Token"] = self._admin_token
|
||||
logger.debug(
|
||||
f"[job:{job_id}] Using admin token for Cloud Task auth, "
|
||||
f"[job:{job_id}] Using admin token for Cloud Task auth via X-Admin-Token, "
|
||||
f"token prefix: {self._admin_token[:8]}..., len={len(self._admin_token)}"
|
||||
)
|
||||
|
||||
|
||||
+104
-4
@@ -12,13 +12,19 @@ from unittest.mock import Mock, MagicMock, AsyncMock, patch
|
||||
from datetime import datetime, UTC
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
# Mock google.auth.default for unit tests if not using emulator
|
||||
# This prevents DefaultCredentialsError during imports
|
||||
# Mock google.auth.default AND firestore for unit tests if not using emulator
|
||||
# This prevents DefaultCredentialsError and FirestoreClient initialization during imports
|
||||
if 'FIRESTORE_EMULATOR_HOST' not in os.environ:
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
# Only mock the default() function, not the entire module
|
||||
# This allows other google.auth imports to work normally
|
||||
# Set up test environment variables BEFORE importing any backend modules
|
||||
os.environ.setdefault('ADMIN_TOKENS', 'test-admin-token')
|
||||
os.environ.setdefault('GOOGLE_CLOUD_PROJECT', 'test-project')
|
||||
os.environ.setdefault('GCS_BUCKET_NAME', 'test-bucket')
|
||||
os.environ.setdefault('FIRESTORE_COLLECTION', 'jobs')
|
||||
os.environ.setdefault('ENVIRONMENT', 'test')
|
||||
|
||||
# Mock google.auth.default - prevents credential errors
|
||||
try:
|
||||
import google.auth
|
||||
mock_credentials = MagicMock()
|
||||
@@ -30,10 +36,104 @@ if 'FIRESTORE_EMULATOR_HOST' not in os.environ:
|
||||
except ImportError:
|
||||
# If google.auth not installed, that's ok for some tests
|
||||
pass
|
||||
|
||||
# Mock google.cloud.firestore.Client - prevents Firestore initialization
|
||||
# This is CRITICAL: when AuthService is instantiated, it creates FirestoreService
|
||||
# which tries to create a real Firestore client. The client returns MagicMocks
|
||||
# which fail when used as enum values (e.g., UserType).
|
||||
try:
|
||||
import google.cloud.firestore as firestore_module
|
||||
|
||||
# Create a mock client that returns proper values for get_token
|
||||
mock_firestore_client = MagicMock()
|
||||
mock_collection = MagicMock()
|
||||
mock_doc = MagicMock()
|
||||
mock_snapshot = MagicMock()
|
||||
|
||||
# For auth token lookups, return None (token not found in Firestore)
|
||||
# This forces validation to use admin tokens from environment
|
||||
mock_snapshot.exists = False
|
||||
mock_snapshot.to_dict.return_value = None
|
||||
mock_doc.get.return_value = mock_snapshot
|
||||
mock_collection.document.return_value = mock_doc
|
||||
mock_firestore_client.collection.return_value = mock_collection
|
||||
|
||||
# Replace the Client class
|
||||
original_client = firestore_module.Client
|
||||
firestore_module.Client = MagicMock(return_value=mock_firestore_client)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Mock google.cloud.storage.Client - prevents GCS initialization
|
||||
try:
|
||||
import google.cloud.storage as storage_module
|
||||
mock_storage_client = MagicMock()
|
||||
mock_bucket = MagicMock()
|
||||
mock_storage_client.bucket.return_value = mock_bucket
|
||||
storage_module.Client = MagicMock(return_value=mock_storage_client)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
from backend.models.job import Job, JobStatus, JobCreate
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_auth_dependency(request):
|
||||
"""Mock the require_auth dependency for all tests using FastAPI's dependency override system."""
|
||||
# Skip for emulator tests and integration tests which use real auth
|
||||
test_path = str(request.fspath)
|
||||
if 'emulator' in test_path or 'integration' in test_path:
|
||||
yield
|
||||
return
|
||||
|
||||
# Skip if FIRESTORE_EMULATOR_HOST is set (running in emulator environment)
|
||||
import os
|
||||
if os.environ.get('FIRESTORE_EMULATOR_HOST'):
|
||||
yield
|
||||
return
|
||||
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.api.dependencies import require_auth, require_admin, require_review_auth, require_instrumental_auth
|
||||
from backend.main import app
|
||||
|
||||
# Create mock auth functions
|
||||
async def mock_require_auth():
|
||||
"""Mock require_auth to always return valid admin credentials."""
|
||||
return ("test-admin-token", UserType.ADMIN, 999)
|
||||
|
||||
async def mock_require_admin():
|
||||
"""Mock require_admin to always return valid admin credentials."""
|
||||
return ("test-admin-token", UserType.ADMIN, 999)
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
"""Mock require_review_auth to always return valid review access."""
|
||||
return (job_id, "full")
|
||||
|
||||
async def mock_require_instrumental_auth(job_id: str = "test123"):
|
||||
"""Mock require_instrumental_auth to always return valid instrumental review access."""
|
||||
return (job_id, "full")
|
||||
|
||||
# Use FastAPI's dependency override system
|
||||
app.dependency_overrides[require_auth] = mock_require_auth
|
||||
app.dependency_overrides[require_admin] = mock_require_admin
|
||||
app.dependency_overrides[require_review_auth] = mock_require_review_auth
|
||||
app.dependency_overrides[require_instrumental_auth] = mock_require_instrumental_auth
|
||||
|
||||
yield
|
||||
|
||||
# Clean up after test
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers():
|
||||
"""Get authentication headers for test requests."""
|
||||
return {
|
||||
"Authorization": "Bearer test-admin-token",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_firestore():
|
||||
"""Mock Firestore client for unit tests."""
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -27,15 +27,15 @@ pytestmark = pytest.mark.skipif(
|
||||
class TestEmulatorBasics:
|
||||
"""Basic emulator connectivity tests."""
|
||||
|
||||
def test_health_endpoint(self, client):
|
||||
def test_health_endpoint(self, client, auth_headers):
|
||||
"""Test health endpoint works."""
|
||||
response = client.get("/api/health")
|
||||
response = client.get("/api/health", )
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "healthy"
|
||||
|
||||
def test_root_endpoint(self, client):
|
||||
def test_root_endpoint(self, client, auth_headers):
|
||||
"""Test root endpoint works."""
|
||||
response = client.get("/")
|
||||
response = client.get("/", )
|
||||
assert response.status_code == 200
|
||||
assert response.json()["service"] == "karaoke-gen-backend"
|
||||
|
||||
@@ -281,13 +281,13 @@ class TestReviewEndpoints:
|
||||
time.sleep(0.2)
|
||||
|
||||
# Should fail - job not in AWAITING_REVIEW status
|
||||
response = client.get(f"/api/review/{job_id}/correction-data")
|
||||
response = client.get(f"/api/review/{job_id}/correction-data", headers=auth_headers)
|
||||
assert response.status_code == 400
|
||||
assert "not ready for review" in response.json()["detail"].lower()
|
||||
|
||||
def test_review_audio_no_job(self, client):
|
||||
def test_review_audio_no_job(self, client, auth_headers):
|
||||
"""Test audio endpoint returns 404 for nonexistent job."""
|
||||
response = client.get("/api/review/nonexistent-job/audio/")
|
||||
response = client.get("/api/review/nonexistent-job/audio/", headers=auth_headers)
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_review_preview_video_stub(self, client, auth_headers):
|
||||
@@ -303,6 +303,7 @@ class TestReviewEndpoints:
|
||||
# Preview video should return error since job not ready
|
||||
response = client.post(
|
||||
f"/api/review/{job_id}/preview-video",
|
||||
headers=auth_headers,
|
||||
json={"corrections": [], "corrected_segments": []}
|
||||
)
|
||||
# Should return 400 (job not in AWAITING_REVIEW state)
|
||||
@@ -320,6 +321,7 @@ class TestReviewEndpoints:
|
||||
# Annotations endpoint should accept data (even if it just logs it)
|
||||
response = client.post(
|
||||
f"/api/review/{job_id}/v1/annotations",
|
||||
headers=auth_headers,
|
||||
json={"type": "test", "data": "test annotation"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
@@ -328,7 +330,7 @@ class TestReviewEndpoints:
|
||||
|
||||
class TestRenderVideoWorker:
|
||||
"""Test render video worker endpoint."""
|
||||
|
||||
|
||||
def test_render_video_worker_endpoint_exists(self, client, auth_headers):
|
||||
"""Test that render-video worker endpoint exists."""
|
||||
# Create a job
|
||||
@@ -338,9 +340,9 @@ class TestRenderVideoWorker:
|
||||
json={"url": "https://youtube.com/watch?v=render-test"}
|
||||
)
|
||||
job_id = create_resp.json()["job_id"]
|
||||
|
||||
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
# Test render-video worker endpoint exists
|
||||
response = client.post(
|
||||
"/api/internal/workers/render-video",
|
||||
|
||||
@@ -28,20 +28,20 @@ class TestHealthRoutes:
|
||||
from backend.main import app
|
||||
return TestClient(app)
|
||||
|
||||
def test_health_endpoint_returns_200(self, client):
|
||||
def test_health_endpoint_returns_200(self, client, auth_headers):
|
||||
"""Test /api/health returns 200 OK."""
|
||||
response = client.get("/api/health")
|
||||
response = client.get("/api/health", )
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_health_endpoint_returns_healthy_status(self, client):
|
||||
def test_health_endpoint_returns_healthy_status(self, client, auth_headers):
|
||||
"""Test health endpoint returns healthy status."""
|
||||
response = client.get("/api/health")
|
||||
response = client.get("/api/health", )
|
||||
data = response.json()
|
||||
assert data["status"] == "healthy"
|
||||
|
||||
def test_root_endpoint_returns_200(self, client):
|
||||
def test_root_endpoint_returns_200(self, client, auth_headers):
|
||||
"""Test root endpoint returns 200."""
|
||||
response = client.get("/")
|
||||
response = client.get("/", )
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
|
||||
@@ -69,6 +69,78 @@ class TestJobModelAudioSearchFields:
|
||||
assert job_create.auto_download is True
|
||||
|
||||
|
||||
class TestYouTubeFieldMapping:
|
||||
"""Test YouTube description field mapping between API and workers.
|
||||
|
||||
CRITICAL: This test class exists because we had a bug where:
|
||||
- The audio_search API endpoint set `youtube_description`
|
||||
- But video_worker.py reads `youtube_description_template`
|
||||
|
||||
These tests ensure both fields are properly set so YouTube uploads work.
|
||||
"""
|
||||
|
||||
def test_job_has_both_youtube_description_fields(self):
|
||||
"""Test Job model has both youtube_description and youtube_description_template."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
enable_youtube_upload=True,
|
||||
youtube_description="This is a karaoke video",
|
||||
youtube_description_template="This is a karaoke video",
|
||||
)
|
||||
|
||||
# Both fields should exist and be set
|
||||
assert job.youtube_description == "This is a karaoke video"
|
||||
assert job.youtube_description_template == "This is a karaoke video"
|
||||
assert job.enable_youtube_upload is True
|
||||
|
||||
def test_job_create_has_youtube_description_template(self):
|
||||
"""Test JobCreate model has youtube_description_template field."""
|
||||
job_create = JobCreate(
|
||||
artist="Test",
|
||||
title="Song",
|
||||
enable_youtube_upload=True,
|
||||
youtube_description="This is a karaoke video",
|
||||
youtube_description_template="This is a karaoke video",
|
||||
)
|
||||
|
||||
assert job_create.youtube_description_template == "This is a karaoke video"
|
||||
|
||||
def test_video_worker_reads_youtube_description_template(self):
|
||||
"""Document what field video_worker expects.
|
||||
|
||||
This is a documentation test - if video_worker changes what field
|
||||
it reads, this test should be updated to match.
|
||||
"""
|
||||
# video_worker.py uses this pattern:
|
||||
# if youtube_credentials and getattr(job, 'youtube_description_template', None):
|
||||
# youtube_desc_path = os.path.join(temp_dir, "youtube_description.txt")
|
||||
# with open(youtube_desc_path, 'w') as f:
|
||||
# f.write(job.youtube_description_template)
|
||||
#
|
||||
# So the job MUST have youtube_description_template set for YouTube upload to work
|
||||
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
enable_youtube_upload=True,
|
||||
youtube_description_template="Template text",
|
||||
)
|
||||
|
||||
# Simulate what video_worker does
|
||||
template = getattr(job, 'youtube_description_template', None)
|
||||
assert template is not None, "youtube_description_template must be set for YouTube upload"
|
||||
assert template == "Template text"
|
||||
|
||||
|
||||
class TestJobStatusAudioSearchStates:
|
||||
"""Test Job status includes audio search states."""
|
||||
|
||||
@@ -172,26 +244,30 @@ class TestAudioSearchResult:
|
||||
class TestAudioSearchServiceInit:
|
||||
"""Test AudioSearchService initialization."""
|
||||
|
||||
@patch.dict('os.environ', {'REDACTED_API_KEY': '', 'OPS_API_KEY': ''}, clear=False)
|
||||
@patch.dict('os.environ', {'RED_API_KEY': '', 'RED_API_URL': '', 'OPS_API_KEY': '', 'OPS_API_URL': ''}, clear=False)
|
||||
def test_init_with_no_keys(self):
|
||||
"""Test initialization without API keys."""
|
||||
# Pass explicit None to override environment
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
|
||||
# Service should have a FlacFetcher internally
|
||||
assert service._fetcher is not None
|
||||
assert service._cached_results == []
|
||||
|
||||
def test_init_with_keys(self):
|
||||
"""Test initialization with API keys."""
|
||||
"""Test initialization with API keys and URLs."""
|
||||
service = AudioSearchService(
|
||||
redacted_api_key="test_redacted_key",
|
||||
red_api_key="test_red_key",
|
||||
red_api_url="https://red.url",
|
||||
ops_api_key="test_ops_key",
|
||||
ops_api_url="https://ops.url",
|
||||
)
|
||||
|
||||
# Keys are passed to FlacFetcher
|
||||
assert service._fetcher._redacted_api_key == "test_redacted_key"
|
||||
# Keys and URLs are passed to FlacFetcher
|
||||
assert service._fetcher._red_api_key == "test_red_key"
|
||||
assert service._fetcher._red_api_url == "https://red.url"
|
||||
assert service._fetcher._ops_api_key == "test_ops_key"
|
||||
assert service._fetcher._ops_api_url == "https://ops.url"
|
||||
|
||||
def test_init_reads_from_environment(self):
|
||||
"""Test initialization reads keys from environment variables."""
|
||||
@@ -219,7 +295,9 @@ class TestAudioSearchServiceSearch:
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
# IMPORTANT: Clear remote client to force local mode, otherwise real API calls are made
|
||||
service._remote_client = None
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = [mock_result]
|
||||
|
||||
@@ -233,7 +311,8 @@ class TestAudioSearchServiceSearch:
|
||||
|
||||
def test_search_no_results_raises_error(self):
|
||||
"""Test search raises NoResultsError when no results."""
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._remote_client = None # Force local mode to use mocked fetcher
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.side_effect = NoResultsError("No results found")
|
||||
|
||||
@@ -249,7 +328,7 @@ class TestAudioSearchServiceSearch:
|
||||
mock_results.append(AudioSearchResult(
|
||||
title=f"Song {i}",
|
||||
artist="Artist",
|
||||
provider=["YouTube", "Redacted", "OPS"][i],
|
||||
provider=["YouTube", "RED", "OPS"][i],
|
||||
url=f"https://example.com/{i}",
|
||||
duration=180 + i * 10,
|
||||
quality=["320kbps", "FLAC", "FLAC"][i],
|
||||
@@ -257,7 +336,8 @@ class TestAudioSearchServiceSearch:
|
||||
index=i,
|
||||
))
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._remote_client = None # Force local mode to use mocked fetcher
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = mock_results
|
||||
|
||||
@@ -285,13 +365,13 @@ class TestAudioSearchServiceSelectBest:
|
||||
AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
url="https://example.com/456",
|
||||
index=1,
|
||||
),
|
||||
]
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.select_best.return_value = 1
|
||||
|
||||
@@ -302,7 +382,7 @@ class TestAudioSearchServiceSelectBest:
|
||||
|
||||
def test_select_best_empty_list_returns_zero(self):
|
||||
"""Test select_best returns 0 for empty list."""
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.select_best.return_value = 0
|
||||
|
||||
@@ -316,7 +396,7 @@ class TestAudioSearchServiceDownload:
|
||||
|
||||
def test_download_without_search_raises_error(self):
|
||||
"""Test download without prior search raises error."""
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
|
||||
with pytest.raises(DownloadError) as exc_info:
|
||||
service.download(0, "/tmp")
|
||||
@@ -353,7 +433,8 @@ class TestAudioSearchServiceDownload:
|
||||
quality="FLAC",
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._remote_client = None # Force local mode to use mocked fetcher
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = [mock_result]
|
||||
service._fetcher.download.return_value = mock_fetch_result
|
||||
@@ -380,7 +461,7 @@ class TestAudioSearchServiceDownload:
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._fetcher.search.return_value = [mock_result]
|
||||
|
||||
@@ -418,23 +499,23 @@ class TestRemoteDownloadPath:
|
||||
"""Test remote download functionality when flacfetch service is configured.
|
||||
|
||||
These tests verify the code path that uses the remote flacfetch service
|
||||
for torrent downloads (Redacted/OPS providers). This would have caught
|
||||
for torrent downloads (RED/OPS providers). This would have caught
|
||||
the 'extra_info' attribute error.
|
||||
|
||||
The tests directly set up the service state without calling search() to avoid
|
||||
the complexity of mocking async remote search operations.
|
||||
"""
|
||||
|
||||
def test_download_uses_remote_for_redacted_provider(self):
|
||||
"""Test download routes to remote service for Redacted provider.
|
||||
def test_download_uses_remote_for_red_provider(self):
|
||||
"""Test download routes to remote service for RED provider.
|
||||
|
||||
This test would have caught: 'AudioSearchResult' object has no attribute 'extra_info'
|
||||
"""
|
||||
# Create a Redacted result (torrent source)
|
||||
# Create a RED result (torrent source)
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted", # Torrent provider - should use remote
|
||||
provider="RED", # Torrent provider - should use remote
|
||||
url="", # No URL for torrent sources
|
||||
quality="FLAC 16bit CD",
|
||||
seeders=50,
|
||||
@@ -443,7 +524,7 @@ class TestRemoteDownloadPath:
|
||||
)
|
||||
|
||||
# Create service with mocked remote client
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
|
||||
# Directly set cached results (simulating after search)
|
||||
@@ -459,16 +540,16 @@ class TestRemoteDownloadPath:
|
||||
filepath="gs://bucket/uploads/job123/audio/Waterloo.flac",
|
||||
artist="ABBA",
|
||||
title="Waterloo",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
quality="FLAC 16bit CD",
|
||||
)
|
||||
service._download_remote = Mock(return_value=mock_download_result)
|
||||
|
||||
# Call download - should route to remote
|
||||
result = service.download(0, "/tmp", gcs_path="uploads/job123/audio/")
|
||||
|
||||
# Verify remote download was called
|
||||
service._download_remote.assert_called_once_with(0, "/tmp", None, "uploads/job123/audio/")
|
||||
|
||||
# Verify remote download was called (includes search_id as last parameter)
|
||||
service._download_remote.assert_called_once_with(0, "/tmp", None, "uploads/job123/audio/", "remote_search_123")
|
||||
assert result.filepath == "gs://bucket/uploads/job123/audio/Waterloo.flac"
|
||||
|
||||
def test_download_uses_remote_for_ops_provider(self):
|
||||
@@ -483,7 +564,7 @@ class TestRemoteDownloadPath:
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
|
||||
# Directly set cached results
|
||||
@@ -521,7 +602,7 @@ class TestRemoteDownloadPath:
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
|
||||
# Directly set cached results
|
||||
@@ -557,13 +638,13 @@ class TestRemoteDownloadPath:
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted", # Would normally use remote
|
||||
provider="RED", # Would normally use remote
|
||||
url="",
|
||||
quality="FLAC",
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
|
||||
# Directly set cached results
|
||||
@@ -578,7 +659,7 @@ class TestRemoteDownloadPath:
|
||||
filepath="/tmp/test.flac",
|
||||
artist="ABBA",
|
||||
title="Waterloo",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
quality="FLAC",
|
||||
)
|
||||
service._fetcher.download.return_value = mock_fetch_result
|
||||
@@ -586,7 +667,7 @@ class TestRemoteDownloadPath:
|
||||
# Call download
|
||||
result = service.download(0, "/tmp")
|
||||
|
||||
# Should use local even though it's Redacted
|
||||
# Should use local even though it's RED
|
||||
service._fetcher.download.assert_called_once()
|
||||
|
||||
def test_download_uses_local_when_no_remote_search_id(self):
|
||||
@@ -594,13 +675,13 @@ class TestRemoteDownloadPath:
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
url="",
|
||||
quality="FLAC",
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
|
||||
# Directly set cached results
|
||||
@@ -615,7 +696,7 @@ class TestRemoteDownloadPath:
|
||||
filepath="/tmp/test.flac",
|
||||
artist="ABBA",
|
||||
title="Waterloo",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
quality="FLAC",
|
||||
)
|
||||
service._fetcher.download.return_value = mock_fetch_result
|
||||
@@ -634,13 +715,13 @@ class TestRemoteDownloadPath:
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
url="",
|
||||
quality="FLAC",
|
||||
index=0,
|
||||
)
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._cached_results = [mock_result]
|
||||
|
||||
@@ -650,7 +731,7 @@ class TestRemoteDownloadPath:
|
||||
|
||||
mock_fetch_result = AudioDownloadResult(
|
||||
filepath="/tmp/test.flac", artist="ABBA", title="Waterloo",
|
||||
provider="Redacted", quality="FLAC",
|
||||
provider="RED", quality="FLAC",
|
||||
)
|
||||
service._fetcher.download.return_value = mock_fetch_result
|
||||
service._download_remote = Mock()
|
||||
@@ -683,7 +764,7 @@ class TestRemoteDownloadPath:
|
||||
mock_result = AudioSearchResult(
|
||||
title="Waterloo",
|
||||
artist="ABBA",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
url="",
|
||||
quality="FLAC 16bit CD",
|
||||
seeders=50,
|
||||
@@ -693,7 +774,7 @@ class TestRemoteDownloadPath:
|
||||
# Verify AudioSearchResult doesn't have extra_info
|
||||
assert not hasattr(mock_result, 'extra_info')
|
||||
|
||||
service = AudioSearchService(redacted_api_key=None, ops_api_key=None)
|
||||
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
|
||||
service._fetcher = Mock()
|
||||
service._cached_results = [mock_result]
|
||||
service._remote_search_id = "search_123"
|
||||
@@ -704,7 +785,7 @@ class TestRemoteDownloadPath:
|
||||
filepath="/tmp/test.flac",
|
||||
artist="ABBA",
|
||||
title="Waterloo",
|
||||
provider="Redacted",
|
||||
provider="RED",
|
||||
quality="FLAC",
|
||||
)
|
||||
service._download_remote = Mock(return_value=mock_download_result)
|
||||
@@ -712,11 +793,259 @@ class TestRemoteDownloadPath:
|
||||
# This should NOT raise AttributeError: 'AudioSearchResult' object has no attribute 'extra_info'
|
||||
result = service.download(0, "/tmp")
|
||||
|
||||
# Should succeed and use remote download for Redacted provider
|
||||
# Should succeed and use remote download for RED provider
|
||||
service._download_remote.assert_called_once()
|
||||
assert result.filepath == "/tmp/test.flac"
|
||||
|
||||
|
||||
class TestAudioSearchThemeSupport:
|
||||
"""Test theme support in audio search requests.
|
||||
|
||||
These tests verify that theme_id and color_overrides are properly:
|
||||
1. Accepted in AudioSearchRequest model
|
||||
2. Passed through to JobCreate
|
||||
3. Result in correct CDG/TXT defaults when theme is set
|
||||
4. Theme style is PREPARED (copied to job folder) when theme_id is set
|
||||
"""
|
||||
|
||||
def test_audio_search_request_accepts_theme_id(self):
|
||||
"""Test AudioSearchRequest model has theme_id field."""
|
||||
from backend.api.routes.audio_search import AudioSearchRequest
|
||||
|
||||
request = AudioSearchRequest(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
theme_id="nomad"
|
||||
)
|
||||
|
||||
assert request.theme_id == "nomad"
|
||||
|
||||
def test_audio_search_request_accepts_color_overrides(self):
|
||||
"""Test AudioSearchRequest model has color_overrides field."""
|
||||
from backend.api.routes.audio_search import AudioSearchRequest
|
||||
|
||||
request = AudioSearchRequest(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
theme_id="nomad",
|
||||
color_overrides={
|
||||
"artist_color": "#ff0000",
|
||||
"title_color": "#00ff00",
|
||||
}
|
||||
)
|
||||
|
||||
assert request.color_overrides["artist_color"] == "#ff0000"
|
||||
assert request.color_overrides["title_color"] == "#00ff00"
|
||||
|
||||
def test_audio_search_request_theme_defaults_cdg_txt(self):
|
||||
"""Test that when theme_id is set, CDG/TXT defaults to enabled.
|
||||
|
||||
This is the key behavior: selecting a theme should automatically
|
||||
enable CDG and TXT output formats.
|
||||
"""
|
||||
from backend.api.routes.audio_search import AudioSearchRequest, _resolve_cdg_txt_defaults
|
||||
|
||||
# When theme_id is set, enable_cdg/enable_txt should default to True
|
||||
request = AudioSearchRequest(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
theme_id="nomad"
|
||||
# enable_cdg and enable_txt are None (not specified)
|
||||
)
|
||||
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
request.theme_id, request.enable_cdg, request.enable_txt
|
||||
)
|
||||
|
||||
assert resolved_cdg is True, "CDG should be enabled by default when theme is set"
|
||||
assert resolved_txt is True, "TXT should be enabled by default when theme is set"
|
||||
|
||||
def test_audio_search_request_no_theme_no_cdg_txt(self):
|
||||
"""Test that without theme_id, CDG/TXT defaults to disabled."""
|
||||
from backend.api.routes.audio_search import AudioSearchRequest, _resolve_cdg_txt_defaults
|
||||
|
||||
request = AudioSearchRequest(
|
||||
artist="Test Artist",
|
||||
title="Test Song"
|
||||
# No theme_id, no enable_cdg, no enable_txt
|
||||
)
|
||||
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
request.theme_id, request.enable_cdg, request.enable_txt
|
||||
)
|
||||
|
||||
assert resolved_cdg is False, "CDG should be disabled by default without theme"
|
||||
assert resolved_txt is False, "TXT should be disabled by default without theme"
|
||||
|
||||
def test_explicit_cdg_txt_overrides_theme_default(self):
|
||||
"""Test that explicit enable_cdg/enable_txt values override theme defaults."""
|
||||
from backend.api.routes.audio_search import AudioSearchRequest, _resolve_cdg_txt_defaults
|
||||
|
||||
# Theme set (would default to True), but explicitly disabled
|
||||
request = AudioSearchRequest(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
theme_id="nomad",
|
||||
enable_cdg=False,
|
||||
enable_txt=False,
|
||||
)
|
||||
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
request.theme_id, request.enable_cdg, request.enable_txt
|
||||
)
|
||||
|
||||
assert resolved_cdg is False, "Explicit False should override theme default"
|
||||
assert resolved_txt is False, "Explicit False should override theme default"
|
||||
|
||||
def test_explicit_cdg_txt_enables_without_theme(self):
|
||||
"""Test that explicit True enables CDG/TXT even without theme."""
|
||||
from backend.api.routes.audio_search import AudioSearchRequest, _resolve_cdg_txt_defaults
|
||||
|
||||
# No theme (would default to False), but explicitly enabled
|
||||
request = AudioSearchRequest(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
enable_cdg=True,
|
||||
enable_txt=True,
|
||||
)
|
||||
|
||||
resolved_cdg, resolved_txt = _resolve_cdg_txt_defaults(
|
||||
request.theme_id, request.enable_cdg, request.enable_txt
|
||||
)
|
||||
|
||||
assert resolved_cdg is True, "Explicit True should enable CDG without theme"
|
||||
assert resolved_txt is True, "Explicit True should enable TXT without theme"
|
||||
|
||||
def test_job_create_receives_theme_from_audio_search(self):
|
||||
"""Test that JobCreate model can receive theme_id and color_overrides."""
|
||||
job_create = JobCreate(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
theme_id="nomad",
|
||||
color_overrides={
|
||||
"artist_color": "#ff0000",
|
||||
"sung_lyrics_color": "#00ff00"
|
||||
},
|
||||
enable_cdg=True,
|
||||
enable_txt=True,
|
||||
)
|
||||
|
||||
assert job_create.theme_id == "nomad"
|
||||
assert job_create.color_overrides["artist_color"] == "#ff0000"
|
||||
assert job_create.color_overrides["sung_lyrics_color"] == "#00ff00"
|
||||
assert job_create.enable_cdg is True
|
||||
assert job_create.enable_txt is True
|
||||
|
||||
def test_job_model_stores_theme_configuration(self):
|
||||
"""Test Job model stores theme configuration correctly."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
theme_id="nomad",
|
||||
color_overrides={
|
||||
"artist_color": "#ff0000"
|
||||
},
|
||||
enable_cdg=True,
|
||||
enable_txt=True,
|
||||
)
|
||||
|
||||
assert job.theme_id == "nomad"
|
||||
assert job.color_overrides["artist_color"] == "#ff0000"
|
||||
assert job.enable_cdg is True
|
||||
assert job.enable_txt is True
|
||||
|
||||
|
||||
class TestAudioSearchThemePreparation:
|
||||
"""Test that audio search endpoint properly prepares theme styles.
|
||||
|
||||
CRITICAL: This test class was added to catch the bug where audio_search.py
|
||||
accepted theme_id but never called prepare_job_style(), resulting in jobs
|
||||
with theme_id set but no style_params_gcs_path or style_assets.
|
||||
|
||||
The symptom: Preview videos show black background instead of themed background.
|
||||
Job ID ffb0b8fa in production demonstrated this issue.
|
||||
"""
|
||||
|
||||
def test_audio_search_with_theme_calls_prepare_job_style(self):
|
||||
"""Test that creating a job via audio search with theme_id prepares the style.
|
||||
|
||||
CRITICAL: This test verifies that when a job is created via the audio-search
|
||||
endpoint with a theme_id (and no custom style files), the code calls
|
||||
prepare_job_style() to set:
|
||||
1. style_params_gcs_path (pointing to the copied style_params.json)
|
||||
2. style_assets (populated with asset mappings)
|
||||
|
||||
Without this, LyricsTranscriber won't have access to the theme's styles
|
||||
and preview videos will have black backgrounds instead of themed ones.
|
||||
"""
|
||||
# Import the endpoint module to access internal functions
|
||||
from backend.api.routes import audio_search as audio_search_module
|
||||
|
||||
# Check if there's an import of prepare_job_style from theme_service
|
||||
source_code_path = audio_search_module.__file__
|
||||
with open(source_code_path, 'r') as f:
|
||||
source_code = f.read()
|
||||
|
||||
# Check for either:
|
||||
# 1. Import of _prepare_theme_for_job from file_upload
|
||||
# 2. Import of prepare_job_style from theme_service
|
||||
# 3. Inline call to theme_service.prepare_job_style
|
||||
has_theme_prep_import = (
|
||||
'_prepare_theme_for_job' in source_code or
|
||||
'prepare_job_style' in source_code
|
||||
)
|
||||
|
||||
assert has_theme_prep_import, (
|
||||
"audio_search.py does not import or call prepare_job_style() or _prepare_theme_for_job(). "
|
||||
"When theme_id is provided without custom style files, the endpoint MUST call "
|
||||
"prepare_job_style() to copy the theme's style_params.json to the job folder. "
|
||||
"Without this, LyricsTranscriber won't have style configuration and preview "
|
||||
"videos will have black backgrounds instead of themed ones."
|
||||
)
|
||||
|
||||
def test_audio_search_code_handles_theme_preparation(self):
|
||||
"""Verify audio_search.py has theme preparation logic similar to file_upload.py.
|
||||
|
||||
This test compares audio_search.py with file_upload.py to ensure they have
|
||||
similar theme preparation patterns. file_upload.py correctly prepares themes,
|
||||
audio_search.py should do the same.
|
||||
"""
|
||||
from backend.api.routes import audio_search as audio_search_module
|
||||
from backend.api.routes import file_upload as file_upload_module
|
||||
|
||||
# Read source code of both modules
|
||||
with open(audio_search_module.__file__, 'r') as f:
|
||||
audio_search_code = f.read()
|
||||
|
||||
with open(file_upload_module.__file__, 'r') as f:
|
||||
file_upload_code = f.read()
|
||||
|
||||
# file_upload.py has this pattern for theme preparation:
|
||||
# if body.theme_id and not has_style_params_upload:
|
||||
# style_params_path, style_assets, youtube_desc = _prepare_theme_for_job(...)
|
||||
assert '_prepare_theme_for_job' in file_upload_code, \
|
||||
"file_upload.py should have _prepare_theme_for_job function"
|
||||
|
||||
# audio_search.py should have similar pattern
|
||||
# Look for either the function or a similar conditional check
|
||||
# STRICT CHECK: Look for actual theme preparation logic being CALLED, not just mentioned
|
||||
has_theme_preparation_call = (
|
||||
# Check for import or call of theme preparation function
|
||||
'_prepare_theme_for_job(' in audio_search_code or
|
||||
'prepare_job_style(' in audio_search_code
|
||||
)
|
||||
|
||||
assert has_theme_preparation_call, (
|
||||
"audio_search.py does not CALL theme preparation logic. "
|
||||
"It accepts theme_id but never prepares the theme style like file_upload.py does. "
|
||||
"Add a call to _prepare_theme_for_job() when theme_id is set and no style files are uploaded."
|
||||
)
|
||||
|
||||
|
||||
class TestFlacfetchIntegration:
|
||||
"""
|
||||
Integration tests that verify flacfetch imports work correctly.
|
||||
@@ -775,7 +1104,8 @@ class TestFlacfetchIntegration:
|
||||
pytest.importorskip("flacfetch")
|
||||
|
||||
service = AudioSearchService(
|
||||
redacted_api_key=None,
|
||||
red_api_key=None,
|
||||
red_api_url=None,
|
||||
ops_api_key=None,
|
||||
)
|
||||
|
||||
@@ -835,13 +1165,13 @@ class TestAudioSearchApiRouteDownload:
|
||||
from backend.api.routes.audio_search import _download_and_start_processing
|
||||
import asyncio
|
||||
|
||||
# Setup mock job with Redacted search result
|
||||
# Setup mock job with RED search result
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Unwanted',
|
||||
'artist': 'Avril Lavigne',
|
||||
'provider': 'Redacted', # Torrent source
|
||||
'provider': 'RED', # Torrent source
|
||||
'quality': 'FLAC 16bit CD',
|
||||
}]
|
||||
}
|
||||
@@ -956,13 +1286,13 @@ class TestAudioSearchApiRouteDownload:
|
||||
from backend.api.routes.audio_search import _download_and_start_processing
|
||||
import asyncio
|
||||
|
||||
# Setup mock job with Redacted search result
|
||||
# Setup mock job with RED search result
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Test Artist',
|
||||
'provider': 'Redacted',
|
||||
'provider': 'RED',
|
||||
'quality': 'FLAC',
|
||||
}]
|
||||
}
|
||||
@@ -1012,13 +1342,13 @@ class TestAudioSearchApiRouteDownload:
|
||||
import asyncio
|
||||
import tempfile
|
||||
|
||||
# Setup mock job with Redacted search result
|
||||
# Setup mock job with RED search result
|
||||
mock_job = Mock()
|
||||
mock_job.state_data = {
|
||||
'audio_search_results': [{
|
||||
'title': 'Test',
|
||||
'artist': 'Test',
|
||||
'provider': 'Redacted', # Torrent source, but remote is disabled
|
||||
'provider': 'RED', # Torrent source, but remote is disabled
|
||||
'quality': 'FLAC',
|
||||
}]
|
||||
}
|
||||
|
||||
@@ -3,13 +3,28 @@ Unit tests for audio analysis and editing services.
|
||||
|
||||
These tests verify the backend service wrappers that use the shared
|
||||
karaoke_gen.instrumental_review module with GCS integration.
|
||||
|
||||
NOTE: These tests require ffmpeg to be installed. They will be skipped
|
||||
if ffmpeg is not available (e.g., in CI environments without ffmpeg).
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch, ANY
|
||||
|
||||
# Check if ffmpeg is available
|
||||
def _ffmpeg_available():
|
||||
"""Check if ffmpeg is available on the system."""
|
||||
return shutil.which('ffmpeg') is not None
|
||||
|
||||
# Skip all tests in this module if ffmpeg is not available
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not _ffmpeg_available(),
|
||||
reason="ffmpeg not available - required for audio processing tests"
|
||||
)
|
||||
|
||||
from pydub import AudioSegment
|
||||
from pydub.generators import Sine
|
||||
|
||||
|
||||
@@ -96,15 +96,15 @@ def auth_headers():
|
||||
class TestEmulatorBasics:
|
||||
"""Basic emulator connectivity tests."""
|
||||
|
||||
def test_health_endpoint(self, client):
|
||||
def test_health_endpoint(self, client, auth_headers):
|
||||
"""Test health endpoint works."""
|
||||
response = client.get("/api/health")
|
||||
response = client.get("/api/health", )
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "healthy"
|
||||
|
||||
def test_root_endpoint(self, client):
|
||||
def test_root_endpoint(self, client, auth_headers):
|
||||
"""Test root endpoint works."""
|
||||
response = client.get("/")
|
||||
response = client.get("/", )
|
||||
assert response.status_code == 200
|
||||
assert response.json()["service"] == "karaoke-gen-backend"
|
||||
|
||||
|
||||
@@ -1122,9 +1122,10 @@ class TestFinaliseOnlyModels:
|
||||
FinaliseOnlyFileRequest(filename="with_vocals.mkv", content_type="video/mkv", file_type="with_vocals"),
|
||||
]
|
||||
)
|
||||
|
||||
assert request.enable_cdg is True
|
||||
assert request.enable_txt is True
|
||||
|
||||
# CDG/TXT default to None (server resolves based on theme_id)
|
||||
assert request.enable_cdg is None
|
||||
assert request.enable_txt is None
|
||||
assert request.brand_prefix is None
|
||||
assert request.keep_brand_code is None
|
||||
assert request.enable_youtube_upload is False
|
||||
@@ -1270,13 +1271,14 @@ class TestCreateJobFromUrlRequest:
|
||||
request = CreateJobFromUrlRequest(
|
||||
url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
||||
)
|
||||
|
||||
|
||||
assert request.url == "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
||||
assert request.artist is None
|
||||
assert request.title is None
|
||||
assert request.enable_cdg is True
|
||||
assert request.enable_txt is True
|
||||
|
||||
# CDG/TXT default to None (server resolves based on theme_id)
|
||||
assert request.enable_cdg is None
|
||||
assert request.enable_txt is None
|
||||
|
||||
def test_create_with_artist_and_title(self):
|
||||
"""Test creating request with URL, artist, and title."""
|
||||
from backend.api.routes.file_upload import CreateJobFromUrlRequest
|
||||
|
||||
@@ -188,7 +188,7 @@ class TestFlacfetchClientSearch:
|
||||
{
|
||||
"title": "Waterloo",
|
||||
"artist": "ABBA",
|
||||
"provider": "Redacted",
|
||||
"provider": "RED",
|
||||
"quality": "FLAC 16bit CD",
|
||||
"seeders": 50,
|
||||
"index": 0,
|
||||
|
||||
@@ -11,7 +11,6 @@ Tests for:
|
||||
import pytest
|
||||
from datetime import datetime
|
||||
from unittest.mock import MagicMock, patch, AsyncMock
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
@@ -117,16 +116,14 @@ def silent_job():
|
||||
class TestGetInstrumentalAnalysis:
|
||||
"""Tests for GET /api/jobs/{job_id}/instrumental-analysis."""
|
||||
|
||||
def test_get_analysis_returns_data(self, mock_job_manager, mock_storage_service, sample_job):
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_analysis_returns_data(self, mock_job_manager, mock_storage_service, sample_job):
|
||||
"""GET /instrumental-analysis should return analysis data."""
|
||||
mock_job_manager.get_job.return_value = sample_job
|
||||
|
||||
from backend.api.routes.jobs import get_instrumental_analysis
|
||||
import asyncio
|
||||
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
get_instrumental_analysis("test-job-123")
|
||||
)
|
||||
result = await get_instrumental_analysis("test-job-123")
|
||||
|
||||
assert result["job_id"] == "test-job-123"
|
||||
assert result["artist"] == "Test Artist"
|
||||
@@ -134,23 +131,22 @@ class TestGetInstrumentalAnalysis:
|
||||
assert result["analysis"]["has_audible_content"] is True
|
||||
assert len(result["analysis"]["audible_segments"]) == 2
|
||||
|
||||
def test_get_analysis_includes_audio_urls(self, mock_job_manager, mock_storage_service, sample_job):
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_analysis_includes_audio_urls(self, mock_job_manager, mock_storage_service, sample_job):
|
||||
"""GET /instrumental-analysis should include audio URLs."""
|
||||
mock_job_manager.get_job.return_value = sample_job
|
||||
|
||||
from backend.api.routes.jobs import get_instrumental_analysis
|
||||
import asyncio
|
||||
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
get_instrumental_analysis("test-job-123")
|
||||
)
|
||||
result = await get_instrumental_analysis("test-job-123")
|
||||
|
||||
assert "audio_urls" in result
|
||||
assert "clean_instrumental" in result["audio_urls"]
|
||||
assert "backing_vocals" in result["audio_urls"]
|
||||
assert "with_backing" in result["audio_urls"]
|
||||
|
||||
def test_get_analysis_includes_waveform_url(self, mock_job_manager, sample_job):
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_analysis_includes_waveform_url(self, mock_job_manager, sample_job):
|
||||
"""GET /instrumental-analysis should include waveform URL."""
|
||||
mock_job_manager.get_job.return_value = sample_job
|
||||
|
||||
@@ -161,59 +157,50 @@ class TestGetInstrumentalAnalysis:
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
|
||||
from backend.api.routes.jobs import get_instrumental_analysis
|
||||
import asyncio
|
||||
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
get_instrumental_analysis("test-job-123")
|
||||
)
|
||||
result = await get_instrumental_analysis("test-job-123")
|
||||
|
||||
assert "waveform_url" in result
|
||||
# Waveform URL should be generated from the file_urls
|
||||
assert result["waveform_url"] == "https://storage.googleapis.com/signed-url"
|
||||
|
||||
def test_get_analysis_silent_audio(self, mock_job_manager, mock_storage_service, silent_job):
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_analysis_silent_audio(self, mock_job_manager, mock_storage_service, silent_job):
|
||||
"""GET /instrumental-analysis should correctly report silent audio."""
|
||||
mock_job_manager.get_job.return_value = silent_job
|
||||
|
||||
from backend.api.routes.jobs import get_instrumental_analysis
|
||||
import asyncio
|
||||
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
get_instrumental_analysis("test-job-silent")
|
||||
)
|
||||
result = await get_instrumental_analysis("test-job-silent")
|
||||
|
||||
assert result["analysis"]["has_audible_content"] is False
|
||||
assert result["analysis"]["recommended_selection"] == "clean"
|
||||
assert len(result["analysis"]["audible_segments"]) == 0
|
||||
|
||||
def test_get_analysis_job_not_found(self, mock_job_manager):
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_analysis_job_not_found(self, mock_job_manager):
|
||||
"""GET /instrumental-analysis should return 404 for non-existent job."""
|
||||
mock_job_manager.get_job.return_value = None
|
||||
|
||||
from backend.api.routes.jobs import get_instrumental_analysis
|
||||
from fastapi import HTTPException
|
||||
import asyncio
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
get_instrumental_analysis("non-existent")
|
||||
)
|
||||
await get_instrumental_analysis("non-existent")
|
||||
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
def test_get_analysis_wrong_status(self, mock_job_manager, sample_job):
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_analysis_wrong_status(self, mock_job_manager, sample_job):
|
||||
"""GET /instrumental-analysis should return 400 for wrong job status."""
|
||||
sample_job.status = JobStatus.PENDING
|
||||
mock_job_manager.get_job.return_value = sample_job
|
||||
|
||||
from backend.api.routes.jobs import get_instrumental_analysis
|
||||
from fastapi import HTTPException
|
||||
import asyncio
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
get_instrumental_analysis("test-job-123")
|
||||
)
|
||||
await get_instrumental_analysis("test-job-123")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
@@ -226,39 +213,34 @@ class TestAudioStream:
|
||||
mock_job_manager.get_job.return_value = sample_job
|
||||
|
||||
from backend.api.routes.jobs import stream_audio
|
||||
import asyncio
|
||||
|
||||
# This will try to stream from GCS which we can't test easily
|
||||
# Instead, verify the function exists and has correct signature
|
||||
assert callable(stream_audio)
|
||||
|
||||
def test_stream_invalid_stem_type(self, mock_job_manager, sample_job):
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_invalid_stem_type(self, mock_job_manager, sample_job):
|
||||
"""Should return 400 for invalid stem type."""
|
||||
mock_job_manager.get_job.return_value = sample_job
|
||||
|
||||
from backend.api.routes.jobs import stream_audio
|
||||
from fastapi import HTTPException
|
||||
import asyncio
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
stream_audio("test-job-123", "invalid_stem")
|
||||
)
|
||||
await stream_audio("test-job-123", "invalid_stem")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
def test_stream_job_not_found(self, mock_job_manager):
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_job_not_found(self, mock_job_manager):
|
||||
"""Should return 404 for non-existent job."""
|
||||
mock_job_manager.get_job.return_value = None
|
||||
|
||||
from backend.api.routes.jobs import stream_audio
|
||||
from fastapi import HTTPException
|
||||
import asyncio
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
stream_audio("non-existent", "backing_vocals")
|
||||
)
|
||||
await stream_audio("non-existent", "backing_vocals")
|
||||
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
@@ -293,27 +275,26 @@ class TestCreateCustomInstrumental:
|
||||
|
||||
assert "At least one mute region is required" in str(exc_info.value)
|
||||
|
||||
def test_create_custom_job_not_found(self, mock_job_manager):
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_custom_job_not_found(self, mock_job_manager):
|
||||
"""Should return 404 for non-existent job."""
|
||||
mock_job_manager.get_job.return_value = None
|
||||
|
||||
from backend.api.routes.jobs import create_custom_instrumental
|
||||
from backend.models.requests import CreateCustomInstrumentalRequest, MuteRegionRequest
|
||||
from fastapi import HTTPException
|
||||
import asyncio
|
||||
|
||||
request = CreateCustomInstrumentalRequest(
|
||||
mute_regions=[MuteRegionRequest(start_seconds=10.0, end_seconds=20.0)]
|
||||
)
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
create_custom_instrumental("non-existent", request)
|
||||
)
|
||||
await create_custom_instrumental("non-existent", request)
|
||||
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
def test_create_custom_wrong_status(self, mock_job_manager, sample_job):
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_custom_wrong_status(self, mock_job_manager, sample_job):
|
||||
"""Should return 400 for wrong job status."""
|
||||
sample_job.status = JobStatus.PENDING
|
||||
mock_job_manager.get_job.return_value = sample_job
|
||||
@@ -321,16 +302,13 @@ class TestCreateCustomInstrumental:
|
||||
from backend.api.routes.jobs import create_custom_instrumental
|
||||
from backend.models.requests import CreateCustomInstrumentalRequest, MuteRegionRequest
|
||||
from fastapi import HTTPException
|
||||
import asyncio
|
||||
|
||||
request = CreateCustomInstrumentalRequest(
|
||||
mute_regions=[MuteRegionRequest(start_seconds=10.0, end_seconds=20.0)]
|
||||
)
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
create_custom_instrumental("test-job-123", request)
|
||||
)
|
||||
await create_custom_instrumental("test-job-123", request)
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
@@ -338,34 +316,30 @@ class TestCreateCustomInstrumental:
|
||||
class TestGetWaveformData:
|
||||
"""Tests for GET /api/jobs/{job_id}/waveform-data."""
|
||||
|
||||
def test_get_waveform_data_job_not_found(self, mock_job_manager):
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_waveform_data_job_not_found(self, mock_job_manager):
|
||||
"""Should return 404 for non-existent job."""
|
||||
mock_job_manager.get_job.return_value = None
|
||||
|
||||
from backend.api.routes.jobs import get_waveform_data
|
||||
from fastapi import HTTPException
|
||||
import asyncio
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
get_waveform_data("non-existent")
|
||||
)
|
||||
await get_waveform_data("non-existent")
|
||||
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
def test_get_waveform_data_wrong_status(self, mock_job_manager, sample_job):
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_waveform_data_wrong_status(self, mock_job_manager, sample_job):
|
||||
"""Should return 400 for wrong job status."""
|
||||
sample_job.status = JobStatus.PENDING
|
||||
mock_job_manager.get_job.return_value = sample_job
|
||||
|
||||
from backend.api.routes.jobs import get_waveform_data
|
||||
from fastapi import HTTPException
|
||||
import asyncio
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
asyncio.get_event_loop().run_until_complete(
|
||||
get_waveform_data("test-job-123")
|
||||
)
|
||||
await get_waveform_data("test-job-123")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ class TestAudioWorkerEndpoint:
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_audio_worker_requires_auth(self, client):
|
||||
def test_audio_worker_requires_auth(self, client, auth_headers):
|
||||
"""Test audio worker requires authentication."""
|
||||
response = client.post(
|
||||
"/api/internal/workers/audio",
|
||||
@@ -128,7 +128,7 @@ class TestLyricsWorkerEndpoint:
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_lyrics_worker_requires_auth(self, client):
|
||||
def test_lyrics_worker_requires_auth(self, client, auth_headers):
|
||||
"""Test lyrics worker requires authentication."""
|
||||
response = client.post(
|
||||
"/api/internal/workers/lyrics",
|
||||
@@ -158,7 +158,7 @@ class TestScreensWorkerEndpoint:
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_screens_worker_requires_auth(self, client):
|
||||
def test_screens_worker_requires_auth(self, client, auth_headers):
|
||||
"""Test screens worker requires authentication."""
|
||||
response = client.post(
|
||||
"/api/internal/workers/screens",
|
||||
@@ -188,7 +188,7 @@ class TestVideoWorkerEndpoint:
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_video_worker_requires_auth(self, client):
|
||||
def test_video_worker_requires_auth(self, client, auth_headers):
|
||||
"""Test video worker requires authentication."""
|
||||
response = client.post(
|
||||
"/api/internal/workers/video",
|
||||
@@ -218,7 +218,7 @@ class TestRenderVideoWorkerEndpoint:
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_render_video_worker_requires_auth(self, client):
|
||||
def test_render_video_worker_requires_auth(self, client, auth_headers):
|
||||
"""Test render-video worker requires authentication."""
|
||||
response = client.post(
|
||||
"/api/internal/workers/render-video",
|
||||
|
||||
@@ -102,6 +102,37 @@ class TestJobCreation:
|
||||
|
||||
assert job.status == JobStatus.PENDING
|
||||
assert job.progress == 0
|
||||
|
||||
def test_create_job_with_distribution_settings(self, job_manager, mock_firestore_service):
|
||||
"""Test that distribution settings are passed from JobCreate to Job.
|
||||
|
||||
This was a bug where brand_prefix, dropbox_path, gdrive_folder_id, and
|
||||
discord_webhook_url were NOT being passed to the Job constructor.
|
||||
"""
|
||||
job_create = JobCreate(
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
brand_prefix="NOMAD",
|
||||
discord_webhook_url="https://discord.com/webhook/test",
|
||||
dropbox_path="/Karaoke/Tracks-Organized",
|
||||
gdrive_folder_id="1abc123xyz",
|
||||
enable_youtube_upload=True,
|
||||
)
|
||||
|
||||
job = job_manager.create_job(job_create)
|
||||
|
||||
# Verify distribution settings are passed through
|
||||
assert job.brand_prefix == "NOMAD"
|
||||
assert job.discord_webhook_url == "https://discord.com/webhook/test"
|
||||
assert job.dropbox_path == "/Karaoke/Tracks-Organized"
|
||||
assert job.gdrive_folder_id == "1abc123xyz"
|
||||
assert job.enable_youtube_upload is True
|
||||
|
||||
# Verify Firestore was called with job containing these fields
|
||||
mock_firestore_service.create_job.assert_called_once()
|
||||
created_job = mock_firestore_service.create_job.call_args[0][0]
|
||||
assert created_job.brand_prefix == "NOMAD"
|
||||
assert created_job.dropbox_path == "/Karaoke/Tracks-Organized"
|
||||
|
||||
|
||||
class TestJobRetrieval:
|
||||
|
||||
@@ -68,20 +68,20 @@ def client(mock_job_manager, mock_worker_service):
|
||||
class TestGetJob:
|
||||
"""Tests for GET /api/jobs/{job_id}."""
|
||||
|
||||
def test_get_job_returns_200(self, client, mock_job_manager, mock_job):
|
||||
def test_get_job_returns_200(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test getting an existing job returns 200."""
|
||||
response = client.get("/api/jobs/test123")
|
||||
response = client.get("/api/jobs/test123", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_get_job_returns_job_data(self, client, mock_job_manager, mock_job):
|
||||
def test_get_job_returns_job_data(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test response contains job data."""
|
||||
response = client.get("/api/jobs/test123")
|
||||
response = client.get("/api/jobs/test123", headers=auth_headers)
|
||||
data = response.json()
|
||||
assert data["job_id"] == "test123"
|
||||
assert data["status"] == "pending"
|
||||
assert data["artist"] == "Test Artist"
|
||||
|
||||
def test_get_nonexistent_job_returns_404(self, mock_worker_service):
|
||||
def test_get_nonexistent_job_returns_404(self, mock_worker_service, auth_headers):
|
||||
"""Test getting non-existent job returns 404."""
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.get_job.return_value = None
|
||||
@@ -95,58 +95,60 @@ class TestGetJob:
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.get("/api/jobs/nonexistent")
|
||||
response = client.get("/api/jobs/nonexistent", headers=auth_headers)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestListJobs:
|
||||
"""Tests for GET /api/jobs."""
|
||||
|
||||
def test_list_jobs_returns_200(self, client):
|
||||
def test_list_jobs_returns_200(self, client, auth_headers):
|
||||
"""Test listing jobs returns 200."""
|
||||
response = client.get("/api/jobs")
|
||||
response = client.get("/api/jobs", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_list_jobs_returns_array(self, client, mock_job_manager):
|
||||
def test_list_jobs_returns_array(self, client, mock_job_manager, auth_headers):
|
||||
"""Test response is an array of jobs."""
|
||||
response = client.get("/api/jobs")
|
||||
response = client.get("/api/jobs", headers=auth_headers)
|
||||
data = response.json()
|
||||
assert isinstance(data, list)
|
||||
assert len(data) == 1
|
||||
assert data[0]["job_id"] == "test123"
|
||||
|
||||
def test_list_jobs_with_status_filter(self, client, mock_job_manager):
|
||||
def test_list_jobs_with_status_filter(self, client, mock_job_manager, auth_headers):
|
||||
"""Test listing jobs with status filter."""
|
||||
response = client.get("/api/jobs?status=pending")
|
||||
response = client.get("/api/jobs?status=pending", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_list_jobs_with_limit(self, client, mock_job_manager):
|
||||
def test_list_jobs_with_limit(self, client, mock_job_manager, auth_headers):
|
||||
"""Test listing jobs with limit."""
|
||||
response = client.get("/api/jobs?limit=10")
|
||||
response = client.get("/api/jobs?limit=10", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
class TestCreateJob:
|
||||
"""Tests for POST /api/jobs."""
|
||||
|
||||
def test_create_job_with_url_returns_200(self, client, mock_job_manager):
|
||||
def test_create_job_with_url_returns_200(self, client, mock_job_manager, auth_headers):
|
||||
"""Test creating job with URL returns 200."""
|
||||
response = client.post(
|
||||
"/api/jobs",
|
||||
json={"url": "https://youtube.com/watch?v=test123"}
|
||||
json={"url": "https://youtube.com/watch?v=test123"},
|
||||
headers=auth_headers
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_create_job_returns_job_id(self, client, mock_job_manager):
|
||||
def test_create_job_returns_job_id(self, client, mock_job_manager, auth_headers):
|
||||
"""Test create response contains job_id."""
|
||||
response = client.post(
|
||||
"/api/jobs",
|
||||
json={"url": "https://youtube.com/watch?v=test"}
|
||||
json={"url": "https://youtube.com/watch?v=test"},
|
||||
headers=auth_headers
|
||||
)
|
||||
data = response.json()
|
||||
assert "job_id" in data
|
||||
|
||||
def test_create_job_with_artist_title(self, client, mock_job_manager):
|
||||
def test_create_job_with_artist_title(self, client, mock_job_manager, auth_headers):
|
||||
"""Test creating job with artist and title."""
|
||||
response = client.post(
|
||||
"/api/jobs",
|
||||
@@ -154,7 +156,8 @@ class TestCreateJob:
|
||||
"url": "https://youtube.com/watch?v=test",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song"
|
||||
}
|
||||
},
|
||||
headers=auth_headers
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -162,12 +165,12 @@ class TestCreateJob:
|
||||
class TestDeleteJob:
|
||||
"""Tests for DELETE /api/jobs/{job_id}."""
|
||||
|
||||
def test_delete_job_returns_200(self, client, mock_job_manager):
|
||||
def test_delete_job_returns_200(self, client, mock_job_manager, auth_headers):
|
||||
"""Test deleting job returns 200."""
|
||||
response = client.delete("/api/jobs/test123")
|
||||
response = client.delete("/api/jobs/test123", headers=auth_headers)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_delete_nonexistent_job(self, mock_worker_service):
|
||||
def test_delete_nonexistent_job(self, mock_worker_service, auth_headers):
|
||||
"""Test deleting non-existent job."""
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_manager.delete_job.return_value = False
|
||||
@@ -181,7 +184,7 @@ class TestDeleteJob:
|
||||
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
|
||||
from backend.main import app
|
||||
client = TestClient(app)
|
||||
response = client.delete("/api/jobs/nonexistent")
|
||||
response = client.delete("/api/jobs/nonexistent", headers=auth_headers)
|
||||
# Either 200 or 404 depending on implementation
|
||||
assert response.status_code in [200, 404]
|
||||
|
||||
@@ -189,12 +192,13 @@ class TestDeleteJob:
|
||||
class TestCancelJob:
|
||||
"""Tests for POST /api/jobs/{job_id}/cancel."""
|
||||
|
||||
def test_cancel_job_returns_200(self, client, mock_job_manager, mock_job):
|
||||
def test_cancel_job_returns_200(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test cancelling job returns 200."""
|
||||
mock_job_manager.cancel_job.return_value = mock_job
|
||||
response = client.post(
|
||||
"/api/jobs/test123/cancel",
|
||||
json={}
|
||||
json={},
|
||||
headers=auth_headers
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -202,7 +206,7 @@ class TestCancelJob:
|
||||
class TestSubmitCorrections:
|
||||
"""Tests for POST /api/jobs/{job_id}/corrections."""
|
||||
|
||||
def test_submit_corrections_returns_200(self, client, mock_job_manager, mock_job):
|
||||
def test_submit_corrections_returns_200(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test submitting corrections returns 200."""
|
||||
# Job needs to be in AWAITING_REVIEW or IN_REVIEW status
|
||||
review_job = Job(
|
||||
@@ -222,7 +226,8 @@ class TestSubmitCorrections:
|
||||
"lines": [],
|
||||
"metadata": {"source": "test"}
|
||||
}
|
||||
}
|
||||
},
|
||||
headers=auth_headers
|
||||
)
|
||||
# Should be 200 or validation error
|
||||
assert response.status_code in [200, 400, 422]
|
||||
@@ -231,11 +236,12 @@ class TestSubmitCorrections:
|
||||
class TestSelectInstrumental:
|
||||
"""Tests for POST /api/jobs/{job_id}/select-instrumental."""
|
||||
|
||||
def test_select_instrumental_requires_selection_field(self, client, mock_job_manager, mock_job):
|
||||
def test_select_instrumental_requires_selection_field(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test instrumental selection requires selection field."""
|
||||
response = client.post(
|
||||
"/api/jobs/test123/select-instrumental",
|
||||
json={} # Missing selection field
|
||||
json={}, # Missing selection field
|
||||
headers=auth_headers
|
||||
)
|
||||
# Missing field should cause validation error
|
||||
assert response.status_code == 422
|
||||
@@ -244,9 +250,9 @@ class TestSelectInstrumental:
|
||||
class TestStartReview:
|
||||
"""Tests for POST /api/jobs/{job_id}/start-review."""
|
||||
|
||||
def test_start_review_endpoint_exists(self, client, mock_job_manager, mock_job):
|
||||
def test_start_review_endpoint_exists(self, client, mock_job_manager, mock_job, auth_headers):
|
||||
"""Test start review endpoint exists."""
|
||||
response = client.post("/api/jobs/test123/start-review")
|
||||
response = client.post("/api/jobs/test123/start-review", headers=auth_headers)
|
||||
# Should not be 404 or 405
|
||||
assert response.status_code not in [404, 405]
|
||||
|
||||
@@ -146,8 +146,9 @@ class TestUploadSubmissionRequest:
|
||||
def test_default_options(self):
|
||||
"""Test default option values."""
|
||||
request = UploadSubmissionRequest(artist="Test", title="Test")
|
||||
assert request.enable_cdg is True
|
||||
assert request.enable_txt is True
|
||||
# CDG/TXT disabled by default (requires style config)
|
||||
assert request.enable_cdg is False
|
||||
assert request.enable_txt is False
|
||||
assert request.enable_youtube_upload is False
|
||||
|
||||
|
||||
|
||||
@@ -67,12 +67,31 @@ class TestJobStatusTransitions:
|
||||
"""Test FAILED status can transition to retry checkpoint states."""
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
valid_transitions = STATE_TRANSITIONS.get(JobStatus.FAILED, [])
|
||||
|
||||
|
||||
# FAILED should allow retry transitions
|
||||
assert JobStatus.INSTRUMENTAL_SELECTED in valid_transitions, "FAILED should allow retry to INSTRUMENTAL_SELECTED"
|
||||
assert JobStatus.REVIEW_COMPLETE in valid_transitions, "FAILED should allow retry to REVIEW_COMPLETE"
|
||||
assert JobStatus.LYRICS_COMPLETE in valid_transitions, "FAILED should allow retry to LYRICS_COMPLETE"
|
||||
|
||||
def test_cancelled_can_transition_for_retry(self):
|
||||
"""Test CANCELLED status can transition to retry checkpoint states."""
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
valid_transitions = STATE_TRANSITIONS.get(JobStatus.CANCELLED, [])
|
||||
|
||||
# CANCELLED should allow same retry transitions as FAILED
|
||||
assert JobStatus.INSTRUMENTAL_SELECTED in valid_transitions, "CANCELLED should allow retry to INSTRUMENTAL_SELECTED"
|
||||
assert JobStatus.REVIEW_COMPLETE in valid_transitions, "CANCELLED should allow retry to REVIEW_COMPLETE"
|
||||
assert JobStatus.LYRICS_COMPLETE in valid_transitions, "CANCELLED should allow retry to LYRICS_COMPLETE"
|
||||
assert JobStatus.DOWNLOADING in valid_transitions, "CANCELLED should allow retry to DOWNLOADING (restart)"
|
||||
|
||||
def test_failed_can_restart_from_beginning(self):
|
||||
"""Test FAILED status can transition to DOWNLOADING for restart from beginning."""
|
||||
from backend.models.job import STATE_TRANSITIONS
|
||||
valid_transitions = STATE_TRANSITIONS.get(JobStatus.FAILED, [])
|
||||
|
||||
# FAILED should allow restart from beginning
|
||||
assert JobStatus.DOWNLOADING in valid_transitions, "FAILED should allow restart to DOWNLOADING"
|
||||
|
||||
|
||||
class TestJobModelSerialization:
|
||||
"""Tests for Job model serialization to/from API."""
|
||||
@@ -119,3 +138,145 @@ class TestJobModelSerialization:
|
||||
assert job.url is None
|
||||
assert job.file_urls == {}
|
||||
|
||||
|
||||
class TestRetryEndpoint:
|
||||
"""Tests for the retry job endpoint."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_manager(self):
|
||||
"""Create mock job manager."""
|
||||
return MagicMock()
|
||||
|
||||
@pytest.fixture
|
||||
def mock_worker_service(self):
|
||||
"""Create mock worker service."""
|
||||
return MagicMock()
|
||||
|
||||
def test_retry_rejects_pending_job(self, mock_job_manager):
|
||||
"""Test retry endpoint rejects jobs that are not failed or cancelled."""
|
||||
# Create a pending job
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.PENDING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song"
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
# The endpoint should reject this with a 400 error
|
||||
# (status check happens before any logic)
|
||||
assert job.status not in [JobStatus.FAILED, JobStatus.CANCELLED]
|
||||
|
||||
def test_retry_accepts_failed_job(self, mock_job_manager):
|
||||
"""Test retry endpoint accepts failed jobs."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
input_media_gcs_path="jobs/test123/input/audio.flac"
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
# Status should be accepted
|
||||
assert job.status in [JobStatus.FAILED, JobStatus.CANCELLED]
|
||||
|
||||
def test_retry_accepts_cancelled_job(self, mock_job_manager):
|
||||
"""Test retry endpoint accepts cancelled jobs."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.CANCELLED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
input_media_gcs_path="jobs/test123/input/audio.flac"
|
||||
)
|
||||
mock_job_manager.get_job.return_value = job
|
||||
|
||||
# Status should be accepted
|
||||
assert job.status in [JobStatus.FAILED, JobStatus.CANCELLED]
|
||||
|
||||
def test_retry_checkpoint_detection_video_generation(self):
|
||||
"""Test retry detects video generation checkpoint."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
file_urls={
|
||||
'videos': {'with_vocals': 'gs://bucket/path/video.mkv'}
|
||||
},
|
||||
state_data={
|
||||
'instrumental_selection': 'clean'
|
||||
}
|
||||
)
|
||||
|
||||
# This job has video and instrumental selection - should retry from video generation
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
has_instrumental_selection = (job.state_data or {}).get('instrumental_selection')
|
||||
assert has_video and has_instrumental_selection
|
||||
|
||||
def test_retry_checkpoint_detection_render_stage(self):
|
||||
"""Test retry detects render stage checkpoint."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.FAILED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
file_urls={
|
||||
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
|
||||
'screens': {'title': 'gs://bucket/path/title.mov'}
|
||||
}
|
||||
)
|
||||
|
||||
# This job has corrections and screens - should retry from render
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
has_screens = job.file_urls.get('screens', {}).get('title')
|
||||
has_video = job.file_urls.get('videos', {}).get('with_vocals')
|
||||
assert has_corrections and has_screens and not has_video
|
||||
|
||||
def test_retry_checkpoint_detection_from_beginning(self):
|
||||
"""Test retry detects need to restart from beginning."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.CANCELLED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
input_media_gcs_path="jobs/test123/input/audio.flac",
|
||||
file_urls={} # No progress yet
|
||||
)
|
||||
|
||||
# This job has input audio but no other files - should restart from beginning
|
||||
has_input = job.input_media_gcs_path
|
||||
has_stems = job.file_urls.get('stems', {}).get('instrumental_clean')
|
||||
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
assert has_input and not has_stems and not has_corrections
|
||||
|
||||
def test_retry_no_input_audio(self):
|
||||
"""Test retry fails when no input audio available."""
|
||||
job = Job(
|
||||
job_id="test123",
|
||||
status=JobStatus.CANCELLED,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
artist="Test",
|
||||
title="Song",
|
||||
# No input_media_gcs_path and no url
|
||||
file_urls={}
|
||||
)
|
||||
|
||||
# This job has no input audio - should not be retryable
|
||||
has_input = job.input_media_gcs_path or job.url
|
||||
assert not has_input
|
||||
|
||||
@@ -16,12 +16,20 @@ from unittest.mock import Mock, MagicMock, patch, AsyncMock
|
||||
from io import BytesIO
|
||||
|
||||
# Test the remote CLI's style parsing
|
||||
# Skip this class if flacfetch is not properly installed (remote_cli depends on it)
|
||||
try:
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, Config
|
||||
_remote_cli_available = True
|
||||
except ImportError:
|
||||
_remote_cli_available = False
|
||||
|
||||
|
||||
@pytest.mark.skipif(not _remote_cli_available, reason="flacfetch not properly installed")
|
||||
class TestRemoteCLIStyleParsing:
|
||||
"""Test that remote CLI correctly parses style_params.json."""
|
||||
|
||||
def test_parse_style_params_extracts_file_paths(self):
|
||||
"""Test that _parse_style_params extracts all file references."""
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, Config
|
||||
|
||||
# Create a mock style_params.json
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
@@ -79,7 +87,6 @@ class TestRemoteCLIStyleParsing:
|
||||
|
||||
def test_parse_style_params_handles_missing_files(self):
|
||||
"""Test that _parse_style_params ignores non-existent files."""
|
||||
from karaoke_gen.utils.remote_cli import RemoteKaraokeClient, Config
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
style_params = {
|
||||
|
||||
@@ -0,0 +1,516 @@
|
||||
"""
|
||||
Tests for the theme service and API endpoints.
|
||||
|
||||
Tests theme listing, retrieval, color override application, and job style preparation.
|
||||
"""
|
||||
import json
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch, Mock
|
||||
from datetime import datetime
|
||||
|
||||
from backend.models.theme import (
|
||||
ThemeSummary,
|
||||
ThemeDetail,
|
||||
ThemeMetadata,
|
||||
ThemeRegistry,
|
||||
ColorOverrides,
|
||||
hex_to_rgba,
|
||||
rgba_to_hex,
|
||||
)
|
||||
from backend.services.theme_service import ThemeService, get_theme_service
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Color Conversion Tests
|
||||
# =============================================================================
|
||||
|
||||
class TestColorConversion:
|
||||
"""Tests for hex/rgba color conversion utilities."""
|
||||
|
||||
def test_hex_to_rgba_basic(self):
|
||||
"""Test basic hex to RGBA conversion."""
|
||||
result = hex_to_rgba("#7070F7")
|
||||
assert result == "112, 112, 247, 255"
|
||||
|
||||
def test_hex_to_rgba_with_custom_alpha(self):
|
||||
"""Test hex to RGBA with custom alpha."""
|
||||
result = hex_to_rgba("#FF0000", alpha=128)
|
||||
assert result == "255, 0, 0, 128"
|
||||
|
||||
def test_hex_to_rgba_lowercase(self):
|
||||
"""Test hex with lowercase letters."""
|
||||
result = hex_to_rgba("#abcdef")
|
||||
assert result == "171, 205, 239, 255"
|
||||
|
||||
def test_hex_to_rgba_without_hash(self):
|
||||
"""Test hex without leading hash."""
|
||||
result = hex_to_rgba("FFFFFF")
|
||||
assert result == "255, 255, 255, 255"
|
||||
|
||||
def test_rgba_to_hex_basic(self):
|
||||
"""Test basic RGBA to hex conversion."""
|
||||
result = rgba_to_hex("112, 112, 247, 255")
|
||||
assert result == "#7070f7"
|
||||
|
||||
def test_rgba_to_hex_ignores_alpha(self):
|
||||
"""Test that alpha is ignored in conversion."""
|
||||
result = rgba_to_hex("255, 0, 0, 128")
|
||||
assert result == "#ff0000"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# ColorOverrides Model Tests
|
||||
# =============================================================================
|
||||
|
||||
class TestColorOverrides:
|
||||
"""Tests for ColorOverrides model."""
|
||||
|
||||
def test_has_overrides_empty(self):
|
||||
"""Test has_overrides with no overrides set."""
|
||||
overrides = ColorOverrides()
|
||||
assert overrides.has_overrides() is False
|
||||
|
||||
def test_has_overrides_with_artist_color(self):
|
||||
"""Test has_overrides with artist_color set."""
|
||||
overrides = ColorOverrides(artist_color="#FF0000")
|
||||
assert overrides.has_overrides() is True
|
||||
|
||||
def test_has_overrides_with_all_colors(self):
|
||||
"""Test has_overrides with all colors set."""
|
||||
overrides = ColorOverrides(
|
||||
artist_color="#FF0000",
|
||||
title_color="#00FF00",
|
||||
sung_lyrics_color="#0000FF",
|
||||
unsung_lyrics_color="#FFFF00",
|
||||
)
|
||||
assert overrides.has_overrides() is True
|
||||
|
||||
def test_to_dict_excludes_none(self):
|
||||
"""Test to_dict excludes None values."""
|
||||
overrides = ColorOverrides(artist_color="#FF0000")
|
||||
result = overrides.to_dict()
|
||||
assert result == {"artist_color": "#FF0000"}
|
||||
assert "title_color" not in result
|
||||
|
||||
def test_color_validation_valid(self):
|
||||
"""Test color validation accepts valid hex colors."""
|
||||
overrides = ColorOverrides(artist_color="#AbCdEf")
|
||||
assert overrides.artist_color == "#AbCdEf"
|
||||
|
||||
def test_color_validation_invalid(self):
|
||||
"""Test color validation rejects invalid colors."""
|
||||
with pytest.raises(ValueError):
|
||||
ColorOverrides(artist_color="red")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
ColorOverrides(artist_color="#GGG")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# ThemeService Tests
|
||||
# =============================================================================
|
||||
|
||||
class TestThemeService:
|
||||
"""Tests for ThemeService."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_storage(self):
|
||||
"""Create a mock storage service."""
|
||||
storage = MagicMock()
|
||||
return storage
|
||||
|
||||
@pytest.fixture
|
||||
def sample_metadata(self):
|
||||
"""Sample theme metadata for testing."""
|
||||
return {
|
||||
"version": 1,
|
||||
"themes": [
|
||||
{
|
||||
"id": "nomad",
|
||||
"name": "Nomad Karaoke",
|
||||
"description": "Golden artist text, professional look",
|
||||
"is_default": True,
|
||||
},
|
||||
{
|
||||
"id": "default",
|
||||
"name": "Default",
|
||||
"description": "Clean white text on black background",
|
||||
"is_default": False,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@pytest.fixture
|
||||
def sample_style_params(self):
|
||||
"""Sample style params for testing."""
|
||||
return {
|
||||
"intro": {
|
||||
"artist_color": "#ffdf6b",
|
||||
"title_color": "#ffffff",
|
||||
"background_image": "intro_bg.png",
|
||||
"font": "Montserrat-Bold.ttf",
|
||||
},
|
||||
"end": {
|
||||
"artist_color": "#ffdf6b",
|
||||
"title_color": "#ffffff",
|
||||
"background_image": "end_bg.png",
|
||||
"font": "Montserrat-Bold.ttf",
|
||||
},
|
||||
"karaoke": {
|
||||
"primary_color": "112, 112, 247, 255",
|
||||
"secondary_color": "255, 255, 255, 255",
|
||||
"background_image": "karaoke_bg.png",
|
||||
"font_path": "Montserrat-Bold.ttf",
|
||||
},
|
||||
"cdg": {
|
||||
"active_fill": "#7070F7",
|
||||
"inactive_fill": "#FFFFFF",
|
||||
"font_path": "Montserrat-Bold.ttf",
|
||||
},
|
||||
}
|
||||
|
||||
def test_list_themes_returns_summaries(self, mock_storage, sample_metadata):
|
||||
"""Test list_themes returns ThemeSummary objects."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url.com/preview.png"
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
themes = service.list_themes()
|
||||
|
||||
assert len(themes) == 2
|
||||
assert themes[0].id == "nomad"
|
||||
assert themes[0].name == "Nomad Karaoke"
|
||||
assert themes[0].is_default is True
|
||||
assert themes[0].preview_url is not None
|
||||
|
||||
def test_list_themes_handles_missing_preview(self, mock_storage, sample_metadata):
|
||||
"""Test list_themes handles missing preview images gracefully."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
mock_storage.file_exists.return_value = False
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
themes = service.list_themes()
|
||||
|
||||
assert len(themes) == 2
|
||||
assert themes[0].preview_url is None
|
||||
|
||||
def test_get_theme_returns_detail(self, mock_storage, sample_metadata, sample_style_params):
|
||||
"""Test get_theme returns ThemeDetail with style params."""
|
||||
mock_storage.download_json.side_effect = [sample_metadata, sample_style_params]
|
||||
mock_storage.file_exists.return_value = True
|
||||
mock_storage.generate_signed_url.return_value = "https://signed-url.com/preview.png"
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
theme = service.get_theme("nomad")
|
||||
|
||||
assert theme is not None
|
||||
assert theme.id == "nomad"
|
||||
assert theme.name == "Nomad Karaoke"
|
||||
assert "intro" in theme.style_params
|
||||
assert theme.style_params["intro"]["artist_color"] == "#ffdf6b"
|
||||
|
||||
def test_get_theme_returns_none_for_unknown(self, mock_storage, sample_metadata):
|
||||
"""Test get_theme returns None for unknown theme ID."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
theme = service.get_theme("unknown-theme")
|
||||
|
||||
assert theme is None
|
||||
|
||||
def test_theme_exists_true(self, mock_storage, sample_metadata):
|
||||
"""Test theme_exists returns True for existing theme."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
assert service.theme_exists("nomad") is True
|
||||
|
||||
def test_theme_exists_false(self, mock_storage, sample_metadata):
|
||||
"""Test theme_exists returns False for unknown theme."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
assert service.theme_exists("unknown") is False
|
||||
|
||||
def test_get_default_theme_id(self, mock_storage, sample_metadata):
|
||||
"""Test get_default_theme_id returns the default theme."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
assert service.get_default_theme_id() == "nomad"
|
||||
|
||||
def test_get_default_theme_id_no_default(self, mock_storage):
|
||||
"""Test get_default_theme_id returns None when no default."""
|
||||
mock_storage.download_json.return_value = {
|
||||
"version": 1,
|
||||
"themes": [{"id": "test", "name": "Test", "description": "Test", "is_default": False}],
|
||||
}
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
assert service.get_default_theme_id() is None
|
||||
|
||||
def test_apply_color_overrides_no_changes(self, sample_style_params):
|
||||
"""Test apply_color_overrides with empty overrides."""
|
||||
service = ThemeService()
|
||||
overrides = ColorOverrides()
|
||||
|
||||
result = service.apply_color_overrides(sample_style_params, overrides)
|
||||
|
||||
# Should return original (no deep copy needed when no changes)
|
||||
assert result == sample_style_params
|
||||
|
||||
def test_apply_color_overrides_artist_color(self, sample_style_params):
|
||||
"""Test apply_color_overrides applies artist_color."""
|
||||
service = ThemeService()
|
||||
overrides = ColorOverrides(artist_color="#FF0000")
|
||||
|
||||
result = service.apply_color_overrides(sample_style_params, overrides)
|
||||
|
||||
assert result["intro"]["artist_color"] == "#FF0000"
|
||||
assert result["end"]["artist_color"] == "#FF0000"
|
||||
assert result["cdg"]["artist_color"] == "#FF0000"
|
||||
# Original should be unchanged
|
||||
assert sample_style_params["intro"]["artist_color"] == "#ffdf6b"
|
||||
|
||||
def test_apply_color_overrides_sung_lyrics_color(self, sample_style_params):
|
||||
"""Test apply_color_overrides applies sung_lyrics_color with conversion."""
|
||||
service = ThemeService()
|
||||
overrides = ColorOverrides(sung_lyrics_color="#FF0000")
|
||||
|
||||
result = service.apply_color_overrides(sample_style_params, overrides)
|
||||
|
||||
# Karaoke uses RGBA format
|
||||
assert result["karaoke"]["primary_color"] == "255, 0, 0, 255"
|
||||
# CDG uses hex
|
||||
assert result["cdg"]["active_fill"] == "#FF0000"
|
||||
|
||||
def test_apply_color_overrides_unsung_lyrics_color(self, sample_style_params):
|
||||
"""Test apply_color_overrides applies unsung_lyrics_color."""
|
||||
service = ThemeService()
|
||||
overrides = ColorOverrides(unsung_lyrics_color="#00FF00")
|
||||
|
||||
result = service.apply_color_overrides(sample_style_params, overrides)
|
||||
|
||||
assert result["karaoke"]["secondary_color"] == "0, 255, 0, 255"
|
||||
assert result["cdg"]["inactive_fill"] == "#00FF00"
|
||||
|
||||
def test_metadata_cache(self, mock_storage, sample_metadata):
|
||||
"""Test metadata caching works."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
|
||||
# First call loads from GCS
|
||||
service.list_themes()
|
||||
assert mock_storage.download_json.call_count == 1
|
||||
|
||||
# Second call uses cache
|
||||
service.list_themes()
|
||||
assert mock_storage.download_json.call_count == 1
|
||||
|
||||
def test_invalidate_cache(self, mock_storage, sample_metadata):
|
||||
"""Test cache invalidation."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
|
||||
# Load metadata
|
||||
service.list_themes()
|
||||
assert mock_storage.download_json.call_count == 1
|
||||
|
||||
# Invalidate cache
|
||||
service.invalidate_cache()
|
||||
|
||||
# Next call should reload
|
||||
service.list_themes()
|
||||
assert mock_storage.download_json.call_count == 2
|
||||
|
||||
def test_prepare_job_style(self, mock_storage, sample_metadata, sample_style_params):
|
||||
"""Test prepare_job_style creates job style from theme."""
|
||||
mock_storage.download_json.side_effect = [sample_metadata, sample_style_params]
|
||||
mock_storage.file_exists.return_value = True
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
style_path, style_assets = service.prepare_job_style("job123", "nomad")
|
||||
|
||||
# Should upload modified style_params.json
|
||||
mock_storage.upload_json.assert_called_once()
|
||||
assert style_path == "uploads/job123/style/style_params.json"
|
||||
|
||||
def test_prepare_job_style_with_overrides(self, mock_storage, sample_metadata, sample_style_params):
|
||||
"""Test prepare_job_style applies color overrides."""
|
||||
# prepare_job_style calls get_theme_style_params which directly downloads style_params.json
|
||||
# No metadata lookup happens unless we've cached it previously
|
||||
mock_storage.download_json.return_value = sample_style_params
|
||||
mock_storage.file_exists.return_value = True
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
overrides = ColorOverrides(artist_color="#FF0000")
|
||||
|
||||
style_path, style_assets = service.prepare_job_style("job123", "nomad", overrides)
|
||||
|
||||
# Check that upload_json was called with modified style params
|
||||
call_args = mock_storage.upload_json.call_args
|
||||
uploaded_path = call_args[0][0] # First positional arg is the path
|
||||
uploaded_style = call_args[0][1] # Second positional arg is the data
|
||||
|
||||
assert uploaded_path == "uploads/job123/style/style_params.json"
|
||||
# Check that artist_color override was applied
|
||||
assert uploaded_style["intro"]["artist_color"] == "#FF0000"
|
||||
assert uploaded_style["end"]["artist_color"] == "#FF0000"
|
||||
|
||||
def test_prepare_job_style_unknown_theme_raises(self, mock_storage, sample_metadata):
|
||||
"""Test prepare_job_style raises for unknown theme."""
|
||||
# First download_json returns metadata (no unknown theme)
|
||||
# Second download_json for style_params.json should fail
|
||||
def download_json_side_effect(path):
|
||||
if "_metadata.json" in path:
|
||||
return sample_metadata
|
||||
# Unknown theme path - raise exception
|
||||
raise Exception(f"File not found: {path}")
|
||||
|
||||
mock_storage.download_json.side_effect = download_json_side_effect
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
|
||||
with pytest.raises(ValueError, match="Theme not found"):
|
||||
service.prepare_job_style("job123", "unknown-theme")
|
||||
|
||||
def test_get_youtube_description(self, mock_storage, sample_metadata):
|
||||
"""Test get_youtube_description returns template text."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
mock_storage.file_exists.return_value = True
|
||||
|
||||
# Mock the download_file to write content to temp file
|
||||
def mock_download(gcs_path, local_path):
|
||||
with open(local_path, "w") as f:
|
||||
f.write("Thank you for watching!")
|
||||
|
||||
mock_storage.download_file.side_effect = mock_download
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
desc = service.get_youtube_description("nomad")
|
||||
|
||||
assert desc == "Thank you for watching!"
|
||||
|
||||
def test_get_youtube_description_not_found(self, mock_storage, sample_metadata):
|
||||
"""Test get_youtube_description returns None when no template."""
|
||||
mock_storage.download_json.return_value = sample_metadata
|
||||
mock_storage.file_exists.return_value = False
|
||||
|
||||
service = ThemeService(storage=mock_storage)
|
||||
desc = service.get_youtube_description("nomad")
|
||||
|
||||
assert desc is None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# API Endpoint Tests
|
||||
# =============================================================================
|
||||
|
||||
class TestThemeAPI:
|
||||
"""Tests for theme API endpoints."""
|
||||
|
||||
@pytest.fixture
|
||||
def sample_metadata(self):
|
||||
"""Sample theme metadata."""
|
||||
return {
|
||||
"version": 1,
|
||||
"themes": [
|
||||
{
|
||||
"id": "nomad",
|
||||
"name": "Nomad Karaoke",
|
||||
"description": "Golden artist text",
|
||||
"is_default": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
def test_list_themes_endpoint(self, test_client, sample_metadata):
|
||||
"""Test GET /api/themes returns theme list."""
|
||||
with patch("backend.api.routes.themes.get_theme_service") as mock_get_service:
|
||||
mock_service = MagicMock()
|
||||
mock_service.list_themes.return_value = [
|
||||
ThemeSummary(
|
||||
id="nomad",
|
||||
name="Nomad Karaoke",
|
||||
description="Golden artist text",
|
||||
preview_url="https://example.com/preview.png",
|
||||
is_default=True,
|
||||
)
|
||||
]
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = test_client.get("/api/themes")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["themes"]) == 1
|
||||
assert data["themes"][0]["id"] == "nomad"
|
||||
assert data["themes"][0]["is_default"] is True
|
||||
|
||||
def test_get_theme_endpoint(self, test_client):
|
||||
"""Test GET /api/themes/{theme_id} returns theme detail."""
|
||||
with patch("backend.api.routes.themes.get_theme_service") as mock_get_service:
|
||||
mock_service = MagicMock()
|
||||
mock_service.get_theme.return_value = ThemeDetail(
|
||||
id="nomad",
|
||||
name="Nomad Karaoke",
|
||||
description="Golden artist text",
|
||||
is_default=True,
|
||||
style_params={"intro": {"artist_color": "#ffdf6b"}},
|
||||
)
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = test_client.get("/api/themes/nomad")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["theme"]["id"] == "nomad"
|
||||
assert "style_params" in data["theme"]
|
||||
|
||||
def test_get_theme_not_found(self, test_client):
|
||||
"""Test GET /api/themes/{theme_id} returns 404 for unknown theme."""
|
||||
with patch("backend.api.routes.themes.get_theme_service") as mock_get_service:
|
||||
mock_service = MagicMock()
|
||||
mock_service.get_theme.return_value = None
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = test_client.get("/api/themes/unknown")
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_get_theme_preview_endpoint(self, test_client):
|
||||
"""Test GET /api/themes/{theme_id}/preview returns preview URL."""
|
||||
with patch("backend.api.routes.themes.get_theme_service") as mock_get_service:
|
||||
mock_service = MagicMock()
|
||||
mock_service.theme_exists.return_value = True
|
||||
mock_service.get_theme.return_value = ThemeDetail(
|
||||
id="nomad",
|
||||
name="Nomad Karaoke",
|
||||
description="Golden artist text",
|
||||
preview_url="https://example.com/preview.png",
|
||||
is_default=True,
|
||||
)
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = test_client.get("/api/themes/nomad/preview")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "preview_url" in data
|
||||
|
||||
def test_get_youtube_description_endpoint(self, test_client):
|
||||
"""Test GET /api/themes/{theme_id}/youtube-description returns description."""
|
||||
with patch("backend.api.routes.themes.get_theme_service") as mock_get_service:
|
||||
mock_service = MagicMock()
|
||||
mock_service.theme_exists.return_value = True
|
||||
mock_service.get_youtube_description.return_value = "Thank you for watching!"
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = test_client.get("/api/themes/nomad/youtube-description")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["description"] == "Thank you for watching!"
|
||||
@@ -10,6 +10,14 @@ from io import BytesIO
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def upload_auth_headers():
|
||||
"""Auth headers for file upload tests (no Content-Type, let multipart work)."""
|
||||
return {
|
||||
"Authorization": "Bearer test-admin-token"
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job():
|
||||
"""Create a standard mock job."""
|
||||
@@ -65,37 +73,41 @@ def client(mock_services):
|
||||
class TestFileUploadEndpoint:
|
||||
"""Tests for POST /api/jobs/upload."""
|
||||
|
||||
def test_upload_flac_returns_200(self, client, mock_services):
|
||||
def test_upload_flac_returns_200(self, client, mock_services, upload_auth_headers):
|
||||
"""Test uploading FLAC file returns 200."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"fake audio"), "audio/flac")},
|
||||
data={"artist": "Test Artist", "title": "Test Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_upload_mp3_returns_200(self, client, mock_services):
|
||||
def test_upload_mp3_returns_200(self, client, mock_services, upload_auth_headers):
|
||||
"""Test uploading MP3 file returns 200."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.mp3", BytesIO(b"fake audio"), "audio/mpeg")},
|
||||
data={"artist": "Test Artist", "title": "Test Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_upload_wav_returns_200(self, client, mock_services):
|
||||
def test_upload_wav_returns_200(self, client, mock_services, upload_auth_headers):
|
||||
"""Test uploading WAV file returns 200."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.wav", BytesIO(b"fake audio"), "audio/wav")},
|
||||
data={"artist": "Test Artist", "title": "Test Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_upload_returns_job_id(self, client, mock_services):
|
||||
def test_upload_returns_job_id(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload response contains job_id."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"fake audio"), "audio/flac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
@@ -103,10 +115,11 @@ class TestFileUploadEndpoint:
|
||||
assert "job_id" in data
|
||||
assert data["status"] == "success"
|
||||
|
||||
def test_upload_returns_filename(self, client, mock_services):
|
||||
def test_upload_returns_filename(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload response contains original filename."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("my_song.flac", BytesIO(b"fake audio"), "audio/flac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
@@ -114,84 +127,93 @@ class TestFileUploadEndpoint:
|
||||
assert "filename" in data
|
||||
assert data["filename"] == "my_song.flac"
|
||||
|
||||
def test_upload_rejects_txt_file(self, client, mock_services):
|
||||
def test_upload_rejects_txt_file(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload rejects text files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.txt", BytesIO(b"not audio"), "text/plain")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
def test_upload_rejects_pdf_file(self, client, mock_services):
|
||||
def test_upload_rejects_pdf_file(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload rejects PDF files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("doc.pdf", BytesIO(b"pdf content"), "application/pdf")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
def test_upload_rejects_exe_file(self, client, mock_services):
|
||||
def test_upload_rejects_exe_file(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload rejects executable files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("app.exe", BytesIO(b"exe content"), "application/octet-stream")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
def test_upload_requires_artist(self, client, mock_services):
|
||||
def test_upload_requires_artist(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload requires artist field."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"audio"), "audio/flac")},
|
||||
data={"title": "Song"} # Missing artist
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_upload_requires_title(self, client, mock_services):
|
||||
def test_upload_requires_title(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload requires title field."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"audio"), "audio/flac")},
|
||||
data={"artist": "Artist"} # Missing title
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_upload_requires_file(self, client, mock_services):
|
||||
def test_upload_requires_file(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload requires file."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
data={"artist": "Artist", "title": "Song"}
|
||||
# Missing file
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_upload_triggers_workers(self, client, mock_services):
|
||||
def test_upload_triggers_workers(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload triggers audio and lyrics workers."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"audio"), "audio/flac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
# Workers should be triggered in background
|
||||
|
||||
def test_upload_creates_job(self, client, mock_services):
|
||||
def test_upload_creates_job(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload creates job in job manager."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"audio"), "audio/flac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
mock_services['job_manager'].create_job.assert_called()
|
||||
|
||||
def test_upload_stores_file_to_gcs(self, client, mock_services):
|
||||
def test_upload_stores_file_to_gcs(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload stores file to GCS."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.flac", BytesIO(b"audio"), "audio/flac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
@@ -202,28 +224,31 @@ class TestFileUploadEndpoint:
|
||||
class TestUploadValidation:
|
||||
"""Tests for upload validation logic."""
|
||||
|
||||
def test_upload_accepts_m4a(self, client, mock_services):
|
||||
def test_upload_accepts_m4a(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload accepts M4A files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.m4a", BytesIO(b"audio"), "audio/mp4")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_upload_accepts_ogg(self, client, mock_services):
|
||||
def test_upload_accepts_ogg(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload accepts OGG files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.ogg", BytesIO(b"audio"), "audio/ogg")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_upload_accepts_aac(self, client, mock_services):
|
||||
def test_upload_accepts_aac(self, client, mock_services, upload_auth_headers):
|
||||
"""Test upload accepts AAC files."""
|
||||
response = client.post(
|
||||
"/api/jobs/upload",
|
||||
headers=upload_auth_headers,
|
||||
files={"file": ("test.aac", BytesIO(b"audio"), "audio/aac")},
|
||||
data={"artist": "Test", "title": "Song"}
|
||||
)
|
||||
|
||||
@@ -546,6 +546,36 @@ class TestRenderVideoWorkerConfiguration:
|
||||
assert subtitle_offset == -250
|
||||
|
||||
|
||||
class TestRenderVideoWorkerCountdownPadding:
|
||||
"""Tests for render_video_worker countdown detection and audio padding.
|
||||
|
||||
This ensures that when corrections with countdown timestamps are loaded,
|
||||
the audio is padded to match. This prevents video desynchronization.
|
||||
"""
|
||||
|
||||
def test_countdown_processor_import(self):
|
||||
"""Test that render_video_worker imports CountdownProcessor."""
|
||||
from backend.workers.render_video_worker import CountdownProcessor
|
||||
assert CountdownProcessor is not None
|
||||
|
||||
def test_countdown_processor_has_process_method(self):
|
||||
"""Test that CountdownProcessor has the process method (main API)."""
|
||||
from lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
|
||||
countdown_processor = CountdownProcessor(cache_dir="/tmp")
|
||||
assert hasattr(countdown_processor, 'process')
|
||||
assert callable(countdown_processor.process)
|
||||
|
||||
def test_countdown_processor_constants(self):
|
||||
"""Test that CountdownProcessor has expected constants."""
|
||||
from lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
|
||||
# Verify the constants exist (these control countdown behavior)
|
||||
assert hasattr(CountdownProcessor, 'COUNTDOWN_TEXT')
|
||||
assert hasattr(CountdownProcessor, 'COUNTDOWN_PADDING_SECONDS')
|
||||
assert hasattr(CountdownProcessor, 'COUNTDOWN_THRESHOLD_SECONDS')
|
||||
|
||||
|
||||
class TestDownloadHelpers:
|
||||
"""Tests for download helper functions in workers."""
|
||||
|
||||
|
||||
@@ -405,10 +405,14 @@ async def download_audio(
|
||||
Path to downloaded audio file, or None if failed
|
||||
"""
|
||||
try:
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
|
||||
# Case 1: File was uploaded to GCS
|
||||
if job.input_media_gcs_path:
|
||||
logger.info(f"Job {job_id}: Downloading uploaded file from GCS: {job.input_media_gcs_path}")
|
||||
local_path = os.path.join(temp_dir, job.filename or "input.flac")
|
||||
# Sanitize filename to handle Unicode chars that cause HTTP header encoding issues
|
||||
safe_filename = sanitize_filename(job.filename) if job.filename else "input.flac"
|
||||
local_path = os.path.join(temp_dir, safe_filename)
|
||||
storage.download_file(job.input_media_gcs_path, local_path)
|
||||
logger.info(f"Job {job_id}: Downloaded uploaded file to {local_path}")
|
||||
return local_path
|
||||
|
||||
@@ -37,6 +37,7 @@ from backend.services.tracing import job_span, add_span_event, add_span_attribut
|
||||
|
||||
# Import from lyrics_transcriber (submodule)
|
||||
from lyrics_transcriber.output.generator import OutputGenerator
|
||||
from lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from lyrics_transcriber.types import CorrectionResult
|
||||
from lyrics_transcriber.core.config import OutputConfig
|
||||
|
||||
@@ -112,204 +113,238 @@ async def process_render_video(job_id: str) -> bool:
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
job_log.info(f"Created temp directory: {temp_dir}")
|
||||
# 1. Download corrected corrections data
|
||||
corrections_path = os.path.join(temp_dir, "corrections.json")
|
||||
|
||||
# Try updated corrections first (from human review), fall back to original
|
||||
corrections_gcs_updated = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
corrections_gcs_original = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
|
||||
# Get GCS path from file_urls
|
||||
corrections_url = job.file_urls.get('lyrics', {}).get('corrections_updated')
|
||||
if not corrections_url:
|
||||
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
|
||||
if not corrections_url:
|
||||
# Try direct GCS paths
|
||||
if storage.file_exists(corrections_gcs_updated):
|
||||
corrections_gcs = corrections_gcs_updated
|
||||
elif storage.file_exists(corrections_gcs_original):
|
||||
corrections_gcs = corrections_gcs_original
|
||||
|
||||
# Try updated corrections first (from human review), fall back to original
|
||||
corrections_gcs_updated = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
corrections_gcs_original = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
|
||||
# Get GCS path from file_urls
|
||||
corrections_url = job.file_urls.get('lyrics', {}).get('corrections_updated')
|
||||
if not corrections_url:
|
||||
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
|
||||
if not corrections_url:
|
||||
# Try direct GCS paths
|
||||
if storage.file_exists(corrections_gcs_updated):
|
||||
corrections_gcs = corrections_gcs_updated
|
||||
elif storage.file_exists(corrections_gcs_original):
|
||||
corrections_gcs = corrections_gcs_original
|
||||
else:
|
||||
raise FileNotFoundError(f"No corrections file found for job {job_id}")
|
||||
else:
|
||||
raise FileNotFoundError(f"No corrections file found for job {job_id}")
|
||||
else:
|
||||
# Extract GCS path from URL
|
||||
corrections_gcs = _extract_gcs_path(corrections_url)
|
||||
|
||||
# 2. Load the ORIGINAL corrections (has full structure)
|
||||
original_corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
original_corrections_path = os.path.join(temp_dir, "corrections_original.json")
|
||||
|
||||
job_log.info(f"Downloading original corrections from {original_corrections_gcs}")
|
||||
logger.info(f"Job {job_id}: Downloading original corrections from {original_corrections_gcs}")
|
||||
storage.download_file(original_corrections_gcs, original_corrections_path)
|
||||
|
||||
with open(original_corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
# 3. Check if there are updated corrections (from review UI)
|
||||
# The frontend sends only partial data: {corrections, corrected_segments}
|
||||
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
if storage.file_exists(updated_corrections_gcs):
|
||||
job_log.info("Found updated corrections from review, merging")
|
||||
logger.info(f"Job {job_id}: Found updated corrections, merging")
|
||||
updated_path = os.path.join(temp_dir, "corrections_updated.json")
|
||||
storage.download_file(updated_corrections_gcs, updated_path)
|
||||
# Extract GCS path from URL
|
||||
corrections_gcs = _extract_gcs_path(corrections_url)
|
||||
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
# 2. Load the ORIGINAL corrections (has full structure)
|
||||
original_corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
original_corrections_path = os.path.join(temp_dir, "corrections_original.json")
|
||||
|
||||
# Merge: update the original with the user's corrections
|
||||
if 'corrections' in updated_data:
|
||||
original_data['corrections'] = updated_data['corrections']
|
||||
if 'corrected_segments' in updated_data:
|
||||
original_data['corrected_segments'] = updated_data['corrected_segments']
|
||||
job_log.info(f"Downloading original corrections from {original_corrections_gcs}")
|
||||
logger.info(f"Job {job_id}: Downloading original corrections from {original_corrections_gcs}")
|
||||
storage.download_file(original_corrections_gcs, original_corrections_path)
|
||||
|
||||
job_log.info("Merged user corrections into original data")
|
||||
logger.info(f"Job {job_id}: Merged user corrections into original data")
|
||||
|
||||
# 4. Convert to CorrectionResult
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
|
||||
# 3. Download audio file
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
|
||||
if not audio_gcs_path:
|
||||
raise FileNotFoundError(f"No input audio path for job {job_id}")
|
||||
|
||||
job_log.info(f"Downloading audio from {audio_gcs_path}")
|
||||
logger.info(f"Job {job_id}: Downloading audio from {audio_gcs_path}")
|
||||
storage.download_file(audio_gcs_path, audio_path)
|
||||
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
|
||||
|
||||
# 4. Get or create styles using the unified style loader
|
||||
job_log.info("Loading style configuration...")
|
||||
job_log.info(f" job.style_params_gcs_path: {job.style_params_gcs_path}")
|
||||
job_log.info(f" job.style_assets: {list(job.style_assets.keys()) if job.style_assets else 'None'}")
|
||||
|
||||
styles_path, style_data = load_styles_from_gcs(
|
||||
style_params_gcs_path=job.style_params_gcs_path,
|
||||
style_assets=job.style_assets,
|
||||
temp_dir=temp_dir,
|
||||
download_func=storage.download_file,
|
||||
logger=job_log,
|
||||
)
|
||||
|
||||
# 5. Configure OutputGenerator
|
||||
output_dir = os.path.join(temp_dir, "output")
|
||||
cache_dir = os.path.join(temp_dir, "cache")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
job_log.info(f"Using styles from: {styles_path}")
|
||||
|
||||
# Get subtitle offset from job (user-specified timing adjustment)
|
||||
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
|
||||
if subtitle_offset != 0:
|
||||
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
|
||||
|
||||
config = OutputConfig(
|
||||
output_dir=output_dir,
|
||||
cache_dir=cache_dir,
|
||||
output_styles_json=styles_path,
|
||||
render_video=True,
|
||||
generate_cdg=False, # CDG optional, generated separately
|
||||
generate_plain_text=True,
|
||||
generate_lrc=True,
|
||||
video_resolution="4k",
|
||||
subtitle_offset_ms=subtitle_offset
|
||||
)
|
||||
|
||||
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
|
||||
|
||||
output_generator = OutputGenerator(config, logger)
|
||||
|
||||
# 6. Generate outputs (video, LRC, ASS, etc.)
|
||||
output_prefix = f"{job.artist or 'Unknown'} - {job.title or 'Unknown'}"
|
||||
job_log.info(f"Generating outputs with prefix '{output_prefix}'")
|
||||
logger.info(f"Job {job_id}: Generating outputs with prefix '{output_prefix}'")
|
||||
|
||||
outputs = output_generator.generate_outputs(
|
||||
transcription_corrected=correction_result,
|
||||
lyrics_results={}, # Reference lyrics already in correction_result
|
||||
output_prefix=output_prefix,
|
||||
audio_filepath=audio_path,
|
||||
artist=job.artist,
|
||||
title=job.title
|
||||
)
|
||||
|
||||
# 7. Upload video to GCS
|
||||
if outputs.video and os.path.exists(outputs.video):
|
||||
video_size = os.path.getsize(outputs.video)
|
||||
job_log.info(f"Video generated: {video_size} bytes")
|
||||
video_gcs_path = f"jobs/{job_id}/videos/with_vocals.mkv"
|
||||
video_url = storage.upload_file(outputs.video, video_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'videos', 'with_vocals', video_url)
|
||||
job_log.info(f"Uploaded with_vocals.mkv to GCS")
|
||||
logger.info(f"Job {job_id}: Uploaded with_vocals.mkv ({video_size} bytes)")
|
||||
else:
|
||||
job_log.error("Video generation failed - no output file produced!")
|
||||
raise Exception("Video generation failed - no output file produced")
|
||||
|
||||
# 8. Upload LRC file
|
||||
if outputs.lrc and os.path.exists(outputs.lrc):
|
||||
lrc_gcs_path = f"jobs/{job_id}/lyrics/karaoke.lrc"
|
||||
lrc_url = storage.upload_file(outputs.lrc, lrc_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'lrc', lrc_url)
|
||||
job_log.info("Uploaded karaoke.lrc")
|
||||
logger.info(f"Job {job_id}: Uploaded karaoke.lrc")
|
||||
|
||||
# 9. Upload ASS subtitle file
|
||||
if outputs.ass and os.path.exists(outputs.ass):
|
||||
ass_gcs_path = f"jobs/{job_id}/lyrics/karaoke.ass"
|
||||
ass_url = storage.upload_file(outputs.ass, ass_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'ass', ass_url)
|
||||
job_log.info("Uploaded karaoke.ass")
|
||||
logger.info(f"Job {job_id}: Uploaded karaoke.ass")
|
||||
|
||||
# 10. Upload corrected text files
|
||||
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
|
||||
txt_gcs_path = f"jobs/{job_id}/lyrics/corrected.txt"
|
||||
txt_url = storage.upload_file(outputs.corrected_txt, txt_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', txt_url)
|
||||
job_log.info("Uploaded corrected.txt")
|
||||
logger.info(f"Job {job_id}: Uploaded corrected.txt")
|
||||
|
||||
# 11. Analyze backing vocals for intelligent instrumental selection
|
||||
job_log.info("Analyzing backing vocals for instrumental selection...")
|
||||
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
|
||||
|
||||
# 12. Transition based on prep_only flag
|
||||
if getattr(job, 'prep_only', False):
|
||||
# Prep-only mode: stop here and mark as prep complete
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.PREP_COMPLETE,
|
||||
progress=100,
|
||||
message="Prep phase complete - download outputs to continue locally"
|
||||
with open(original_corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
# 3. Check if there are updated corrections (from review UI)
|
||||
# The frontend sends only partial data: {corrections, corrected_segments}
|
||||
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
if storage.file_exists(updated_corrections_gcs):
|
||||
job_log.info("Found updated corrections from review, merging")
|
||||
logger.info(f"Job {job_id}: Found updated corrections, merging")
|
||||
updated_path = os.path.join(temp_dir, "corrections_updated.json")
|
||||
storage.download_file(updated_corrections_gcs, updated_path)
|
||||
|
||||
with open(updated_path, 'r', encoding='utf-8') as f:
|
||||
updated_data = json.load(f)
|
||||
|
||||
# Merge: update the original with the user's corrections
|
||||
if 'corrections' in updated_data:
|
||||
original_data['corrections'] = updated_data['corrections']
|
||||
if 'corrected_segments' in updated_data:
|
||||
original_data['corrected_segments'] = updated_data['corrected_segments']
|
||||
|
||||
job_log.info("Merged user corrections into original data")
|
||||
logger.info(f"Job {job_id}: Merged user corrections into original data")
|
||||
|
||||
# 4. Convert to CorrectionResult
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
|
||||
|
||||
# 5. Download audio file
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
|
||||
if not audio_gcs_path:
|
||||
raise FileNotFoundError(f"No input audio path for job {job_id}")
|
||||
|
||||
job_log.info(f"Downloading audio from {audio_gcs_path}")
|
||||
logger.info(f"Job {job_id}: Downloading audio from {audio_gcs_path}")
|
||||
storage.download_file(audio_gcs_path, audio_path)
|
||||
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
|
||||
|
||||
# Process countdown intro if needed (for songs that start too quickly)
|
||||
# This adds "3... 2... 1..." segment and pads audio with 3s silence
|
||||
# Note: Countdown is deferred to this stage (not during lyrics transcription)
|
||||
# so the review UI can show the original timing without the 3s shift
|
||||
countdown_processor = CountdownProcessor(cache_dir=temp_dir, logger=logger)
|
||||
correction_result, audio_path, padding_added, padding_seconds = countdown_processor.process(
|
||||
correction_result=correction_result,
|
||||
audio_filepath=audio_path,
|
||||
)
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY) ===")
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("prep_only", True)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s prep_only=true")
|
||||
else:
|
||||
# Normal mode: proceed to instrumental selection
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_INSTRUMENTAL_SELECTION,
|
||||
progress=80,
|
||||
message="Video rendered - select your instrumental"
|
||||
if padding_added:
|
||||
job_log.info(f"Countdown added: {padding_seconds}s padding applied to audio and timestamps shifted")
|
||||
else:
|
||||
job_log.info("No countdown needed - song starts after 3 seconds")
|
||||
|
||||
# 6. Get or create styles using the unified style loader
|
||||
job_log.info("Loading style configuration...")
|
||||
job_log.info(f" job.style_params_gcs_path: {job.style_params_gcs_path}")
|
||||
job_log.info(f" job.style_assets: {list(job.style_assets.keys()) if job.style_assets else 'None'}")
|
||||
|
||||
styles_path, style_data = load_styles_from_gcs(
|
||||
style_params_gcs_path=job.style_params_gcs_path,
|
||||
style_assets=job.style_assets,
|
||||
temp_dir=temp_dir,
|
||||
download_func=storage.download_file,
|
||||
logger=job_log,
|
||||
)
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE ===")
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s")
|
||||
return True
|
||||
|
||||
# 7. Configure OutputGenerator
|
||||
output_dir = os.path.join(temp_dir, "output")
|
||||
cache_dir = os.path.join(temp_dir, "cache")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
job_log.info(f"Using styles from: {styles_path}")
|
||||
|
||||
# Get subtitle offset from job (user-specified timing adjustment)
|
||||
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
|
||||
if subtitle_offset != 0:
|
||||
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
|
||||
|
||||
config = OutputConfig(
|
||||
output_dir=output_dir,
|
||||
cache_dir=cache_dir,
|
||||
output_styles_json=styles_path,
|
||||
render_video=True,
|
||||
generate_cdg=False, # CDG optional, generated separately
|
||||
generate_plain_text=True,
|
||||
generate_lrc=True,
|
||||
video_resolution="4k",
|
||||
subtitle_offset_ms=subtitle_offset
|
||||
)
|
||||
|
||||
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
|
||||
|
||||
output_generator = OutputGenerator(config, logger)
|
||||
|
||||
# 8. Generate outputs (video, LRC, ASS, etc.)
|
||||
output_prefix = f"{job.artist or 'Unknown'} - {job.title or 'Unknown'}"
|
||||
job_log.info(f"Generating outputs with prefix '{output_prefix}'")
|
||||
logger.info(f"Job {job_id}: Generating outputs with prefix '{output_prefix}'")
|
||||
|
||||
outputs = output_generator.generate_outputs(
|
||||
transcription_corrected=correction_result,
|
||||
lyrics_results={}, # Reference lyrics already in correction_result
|
||||
output_prefix=output_prefix,
|
||||
audio_filepath=audio_path,
|
||||
artist=job.artist,
|
||||
title=job.title
|
||||
)
|
||||
|
||||
# 9. Upload video to GCS
|
||||
if outputs.video and os.path.exists(outputs.video):
|
||||
video_size = os.path.getsize(outputs.video)
|
||||
job_log.info(f"Video generated: {video_size} bytes")
|
||||
video_gcs_path = f"jobs/{job_id}/videos/with_vocals.mkv"
|
||||
video_url = storage.upload_file(outputs.video, video_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'videos', 'with_vocals', video_url)
|
||||
job_log.info(f"Uploaded with_vocals.mkv to GCS")
|
||||
logger.info(f"Job {job_id}: Uploaded with_vocals.mkv ({video_size} bytes)")
|
||||
else:
|
||||
job_log.error("Video generation failed - no output file produced!")
|
||||
raise Exception("Video generation failed - no output file produced")
|
||||
|
||||
# 10. Upload LRC file
|
||||
if outputs.lrc and os.path.exists(outputs.lrc):
|
||||
lrc_gcs_path = f"jobs/{job_id}/lyrics/karaoke.lrc"
|
||||
lrc_url = storage.upload_file(outputs.lrc, lrc_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'lrc', lrc_url)
|
||||
job_log.info("Uploaded karaoke.lrc")
|
||||
logger.info(f"Job {job_id}: Uploaded karaoke.lrc")
|
||||
|
||||
# 11. Upload ASS subtitle file
|
||||
if outputs.ass and os.path.exists(outputs.ass):
|
||||
ass_gcs_path = f"jobs/{job_id}/lyrics/karaoke.ass"
|
||||
ass_url = storage.upload_file(outputs.ass, ass_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'ass', ass_url)
|
||||
job_log.info("Uploaded karaoke.ass")
|
||||
logger.info(f"Job {job_id}: Uploaded karaoke.ass")
|
||||
|
||||
# 12. Upload corrected text files
|
||||
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
|
||||
txt_gcs_path = f"jobs/{job_id}/lyrics/corrected.txt"
|
||||
txt_url = storage.upload_file(outputs.corrected_txt, txt_gcs_path)
|
||||
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', txt_url)
|
||||
job_log.info("Uploaded corrected.txt")
|
||||
logger.info(f"Job {job_id}: Uploaded corrected.txt")
|
||||
|
||||
# 13. Analyze backing vocals for intelligent instrumental selection
|
||||
job_log.info("Analyzing backing vocals for instrumental selection...")
|
||||
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
|
||||
|
||||
# 14. Transition based on prep_only flag and existing instrumental
|
||||
if getattr(job, 'prep_only', False):
|
||||
# Prep-only mode: stop here and mark as prep complete
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.PREP_COMPLETE,
|
||||
progress=100,
|
||||
message="Prep phase complete - download outputs to continue locally"
|
||||
)
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY) ===")
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("prep_only", True)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s prep_only=true")
|
||||
elif getattr(job, 'existing_instrumental_gcs_path', None):
|
||||
# Existing instrumental provided - skip selection, auto-use it
|
||||
# Store selection as 'custom' to indicate user-provided instrumental
|
||||
job_manager.update_state_data(job_id, 'instrumental_selection', 'custom')
|
||||
job_log.info("Existing instrumental provided - skipping selection, using user-provided file")
|
||||
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.INSTRUMENTAL_SELECTED,
|
||||
progress=82,
|
||||
message="Using user-provided instrumental"
|
||||
)
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE (EXISTING INSTRUMENTAL) ===")
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("existing_instrumental", True)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s existing_instrumental=true")
|
||||
|
||||
# Trigger video worker directly since no user selection needed
|
||||
from backend.workers.video_worker import run_video_worker
|
||||
job_log.info("Triggering video worker for final encoding...")
|
||||
await run_video_worker(job_id, job_manager, storage)
|
||||
else:
|
||||
# Normal mode: proceed to instrumental selection
|
||||
job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.AWAITING_INSTRUMENTAL_SELECTION,
|
||||
progress=80,
|
||||
message="Video rendered - select your instrumental"
|
||||
)
|
||||
job_log.info("=== RENDER VIDEO WORKER COMPLETE ===")
|
||||
duration = time.time() - start_time
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
duration = time.time() - start_time
|
||||
|
||||
@@ -478,7 +478,8 @@ def _validate_prerequisites(job) -> bool:
|
||||
logger.error(f"Job {job.job_id}: No instrumental selected")
|
||||
return False
|
||||
|
||||
if instrumental_selection not in ['clean', 'with_backing']:
|
||||
# 'custom' is valid when user provided existing_instrumental
|
||||
if instrumental_selection not in ['clean', 'with_backing', 'custom']:
|
||||
logger.error(f"Job {job.job_id}: Invalid instrumental selection: {instrumental_selection}")
|
||||
return False
|
||||
|
||||
@@ -494,7 +495,14 @@ def _validate_prerequisites(job) -> bool:
|
||||
logger.error(f"Job {job.job_id}: Missing lyrics video")
|
||||
return False
|
||||
|
||||
# Check instrumental exists
|
||||
# Check instrumental exists - for 'custom', check existing_instrumental_gcs_path instead of stems
|
||||
if instrumental_selection == 'custom':
|
||||
existing_instrumental_path = getattr(job, 'existing_instrumental_gcs_path', None)
|
||||
if not existing_instrumental_path:
|
||||
logger.error(f"Job {job.job_id}: Custom instrumental selected but no existing_instrumental_gcs_path")
|
||||
return False
|
||||
return True # Other stem checks not needed for custom instrumental
|
||||
|
||||
stems = job.file_urls.get('stems', {})
|
||||
instrumental_key = 'instrumental_clean' if instrumental_selection == 'clean' else 'instrumental_with_backing'
|
||||
if not stems.get(instrumental_key):
|
||||
|
||||
+2
-2
@@ -75,8 +75,8 @@ steps:
|
||||
--concurrency 1 \
|
||||
--max-instances 50 \
|
||||
--min-instances 0 \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=$PROJECT_ID,GCS_BUCKET_NAME=karaoke-gen-storage-$PROJECT_ID,FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,REDACTED_API_KEY=redacted-api-key:latest,OPS_API_KEY=ops-api-key:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest"
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=$PROJECT_ID,GCS_BUCKET_NAME=karaoke-gen-storage-$PROJECT_ID,FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD" \
|
||||
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest"
|
||||
|
||||
images:
|
||||
- 'us-central1-docker.pkg.dev/$PROJECT_ID/karaoke-repo/karaoke-backend:latest'
|
||||
|
||||
@@ -21,6 +21,7 @@ coverage:
|
||||
default:
|
||||
target: 70% # New code should also meet 70%
|
||||
threshold: 5% # More lenient for patches
|
||||
only_pulls: true # Only run on PRs, not on main branch pushes
|
||||
|
||||
# Disable PR comments entirely since we're satisfied with 70%+ coverage
|
||||
# Status checks will still appear on the PR
|
||||
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
# API Reference
|
||||
|
||||
Base URL: `https://api.nomadkaraoke.com` (production) or `http://localhost:8000` (local)
|
||||
|
||||
## Authentication
|
||||
|
||||
All endpoints except `/health` and `/api/themes` require authentication.
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_TOKEN" ...
|
||||
```
|
||||
|
||||
## Endpoints
|
||||
|
||||
### Health
|
||||
|
||||
```http
|
||||
GET /health
|
||||
```
|
||||
|
||||
No auth required. Returns service status.
|
||||
|
||||
### Jobs
|
||||
|
||||
#### Create Job with Upload
|
||||
|
||||
```http
|
||||
POST /api/jobs/upload
|
||||
Content-Type: multipart/form-data
|
||||
|
||||
file: <audio file>
|
||||
artist: "Artist Name"
|
||||
title: "Song Title"
|
||||
```
|
||||
|
||||
Returns job ID. Triggers async processing.
|
||||
|
||||
#### Get Job Status
|
||||
|
||||
```http
|
||||
GET /api/jobs/{job_id}
|
||||
```
|
||||
|
||||
Response includes:
|
||||
- `status` - Current job state
|
||||
- `file_urls` - Signed URLs for outputs (when ready)
|
||||
- `state_data` - Worker progress details
|
||||
- `timeline` - Processing history
|
||||
|
||||
#### List Jobs
|
||||
|
||||
```http
|
||||
GET /api/jobs
|
||||
GET /api/jobs?status=complete
|
||||
GET /api/jobs?limit=10&offset=0
|
||||
```
|
||||
|
||||
#### Delete Job
|
||||
|
||||
```http
|
||||
DELETE /api/jobs/{job_id}
|
||||
```
|
||||
|
||||
### Review
|
||||
|
||||
#### Get Correction Data
|
||||
|
||||
```http
|
||||
GET /api/review/{job_id}/correction-data
|
||||
```
|
||||
|
||||
Returns lyrics correction data for the review UI.
|
||||
|
||||
#### Complete Review
|
||||
|
||||
```http
|
||||
POST /api/review/{job_id}/complete
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"corrections": [...],
|
||||
"corrected_segments": [...]
|
||||
}
|
||||
```
|
||||
|
||||
Saves corrections and triggers video rendering.
|
||||
|
||||
#### Generate Preview
|
||||
|
||||
```http
|
||||
POST /api/review/{job_id}/preview-video
|
||||
```
|
||||
|
||||
Generates preview video during review.
|
||||
|
||||
#### Stream Audio
|
||||
|
||||
```http
|
||||
GET /api/review/{job_id}/audio/{stem_type}
|
||||
```
|
||||
|
||||
Streams audio for review playback.
|
||||
|
||||
### Instrumental Selection
|
||||
|
||||
```http
|
||||
POST /api/jobs/{job_id}/select-instrumental
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"selection": "clean" // or "with_backing"
|
||||
}
|
||||
```
|
||||
|
||||
### Audio Search
|
||||
|
||||
```http
|
||||
GET /api/audio-search?q=song+name
|
||||
```
|
||||
|
||||
Search for songs (flacfetch integration).
|
||||
|
||||
### Themes
|
||||
|
||||
```http
|
||||
GET /api/themes
|
||||
```
|
||||
|
||||
No auth required. Returns available video themes.
|
||||
|
||||
### Internal (Admin Only)
|
||||
|
||||
These endpoints are used by workers and require admin tokens.
|
||||
|
||||
```http
|
||||
POST /api/internal/jobs/{job_id}/trigger-audio
|
||||
POST /api/internal/jobs/{job_id}/trigger-lyrics
|
||||
POST /api/internal/jobs/{job_id}/trigger-screens
|
||||
POST /api/internal/jobs/{job_id}/trigger-render-video
|
||||
POST /api/internal/jobs/{job_id}/trigger-video
|
||||
```
|
||||
|
||||
## Job States
|
||||
|
||||
| State | Description |
|
||||
|-------|-------------|
|
||||
| `pending` | Created, not started |
|
||||
| `downloading` | Processing input |
|
||||
| `separating_stage1` | Audio separation (1/2) |
|
||||
| `separating_stage2` | Audio separation (2/2) |
|
||||
| `transcribing` | Lyrics transcription |
|
||||
| `generating_screens` | Title/end screens |
|
||||
| `awaiting_review` | Waiting for human review |
|
||||
| `in_review` | Human reviewing |
|
||||
| `review_complete` | Review submitted |
|
||||
| `rendering_video` | Generating karaoke video |
|
||||
| `awaiting_instrumental_selection` | Waiting for selection |
|
||||
| `instrumental_selected` | Selection made |
|
||||
| `generating_video` | Final encoding |
|
||||
| `complete` | Done |
|
||||
| `failed` | Error |
|
||||
|
||||
## Error Responses
|
||||
|
||||
```json
|
||||
{
|
||||
"detail": "Error message"
|
||||
}
|
||||
```
|
||||
|
||||
Common status codes:
|
||||
- `400` - Bad request
|
||||
- `401` - Unauthorized
|
||||
- `404` - Job not found
|
||||
- `500` - Server error
|
||||
|
||||
## Rate Limits
|
||||
|
||||
No rate limits currently implemented.
|
||||
|
||||
## Webhooks
|
||||
|
||||
Not yet implemented. Jobs must be polled for status.
|
||||
@@ -0,0 +1,162 @@
|
||||
# Architecture
|
||||
|
||||
## System Overview
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Frontend (Cloudflare Pages) │
|
||||
│ Next.js + TypeScript │
|
||||
│ https://gen.nomadkaraoke.com │
|
||||
└───────────────────────────┬─────────────────────────────────────┘
|
||||
│ HTTPS
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Backend API (Cloud Run) │
|
||||
│ FastAPI + Python 3.12 │
|
||||
│ https://api.nomadkaraoke.com │
|
||||
│ │
|
||||
│ Workers: │
|
||||
│ • Audio Worker - Stem separation via Modal API │
|
||||
│ • Lyrics Worker - Transcription via AudioShake │
|
||||
│ • Screens Worker - Title/end screen generation │
|
||||
│ • Render Worker - Karaoke video with lyrics │
|
||||
│ • Video Worker - Final assembly and encoding │
|
||||
└───────────────────────────┬─────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────┼─────────────┐
|
||||
▼ ▼ ▼
|
||||
┌──────────┐ ┌──────────┐ ┌──────────────┐
|
||||
│ Firestore│ │ GCS │ │Secret Manager│
|
||||
│ (jobs) │ │ (files) │ │ (API keys) │
|
||||
└──────────┘ └──────────┘ └──────────────┘
|
||||
```
|
||||
|
||||
## Processing Pipeline
|
||||
|
||||
```text
|
||||
1. UPLOAD
|
||||
POST /api/jobs/upload
|
||||
• Save audio to GCS
|
||||
• Create job in Firestore
|
||||
• Trigger parallel workers
|
||||
|
||||
2. PARALLEL PROCESSING
|
||||
┌─────────────────┐ ┌─────────────────┐
|
||||
│ Audio Worker │ │ Lyrics Worker │
|
||||
│ Modal API │ │ AudioShake │
|
||||
│ 2-stage sep │ │ Auto-correct │
|
||||
└────────┬────────┘ └────────┬────────┘
|
||||
└──────────┬───────────┘
|
||||
▼
|
||||
3. SCREENS GENERATION
|
||||
• Title screen (5s video)
|
||||
• End screen (5s video)
|
||||
▼
|
||||
4. HUMAN REVIEW (AWAITING_REVIEW)
|
||||
• React UI for lyrics correction
|
||||
• Preview video generation
|
||||
• Submit corrections
|
||||
▼
|
||||
5. VIDEO RENDERING
|
||||
• Merge corrections with original data
|
||||
• Generate karaoke video with lyrics
|
||||
▼
|
||||
6. INSTRUMENTAL SELECTION
|
||||
• User chooses: clean or with_backing
|
||||
▼
|
||||
7. FINAL VIDEO
|
||||
• Remux with selected instrumental
|
||||
• Concatenate: title + karaoke + end
|
||||
• Encode to 4 formats
|
||||
▼
|
||||
8. COMPLETE
|
||||
• User downloads via signed URLs
|
||||
```
|
||||
|
||||
## Job States
|
||||
|
||||
| State | Description | Human Action |
|
||||
|-------|-------------|--------------|
|
||||
| `pending` | Job created | - |
|
||||
| `downloading` | Processing audio | - |
|
||||
| `separating_stage1` | Audio separation stage 1 | - |
|
||||
| `separating_stage2` | Audio separation stage 2 | - |
|
||||
| `transcribing` | Lyrics transcription | - |
|
||||
| `generating_screens` | Creating title/end screens | - |
|
||||
| `awaiting_review` | **Waiting for human** | Review lyrics |
|
||||
| `in_review` | Human actively reviewing | Edit lyrics |
|
||||
| `review_complete` | Review submitted | - |
|
||||
| `rendering_video` | Generating karaoke video | - |
|
||||
| `awaiting_instrumental_selection` | **Waiting for human** | Choose audio |
|
||||
| `instrumental_selected` | Selection made | - |
|
||||
| `generating_video` | Final encoding | - |
|
||||
| `complete` | All done | Download files |
|
||||
| `failed` | Error occurred | - |
|
||||
|
||||
## GCS File Structure
|
||||
|
||||
```text
|
||||
jobs/{job_id}/
|
||||
├── input/
|
||||
│ └── original.flac # Uploaded audio
|
||||
├── stems/
|
||||
│ ├── vocals.flac
|
||||
│ ├── instrumental_clean.flac
|
||||
│ ├── instrumental_with_backing.flac
|
||||
│ └── ...
|
||||
├── lyrics/
|
||||
│ ├── corrections.json # Auto-corrected
|
||||
│ ├── corrections_updated.json # After human review
|
||||
│ └── karaoke.ass
|
||||
├── screens/
|
||||
│ ├── title.mov
|
||||
│ └── end.mov
|
||||
├── videos/
|
||||
│ └── with_vocals.mkv # Karaoke video
|
||||
└── finals/
|
||||
├── lossless_4k.mp4
|
||||
├── lossless_4k.mkv
|
||||
├── lossy_4k.mp4
|
||||
└── lossy_720p.mp4
|
||||
```
|
||||
|
||||
## LyricsTranscriber Integration
|
||||
|
||||
**Key Design Decision**: We use LyricsTranscriber as a **library**, not a server.
|
||||
|
||||
```text
|
||||
CLI Mode (Original): Cloud Mode (Our Approach):
|
||||
──────────────────── ──────────────────────────
|
||||
LyricsTranscriber LyricsTranscriber
|
||||
├── transcribe() ├── transcribe() ✅
|
||||
├── correct() ├── correct() ✅
|
||||
├── ReviewServer.start() │
|
||||
│ └── BLOCKS (waits) │ (Skip server, save JSON)
|
||||
│ │ ... ASYNC GAP ...
|
||||
│ │ (Human reviews via React)
|
||||
└── OutputGenerator │
|
||||
└── OutputGenerator ✅
|
||||
(called after review)
|
||||
```
|
||||
|
||||
**Use**: `LyricsTranscriber`, `CorrectionResult`, `OutputGenerator`, `OutputConfig`
|
||||
**Don't use**: `ReviewServer`, blocking waits
|
||||
|
||||
## External Services
|
||||
|
||||
| Service | Purpose | Required |
|
||||
|---------|---------|----------|
|
||||
| Modal | GPU audio separation | Yes |
|
||||
| AudioShake | Lyrics transcription | Yes |
|
||||
| Genius | Reference lyrics | Yes |
|
||||
| YouTube API | Video upload | Optional |
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Backend**: FastAPI, Python 3.12, Cloud Run
|
||||
- **Frontend**: Next.js, TypeScript, Cloudflare Pages
|
||||
- **Database**: Firestore
|
||||
- **Storage**: Google Cloud Storage
|
||||
- **Secrets**: Google Secret Manager
|
||||
- **IaC**: Pulumi
|
||||
- **CI/CD**: GitHub Actions
|
||||
@@ -0,0 +1,216 @@
|
||||
# Development Guide
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Python 3.12
|
||||
- Node.js 20+
|
||||
- Docker (for GCS emulator)
|
||||
- Google Cloud SDK with Firestore emulator
|
||||
|
||||
```bash
|
||||
# Install Firestore emulator
|
||||
gcloud components install cloud-firestore-emulator
|
||||
```
|
||||
|
||||
### Backend Setup
|
||||
|
||||
```bash
|
||||
# Create and activate venv
|
||||
python3.12 -m venv venv
|
||||
source venv/bin/activate
|
||||
|
||||
# Install dependencies
|
||||
poetry install
|
||||
|
||||
# Copy environment template
|
||||
cp .env.example .env
|
||||
# Edit .env with required API keys
|
||||
```
|
||||
|
||||
### Frontend Setup
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
cp .env.example .env.local
|
||||
# Edit .env.local with KARAOKE_ACCESS_TOKEN
|
||||
```
|
||||
|
||||
## Running Locally
|
||||
|
||||
### Backend with Emulators
|
||||
|
||||
```bash
|
||||
# Start emulators and backend
|
||||
./scripts/run-backend-local.sh --with-emulators
|
||||
|
||||
# Backend runs at http://localhost:8000
|
||||
# API docs at http://localhost:8000/docs
|
||||
```
|
||||
|
||||
### Frontend
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm run dev
|
||||
# Runs at http://localhost:3000
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
### Backend Tests
|
||||
|
||||
```bash
|
||||
# Run all tests (required before commit)
|
||||
make test 2>&1 | tail -n 500
|
||||
|
||||
# This runs in order:
|
||||
# 1. Unit tests with coverage
|
||||
# 2. Backend unit tests
|
||||
# 3. E2E integration tests with emulators
|
||||
```
|
||||
|
||||
**Important**: Set 10 minute timeout. Tests can take a while with emulators.
|
||||
|
||||
### Frontend Tests
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm run test:all 2>&1 | tail -n 200
|
||||
|
||||
# Individual commands:
|
||||
npm run test:unit # Jest unit tests
|
||||
npm run test:e2e # Playwright E2E tests
|
||||
```
|
||||
|
||||
### Test Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ Unit Tests (Mocked) │ Fast, isolated
|
||||
│ ~62 tests, <1s │
|
||||
├─────────────────────────────────┤
|
||||
│ Emulator Integration Tests │ Local Firestore/GCS
|
||||
│ ~11 tests, ~2s │
|
||||
├─────────────────────────────────┤
|
||||
│ E2E Tests │ Full API + Frontend
|
||||
│ Requires deployed backend │
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
### Automatic (CI/CD)
|
||||
|
||||
Push to `main` triggers GitHub Actions:
|
||||
1. Run tests
|
||||
2. Build Docker image
|
||||
3. Deploy to Cloud Run
|
||||
4. Deploy frontend to Cloudflare Pages
|
||||
|
||||
### Manual Backend Deploy
|
||||
|
||||
```bash
|
||||
# Preview infrastructure changes
|
||||
cd infrastructure
|
||||
pulumi preview
|
||||
|
||||
# Apply changes
|
||||
pulumi up
|
||||
```
|
||||
|
||||
### Manual Frontend Deploy
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm run build
|
||||
npx wrangler pages deploy out
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
### Backend (.env)
|
||||
|
||||
```bash
|
||||
# Required
|
||||
AUDIOSHAKE_API_TOKEN=...
|
||||
GENIUS_ACCESS_TOKEN=...
|
||||
AUDIO_SEPARATOR_API_URL=... # Modal API endpoint
|
||||
|
||||
# GCP (auto-configured in Cloud Run)
|
||||
GOOGLE_CLOUD_PROJECT=...
|
||||
GCS_BUCKET_NAME=...
|
||||
|
||||
# Auth
|
||||
ADMIN_TOKENS=token1,token2
|
||||
```
|
||||
|
||||
### Frontend (.env.local)
|
||||
|
||||
```bash
|
||||
NEXT_PUBLIC_API_URL=http://localhost:8000
|
||||
KARAOKE_ACCESS_TOKEN=... # For E2E tests
|
||||
```
|
||||
|
||||
## Key Scripts
|
||||
|
||||
| Script | Purpose |
|
||||
|--------|---------|
|
||||
| `make test` | Run all backend tests |
|
||||
| `./scripts/run-backend-local.sh` | Start backend with emulators |
|
||||
| `./scripts/start-emulators.sh` | Start emulators only |
|
||||
| `./scripts/stop-emulators.sh` | Stop emulators |
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
karaoke-gen/
|
||||
├── backend/
|
||||
│ ├── api/routes/ # FastAPI endpoints
|
||||
│ ├── models/ # Pydantic models
|
||||
│ ├── services/ # Business logic
|
||||
│ ├── workers/ # Background workers
|
||||
│ └── tests/ # Backend tests
|
||||
├── frontend/
|
||||
│ ├── src/
|
||||
│ │ ├── app/ # Next.js pages
|
||||
│ │ ├── components/ # React components
|
||||
│ │ └── lib/ # Utilities
|
||||
│ └── tests/ # Frontend tests
|
||||
├── infrastructure/ # Pulumi IaC
|
||||
├── karaoke_gen/ # CLI package
|
||||
└── scripts/ # Dev scripts
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Emulators Won't Start
|
||||
|
||||
```bash
|
||||
# Check if already running
|
||||
lsof -i :8080 # Firestore
|
||||
lsof -i :4443 # GCS
|
||||
|
||||
# Stop them
|
||||
./scripts/stop-emulators.sh
|
||||
```
|
||||
|
||||
### Tests Fail with Auth Errors
|
||||
|
||||
Ensure `ADMIN_TOKENS` is set in environment or `.env` file.
|
||||
|
||||
### Docker Issues
|
||||
|
||||
```bash
|
||||
# Ensure Docker is running
|
||||
docker info
|
||||
|
||||
# For GCS emulator
|
||||
docker pull fsouza/fake-gcs-server
|
||||
```
|
||||
|
||||
### Coverage Below Target
|
||||
|
||||
Run `./scripts/run-tests.sh --coverage` and check `htmlcov/index.html` to see uncovered lines.
|
||||
@@ -0,0 +1,164 @@
|
||||
# Lessons Learned
|
||||
|
||||
Key insights for future AI agents working on this codebase.
|
||||
|
||||
## Architecture Decisions
|
||||
|
||||
### LyricsTranscriber: Library, Not Server
|
||||
|
||||
**Problem**: LyricsTranscriber's `ReviewServer` blocks waiting for human input - incompatible with async cloud architecture.
|
||||
|
||||
**Solution**: Use LyricsTranscriber as a library:
|
||||
- Call `transcribe()` and `correct()` for processing
|
||||
- Save `corrections.json` to GCS
|
||||
- Skip `ReviewServer` entirely
|
||||
- Call `OutputGenerator` only after human review completes
|
||||
|
||||
**What to use**: `LyricsTranscriber`, `CorrectionResult`, `OutputGenerator`, `OutputConfig`, `CorrectionOperations`
|
||||
|
||||
**What NOT to use**: `ReviewServer`, `server.start()`, blocking waits
|
||||
|
||||
### Video Generation Timing
|
||||
|
||||
**Wrong**: Generate video during lyrics worker, then review
|
||||
**Right**: Lyrics worker saves JSON → Human reviews → Render worker generates video
|
||||
|
||||
Video must include human-corrected lyrics, so generation happens AFTER review.
|
||||
|
||||
### Parallel Processing
|
||||
|
||||
Audio separation and lyrics transcription run in parallel:
|
||||
- Both can fail independently
|
||||
- Progress tracked separately in `state_data`
|
||||
- Screens generation waits for both to complete
|
||||
|
||||
## Common Gotchas
|
||||
|
||||
### Pydantic Model Fields
|
||||
|
||||
**Problem**: Setting a field that doesn't exist in the Pydantic model silently does nothing.
|
||||
|
||||
```python
|
||||
# BAD - fails silently if field doesn't exist
|
||||
job.input_media_gcs_path = "path/to/file"
|
||||
|
||||
# GOOD - explicit field in model
|
||||
class Job(BaseModel):
|
||||
input_media_gcs_path: Optional[str] = None
|
||||
```
|
||||
|
||||
**Lesson**: Always verify Pydantic model has the field before setting it.
|
||||
|
||||
### Styles Configuration
|
||||
|
||||
ASS subtitle generator requires ALL style fields present and properly typed:
|
||||
|
||||
```python
|
||||
required_fields = [
|
||||
"font", "font_path", "ass_name", # ass_name often missed
|
||||
"primary_color", "secondary_color", "outline_color", "back_color",
|
||||
"bold", "italic", "underline", "strike_out",
|
||||
"scale_x", "scale_y", "spacing", "angle",
|
||||
"border_style", "outline", "shadow",
|
||||
"margin_l", "margin_r", "margin_v", "encoding"
|
||||
]
|
||||
|
||||
# Critical: font_path must be string, not None
|
||||
"font_path": "" # Correct
|
||||
"font_path": None # Causes ASS writer to fail
|
||||
```
|
||||
|
||||
### Frontend Data Format
|
||||
|
||||
The React review UI sends partial correction data:
|
||||
|
||||
```python
|
||||
# Frontend sends:
|
||||
{"corrections": [...], "corrected_segments": [...]}
|
||||
|
||||
# Backend must merge with original corrections.json
|
||||
```
|
||||
|
||||
### Firestore Consistency
|
||||
|
||||
**Problem**: Update job, trigger worker immediately, worker reads stale data.
|
||||
|
||||
**Solution**: Verify updates propagated before triggering workers:
|
||||
```python
|
||||
# Update job
|
||||
await job_manager.update_job(job_id, updates)
|
||||
|
||||
# Verify update visible
|
||||
job = await job_manager.get_job(job_id)
|
||||
if job.input_media_gcs_path:
|
||||
await trigger_worker()
|
||||
```
|
||||
|
||||
## Testing Insights
|
||||
|
||||
### Emulator Tests Catch Real Bugs
|
||||
|
||||
Unit tests with mocks didn't catch the `input_media_gcs_path` bug. Emulator integration tests did because they use real Firestore behavior.
|
||||
|
||||
**Lesson**: Run `make test` which includes emulator tests before every commit.
|
||||
|
||||
### Test Isolation
|
||||
|
||||
Emulator tests need their own `conftest.py` that does NOT mock `google.cloud.*`. Mocks from unit tests can leak into integration tests.
|
||||
|
||||
## Deployment Notes
|
||||
|
||||
### Cloud Run Timeouts
|
||||
|
||||
Default 5-minute timeout may not be enough for video encoding. Consider:
|
||||
- Cloud Run Jobs for long-running tasks
|
||||
- Breaking encoding into smaller chunks
|
||||
- Increasing timeout for specific operations
|
||||
|
||||
### Secret Manager Access
|
||||
|
||||
Cloud Run service account needs `Secret Manager Secret Accessor` role. This is managed via Pulumi in `infrastructure/`.
|
||||
|
||||
### CI/CD: GitHub Actions
|
||||
|
||||
Migrated from Cloud Build to GitHub Actions for:
|
||||
- Simpler configuration
|
||||
- Better visibility
|
||||
- Faster feedback
|
||||
|
||||
### Self-Hosted Runner on GCP
|
||||
|
||||
GitHub-hosted runners have ~14GB disk, which caused failures during Docker builds. Solution: self-hosted runner on GCP with 200GB SSD.
|
||||
|
||||
**Key learnings:**
|
||||
|
||||
1. **GPG in startup scripts**: Always use `gpg --batch` for non-interactive execution
|
||||
2. **setup-python on self-hosted**: Needs Python in tool cache at `$RUNNER/_work/_tool/Python/<version>/x64/` with `x64.complete` marker
|
||||
3. **Debian vs Ubuntu**: PPAs don't work on Debian; use upstream repos (Temurin, NodeSource)
|
||||
4. **pyenv for Python**: More reliable than source builds or distro packages for specific versions
|
||||
|
||||
See `docs/archive/2025-12-28-self-hosted-github-runner.md` for full details.
|
||||
|
||||
## Performance Observations
|
||||
|
||||
| Operation | Duration |
|
||||
|-----------|----------|
|
||||
| Audio separation | 5-8 min |
|
||||
| Lyrics transcription | 2-3 min |
|
||||
| Auto-correction | 30 sec |
|
||||
| Screens generation | 30 sec |
|
||||
| Video rendering | 10-15 min |
|
||||
| Final encoding | 5-10 min |
|
||||
| **Total** | 30-50 min |
|
||||
|
||||
Human review time varies (5-15 min typical).
|
||||
|
||||
## What We'd Do Differently
|
||||
|
||||
1. **Add Pydantic model fields test first** - Would have caught the silent field issue immediately
|
||||
|
||||
2. **Use emulator tests from day one** - Faster feedback than deploying to test
|
||||
|
||||
3. **Design for async human review upfront** - Avoided rearchitecting after discovering ReviewServer blocks
|
||||
|
||||
4. **Keep docs minimal and current** - Less documentation, but always accurate
|
||||
@@ -0,0 +1,318 @@
|
||||
# Mobile UX Best Practices
|
||||
|
||||
This document outlines the mobile-first UX principles and implementation patterns used in this project to ensure a great experience across all screen sizes.
|
||||
|
||||
## Core Principles
|
||||
|
||||
### 1. Mobile-First Responsive Design
|
||||
|
||||
Design for the smallest screen first, then progressively enhance for larger screens.
|
||||
|
||||
```css
|
||||
/* Base styles for mobile */
|
||||
.element {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
/* Enhance for larger screens */
|
||||
@media (min-width: 640px) {
|
||||
.element {
|
||||
width: 280px;
|
||||
padding: 16px;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. No Horizontal Overflow
|
||||
|
||||
The most critical mobile UX issue is horizontal scrolling. Always ensure content fits within the viewport width.
|
||||
|
||||
**Testing for overflow:**
|
||||
```typescript
|
||||
async function hasNoHorizontalOverflow(page: Page): Promise<boolean> {
|
||||
return await page.evaluate(() => {
|
||||
const docWidth = document.documentElement.scrollWidth;
|
||||
const viewportWidth = window.innerWidth;
|
||||
return docWidth <= viewportWidth + 2; // Small tolerance for rounding
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
**Common causes of horizontal overflow:**
|
||||
- Fixed widths (e.g., `width: 340px`)
|
||||
- Horizontal flex layouts without wrapping
|
||||
- Images without `max-width: 100%`
|
||||
- Tables without horizontal scroll containers
|
||||
|
||||
### 3. Touch Target Sizing
|
||||
|
||||
Interactive elements must be easily tappable. Follow these minimum sizes:
|
||||
|
||||
| Platform | Minimum Size | Recommended |
|
||||
|----------|--------------|-------------|
|
||||
| Apple iOS | 44x44px | 48x48px |
|
||||
| Material Design | 48x48px | 48x48px |
|
||||
| Web (general) | 32x32px | 44x44px |
|
||||
|
||||
**Implementation:**
|
||||
```tsx
|
||||
<Button className="min-h-[44px] px-3">
|
||||
<Icon className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">Label</span>
|
||||
</Button>
|
||||
```
|
||||
|
||||
### 4. Progressive Disclosure
|
||||
|
||||
Show less content on mobile, with clear paths to access more:
|
||||
|
||||
- **Icon-only buttons on mobile, labels on desktop:**
|
||||
```tsx
|
||||
<Icon className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Action Label</span>
|
||||
```
|
||||
|
||||
- **Collapsed navigation on mobile**
|
||||
- **Truncated text with expansion options**
|
||||
|
||||
## Layout Patterns
|
||||
|
||||
### Responsive Grid
|
||||
|
||||
Use responsive grid columns that stack on mobile:
|
||||
|
||||
```tsx
|
||||
// Bad - always 2 columns
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
|
||||
// Good - stack on mobile, 2 columns on larger screens
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
|
||||
```
|
||||
|
||||
### Flexible Containers
|
||||
|
||||
Avoid fixed widths. Use percentage-based or responsive widths:
|
||||
|
||||
```css
|
||||
/* Bad */
|
||||
.sidebar {
|
||||
width: 340px;
|
||||
}
|
||||
|
||||
/* Good */
|
||||
.sidebar {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.sidebar {
|
||||
width: 340px;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Flex Wrap for Toolbars
|
||||
|
||||
Allow toolbar items to wrap on smaller screens:
|
||||
|
||||
```tsx
|
||||
<div className="flex flex-wrap gap-2 items-center">
|
||||
{/* Items will wrap naturally */}
|
||||
</div>
|
||||
```
|
||||
|
||||
## Typography
|
||||
|
||||
### Readable Font Sizes
|
||||
|
||||
Minimum font sizes for readability without zooming:
|
||||
|
||||
| Element | Minimum Size | Recommended |
|
||||
|---------|--------------|-------------|
|
||||
| Body text | 14px | 16px |
|
||||
| Labels | 12px | 14px |
|
||||
| Small text/badges | 11px | 12px |
|
||||
|
||||
### Responsive Headings
|
||||
|
||||
```tsx
|
||||
<h1 className="text-base sm:text-xl font-bold truncate">
|
||||
Title Text
|
||||
</h1>
|
||||
```
|
||||
|
||||
## Form Design
|
||||
|
||||
### Input Fields on Mobile
|
||||
|
||||
- Stack form fields vertically on mobile
|
||||
- Use full-width inputs for easier tapping
|
||||
- Ensure proper input type for mobile keyboard optimization
|
||||
|
||||
```tsx
|
||||
<input
|
||||
type="email" // Shows email keyboard
|
||||
inputMode="numeric" // Shows number pad
|
||||
className="w-full min-h-[44px]"
|
||||
/>
|
||||
```
|
||||
|
||||
### Labels and Placeholders
|
||||
|
||||
- Labels should be visible (not just placeholders)
|
||||
- Adequate spacing between label and input
|
||||
- Clear validation feedback
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Automated Testing with Playwright
|
||||
|
||||
Test across multiple viewport sizes representing real devices:
|
||||
|
||||
```typescript
|
||||
const MOBILE_VIEWPORTS = {
|
||||
'iPhone SE': { width: 375, height: 667 },
|
||||
'iPhone 14': { width: 390, height: 844 },
|
||||
'Pixel 7': { width: 412, height: 915 },
|
||||
'iPad Mini': { width: 768, height: 1024 },
|
||||
};
|
||||
|
||||
for (const [name, viewport] of Object.entries(MOBILE_VIEWPORTS)) {
|
||||
test(`page works on ${name}`, async ({ page }) => {
|
||||
await page.setViewportSize(viewport);
|
||||
await page.goto('/');
|
||||
|
||||
// Test for horizontal overflow
|
||||
const hasOverflow = await page.evaluate(() =>
|
||||
document.documentElement.scrollWidth > window.innerWidth + 2
|
||||
);
|
||||
expect(hasOverflow).toBe(false);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Visual Regression Testing
|
||||
|
||||
Capture screenshots at different viewports to catch visual regressions:
|
||||
|
||||
```typescript
|
||||
await expect(page).toHaveScreenshot(`homepage-${deviceName}.png`, {
|
||||
fullPage: true,
|
||||
maxDiffPixelRatio: 0.1,
|
||||
});
|
||||
```
|
||||
|
||||
### Touch Target Validation
|
||||
|
||||
```typescript
|
||||
const buttons = page.locator('button, a, [role="button"]');
|
||||
for (const button of await buttons.all()) {
|
||||
const box = await button.boundingBox();
|
||||
if (box) {
|
||||
expect(box.width).toBeGreaterThanOrEqual(32);
|
||||
expect(box.height).toBeGreaterThanOrEqual(32);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Framework-Specific Guidelines
|
||||
|
||||
### Tailwind CSS (Next.js Frontend)
|
||||
|
||||
Use responsive prefixes consistently:
|
||||
|
||||
```plaintext
|
||||
sm: 640px - Small tablets and up
|
||||
md: 768px - Tablets and up
|
||||
lg: 1024px - Laptops and up
|
||||
xl: 1280px - Desktops and up
|
||||
```
|
||||
|
||||
**Common patterns:**
|
||||
```tsx
|
||||
// Stack on mobile, side-by-side on larger
|
||||
className="flex flex-col sm:flex-row"
|
||||
|
||||
// Hide on mobile, show on larger
|
||||
className="hidden sm:block"
|
||||
|
||||
// Reduce padding on mobile
|
||||
className="p-3 sm:p-4"
|
||||
|
||||
// Smaller font on mobile
|
||||
className="text-xs sm:text-sm"
|
||||
```
|
||||
|
||||
### Material UI (Lyrics Review UI)
|
||||
|
||||
Use the `useMediaQuery` hook:
|
||||
|
||||
```tsx
|
||||
const theme = useTheme();
|
||||
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
|
||||
|
||||
return (
|
||||
<Box sx={{
|
||||
flexDirection: isMobile ? 'column' : 'row',
|
||||
width: isMobile ? '100%' : '280px',
|
||||
}}>
|
||||
```
|
||||
|
||||
### Vanilla CSS (Instrumental Review)
|
||||
|
||||
Use CSS media queries:
|
||||
|
||||
```css
|
||||
.element {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.element {
|
||||
width: 340px;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Checklist for New Features
|
||||
|
||||
Before merging any UI changes, verify:
|
||||
|
||||
- [ ] No horizontal overflow on any mobile viewport (320px - 480px)
|
||||
- [ ] All interactive elements are at least 44x44px
|
||||
- [ ] Text is readable without zooming (minimum 11px)
|
||||
- [ ] Form inputs stack vertically on mobile
|
||||
- [ ] Navigation is accessible on mobile
|
||||
- [ ] Images scale properly with `max-width: 100%`
|
||||
- [ ] Modals/dialogs fit within mobile viewport
|
||||
- [ ] Buttons show icons-only on very small screens
|
||||
- [ ] Playwright mobile tests pass
|
||||
|
||||
## Common Fixes
|
||||
|
||||
### Fix: Horizontal Overflow
|
||||
|
||||
1. **Check for fixed widths** - Replace with responsive values
|
||||
2. **Add flex-wrap** - Allow content to wrap
|
||||
3. **Add overflow-x: hidden** - On containers (use sparingly)
|
||||
4. **Check images** - Add `max-width: 100%`
|
||||
|
||||
### Fix: Touch Target Too Small
|
||||
|
||||
1. **Add minimum height** - `min-h-[44px]`
|
||||
2. **Add padding** - `p-3` or `px-4 py-3`
|
||||
3. **Use icon-only on mobile** - Hide text labels
|
||||
|
||||
### Fix: Text Too Small
|
||||
|
||||
1. **Use responsive font sizes** - `text-xs sm:text-sm`
|
||||
2. **Set minimum body font size** - At least 14px
|
||||
3. **Increase line height** - For better readability
|
||||
|
||||
## Resources
|
||||
|
||||
- [Apple Human Interface Guidelines - Touch Targets](https://developer.apple.com/design/human-interface-guidelines/accessibility)
|
||||
- [Material Design - Touch Targets](https://m3.material.io/foundations/accessible-design/accessibility-basics)
|
||||
- [Tailwind CSS Responsive Design](https://tailwindcss.com/docs/responsive-design)
|
||||
- [Playwright Testing](https://playwright.dev/docs/test-mobile)
|
||||
+34
-177
@@ -1,193 +1,50 @@
|
||||
# Karaoke-Gen Documentation
|
||||
|
||||
This directory contains all documentation for the karaoke-gen project, organized by purpose.
|
||||
> **Status**: Production-ready. First full E2E flow completed 2025-12-28.
|
||||
|
||||
## 📋 Current Status (Updated: 2025-12-08)
|
||||
## What Works
|
||||
|
||||
**Project:** Cloud-hosted karaoke generation with async human review
|
||||
**Backend:** 🔄 Phase 1.3 (85%) - Implementing review architecture
|
||||
**Frontend:** ⏸️ Not started (waiting for backend review flow)
|
||||
**Deployment:** ✅ Cloud Run with custom domain (api.nomadkaraoke.com)
|
||||
**Testing:** 🔄 Local emulator testing in progress
|
||||
- **Web App**: https://gen.nomadkaraoke.com - Upload audio, review lyrics, download videos
|
||||
- **Backend API**: https://api.nomadkaraoke.com - FastAPI on Cloud Run
|
||||
- **CLI Tools**: `karaoke-gen` (local), `karaoke-gen-remote` (cloud)
|
||||
|
||||
### Key Discovery
|
||||
## Current State
|
||||
|
||||
We identified that the `LyricsTranscriber` library's `ReviewServer` **blocks** waiting for human input, which doesn't work in our async cloud architecture. The solution is to:
|
||||
| Component | Status |
|
||||
|-----------|--------|
|
||||
| Audio upload & separation | Working |
|
||||
| Lyrics transcription | Working |
|
||||
| Human lyrics review | Working |
|
||||
| Preview video generation | Working |
|
||||
| Instrumental selection | Working |
|
||||
| Multi-format encoding | Working |
|
||||
| Token-based auth | Working |
|
||||
| Payment flow | Not started |
|
||||
| CI/CD self-hosted runner | Working (GCP) |
|
||||
|
||||
1. Use LyricsTranscriber for transcription + auto-correction
|
||||
2. Save corrections to GCS for async human review
|
||||
3. Use `OutputGenerator` to render video **after** review completes
|
||||
## Known Issues
|
||||
|
||||
See `00-current-plan/CURRENT-STATUS.md` for full details.
|
||||
- CDG format generation requires additional style configuration
|
||||
- Long audio files (>10 min) may timeout on some workers
|
||||
|
||||
---
|
||||
## Quick Links
|
||||
|
||||
## 📂 Documentation Structure
|
||||
| Doc | Purpose |
|
||||
|-----|---------|
|
||||
| [ARCHITECTURE.md](ARCHITECTURE.md) | System design, data flow, integrations |
|
||||
| [DEVELOPMENT.md](DEVELOPMENT.md) | Local setup, testing, deployment |
|
||||
| [API.md](API.md) | Backend endpoint reference |
|
||||
| [LESSONS-LEARNED.md](LESSONS-LEARNED.md) | Key insights for future agents |
|
||||
| [archive/](archive/) | Historical documentation |
|
||||
|
||||
### `00-current-plan/` - **START HERE**
|
||||
Active migration plan and current status.
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| **`CURRENT-STATUS.md`** | Where we are now, what's working, what's next |
|
||||
| **`WHATS-NEXT.md`** | Detailed plan for review architecture implementation |
|
||||
| **`WORKER-IMPLEMENTATION-PLAN.md`** | Worker responsibilities and implementation details |
|
||||
| `MASTER-PLAN.md` | Overall migration strategy |
|
||||
| `CLOUD-MIGRATION-REQUIREMENTS.md` | Architectural analysis from CLI workflow |
|
||||
|
||||
### `01-reference/` - Reference Documentation
|
||||
Core system documentation.
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| **`ARCHITECTURE.md`** | Cloud + CLI architecture with diagrams |
|
||||
| `KARAOKE-GEN-CLI-WORKFLOW.md` | CLI workflow breakdown (8 stages) |
|
||||
| `API-MANUAL-TESTING.md` | How to test backend API with curl |
|
||||
| `AUTHENTICATION.md` | Token-based auth system |
|
||||
| `CLOUD-RUN-ARCHITECTURE.md` | Cloud Run concepts |
|
||||
|
||||
### `02-implementation-history/` - Session Logs
|
||||
Historical implementation records.
|
||||
|
||||
### `03-deployment/` - Deployment Guides
|
||||
How to deploy and operate the system.
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| **`EMULATOR-TESTING.md`** | Local testing with Firestore/GCS emulators |
|
||||
| **`SETUP-VENV.md`** | Python venv setup |
|
||||
| **`LOCAL-VALIDATION.md`** | Validate before deploying |
|
||||
| **`OBSERVABILITY-GUIDE.md`** | Debug production issues |
|
||||
|
||||
### `04-testing/` - Testing Guides
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| **`TESTING-GUIDE.md`** | Complete testing guide |
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### I want to understand the current state:
|
||||
1. Read `00-current-plan/CURRENT-STATUS.md` - where we are now
|
||||
2. Read `00-current-plan/WHATS-NEXT.md` - what needs to be done
|
||||
3. Read `01-reference/ARCHITECTURE.md` - system architecture
|
||||
|
||||
### I want to work on the backend:
|
||||
1. Read `03-deployment/EMULATOR-TESTING.md` - local testing setup
|
||||
2. Read `00-current-plan/WORKER-IMPLEMENTATION-PLAN.md` - worker details
|
||||
3. Run `./scripts/run-backend-local.sh --with-emulators`
|
||||
|
||||
### I want to test:
|
||||
```bash
|
||||
# Start backend with emulators
|
||||
./scripts/run-backend-local.sh --with-emulators
|
||||
|
||||
# Upload test file
|
||||
curl -X POST http://localhost:8000/api/jobs/upload \
|
||||
-F "file=@tests/data/waterloo10sec.flac" \
|
||||
-F "artist=ABBA" \
|
||||
-F "title=Waterloo"
|
||||
|
||||
# Check status
|
||||
curl http://localhost:8000/api/jobs/{job_id}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Current Phase: Review Architecture
|
||||
|
||||
**Goal:** Implement async human review workflow
|
||||
|
||||
**What Works:**
|
||||
- ✅ File upload → GCS
|
||||
- ✅ Audio separation via Modal API
|
||||
- ✅ Lyrics transcription via AudioShake
|
||||
- ✅ Auto-correction via LyricsTranscriber
|
||||
- ✅ Title/end screen generation
|
||||
- ✅ Instrumental selection endpoint
|
||||
|
||||
**What's Being Implemented:**
|
||||
- 🔄 Review API endpoints (`GET/POST /api/jobs/{id}/review`)
|
||||
- 🔄 Render Video Worker (uses `OutputGenerator` after review)
|
||||
- 🔄 Updated state machine with `RENDERING_VIDEO` state
|
||||
|
||||
**The Key Insight:**
|
||||
```
|
||||
WRONG: Lyrics Worker → Generate Video → Review → ???
|
||||
RIGHT: Lyrics Worker → Save JSON → Human Review → Render Video → Final Assembly
|
||||
```
|
||||
|
||||
Video generation happens AFTER human review, not during the lyrics worker.
|
||||
|
||||
---
|
||||
|
||||
## 📝 Key Technical Decisions
|
||||
|
||||
### Why Not Use LyricsTranscriber's ReviewServer?
|
||||
|
||||
The `ReviewServer` class (in `lyrics_transcriber/review/server.py`):
|
||||
- Starts a local web server on port 8000
|
||||
- Opens a browser window
|
||||
- **BLOCKS** the thread until human submits corrections
|
||||
- Designed for local CLI operation
|
||||
|
||||
This doesn't work in Cloud Run where:
|
||||
- We can't open browsers
|
||||
- Workers must be non-blocking
|
||||
- Human review happens asynchronously via React frontend
|
||||
|
||||
**Solution:** Use the data structures and `OutputGenerator` directly, skip the server.
|
||||
|
||||
### Why Separate Video Rendering?
|
||||
## Workflow Summary
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ Lyrics Worker │ ──▶ │ Human Reviews │ ──▶ │ Render Worker │
|
||||
│ │ │ (React UI) │ │ │
|
||||
│ • Transcribe │ │ • Corrects │ │ • OutputGenerator│
|
||||
│ • Auto-correct │ │ • Saves JSON │ │ • with_vocals.mkv│
|
||||
│ • Save JSON │ │ │ │ │
|
||||
│ • NO VIDEO │ │ │ │ │
|
||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||
Upload Audio → Parallel Processing → Human Review → Video Generation → Download
|
||||
│ │
|
||||
(Modal + AudioShake) (LyricsTranscriber UI)
|
||||
```
|
||||
|
||||
The video must include the human-corrected lyrics, so it can only be generated AFTER review.
|
||||
## For AI Agents
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Job State Flow
|
||||
|
||||
```
|
||||
PENDING → DOWNLOADING → [parallel audio+lyrics] → GENERATING_SCREENS
|
||||
↓
|
||||
AWAITING_REVIEW → IN_REVIEW → REVIEW_COMPLETE
|
||||
↓
|
||||
RENDERING_VIDEO (NEW)
|
||||
↓
|
||||
AWAITING_INSTRUMENTAL_SELECTION → INSTRUMENTAL_SELECTED
|
||||
↓
|
||||
GENERATING_VIDEO → COMPLETE
|
||||
```
|
||||
|
||||
Two human interaction points:
|
||||
1. **AWAITING_REVIEW** - User corrects lyrics
|
||||
2. **AWAITING_INSTRUMENTAL_SELECTION** - User chooses audio track
|
||||
|
||||
---
|
||||
|
||||
## 📞 Getting Help
|
||||
|
||||
1. Check `00-current-plan/CURRENT-STATUS.md` first
|
||||
2. Look for specific guides in `03-deployment/`
|
||||
3. Review session history in `02-implementation-history/`
|
||||
|
||||
### Common Issues
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| Emulator not starting | Check ports 8080, 4443 are free |
|
||||
| "Missing lyrics video" | Review hasn't happened yet - expected behavior |
|
||||
| Workers not progressing | Check `state_data` in Firestore |
|
||||
| FFmpeg errors | Ensure FFmpeg is in PATH |
|
||||
Start with `CLAUDE.md` in the repo root for essential rules, then reference these docs as needed. Keep this README current when project state changes.
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,80 @@
|
||||
# Self-Hosted GitHub Actions Runner on GCP
|
||||
|
||||
**Date**: 2025-12-28
|
||||
**Status**: Deployed and operational
|
||||
|
||||
## Problem
|
||||
|
||||
GitHub-hosted runners have ~14GB disk space. CI jobs were failing with "No space left on device" during:
|
||||
- Docker builds (multi-stage, large dependencies)
|
||||
- Emulator tests (Docker + Java + Firestore/GCS emulators)
|
||||
- Package builds with poetry
|
||||
|
||||
Workarounds like `jlumbroso/free-disk-space` action helped but weren't reliable.
|
||||
|
||||
## Solution
|
||||
|
||||
Deployed a self-hosted runner on GCP with 200GB SSD via Pulumi IaC.
|
||||
|
||||
### Infrastructure Added
|
||||
|
||||
| Resource | Purpose |
|
||||
|----------|---------|
|
||||
| `github-runner` VM | e2-standard-4, 200GB SSD, Debian 12 |
|
||||
| `github-runner` service account | Minimal permissions for runner |
|
||||
| `github-runner-pat` secret | PAT for runner registration |
|
||||
| IAM bindings | Artifact Registry reader, Secret Manager accessor, logging |
|
||||
|
||||
### Jobs Moved to Self-Hosted
|
||||
|
||||
- `package-build-test`
|
||||
- `backend-unit-tests`
|
||||
- `backend-emulator-tests`
|
||||
- `deploy-backend`
|
||||
|
||||
These use `runs-on: [self-hosted, linux, gcp]` with labels.
|
||||
|
||||
## Issues Encountered
|
||||
|
||||
### 1. GPG tty errors in startup script
|
||||
|
||||
**Problem**: `gpg --dearmor` failed with "cannot open /dev/tty" in non-interactive startup.
|
||||
|
||||
**Fix**: Add `--batch` flag to all GPG commands.
|
||||
|
||||
### 2. setup-python can't find Python 3.13 on Debian 12
|
||||
|
||||
**Problem**: `actions/setup-python@v5` couldn't find pre-built Python 3.13 for Debian 12 on self-hosted runners.
|
||||
|
||||
**Fix**:
|
||||
1. Install Python 3.13 via pyenv on the runner
|
||||
2. Copy to tool cache: `_work/_tool/Python/3.13.0/x64/`
|
||||
3. Create marker file: `x64.complete`
|
||||
|
||||
### 3. Java 21 not in Debian repos
|
||||
|
||||
**Problem**: `openjdk-21-jdk` not available in Debian 12 stable.
|
||||
|
||||
**Fix**: Use Temurin (Adoptium) repository directly.
|
||||
|
||||
## Key Files
|
||||
|
||||
- `infrastructure/__main__.py` - Runner VM and IAM setup
|
||||
- `infrastructure/README.md` - Setup instructions
|
||||
- `.github/workflows/ci.yml` - Jobs using self-hosted runner
|
||||
|
||||
## Lessons for Future
|
||||
|
||||
1. **Self-hosted runners need explicit tool setup** - Unlike GitHub-hosted, tools aren't pre-installed in expected locations
|
||||
2. **setup-python tool cache location**: `$RUNNER_DIR/_work/_tool/Python/<version>/x64/`
|
||||
3. **GPG in scripts**: Always use `--batch` for non-interactive execution
|
||||
4. **Debian vs Ubuntu**: Many GitHub Actions assume Ubuntu; PPAs don't work on Debian
|
||||
|
||||
## Cost
|
||||
|
||||
~$50/month for e2-standard-4 running 24/7 (covered by GCP free credits).
|
||||
|
||||
## PRs
|
||||
|
||||
- #95: Initial self-hosted runner setup
|
||||
- #97: Make startup script reproducible (pyenv, tool cache, GPG fixes)
|
||||
@@ -0,0 +1,123 @@
|
||||
# Agent Instructions: Nomad Karaoke E2E Production Testing
|
||||
|
||||
## Context
|
||||
|
||||
You are acting on behalf of Andrew, the creator of Nomad Karaoke, who is building a fully functional end-to-end karaoke video generation platform. The platform has two modes:
|
||||
|
||||
1. **Local CLI** (`karaoke-gen`) - For power users running locally
|
||||
2. **Public Web Service** (`gen.nomadkaraoke.com`) - For paying customers ($5/track via Stripe)
|
||||
|
||||
## Current State
|
||||
|
||||
The platform has been under heavy development with many features implemented, but **end-to-end functionality for real users on gen.nomadkaraoke.com is not fully working yet**. The goal is to make the complete user journey functional in production.
|
||||
|
||||
## Business Model (Planned)
|
||||
|
||||
- **buy.nomadkaraoke.com** - Customer intro/landing page with Stripe payment flow
|
||||
- Payment generates a single-use token
|
||||
- Customer is redirected to **gen.nomadkaraoke.com** with token ready to use
|
||||
- Each track costs $5
|
||||
|
||||
## Your Primary Mission
|
||||
|
||||
**Test and fix the production system until end-to-end karaoke generation works reliably.**
|
||||
|
||||
### The Complete User Journey to Test
|
||||
|
||||
1. **Input** - User enters artist name and song title
|
||||
2. **Audio Selection** - User selects audio source
|
||||
3. **Download & Preparation** - System downloads and prepares audio (wait for completion)
|
||||
4. **Lyrics Review** - User reviews/corrects lyrics in the web UI
|
||||
5. **Preview Video** - Wait for preview video to load
|
||||
6. **Submit Review** - User submits corrected lyrics
|
||||
7. **Render Stage** - Wait for render to complete
|
||||
8. **Instrumental Selection** - User selects instrumental via web UI
|
||||
9. **Final Render & Distribution** - Wait for final render and distribution
|
||||
10. **Verification** - Click to view uploaded YouTube video
|
||||
11. **Verification** - Click Dropbox folder link to view shared folder
|
||||
|
||||
## Your Working Process
|
||||
|
||||
Use Playwright to automate and test this journey against **live production** at `gen.nomadkaraoke.com`.
|
||||
|
||||
### The Fix Loop
|
||||
|
||||
When you encounter something broken:
|
||||
|
||||
1. **Investigate** - Understand the root cause
|
||||
2. **Fix** - Implement the fix
|
||||
3. **Improve Tests** - Add/update tests to cover the issue
|
||||
4. **Refactor** - Clean up if necessary
|
||||
5. **PR** - Create a pull request with clear description
|
||||
6. **CI** - Ensure all checks pass
|
||||
7. **Merge** - Merge the PR
|
||||
8. **Deploy** - Wait for deployment to complete
|
||||
9. **Retest** - Test again in production
|
||||
10. **Repeat** - Continue until everything works
|
||||
|
||||
## Key Rules
|
||||
|
||||
### From CLAUDE.md (Must Follow)
|
||||
|
||||
- **Never commit directly to `main`** - Always use feature branches
|
||||
- **Always run tests before committing** - `make test` for backend, `cd frontend && npm run test:all` for frontend
|
||||
- **Bump version** in `pyproject.toml` for every commit
|
||||
- **Use git worktrees** for non-trivial changes
|
||||
- **Infrastructure changes** must go through Pulumi IaC
|
||||
|
||||
### Testing Commands
|
||||
|
||||
```bash
|
||||
# Backend tests (10 min timeout, limit output)
|
||||
make test 2>&1 | tail -n 500
|
||||
|
||||
# Frontend tests
|
||||
cd frontend && npm run test:all 2>&1 | tail -n 200
|
||||
```
|
||||
|
||||
### Pre-commit Checklist
|
||||
|
||||
- [ ] Tests pass
|
||||
- [ ] Version bumped in `pyproject.toml`
|
||||
- [ ] PR created with clear description
|
||||
- [ ] CI checks pass before merge
|
||||
|
||||
## Permissions
|
||||
|
||||
You have permission to:
|
||||
|
||||
- Run any command necessary
|
||||
- Use Playwright to interact with browsers
|
||||
- Make changes to any part of the codebase
|
||||
- Create PRs and merge them (after CI passes)
|
||||
- Test against live production
|
||||
|
||||
## Success Criteria
|
||||
|
||||
The mission is complete when:
|
||||
|
||||
1. Any artist/title can be entered on gen.nomadkaraoke.com
|
||||
2. The full generation process completes successfully
|
||||
3. A karaoke video is uploaded to YouTube
|
||||
4. Files are distributed to Dropbox
|
||||
5. The entire flow is covered by automated E2E tests
|
||||
|
||||
## Key URLs
|
||||
|
||||
- **Production Frontend**: https://gen.nomadkaraoke.com
|
||||
- **Production API**: https://api.nomadkaraoke.com (inferred from README)
|
||||
- **Lyrics Review UI**: https://gen.nomadkaraoke.com/lyrics/
|
||||
|
||||
## Reference Documentation
|
||||
|
||||
- `/Users/andrew/Projects/karaoke-gen/README.md` - Main project documentation
|
||||
- `/Users/andrew/Projects/karaoke-gen/CLAUDE.md` - AI assistant guidelines
|
||||
- `/Users/andrew/Projects/karaoke-gen/docs/01-reference/` - Reference documentation
|
||||
- `/Users/andrew/Projects/karaoke-gen/docs/00-current-plan/` - Planning documents (may be outdated)
|
||||
|
||||
## Notes
|
||||
|
||||
- Some docs in `docs/00-current-plan/` may be outdated - review, evaluate, and move/delete as appropriate
|
||||
- Focus on making things work, not perfect
|
||||
- Ship iteratively - fix one thing at a time
|
||||
- Document issues you find as you go
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,197 @@
|
||||
# GitHub Actions Docker Builds - Cost Optimization
|
||||
|
||||
**Date:** 2025-12-28
|
||||
**Problem:** Cloud Build costing $100+/month with slow builds
|
||||
**Solution:** Move Docker builds to GitHub Actions with registry caching
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
This document describes the migration from Google Cloud Build to GitHub Actions for Docker image builds. This change eliminates Cloud Build costs while improving build speeds through better caching.
|
||||
|
||||
## Cost Comparison
|
||||
|
||||
| Approach | Monthly Cost | Build Speed | Caching |
|
||||
|----------|-------------|-------------|---------|
|
||||
| **Cloud Build (N1_HIGHCPU_32)** | ~$100+ | 5-15 min | Limited |
|
||||
| **GitHub Actions + Registry Cache** | **$0** | 2-5 min | Excellent |
|
||||
|
||||
### Why Cloud Build Was Expensive
|
||||
|
||||
1. **N1_HIGHCPU_32 pricing**: ~$0.064/build-minute (21x more than default)
|
||||
2. **No persistent layer cache**: Each build re-downloaded dependencies
|
||||
3. **Cold start overhead**: Spinning up build VMs added latency
|
||||
4. **Large dependency tree**: torch, transformers, etc. = ~500 packages
|
||||
|
||||
### Why GitHub Actions Is Free
|
||||
|
||||
- **Public repositories**: Unlimited build minutes on GitHub-hosted runners
|
||||
- **Registry cache**: Layers cached in Artifact Registry, persist between builds
|
||||
- **BuildKit mode=max**: Caches ALL intermediate layers, not just final
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────────┐
|
||||
│ NEW BUILD PIPELINE │
|
||||
├─────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ GitHub Actions (Free) │
|
||||
│ ├── docker/setup-buildx-action (BuildKit) │
|
||||
│ ├── google-github-actions/auth (Workload Identity) │
|
||||
│ └── docker/build-push-action │
|
||||
│ ├── cache-from: type=registry,ref=...karaoke-backend:cache │
|
||||
│ └── cache-to: type=registry,ref=...karaoke-backend:cache,mode=max│
|
||||
│ │
|
||||
│ Artifact Registry │
|
||||
│ ├── karaoke-backend:latest (production image) │
|
||||
│ ├── karaoke-backend:cache (build cache - ALL layers) │
|
||||
│ ├── karaoke-backend-base:latest (base image with deps) │
|
||||
│ └── karaoke-backend-base:cache (base cache) │
|
||||
│ │
|
||||
│ Build Times (Expected): │
|
||||
│ ├── First build (cold): ~8-10 min │
|
||||
│ ├── Code-only changes: ~2-3 min (cache hit) │
|
||||
│ └── Dependency changes: ~6-8 min (partial cache hit) │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## How It Works
|
||||
|
||||
### Two-Stage Build Pattern
|
||||
|
||||
We maintain the existing two-stage build pattern for efficiency:
|
||||
|
||||
1. **Base Image** (`karaoke-backend-base`)
|
||||
- Contains Python 3.11, ffmpeg, system dependencies
|
||||
- All pip dependencies pre-installed
|
||||
- Only rebuilt when `poetry.lock` or `Dockerfile.base` changes
|
||||
- Hash-based change detection via image labels
|
||||
|
||||
2. **App Image** (`karaoke-backend`)
|
||||
- Built FROM the base image
|
||||
- Contains only application code
|
||||
- Fast rebuilds (~2 min) for code-only changes
|
||||
|
||||
### Registry Cache
|
||||
|
||||
The key optimization is using Artifact Registry as a persistent layer cache:
|
||||
|
||||
```yaml
|
||||
- uses: docker/build-push-action@v6
|
||||
with:
|
||||
cache-from: type=registry,ref=.../karaoke-backend:cache
|
||||
cache-to: type=registry,ref=.../karaoke-backend:cache,mode=max
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- `mode=max` caches ALL layers, not just the final image
|
||||
- Cache persists between CI runs (unlike GitHub Actions cache which has 10GB limit)
|
||||
- Layers only re-built when inputs change
|
||||
|
||||
---
|
||||
|
||||
## Files Changed
|
||||
|
||||
### New Files
|
||||
|
||||
- **`.dockerignore`** - Reduces build context from ~1GB to ~10MB
|
||||
|
||||
### Modified Files
|
||||
|
||||
- **`.github/workflows/ci.yml`** - `deploy-backend` job rewritten to use:
|
||||
- `docker/setup-buildx-action@v3`
|
||||
- `docker/build-push-action@v6`
|
||||
- Registry caching to Artifact Registry
|
||||
|
||||
### Kept (as fallback)
|
||||
|
||||
- **`cloudbuild.yaml`** - Still works for manual triggers
|
||||
- **`cloudbuild-base.yaml`** - Still works for manual base image builds
|
||||
|
||||
---
|
||||
|
||||
## Manual Builds (Fallback)
|
||||
|
||||
If GitHub Actions fails, you can still use Cloud Build:
|
||||
|
||||
```bash
|
||||
# Build base image (only if dependencies changed)
|
||||
gcloud builds submit --config=cloudbuild-base.yaml --project=nomadkaraoke
|
||||
|
||||
# Build and deploy app image
|
||||
gcloud builds submit --config=cloudbuild.yaml --project=nomadkaraoke
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Monitoring
|
||||
|
||||
### Check Build Cache Usage
|
||||
|
||||
View cache images in Artifact Registry:
|
||||
|
||||
```bash
|
||||
gcloud artifacts docker images list \
|
||||
us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo \
|
||||
--include-tags
|
||||
```
|
||||
|
||||
You should see `*:cache` tags for both base and app images.
|
||||
|
||||
### Compare Build Times
|
||||
|
||||
- **GitHub Actions**: Check workflow run times in Actions tab
|
||||
- **Previous Cloud Build**: ~5-15 min per build
|
||||
- **Expected with cache**: ~2-3 min for code changes
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Cache Miss (Slow Build)
|
||||
|
||||
If builds are slow despite no dependency changes:
|
||||
|
||||
1. Check if cache image exists:
|
||||
```bash
|
||||
docker pull us-central1-docker.pkg.dev/nomadkaraoke/karaoke-repo/karaoke-backend:cache
|
||||
```
|
||||
|
||||
2. Force cache rebuild by pushing to `main` with a small change
|
||||
|
||||
### Disk Space Issues
|
||||
|
||||
GitHub Actions runners have limited disk. If base image builds fail:
|
||||
|
||||
1. The workflow includes `jlumbroso/free-disk-space` action
|
||||
2. It removes Android SDK, Haskell, .NET, etc. to free ~20GB
|
||||
|
||||
### Authentication Issues
|
||||
|
||||
If `docker push` fails with permission errors:
|
||||
|
||||
1. Check Workload Identity is configured correctly
|
||||
2. Verify service account has `roles/artifactregistry.writer`
|
||||
|
||||
---
|
||||
|
||||
## Future Improvements
|
||||
|
||||
1. **Parallel base/app builds**: If base is unchanged, start app build immediately
|
||||
2. **GitHub Actions cache fallback**: Use GHA cache when registry is slow
|
||||
3. **Build metrics**: Track build times and cache hit rates
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
- [Docker Build with GitHub Actions](https://docs.docker.com/build/ci/github-actions/)
|
||||
- [Registry Cache Backend](https://docs.docker.com/build/cache/backends/registry/)
|
||||
- [Cache Management](https://docs.docker.com/build/ci/github-actions/cache/)
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loaded 100 of 308 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user