mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-22 05:47:55 +09:00
Compare commits
23
Commits
No files matched your search
@@ -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
|
||||
+236
-118
@@ -18,11 +18,13 @@ concurrency:
|
||||
jobs:
|
||||
# ============================================
|
||||
# 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 }}
|
||||
@@ -61,14 +63,14 @@ jobs:
|
||||
echo "| Dependencies | ${{ steps.filter.outputs.deps }} |" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
# ============================================
|
||||
# FRONTEND TESTS
|
||||
# FRONTEND TESTS (PRs only - main skips tests)
|
||||
# ============================================
|
||||
|
||||
frontend-unit-tests:
|
||||
name: "Frontend - Unit Tests"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.frontend == 'true' || github.ref == 'refs/heads/main' }}
|
||||
if: github.ref != 'refs/heads/main' && needs.changes.outputs.frontend == 'true'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -95,15 +97,40 @@ jobs:
|
||||
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 (karaoke-gen Python CLI)
|
||||
# PACKAGE TESTS (PRs only - main skips tests)
|
||||
# ============================================
|
||||
|
||||
package-unit-tests:
|
||||
name: "Package - Unit Tests (70% coverage)"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true' || github.ref == 'refs/heads/main' }}
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -161,7 +188,7 @@ jobs:
|
||||
name: "Package - Integration Tests"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true' || github.ref == 'refs/heads/main' }}
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true')
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -206,11 +233,15 @@ jobs:
|
||||
- name: Run integration tests
|
||||
run: poetry run pytest tests/integration/ -v
|
||||
|
||||
package-build:
|
||||
name: "Package - Build & Install"
|
||||
package-build-test:
|
||||
name: "Package - Build & Install (Test)"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [changes, package-unit-tests, package-integration-tests]
|
||||
if: ${{ 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' || github.ref == 'refs/heads/main') }}
|
||||
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:
|
||||
@@ -254,22 +285,15 @@ jobs:
|
||||
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
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true' || github.ref == 'refs/heads/main' }}
|
||||
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
|
||||
@@ -314,14 +338,18 @@ jobs:
|
||||
name: "Backend - Emulator Integration Tests"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || needs.changes.outputs.deps == 'true' || github.ref == 'refs/heads/main' }}
|
||||
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
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
with:
|
||||
tool-cache: false
|
||||
android: true
|
||||
haskell: true
|
||||
dotnet: true
|
||||
large-packages: false
|
||||
docker-images: false
|
||||
swap-storage: false
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
@@ -384,7 +412,7 @@ jobs:
|
||||
name: "Backend - Code Quality"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: ${{ needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true' || github.ref == 'refs/heads/main' }}
|
||||
if: github.ref != 'refs/heads/main' && (needs.changes.outputs.backend == 'true' || needs.changes.outputs.package == 'true')
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
@@ -419,9 +447,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
|
||||
@@ -512,11 +609,7 @@ jobs:
|
||||
deploy-frontend:
|
||||
name: "Deploy - Frontend (GitHub Pages)"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [frontend-unit-tests]
|
||||
if: ${{ always() && github.ref == 'refs/heads/main' && github.event_name == 'push' && (needs.frontend-unit-tests.result == 'success' || needs.frontend-unit-tests.result == 'skipped') }}
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -588,12 +681,32 @@ jobs:
|
||||
deploy-backend:
|
||||
name: "Deploy - Backend (Cloud Run)"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [backend-unit-tests, backend-emulator-tests, backend-lint]
|
||||
if: ${{ always() && github.ref == 'refs/heads/main' && github.event_name == 'push' && (needs.backend-unit-tests.result == 'success' || needs.backend-unit-tests.result == 'skipped') && (needs.backend-emulator-tests.result == 'success' || needs.backend-emulator-tests.result == 'skipped') && (needs.backend-lint.result == 'success' || needs.backend-lint.result == 'skipped') }}
|
||||
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:
|
||||
# ============================================
|
||||
# Free disk space FIRST - before anything else
|
||||
# This prevents "No space left on device" errors
|
||||
# ============================================
|
||||
- name: Free disk space (aggressive)
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
with:
|
||||
tool-cache: true
|
||||
android: true
|
||||
haskell: true
|
||||
dotnet: true
|
||||
large-packages: true
|
||||
docker-images: true
|
||||
swap-storage: true
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -638,21 +751,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
|
||||
@@ -661,10 +790,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
|
||||
@@ -672,88 +801,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'
|
||||
@@ -804,6 +918,10 @@ jobs:
|
||||
echo "Commit: ${{ github.sha }}"
|
||||
echo "Branch: ${{ github.ref_name }}"
|
||||
echo "Run: ${{ github.run_number }}"
|
||||
echo ""
|
||||
echo "📊 Cost savings: This build used FREE GitHub Actions instead of Cloud Build"
|
||||
echo " Previously: ~\$0.064/min with N1_HIGHCPU_32"
|
||||
echo " Now: \$0 (public repo) with registry-cached builds"
|
||||
|
||||
- name: Skipped deployment summary
|
||||
if: steps.version_check.outputs.needs_deploy == 'false'
|
||||
|
||||
@@ -18,18 +18,15 @@ Create descriptive branch names like `feature/add-discord-notifications`, `fix/a
|
||||
|
||||
### Using Git Worktrees
|
||||
|
||||
**For non-trivial changes** (new features, multi-file edits, refactors):
|
||||
- Create a git worktree in the parent folder before making any file changes:
|
||||
```bash
|
||||
git worktree add ../karaoke-gen-feat-xyz feature/xyz
|
||||
```
|
||||
**All changes require a git worktree.** Since all changes must go through a PR, always create a worktree in the parent folder before making any file changes:
|
||||
|
||||
```bash
|
||||
git worktree add -b feature/xyz ../karaoke-gen-feat-xyz main
|
||||
```
|
||||
|
||||
- This keeps the main directory clean on `main` and enables parallel work on multiple features
|
||||
- Name the worktree folder descriptively, e.g., `../karaoke-gen-fix-audio-sync`
|
||||
|
||||
**For trivial changes** (typos, single-line fixes):
|
||||
- Creating a branch in the current directory is acceptable
|
||||
- Use `git checkout -b fix/typo-xyz` before making changes
|
||||
|
||||
**Cleanup:** When done with a worktree, remove it with:
|
||||
```bash
|
||||
git worktree remove ../karaoke-gen-feat-xyz
|
||||
@@ -75,11 +72,13 @@ Do not attempt to work around auth issues or make assumptions about credentials.
|
||||
|
||||
## Version Management
|
||||
|
||||
When committing and pushing changes, always bump the patch version in `pyproject.toml`.
|
||||
When committing and pushing **code changes**, 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.
|
||||
**Skip version bumps** for documentation-only changes (e.g., updating `CLAUDE.md`, `README.md`, or other markdown files) that don't affect deployed code.
|
||||
|
||||
This ensures every code release has a unique version number for tracking and deployment purposes.
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
@@ -129,3 +128,25 @@ Individual test commands:
|
||||
|
||||
**Do not commit or push code that fails tests. Fix any test failures before proceeding.**
|
||||
|
||||
## Related Projects
|
||||
|
||||
### flacfetch
|
||||
|
||||
**Location:** `/Users/andrew/Projects/flacfetch`
|
||||
|
||||
The `flacfetch` package is a dependency of karaoke-gen that we also own. When working on features that interact with flacfetch, you can read and modify its code directly.
|
||||
|
||||
**Workflow for flacfetch changes:**
|
||||
|
||||
1. Navigate to `/Users/andrew/Projects/flacfetch`
|
||||
2. Make changes directly on `main` (no PR required for this repo)
|
||||
3. Run tests and ensure they pass
|
||||
4. Bump the version in flacfetch's `pyproject.toml`
|
||||
5. Commit and push to `main`
|
||||
6. Wait for CI workflow to complete and auto-release the new version
|
||||
7. Return to karaoke-gen and update the poetry dependency:
|
||||
```bash
|
||||
poetry update flacfetch
|
||||
```
|
||||
8. Commit the updated `poetry.lock` in karaoke-gen
|
||||
|
||||
@@ -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/)
|
||||
@@ -29,10 +29,6 @@ jest.mock('../job/OutputLinks', () => ({
|
||||
OutputLinks: () => <div data-testid="output-links">Output Links</div>
|
||||
}))
|
||||
|
||||
jest.mock('../job/InstrumentalSelector', () => ({
|
||||
InstrumentalSelector: () => <div data-testid="instrumental-selector">Instrumental Selector</div>
|
||||
}))
|
||||
|
||||
jest.mock('../audio-search/AudioSearchDialog', () => ({
|
||||
AudioSearchDialog: () => <div data-testid="audio-search-dialog">Audio Search Dialog</div>
|
||||
}))
|
||||
@@ -135,11 +131,20 @@ describe('JobCard', () => {
|
||||
expect(screen.getByRole('button', { name: 'Select Audio' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows instrumental selection button for awaiting_instrumental_selection status', () => {
|
||||
const instrumentalJob = { ...mockJob, status: 'awaiting_instrumental_selection' }
|
||||
it('shows instrumental selection link for awaiting_instrumental_selection status', () => {
|
||||
const instrumentalJob = {
|
||||
...mockJob,
|
||||
status: 'awaiting_instrumental_selection',
|
||||
instrumental_token: 'test-instrumental-token'
|
||||
}
|
||||
render(<JobCard job={instrumentalJob} onRefresh={mockOnRefresh} />)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Select Instrumental' })).toBeInTheDocument()
|
||||
const instrumentalLink = screen.getByText('Select Instrumental')
|
||||
expect(instrumentalLink).toBeInTheDocument()
|
||||
const href = instrumentalLink.closest('a')?.getAttribute('href') || ''
|
||||
expect(href).toContain('/instrumental/')
|
||||
expect(href).toContain('baseApiUrl=')
|
||||
expect(href).toContain('instrumentalToken=test-instrumental-token')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -164,7 +169,7 @@ describe('JobCard', () => {
|
||||
render(<JobCard job={instrumentalJob} onRefresh={mockOnRefresh} />)
|
||||
|
||||
expect(screen.getByText(/Will auto-select clean/)).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Select Instrumental' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Select Instrumental')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows auto-select message for awaiting_audio_selection status', () => {
|
||||
|
||||
@@ -1,263 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useState, useEffect, useCallback } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Slider } from "@/components/ui/slider"
|
||||
import { Play, Pause, SkipBack, SkipForward, Volume2, VolumeX } from "lucide-react"
|
||||
|
||||
interface AudioPlayerProps {
|
||||
src: string
|
||||
onTimeUpdate?: (currentTime: number) => void
|
||||
onDurationChange?: (duration: number) => void
|
||||
seekTo?: number
|
||||
label?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function AudioPlayer({
|
||||
src,
|
||||
onTimeUpdate,
|
||||
onDurationChange,
|
||||
seekTo,
|
||||
label,
|
||||
className = "",
|
||||
}: AudioPlayerProps) {
|
||||
const audioRef = useRef<HTMLAudioElement>(null)
|
||||
const [isPlaying, setIsPlaying] = useState(false)
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [duration, setDuration] = useState(0)
|
||||
const [volume, setVolume] = useState(1)
|
||||
const [isMuted, setIsMuted] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
|
||||
// Handle external seek requests
|
||||
useEffect(() => {
|
||||
if (seekTo !== undefined && audioRef.current && !isNaN(seekTo)) {
|
||||
audioRef.current.currentTime = seekTo
|
||||
}
|
||||
}, [seekTo])
|
||||
|
||||
// Handle audio events
|
||||
useEffect(() => {
|
||||
const audio = audioRef.current
|
||||
if (!audio) return
|
||||
|
||||
const handleTimeUpdate = () => {
|
||||
setCurrentTime(audio.currentTime)
|
||||
onTimeUpdate?.(audio.currentTime)
|
||||
}
|
||||
|
||||
const handleDurationChange = () => {
|
||||
setDuration(audio.duration)
|
||||
onDurationChange?.(audio.duration)
|
||||
}
|
||||
|
||||
const handleLoadedData = () => {
|
||||
setIsLoading(false)
|
||||
setDuration(audio.duration)
|
||||
onDurationChange?.(audio.duration)
|
||||
}
|
||||
|
||||
const handleEnded = () => {
|
||||
setIsPlaying(false)
|
||||
}
|
||||
|
||||
const handleLoadStart = () => {
|
||||
setIsLoading(true)
|
||||
}
|
||||
|
||||
const handleCanPlay = () => {
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
// Sync isPlaying state with actual audio element state
|
||||
const handlePlay = () => {
|
||||
setIsPlaying(true)
|
||||
}
|
||||
|
||||
const handlePause = () => {
|
||||
setIsPlaying(false)
|
||||
}
|
||||
|
||||
audio.addEventListener("timeupdate", handleTimeUpdate)
|
||||
audio.addEventListener("durationchange", handleDurationChange)
|
||||
audio.addEventListener("loadeddata", handleLoadedData)
|
||||
audio.addEventListener("ended", handleEnded)
|
||||
audio.addEventListener("loadstart", handleLoadStart)
|
||||
audio.addEventListener("canplay", handleCanPlay)
|
||||
audio.addEventListener("play", handlePlay)
|
||||
audio.addEventListener("pause", handlePause)
|
||||
|
||||
return () => {
|
||||
audio.removeEventListener("timeupdate", handleTimeUpdate)
|
||||
audio.removeEventListener("durationchange", handleDurationChange)
|
||||
audio.removeEventListener("loadeddata", handleLoadedData)
|
||||
audio.removeEventListener("ended", handleEnded)
|
||||
audio.removeEventListener("loadstart", handleLoadStart)
|
||||
audio.removeEventListener("canplay", handleCanPlay)
|
||||
audio.removeEventListener("play", handlePlay)
|
||||
audio.removeEventListener("pause", handlePause)
|
||||
}
|
||||
}, [onTimeUpdate, onDurationChange])
|
||||
|
||||
// Update volume
|
||||
useEffect(() => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.volume = isMuted ? 0 : volume
|
||||
}
|
||||
}, [volume, isMuted])
|
||||
|
||||
const togglePlay = useCallback(async () => {
|
||||
const audio = audioRef.current
|
||||
if (!audio) return
|
||||
|
||||
try {
|
||||
if (audio.paused) {
|
||||
await audio.play()
|
||||
} else {
|
||||
audio.pause()
|
||||
}
|
||||
// State will be updated by the play/pause event listeners
|
||||
} catch (error) {
|
||||
// Play was prevented (e.g., user hasn't interacted with page yet)
|
||||
console.warn("Audio playback was prevented:", error)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleSeek = useCallback((value: number[]) => {
|
||||
const audio = audioRef.current
|
||||
if (!audio) return
|
||||
|
||||
const newTime = value[0]
|
||||
audio.currentTime = newTime
|
||||
setCurrentTime(newTime)
|
||||
}, [])
|
||||
|
||||
const skipBackward = useCallback(() => {
|
||||
const audio = audioRef.current
|
||||
if (!audio) return
|
||||
|
||||
audio.currentTime = Math.max(0, audio.currentTime - 5)
|
||||
}, [])
|
||||
|
||||
const skipForward = useCallback(() => {
|
||||
const audio = audioRef.current
|
||||
if (!audio) return
|
||||
|
||||
audio.currentTime = Math.min(duration, audio.currentTime + 5)
|
||||
}, [duration])
|
||||
|
||||
const toggleMute = useCallback(() => {
|
||||
setIsMuted(!isMuted)
|
||||
}, [isMuted])
|
||||
|
||||
const handleVolumeChange = useCallback((value: number[]) => {
|
||||
setVolume(value[0])
|
||||
if (value[0] > 0 && isMuted) {
|
||||
setIsMuted(false)
|
||||
}
|
||||
}, [isMuted])
|
||||
|
||||
const formatTime = (time: number) => {
|
||||
if (isNaN(time)) return "0:00"
|
||||
const minutes = Math.floor(time / 60)
|
||||
const seconds = Math.floor(time % 60)
|
||||
return `${minutes}:${seconds.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`bg-card rounded-lg p-4 ${className}`}>
|
||||
<audio ref={audioRef} src={src} preload="metadata" />
|
||||
|
||||
{label && (
|
||||
<div className="text-sm font-medium text-muted-foreground mb-3">
|
||||
{label}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Progress bar */}
|
||||
<div className="mb-4">
|
||||
<Slider
|
||||
value={[currentTime]}
|
||||
max={duration || 100}
|
||||
step={0.1}
|
||||
onValueChange={handleSeek}
|
||||
disabled={isLoading}
|
||||
className="w-full"
|
||||
/>
|
||||
<div className="flex justify-between text-xs text-muted-foreground mt-1">
|
||||
<span>{formatTime(currentTime)}</span>
|
||||
<span>{formatTime(duration)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Controls */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={skipBackward}
|
||||
disabled={isLoading}
|
||||
className="h-8 w-8"
|
||||
>
|
||||
<SkipBack className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="default"
|
||||
size="icon"
|
||||
onClick={togglePlay}
|
||||
disabled={isLoading}
|
||||
className="h-10 w-10"
|
||||
>
|
||||
{isPlaying ? (
|
||||
<Pause className="h-5 w-5" />
|
||||
) : (
|
||||
<Play className="h-5 w-5 ml-0.5" />
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={skipForward}
|
||||
disabled={isLoading}
|
||||
className="h-8 w-8"
|
||||
>
|
||||
<SkipForward className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Volume control */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleMute}
|
||||
className="h-8 w-8"
|
||||
>
|
||||
{isMuted || volume === 0 ? (
|
||||
<VolumeX className="h-4 w-4" />
|
||||
) : (
|
||||
<Volume2 className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Slider
|
||||
value={[isMuted ? 0 : volume]}
|
||||
max={1}
|
||||
step={0.1}
|
||||
onValueChange={handleVolumeChange}
|
||||
className="w-20"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading && (
|
||||
<div className="text-xs text-muted-foreground text-center mt-2">
|
||||
Loading audio...
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export { WaveformDisplay } from "./waveform-display"
|
||||
export { AudioPlayer } from "./audio-player"
|
||||
export { RegionSelector } from "./region-selector"
|
||||
@@ -1,222 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Trash2, VolumeX, Plus } from "lucide-react"
|
||||
|
||||
interface MuteRegion {
|
||||
start_seconds: number
|
||||
end_seconds: number
|
||||
}
|
||||
|
||||
interface AudibleSegment {
|
||||
start_seconds: number
|
||||
end_seconds: number
|
||||
duration_seconds: number
|
||||
avg_amplitude_db: number
|
||||
}
|
||||
|
||||
interface RegionSelectorProps {
|
||||
muteRegions: MuteRegion[]
|
||||
audibleSegments?: AudibleSegment[]
|
||||
onAddRegion: (region: MuteRegion) => void
|
||||
onRemoveRegion: (index: number) => void
|
||||
onClearAll: () => void
|
||||
onSeekTo?: (time: number) => void
|
||||
isSelectionMode: boolean
|
||||
onToggleSelectionMode: () => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function RegionSelector({
|
||||
muteRegions,
|
||||
audibleSegments = [],
|
||||
onAddRegion,
|
||||
onRemoveRegion,
|
||||
onClearAll,
|
||||
onSeekTo,
|
||||
isSelectionMode,
|
||||
onToggleSelectionMode,
|
||||
className = "",
|
||||
}: RegionSelectorProps) {
|
||||
const formatTime = (seconds: number) => {
|
||||
const mins = Math.floor(seconds / 60)
|
||||
const secs = Math.floor(seconds % 60)
|
||||
const ms = Math.floor((seconds % 1) * 100)
|
||||
return `${mins}:${secs.toString().padStart(2, "0")}.${ms.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
const formatDuration = (seconds: number) => {
|
||||
if (seconds < 1) {
|
||||
return `${Math.round(seconds * 1000)}ms`
|
||||
}
|
||||
return `${seconds.toFixed(1)}s`
|
||||
}
|
||||
|
||||
const totalMutedDuration = muteRegions.reduce(
|
||||
(sum, r) => sum + (r.end_seconds - r.start_seconds),
|
||||
0
|
||||
)
|
||||
|
||||
// Quick mute: add mute region for an audible segment
|
||||
const handleQuickMute = (segment: AudibleSegment) => {
|
||||
onAddRegion({
|
||||
start_seconds: segment.start_seconds,
|
||||
end_seconds: segment.end_seconds,
|
||||
})
|
||||
}
|
||||
|
||||
// Check if a segment is already muted
|
||||
const isSegmentMuted = (segment: AudibleSegment) => {
|
||||
return muteRegions.some(
|
||||
(r) =>
|
||||
r.start_seconds <= segment.start_seconds &&
|
||||
r.end_seconds >= segment.end_seconds
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`space-y-4 ${className}`}>
|
||||
{/* Selection Mode Toggle */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-lg">Mute Regions</CardTitle>
|
||||
<Button
|
||||
variant={isSelectionMode ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={onToggleSelectionMode}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
{isSelectionMode ? "Click waveform to select" : "Add Region"}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{muteRegions.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No mute regions selected. Click "Add Region" and drag on the waveform to select areas to mute.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{muteRegions.map((region, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center justify-between p-2 bg-muted/50 rounded-lg group"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<VolumeX className="h-4 w-4 text-destructive" />
|
||||
<button
|
||||
onClick={() => onSeekTo?.(region.start_seconds)}
|
||||
className="text-sm font-mono hover:text-primary transition-colors"
|
||||
>
|
||||
{formatTime(region.start_seconds)}
|
||||
</button>
|
||||
<span className="text-muted-foreground">→</span>
|
||||
<button
|
||||
onClick={() => onSeekTo?.(region.end_seconds)}
|
||||
className="text-sm font-mono hover:text-primary transition-colors"
|
||||
>
|
||||
{formatTime(region.end_seconds)}
|
||||
</button>
|
||||
<Badge variant="secondary" className="ml-2">
|
||||
{formatDuration(region.end_seconds - region.start_seconds)}
|
||||
</Badge>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => onRemoveRegion(index)}
|
||||
className="h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div className="flex items-center justify-between pt-2 border-t mt-3">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Total muted: {formatDuration(totalMutedDuration)}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onClearAll}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
Clear All
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Detected Audible Segments */}
|
||||
{audibleSegments.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-lg">Detected Backing Vocals</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
Click a segment to jump to that time, or click the mute button to add it as a mute region.
|
||||
</p>
|
||||
<div className="space-y-2 max-h-64 overflow-y-auto">
|
||||
{audibleSegments.map((segment, index) => {
|
||||
const isMuted = isSegmentMuted(segment)
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={`flex items-center justify-between p-2 rounded-lg transition-colors ${
|
||||
isMuted ? "bg-destructive/10" : "bg-muted/50 hover:bg-muted"
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
onClick={() => onSeekTo?.(segment.start_seconds)}
|
||||
className="flex items-center gap-3 text-left"
|
||||
>
|
||||
<span className="text-sm font-mono">
|
||||
{formatTime(segment.start_seconds)} - {formatTime(segment.end_seconds)}
|
||||
</span>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{formatDuration(segment.duration_seconds)}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`text-xs ${
|
||||
segment.avg_amplitude_db > -20
|
||||
? "border-yellow-500 text-yellow-500"
|
||||
: "border-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{segment.avg_amplitude_db.toFixed(1)}dB
|
||||
</Badge>
|
||||
</button>
|
||||
{!isMuted && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleQuickMute(segment)}
|
||||
className="text-xs"
|
||||
>
|
||||
<VolumeX className="h-3 w-3 mr-1" />
|
||||
Mute
|
||||
</Button>
|
||||
)}
|
||||
{isMuted && (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
Muted
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useEffect, useState, useCallback } from "react"
|
||||
|
||||
interface AudibleSegment {
|
||||
start_seconds: number
|
||||
end_seconds: number
|
||||
duration_seconds: number
|
||||
avg_amplitude_db: number
|
||||
}
|
||||
|
||||
interface MuteRegion {
|
||||
start_seconds: number
|
||||
end_seconds: number
|
||||
}
|
||||
|
||||
interface WaveformDisplayProps {
|
||||
amplitudes: number[]
|
||||
duration: number
|
||||
currentTime?: number
|
||||
segments?: AudibleSegment[]
|
||||
muteRegions?: MuteRegion[]
|
||||
onSeek?: (time: number) => void
|
||||
onRegionSelect?: (region: MuteRegion) => void
|
||||
isSelecting?: boolean
|
||||
width?: number
|
||||
height?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function WaveformDisplay({
|
||||
amplitudes,
|
||||
duration,
|
||||
currentTime = 0,
|
||||
segments = [],
|
||||
muteRegions = [],
|
||||
onSeek,
|
||||
onRegionSelect,
|
||||
isSelecting = false,
|
||||
width = 800,
|
||||
height = 150,
|
||||
className = "",
|
||||
}: WaveformDisplayProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [dragStart, setDragStart] = useState<number | null>(null)
|
||||
const [dragEnd, setDragEnd] = useState<number | null>(null)
|
||||
const [hoveredTime, setHoveredTime] = useState<number | null>(null)
|
||||
|
||||
// Convert time to x position
|
||||
const timeToX = useCallback((time: number) => {
|
||||
return (time / duration) * width
|
||||
}, [duration, width])
|
||||
|
||||
// Convert x position to time
|
||||
const xToTime = useCallback((x: number) => {
|
||||
return (x / width) * duration
|
||||
}, [duration, width])
|
||||
|
||||
// Draw the waveform
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
|
||||
const ctx = canvas.getContext("2d")
|
||||
if (!ctx) return
|
||||
|
||||
// Clear canvas
|
||||
ctx.fillStyle = "#1a1a2e"
|
||||
ctx.fillRect(0, 0, width, height)
|
||||
|
||||
const barWidth = width / amplitudes.length
|
||||
const centerY = height / 2
|
||||
|
||||
// Draw mute regions background
|
||||
ctx.fillStyle = "rgba(255, 107, 107, 0.2)"
|
||||
for (const region of muteRegions) {
|
||||
const startX = timeToX(region.start_seconds)
|
||||
const endX = timeToX(region.end_seconds)
|
||||
ctx.fillRect(startX, 0, endX - startX, height)
|
||||
}
|
||||
|
||||
// Draw current drag selection
|
||||
if (isDragging && dragStart !== null && dragEnd !== null) {
|
||||
const startX = Math.min(timeToX(dragStart), timeToX(dragEnd))
|
||||
const endX = Math.max(timeToX(dragStart), timeToX(dragEnd))
|
||||
ctx.fillStyle = "rgba(255, 107, 107, 0.3)"
|
||||
ctx.fillRect(startX, 0, endX - startX, height)
|
||||
}
|
||||
|
||||
// Draw segment highlights
|
||||
for (const segment of segments) {
|
||||
const startX = timeToX(segment.start_seconds)
|
||||
const endX = timeToX(segment.end_seconds)
|
||||
const startIdx = Math.floor((segment.start_seconds / duration) * amplitudes.length)
|
||||
const endIdx = Math.ceil((segment.end_seconds / duration) * amplitudes.length)
|
||||
|
||||
ctx.fillStyle = "rgba(233, 69, 96, 0.4)"
|
||||
for (let i = startIdx; i < endIdx && i < amplitudes.length; i++) {
|
||||
const amplitude = amplitudes[i]
|
||||
const barHeight = amplitude * height * 0.8
|
||||
const x = i * barWidth
|
||||
ctx.fillRect(x, centerY - barHeight / 2, barWidth - 1, barHeight)
|
||||
}
|
||||
}
|
||||
|
||||
// Draw main waveform
|
||||
ctx.fillStyle = "#4a90d9"
|
||||
for (let i = 0; i < amplitudes.length; i++) {
|
||||
const amplitude = amplitudes[i]
|
||||
const barHeight = amplitude * height * 0.8
|
||||
const x = i * barWidth
|
||||
ctx.fillRect(x, centerY - barHeight / 2, barWidth - 1, barHeight)
|
||||
}
|
||||
|
||||
// Draw silence threshold line
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.2)"
|
||||
ctx.setLineDash([5, 5])
|
||||
ctx.beginPath()
|
||||
const thresholdY = height * 0.5 // Visual representation
|
||||
ctx.moveTo(0, thresholdY)
|
||||
ctx.lineTo(width, thresholdY)
|
||||
ctx.stroke()
|
||||
ctx.setLineDash([])
|
||||
|
||||
// Draw playhead
|
||||
if (currentTime > 0) {
|
||||
const playheadX = timeToX(currentTime)
|
||||
ctx.strokeStyle = "#ffffff"
|
||||
ctx.lineWidth = 2
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(playheadX, 0)
|
||||
ctx.lineTo(playheadX, height)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Draw hover position
|
||||
if (hoveredTime !== null && !isDragging) {
|
||||
const hoverX = timeToX(hoveredTime)
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.5)"
|
||||
ctx.lineWidth = 1
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(hoverX, 0)
|
||||
ctx.lineTo(hoverX, height)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Draw time axis
|
||||
ctx.fillStyle = "#ffffff"
|
||||
ctx.font = "10px sans-serif"
|
||||
ctx.textAlign = "center"
|
||||
|
||||
const tickInterval = duration > 300 ? 60 : duration > 60 ? 30 : 10
|
||||
for (let t = 0; t <= duration; t += tickInterval) {
|
||||
const x = timeToX(t)
|
||||
const minutes = Math.floor(t / 60)
|
||||
const seconds = Math.floor(t % 60)
|
||||
const label = `${minutes}:${seconds.toString().padStart(2, "0")}`
|
||||
ctx.fillText(label, x, height - 5)
|
||||
|
||||
// Tick mark
|
||||
ctx.strokeStyle = "rgba(255, 255, 255, 0.3)"
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(x, height - 20)
|
||||
ctx.lineTo(x, height - 15)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
}, [amplitudes, duration, currentTime, segments, muteRegions, width, height, isDragging, dragStart, dragEnd, hoveredTime, timeToX])
|
||||
|
||||
// Handle mouse events for seeking and region selection
|
||||
const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
const x = e.clientX - rect.left
|
||||
const time = xToTime(x)
|
||||
|
||||
if (isSelecting) {
|
||||
setIsDragging(true)
|
||||
setDragStart(time)
|
||||
setDragEnd(time)
|
||||
} else if (onSeek) {
|
||||
onSeek(time)
|
||||
}
|
||||
}
|
||||
|
||||
const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
const x = e.clientX - rect.left
|
||||
const time = xToTime(x)
|
||||
|
||||
setHoveredTime(time)
|
||||
|
||||
if (isDragging && isSelecting) {
|
||||
setDragEnd(time)
|
||||
}
|
||||
}
|
||||
|
||||
const handleMouseUp = () => {
|
||||
if (isDragging && dragStart !== null && dragEnd !== null && onRegionSelect) {
|
||||
const start = Math.min(dragStart, dragEnd)
|
||||
const end = Math.max(dragStart, dragEnd)
|
||||
|
||||
// Only create region if it's at least 0.1 seconds
|
||||
if (end - start >= 0.1) {
|
||||
onRegionSelect({ start_seconds: start, end_seconds: end })
|
||||
}
|
||||
}
|
||||
|
||||
setIsDragging(false)
|
||||
setDragStart(null)
|
||||
setDragEnd(null)
|
||||
}
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
setHoveredTime(null)
|
||||
if (isDragging) {
|
||||
handleMouseUp()
|
||||
}
|
||||
}
|
||||
|
||||
// Format time for tooltip
|
||||
const formatTime = (time: number) => {
|
||||
const minutes = Math.floor(time / 60)
|
||||
const seconds = Math.floor(time % 60)
|
||||
const ms = Math.floor((time % 1) * 100)
|
||||
return `${minutes}:${seconds.toString().padStart(2, "0")}.${ms.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`relative ${className}`}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={width}
|
||||
height={height}
|
||||
className={`rounded-lg ${isSelecting ? "cursor-crosshair" : "cursor-pointer"}`}
|
||||
onMouseDown={handleMouseDown}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseUp={handleMouseUp}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
/>
|
||||
|
||||
{/* Time tooltip */}
|
||||
{hoveredTime !== null && (
|
||||
<div
|
||||
className="absolute top-0 transform -translate-x-1/2 bg-black/80 text-white text-xs px-2 py-1 rounded pointer-events-none"
|
||||
style={{ left: timeToX(hoveredTime) }}
|
||||
>
|
||||
{formatTime(hoveredTime)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { api, InstrumentalOption } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Loader2, Music2, Play, Pause } from "lucide-react"
|
||||
|
||||
interface InstrumentalSelectorProps {
|
||||
jobId: string
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSelect: () => void
|
||||
}
|
||||
|
||||
export function InstrumentalSelector({ jobId, open, onClose, onSelect }: InstrumentalSelectorProps) {
|
||||
const [options, setOptions] = useState<InstrumentalOption[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isSelecting, setIsSelecting] = useState(false)
|
||||
const [error, setError] = useState("")
|
||||
const [playingId, setPlayingId] = useState<string | null>(null)
|
||||
const [audioElements, setAudioElements] = useState<Map<string, HTMLAudioElement>>(new Map())
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
loadOptions()
|
||||
}
|
||||
return () => {
|
||||
// Cleanup audio elements
|
||||
audioElements.forEach(audio => {
|
||||
audio.pause()
|
||||
audio.src = ""
|
||||
})
|
||||
}
|
||||
}, [open])
|
||||
|
||||
async function loadOptions() {
|
||||
setIsLoading(true)
|
||||
setError("")
|
||||
try {
|
||||
const data = await api.getInstrumentalOptions(jobId)
|
||||
setOptions(data.options || [])
|
||||
} catch (err: any) {
|
||||
console.error("Failed to load instrumental options:", err)
|
||||
setError(err.message || "Failed to load options")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSelect(selection: 'clean' | 'with_backing') {
|
||||
setIsSelecting(true)
|
||||
try {
|
||||
await api.selectInstrumental(jobId, selection)
|
||||
onSelect()
|
||||
onClose()
|
||||
} catch (err: any) {
|
||||
console.error("Failed to select instrumental:", err)
|
||||
setError(err.message || "Failed to select instrumental")
|
||||
} finally {
|
||||
setIsSelecting(false)
|
||||
}
|
||||
}
|
||||
|
||||
function togglePlayback(optionId: string, audioUrl: string) {
|
||||
if (playingId === optionId) {
|
||||
// Pause current
|
||||
const audio = audioElements.get(optionId)
|
||||
if (audio) {
|
||||
audio.pause()
|
||||
}
|
||||
setPlayingId(null)
|
||||
} else {
|
||||
// Stop any currently playing audio
|
||||
audioElements.forEach(audio => audio.pause())
|
||||
|
||||
// Play new audio
|
||||
let audio = audioElements.get(optionId)
|
||||
if (!audio) {
|
||||
audio = new Audio(audioUrl)
|
||||
audio.addEventListener('ended', () => setPlayingId(null))
|
||||
audioElements.set(optionId, audio)
|
||||
setAudioElements(new Map(audioElements))
|
||||
}
|
||||
audio.play()
|
||||
setPlayingId(optionId)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-2xl bg-slate-900 border-slate-700">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-white">Select Instrumental Version</DialogTitle>
|
||||
<DialogDescription className="text-slate-400">
|
||||
Choose between a clean instrumental or one with backing vocals
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-slate-400" />
|
||||
<span className="ml-2 text-slate-400">Loading options...</span>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="text-center py-8 text-red-400">{error}</div>
|
||||
) : options.length === 0 ? (
|
||||
<div className="text-center py-8 text-slate-500">
|
||||
<Music2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p>No instrumental options available</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{options.map((option) => (
|
||||
<div
|
||||
key={option.id}
|
||||
className="border border-slate-700 rounded-lg p-4 hover:bg-slate-800/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex-1">
|
||||
<p className="font-medium text-white">{option.label}</p>
|
||||
{option.duration_seconds && (
|
||||
<p className="text-xs text-slate-400 mt-1">
|
||||
Duration: {Math.floor(option.duration_seconds / 60)}:
|
||||
{(option.duration_seconds % 60).toString().padStart(2, '0')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{option.audio_url && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => togglePlayback(option.id, option.audio_url)}
|
||||
className="text-slate-400 hover:text-white"
|
||||
>
|
||||
{playingId === option.id ? (
|
||||
<Pause className="w-4 h-4" />
|
||||
) : (
|
||||
<Play className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleSelect(option.id as 'clean' | 'with_backing')}
|
||||
disabled={isSelecting}
|
||||
className="bg-pink-600 hover:bg-pink-500 text-white"
|
||||
>
|
||||
{isSelecting ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
) : (
|
||||
"Select"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import { Loader2, ExternalLink, Zap } from "lucide-react"
|
||||
import { JobActions } from "./JobActions"
|
||||
import { JobLogs } from "./JobLogs"
|
||||
import { OutputLinks } from "./OutputLinks"
|
||||
import { InstrumentalSelector } from "./InstrumentalSelector"
|
||||
import { AudioSearchDialog } from "../audio-search/AudioSearchDialog"
|
||||
import { getJobStep, formatStepIndicator, getJobProgressPercent } from "@/lib/job-status"
|
||||
|
||||
@@ -78,7 +77,6 @@ interface JobCardProps {
|
||||
export function JobCard({ job, onRefresh }: JobCardProps) {
|
||||
const [showLogs, setShowLogs] = useState(false)
|
||||
const [showAudioSearch, setShowAudioSearch] = useState(false)
|
||||
const [showInstrumentalSelector, setShowInstrumentalSelector] = useState(false)
|
||||
const { enabled: autoModeEnabled, isProcessing: isAutoProcessing } = useAutoMode()
|
||||
|
||||
const createdAt = new Date(job.created_at).toLocaleString()
|
||||
@@ -113,6 +111,18 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
|
||||
return url
|
||||
}
|
||||
|
||||
// Build instrumental review URL for awaiting_instrumental_selection status
|
||||
const getInstrumentalUrl = () => {
|
||||
const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com'
|
||||
const baseApiUrl = `${backendUrl}/api/jobs/${job.job_id}`
|
||||
const encodedApiUrl = encodeURIComponent(baseApiUrl)
|
||||
let url = `/instrumental/?baseApiUrl=${encodedApiUrl}`
|
||||
if (job.instrumental_token) {
|
||||
url += `&instrumentalToken=${encodeURIComponent(job.instrumental_token)}`
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
// Render primary action button based on status
|
||||
const renderPrimaryAction = () => {
|
||||
if (autoModeEnabled && isInteractive) {
|
||||
@@ -163,13 +173,15 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
|
||||
|
||||
if (job.status === "awaiting_instrumental_selection") {
|
||||
return (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setShowInstrumentalSelector(true)}
|
||||
className="text-xs h-7 px-3 bg-blue-600 hover:bg-blue-500"
|
||||
<a
|
||||
href={getInstrumentalUrl()}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-blue-600 hover:bg-blue-500 text-white"
|
||||
>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
Select Instrumental
|
||||
</Button>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -235,13 +247,6 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
|
||||
onClose={() => setShowAudioSearch(false)}
|
||||
onSelect={onRefresh}
|
||||
/>
|
||||
|
||||
<InstrumentalSelector
|
||||
jobId={job.job_id}
|
||||
open={showInstrumentalSelector}
|
||||
onClose={() => setShowInstrumentalSelector(false)}
|
||||
onSelect={onRefresh}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
export { JobCard, StatusBadge } from "./JobCard"
|
||||
export { JobCard } from "./JobCard"
|
||||
export { JobActions } from "./JobActions"
|
||||
export { JobLogs } from "./JobLogs"
|
||||
export { OutputLinks } from "./OutputLinks"
|
||||
export { InstrumentalSelector } from "./InstrumentalSelector"
|
||||
|
||||
@@ -63,6 +63,7 @@ export interface Job {
|
||||
message?: string;
|
||||
}>;
|
||||
review_token?: string;
|
||||
instrumental_token?: string;
|
||||
audio_hash?: string;
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1696,7 +1696,7 @@ class RemoteFlacFetchAudioFetcher(AudioFetcher):
|
||||
import re
|
||||
|
||||
self.logger.info(f"[RemoteFlacFetcher] Downloading from URL: {url}")
|
||||
self.logger.info(f"[RemoteFlacFetcher] Using local flacfetch for YouTube download (no remote API needed)")
|
||||
self.logger.info("[RemoteFlacFetcher] Using local flacfetch for YouTube download (no remote API needed)")
|
||||
|
||||
try:
|
||||
# Use local flacfetch for YouTube downloads - no need for remote API
|
||||
@@ -1762,7 +1762,7 @@ class RemoteFlacFetchAudioFetcher(AudioFetcher):
|
||||
except ImportError as e:
|
||||
raise DownloadError(
|
||||
f"flacfetch is required for URL downloads but import failed: {e}"
|
||||
)
|
||||
) from e
|
||||
except Exception as e:
|
||||
raise DownloadError(f"Failed to download from URL {url}: {e}") from e
|
||||
|
||||
|
||||
@@ -503,7 +503,7 @@ class KaraokePrep:
|
||||
)
|
||||
|
||||
# Update extractor to reflect the source
|
||||
self.extractor = f"youtube"
|
||||
self.extractor = "youtube"
|
||||
else:
|
||||
# Use flacfetch to search and download audio
|
||||
self.logger.info(f"Using flacfetch to search and download: {self.artist} - {self.title}")
|
||||
|
||||
Generated
+3
-3
@@ -1873,14 +1873,14 @@ platformdirs = ">=4.3.6"
|
||||
|
||||
[[package]]
|
||||
name = "flacfetch"
|
||||
version = "0.15.0"
|
||||
version = "0.15.1"
|
||||
description = "Search and download high-quality audio from multiple sources"
|
||||
optional = false
|
||||
python-versions = ">=3.8"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "flacfetch-0.15.0-py3-none-any.whl", hash = "sha256:fa2eb155dd92113d37952fe0df5587ce472c85d5c924574342955c0968e802a1"},
|
||||
{file = "flacfetch-0.15.0.tar.gz", hash = "sha256:ff7ce633d89fae69c7c221a8244afdf56598bfbe2b1ae71e6584df424b9ca995"},
|
||||
{file = "flacfetch-0.15.1-py3-none-any.whl", hash = "sha256:d50beda83866a8d5567e50e6a2f714379a3c48fae23ccbe5f8153403a5979f09"},
|
||||
{file = "flacfetch-0.15.1.tar.gz", hash = "sha256:d0953931e63d858d71f5e9ece61a82886b8104c2b30be0bdf7b53c97290e6610"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.76.17"
|
||||
version = "0.76.22"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -568,7 +568,7 @@ class TestAsync:
|
||||
basic_karaoke_gen.title = None # Missing title
|
||||
|
||||
# Test that ValueError is raised
|
||||
with pytest.raises(ValueError, match="Either a local file path.*or both artist and title must be provided"):
|
||||
with pytest.raises(ValueError, match=r"Either a local file path.*or both artist and title must be provided"):
|
||||
await basic_karaoke_gen.process()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -610,7 +610,10 @@ class TestAsync:
|
||||
with patch.object(basic_karaoke_gen, 'prep_single_track', new_callable=AsyncMock) as mock_prep_single_track:
|
||||
mock_prep_single_track.return_value = {"track": "result"}
|
||||
|
||||
result = await basic_karaoke_gen.process()
|
||||
await basic_karaoke_gen.process()
|
||||
|
||||
# Verify prep_single_track was called
|
||||
mock_prep_single_track.assert_called_once()
|
||||
|
||||
# Verify URL mode was enabled
|
||||
assert basic_karaoke_gen._use_audio_fetcher is True
|
||||
@@ -631,7 +634,10 @@ class TestAsync:
|
||||
with patch.object(basic_karaoke_gen, 'prep_single_track', new_callable=AsyncMock) as mock_prep_single_track:
|
||||
mock_prep_single_track.return_value = {"track": "result"}
|
||||
|
||||
result = await basic_karaoke_gen.process()
|
||||
await basic_karaoke_gen.process()
|
||||
|
||||
# Verify prep_single_track was called
|
||||
mock_prep_single_track.assert_called_once()
|
||||
|
||||
# Verify URL mode was enabled
|
||||
assert basic_karaoke_gen._use_audio_fetcher is True
|
||||
@@ -645,7 +651,6 @@ class TestKaraokePrepIsUrlHelper:
|
||||
@pytest.fixture
|
||||
def karaoke_prep(self, tmp_path):
|
||||
"""Create a KaraokePrep instance for testing."""
|
||||
from karaoke_gen.karaoke_gen import KaraokePrep
|
||||
return KaraokePrep(
|
||||
artist="Test",
|
||||
title="Test",
|
||||
|
||||
@@ -2452,7 +2452,7 @@ class TestFlacFetchAudioFetcherDownloadFromUrl:
|
||||
mock_manager.download_by_id.return_value = downloaded_path
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
result = fetcher.download_from_url(
|
||||
fetcher.download_from_url(
|
||||
url="https://www.youtube.com/embed/dQw4w9WgXcQ",
|
||||
output_dir=str(tmp_path),
|
||||
)
|
||||
@@ -2468,7 +2468,7 @@ class TestFlacFetchAudioFetcherDownloadFromUrl:
|
||||
mock_manager.download_by_id.return_value = downloaded_path
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
result = fetcher.download_from_url(
|
||||
fetcher.download_from_url(
|
||||
url="https://www.youtube.com/watch?v=test123test",
|
||||
output_dir=str(tmp_path),
|
||||
artist="Test Artist",
|
||||
@@ -2486,7 +2486,7 @@ class TestFlacFetchAudioFetcherDownloadFromUrl:
|
||||
mock_manager.download_by_id.return_value = downloaded_path
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
result = fetcher.download_from_url(
|
||||
fetcher.download_from_url(
|
||||
url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
|
||||
output_dir=str(tmp_path),
|
||||
)
|
||||
@@ -2563,7 +2563,7 @@ class TestRemoteFlacFetchAudioFetcherDownloadFromUrl:
|
||||
@patch('flacfetch.providers.youtube.YoutubeProvider')
|
||||
@patch('flacfetch.downloaders.youtube.YoutubeDownloader')
|
||||
def test_download_from_url_uses_local_flacfetch(
|
||||
self, mock_yt_downloader, mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
|
||||
self, mock_yt_downloader, _mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
|
||||
):
|
||||
"""Test that download_from_url uses local flacfetch (not remote API)."""
|
||||
mock_manager_instance = MagicMock()
|
||||
@@ -2593,7 +2593,7 @@ class TestRemoteFlacFetchAudioFetcherDownloadFromUrl:
|
||||
@patch('flacfetch.providers.youtube.YoutubeProvider')
|
||||
@patch('flacfetch.downloaders.youtube.YoutubeDownloader')
|
||||
def test_download_from_url_extracts_video_id(
|
||||
self, mock_yt_downloader, mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
|
||||
self, _mock_yt_downloader, _mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
|
||||
):
|
||||
"""Test that video ID is extracted from URL correctly."""
|
||||
mock_manager_instance = MagicMock()
|
||||
@@ -2612,7 +2612,7 @@ class TestRemoteFlacFetchAudioFetcherDownloadFromUrl:
|
||||
@patch('flacfetch.providers.youtube.YoutubeProvider')
|
||||
@patch('flacfetch.downloaders.youtube.YoutubeDownloader')
|
||||
def test_download_from_url_raises_on_failure(
|
||||
self, mock_yt_downloader, mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
|
||||
self, _mock_yt_downloader, _mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
|
||||
):
|
||||
"""Test that DownloadError is raised on failure."""
|
||||
mock_manager_instance = MagicMock()
|
||||
|
||||
Reference in new issue
Block a user