mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-05 09:28:25 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c9e434037b | ||
|
|
17265a6f28 | ||
|
|
5e7ede1cfe | ||
|
|
7294db2f6d | ||
|
|
83c75a9d98 |
No files matched your search
@@ -0,0 +1,109 @@
|
||||
# Plan: Admin Feedback Visibility
|
||||
|
||||
**Created:** 2026-03-23
|
||||
**Branch:** feat/sess-20260323-1454-feedback-email-debug
|
||||
**Status:** Draft
|
||||
|
||||
## Overview
|
||||
|
||||
User feedback submissions are stored in Firestore (`user_feedback` collection) but are completely invisible to the admin. The admin panel only shows a boolean "Feedback Submitted: Yes/No" badge per user. This plan adds:
|
||||
|
||||
1. **Admin UI page** to browse and review all submitted feedback
|
||||
2. **Email notification** to admin@nomadkaraoke.com on each new submission
|
||||
|
||||
## Requirements
|
||||
|
||||
- [ ] Admin page at `/admin/feedback` listing all feedback with ratings, text, timestamps, and user info
|
||||
- [ ] Sortable by date (newest first by default) and filterable by search (email)
|
||||
- [ ] Star ratings rendered visually (not just numbers)
|
||||
- [ ] Email sent to admin@nomadkaraoke.com immediately when feedback is submitted
|
||||
- [ ] Email includes all feedback content (ratings, text fields, user email)
|
||||
- [ ] Test data filtering works (exclude_test toggle)
|
||||
- [ ] Sidebar navigation includes new "Feedback" item
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Admin API Endpoint
|
||||
Add `GET /api/admin/feedback` to `backend/api/routes/admin.py`. Follows the standard admin endpoint pattern: `require_admin` dependency, pagination with `limit`/`offset`/`search`/`exclude_test`, returns Pydantic response model. Queries `user_feedback` Firestore collection.
|
||||
|
||||
### Admin UI Page
|
||||
New page at `frontend/app/admin/feedback/page.tsx`. Follows existing admin page patterns (Card, Table, Badge, pagination, search input, loading states). Uses `adminApi.listFeedback()` to fetch data.
|
||||
|
||||
### Email Notification
|
||||
Add a new method to `EmailService` (or call `send_email` directly) from the `submit_user_feedback` endpoint in `users.py`. Uses the existing SendGrid infrastructure — no new template service templates needed since this is an internal admin notification (simple HTML table with the feedback data).
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Backend — Admin feedback list endpoint
|
||||
|
||||
1. [ ] Add `AdminFeedbackItem` and `AdminFeedbackListResponse` Pydantic models to `admin.py`
|
||||
2. [ ] Add `GET /api/admin/feedback` endpoint with:
|
||||
- Pagination: `limit=50`, `offset=0`
|
||||
- Search by user email
|
||||
- `exclude_test` filter (reuse `is_test_email`)
|
||||
- Sort by `created_at` descending
|
||||
- Return: items, total, offset, limit, has_more
|
||||
3. [ ] Add aggregate stats in response: average ratings, total count
|
||||
|
||||
### Step 2: Backend — Email notification on submission
|
||||
|
||||
4. [ ] Add `send_feedback_notification` method to `EmailService` that sends an HTML email to `admin@nomadkaraoke.com` containing:
|
||||
- User email
|
||||
- All 4 star ratings
|
||||
- All text fields
|
||||
- Would recommend / would use again
|
||||
- Submitted timestamp
|
||||
- Link to admin feedback page
|
||||
5. [ ] Call `send_feedback_notification` from `submit_user_feedback` in `users.py` (fire-and-forget, don't block the user response on email success)
|
||||
|
||||
### Step 3: Frontend — Admin API client
|
||||
|
||||
6. [ ] Add `listFeedback` method to `adminApi` in `frontend/lib/api.ts`
|
||||
7. [ ] Add TypeScript types for `AdminFeedbackItem` and `AdminFeedbackListResponse`
|
||||
|
||||
### Step 4: Frontend — Admin feedback page
|
||||
|
||||
8. [ ] Create `frontend/app/admin/feedback/page.tsx` with:
|
||||
- Table: user email, date, overall rating (stars), ease of use, lyrics accuracy, correction experience, would recommend, would use again
|
||||
- Expandable rows or click-to-detail for text fields (what went well, what could improve, additional comments)
|
||||
- Search by email
|
||||
- Pagination (50 per page)
|
||||
- Refresh button
|
||||
- Test data toggle (via `useAdminSettings`)
|
||||
9. [ ] Add "Feedback" item to admin sidebar in `frontend/components/admin/admin-sidebar.tsx` with `MessageSquare` icon
|
||||
|
||||
### Step 5: Testing
|
||||
|
||||
10. [ ] Backend unit test for `GET /api/admin/feedback` endpoint (pagination, search, exclude_test)
|
||||
11. [ ] Backend unit test for `send_feedback_notification` email method
|
||||
12. [ ] Frontend component test for feedback page (render, empty state)
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `backend/api/routes/admin.py` | Modify | Add feedback list endpoint + response models |
|
||||
| `backend/api/routes/users.py` | Modify | Add email notification call in `submit_user_feedback` |
|
||||
| `backend/services/email_service.py` | Modify | Add `send_feedback_notification` method |
|
||||
| `frontend/lib/api.ts` | Modify | Add `adminApi.listFeedback()` method + types |
|
||||
| `frontend/app/admin/feedback/page.tsx` | Create | Admin feedback review page |
|
||||
| `frontend/components/admin/admin-sidebar.tsx` | Modify | Add "Feedback" nav item |
|
||||
| `backend/tests/test_admin_feedback.py` | Create | Tests for admin feedback endpoint |
|
||||
| `backend/tests/test_feedback_email.py` | Create | Tests for feedback email notification |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit tests**: Admin endpoint (pagination, filtering, sorting), email method (content formatting, send call)
|
||||
- **Integration**: Submit feedback → verify email service called
|
||||
- **Manual verification**: Check email arrives in admin@nomadkaraoke.com inbox after submission
|
||||
|
||||
## Open Questions
|
||||
|
||||
- [ ] Should the admin page show feedback from the old `beta_feedback` collection too, or just `user_feedback`? (Recommendation: just `user_feedback` — the beta collection is legacy)
|
||||
- [ ] Should there be any spam/quality detection flagging? (Some submissions appear to game the system for credits)
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
- Backend: Remove endpoint from admin.py, revert email call in users.py
|
||||
- Frontend: Delete feedback page, remove sidebar item
|
||||
- No data migration needed — Firestore collection unchanged
|
||||
@@ -3794,3 +3794,109 @@ async def get_ip_info_batch(
|
||||
raise HTTPException(status_code=400, detail="Maximum 100 IPs per batch request")
|
||||
geo_service = get_ip_geolocation_service()
|
||||
return geo_service.lookup_ips_batch(request.ips)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# User Feedback
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class AdminFeedbackItem(BaseModel):
|
||||
"""Single feedback submission for admin view."""
|
||||
id: str
|
||||
user_email: str
|
||||
created_at: Optional[str] = None
|
||||
overall_rating: int
|
||||
ease_of_use_rating: int
|
||||
lyrics_accuracy_rating: int
|
||||
correction_experience_rating: int
|
||||
what_went_well: Optional[str] = None
|
||||
what_could_improve: Optional[str] = None
|
||||
additional_comments: Optional[str] = None
|
||||
would_recommend: bool = True
|
||||
would_use_again: bool = True
|
||||
|
||||
|
||||
class AdminFeedbackListResponse(BaseModel):
|
||||
"""Paginated list of feedback submissions."""
|
||||
items: List[AdminFeedbackItem]
|
||||
total: int
|
||||
offset: int
|
||||
limit: int
|
||||
has_more: bool
|
||||
avg_overall_rating: Optional[float] = None
|
||||
avg_ease_of_use_rating: Optional[float] = None
|
||||
avg_lyrics_accuracy_rating: Optional[float] = None
|
||||
avg_correction_experience_rating: Optional[float] = None
|
||||
|
||||
|
||||
@router.get("/feedback", response_model=AdminFeedbackListResponse)
|
||||
def list_user_feedback(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
search: Optional[str] = None,
|
||||
exclude_test: bool = False,
|
||||
auth_result: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""List all user feedback submissions with pagination and search."""
|
||||
limit = max(1, min(limit, 200))
|
||||
offset = max(0, offset)
|
||||
|
||||
user_service = get_user_service()
|
||||
db = user_service.db
|
||||
|
||||
items = []
|
||||
for doc in db.collection("user_feedback").stream():
|
||||
data = doc.to_dict()
|
||||
email = data.get("user_email", "")
|
||||
|
||||
if exclude_test and is_test_email(email):
|
||||
continue
|
||||
|
||||
if search and search.lower() not in email.lower():
|
||||
continue
|
||||
|
||||
created_at = data.get("created_at")
|
||||
if created_at is not None and hasattr(created_at, "isoformat"):
|
||||
created_at = created_at.isoformat()
|
||||
elif created_at is not None:
|
||||
created_at = str(created_at)
|
||||
|
||||
items.append(AdminFeedbackItem(
|
||||
id=data.get("id", doc.id),
|
||||
user_email=email,
|
||||
created_at=created_at,
|
||||
overall_rating=data.get("overall_rating", 0),
|
||||
ease_of_use_rating=data.get("ease_of_use_rating", 0),
|
||||
lyrics_accuracy_rating=data.get("lyrics_accuracy_rating", 0),
|
||||
correction_experience_rating=data.get("correction_experience_rating", 0),
|
||||
what_went_well=data.get("what_went_well"),
|
||||
what_could_improve=data.get("what_could_improve"),
|
||||
additional_comments=data.get("additional_comments"),
|
||||
would_recommend=data.get("would_recommend", True),
|
||||
would_use_again=data.get("would_use_again", True),
|
||||
))
|
||||
|
||||
# Sort by newest first
|
||||
items.sort(key=lambda x: x.created_at or "", reverse=True)
|
||||
|
||||
# Compute aggregate stats
|
||||
total = len(items)
|
||||
avg_overall = sum(i.overall_rating for i in items) / total if total else None
|
||||
avg_ease = sum(i.ease_of_use_rating for i in items) / total if total else None
|
||||
avg_lyrics = sum(i.lyrics_accuracy_rating for i in items) / total if total else None
|
||||
avg_correction = sum(i.correction_experience_rating for i in items) / total if total else None
|
||||
|
||||
paginated = items[offset:offset + limit]
|
||||
|
||||
return AdminFeedbackListResponse(
|
||||
items=paginated,
|
||||
total=total,
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
has_more=(offset + limit) < total,
|
||||
avg_overall_rating=round(avg_overall, 2) if avg_overall is not None else None,
|
||||
avg_ease_of_use_rating=round(avg_ease, 2) if avg_ease is not None else None,
|
||||
avg_lyrics_accuracy_rating=round(avg_lyrics, 2) if avg_lyrics is not None else None,
|
||||
avg_correction_experience_rating=round(avg_correction, 2) if avg_correction is not None else None,
|
||||
)
|
||||
@@ -308,6 +308,39 @@ async def flacfetch_health() -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/audio-separator")
|
||||
async def audio_separator_health() -> Dict[str, Any]:
|
||||
"""
|
||||
Return the installed audio-separator package version.
|
||||
|
||||
Does NOT call the remote GPU service — that would cold-start an expensive
|
||||
Cloud Run GPU instance (~$0.07 per wake). Instead reports the locally
|
||||
installed package version, which matches what the audio worker uses.
|
||||
|
||||
No authentication required.
|
||||
"""
|
||||
from backend.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
if not settings.audio_separator_api_url:
|
||||
return {
|
||||
"available": False,
|
||||
"status": "not_configured",
|
||||
}
|
||||
|
||||
try:
|
||||
from importlib.metadata import version
|
||||
pkg_version = version("audio-separator")
|
||||
except Exception:
|
||||
pkg_version = None
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"status": "ok",
|
||||
"version": pkg_version,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/detailed")
|
||||
async def detailed_health_check() -> Dict[str, Any]:
|
||||
"""
|
||||
|
||||
@@ -1223,6 +1223,25 @@ async def submit_user_feedback(
|
||||
f"credits granted: {credits_granted}"
|
||||
)
|
||||
|
||||
# Send admin notification email (fire-and-forget)
|
||||
try:
|
||||
from backend.services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
email_service.send_feedback_notification(
|
||||
user_email=user.email,
|
||||
overall_rating=request.overall_rating,
|
||||
ease_of_use_rating=request.ease_of_use_rating,
|
||||
lyrics_accuracy_rating=request.lyrics_accuracy_rating,
|
||||
correction_experience_rating=request.correction_experience_rating,
|
||||
what_went_well=request.what_went_well,
|
||||
what_could_improve=request.what_could_improve,
|
||||
additional_comments=request.additional_comments,
|
||||
would_recommend=request.would_recommend,
|
||||
would_use_again=request.would_use_again,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to send feedback notification email: {e}")
|
||||
|
||||
return UserFeedbackResponse(
|
||||
status="success",
|
||||
message=f"Thank you for your feedback! You earned {credits_granted} free credits.",
|
||||
|
||||
@@ -1416,6 +1416,138 @@ Open Job: {app_url}
|
||||
)
|
||||
|
||||
|
||||
def send_feedback_notification(
|
||||
self,
|
||||
user_email: str,
|
||||
overall_rating: int,
|
||||
ease_of_use_rating: int,
|
||||
lyrics_accuracy_rating: int,
|
||||
correction_experience_rating: int,
|
||||
what_went_well: Optional[str] = None,
|
||||
what_could_improve: Optional[str] = None,
|
||||
additional_comments: Optional[str] = None,
|
||||
would_recommend: bool = True,
|
||||
would_use_again: bool = True,
|
||||
) -> bool:
|
||||
"""
|
||||
Send admin notification when a user submits product feedback.
|
||||
|
||||
Args:
|
||||
user_email: Email of the user who submitted feedback
|
||||
overall_rating: 1-5 star rating
|
||||
ease_of_use_rating: 1-5 star rating
|
||||
lyrics_accuracy_rating: 1-5 star rating
|
||||
correction_experience_rating: 1-5 star rating
|
||||
what_went_well: Optional text feedback
|
||||
what_could_improve: Optional text feedback
|
||||
additional_comments: Optional text feedback
|
||||
would_recommend: Whether user would recommend
|
||||
would_use_again: Whether user would use again
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully
|
||||
"""
|
||||
admin_email = os.getenv("ADMIN_NOTIFICATION_EMAIL", "admin@nomadkaraoke.com")
|
||||
subject = f"New Feedback from {user_email} — {overall_rating}/5 overall"
|
||||
|
||||
def stars(rating: int) -> str:
|
||||
return "★" * rating + "☆" * (5 - rating)
|
||||
|
||||
def text_block(label: str, value: Optional[str]) -> str:
|
||||
if not value:
|
||||
return ""
|
||||
escaped = html.escape(value).replace("\n", "<br>")
|
||||
return f"""
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold; vertical-align: top; white-space: nowrap;">{label}</td>
|
||||
<td style="padding: 8px 12px;">{escaped}</td>
|
||||
</tr>"""
|
||||
|
||||
recommend_badge = "Yes ✓" if would_recommend else "No ✗"
|
||||
use_again_badge = "Yes ✓" if would_use_again else "No ✗"
|
||||
|
||||
admin_url = f"{self.frontend_url}/admin/feedback"
|
||||
|
||||
extra_styles = """
|
||||
.feedback-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 16px 0;
|
||||
}
|
||||
.feedback-table td {
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
.stars {
|
||||
color: #eab308;
|
||||
font-size: 18px;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
"""
|
||||
|
||||
content = f"""
|
||||
<p>New product feedback submitted by <strong>{html.escape(user_email)}</strong>:</p>
|
||||
|
||||
<table class="feedback-table">
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Overall</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(overall_rating)}</span> ({overall_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Ease of Use</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(ease_of_use_rating)}</span> ({ease_of_use_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Lyrics Accuracy</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(lyrics_accuracy_rating)}</span> ({lyrics_accuracy_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Correction Experience</td>
|
||||
<td style="padding: 8px 12px;"><span class="stars">{stars(correction_experience_rating)}</span> ({correction_experience_rating}/5)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Would Recommend</td>
|
||||
<td style="padding: 8px 12px;">{recommend_badge}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 8px 12px; font-weight: bold;">Would Use Again</td>
|
||||
<td style="padding: 8px 12px;">{use_again_badge}</td>
|
||||
</tr>
|
||||
{text_block("What went well", what_went_well)}
|
||||
{text_block("What could improve", what_could_improve)}
|
||||
{text_block("Additional comments", additional_comments)}
|
||||
</table>
|
||||
|
||||
<p style="text-align: center;">
|
||||
<a href="{admin_url}" class="button">View All Feedback</a>
|
||||
</p>
|
||||
"""
|
||||
|
||||
text_content = f"""New Feedback from {user_email}
|
||||
|
||||
Overall: {overall_rating}/5
|
||||
Ease of Use: {ease_of_use_rating}/5
|
||||
Lyrics Accuracy: {lyrics_accuracy_rating}/5
|
||||
Correction Experience: {correction_experience_rating}/5
|
||||
Would Recommend: {recommend_badge}
|
||||
Would Use Again: {use_again_badge}
|
||||
|
||||
What went well: {what_went_well or '(empty)'}
|
||||
What could improve: {what_could_improve or '(empty)'}
|
||||
Additional comments: {additional_comments or '(empty)'}
|
||||
|
||||
View all feedback: {admin_url}
|
||||
"""
|
||||
|
||||
html_content = self._build_email_html(content, extra_styles)
|
||||
|
||||
return self.provider.send_email(
|
||||
to_email=admin_email,
|
||||
subject=subject,
|
||||
html_content=html_content,
|
||||
text_content=text_content,
|
||||
)
|
||||
|
||||
|
||||
# Global instance
|
||||
_email_service = None
|
||||
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
"""
|
||||
Unit tests for admin feedback endpoint and feedback email notification.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from datetime import datetime
|
||||
|
||||
from backend.services.email_service import EmailService
|
||||
|
||||
|
||||
class TestAdminFeedbackEndpoint:
|
||||
"""Tests for GET /api/admin/feedback endpoint."""
|
||||
|
||||
def _make_feedback_doc(self, email="user@example.com", overall=4, **kwargs):
|
||||
"""Create a mock Firestore feedback document."""
|
||||
doc = Mock()
|
||||
doc.id = kwargs.get("id", "test-id-1")
|
||||
data = {
|
||||
"id": doc.id,
|
||||
"user_email": email,
|
||||
"created_at": kwargs.get("created_at", datetime(2026, 3, 1, 12, 0, 0)),
|
||||
"overall_rating": overall,
|
||||
"ease_of_use_rating": kwargs.get("ease_of_use", 4),
|
||||
"lyrics_accuracy_rating": kwargs.get("lyrics_accuracy", 3),
|
||||
"correction_experience_rating": kwargs.get("correction_experience", 4),
|
||||
"what_went_well": kwargs.get("what_went_well", "Great app"),
|
||||
"what_could_improve": kwargs.get("what_could_improve", "More songs"),
|
||||
"additional_comments": kwargs.get("additional_comments", None),
|
||||
"would_recommend": kwargs.get("would_recommend", True),
|
||||
"would_use_again": kwargs.get("would_use_again", True),
|
||||
}
|
||||
doc.to_dict.return_value = data
|
||||
return doc
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_returns_items(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that feedback items are returned correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
|
||||
doc2 = self._make_feedback_doc("bob@example.com", 3, id="id-2")
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 2
|
||||
assert len(result.items) == 2
|
||||
assert result.has_more is False
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_search_filter(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that search filters by email."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
|
||||
doc2 = self._make_feedback_doc("bob@example.com", 3, id="id-2")
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search="alice", exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
assert result.items[0].user_email == "alice@example.com"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_exclude_test(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that test emails are excluded when exclude_test=True."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
|
||||
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
|
||||
doc2 = self._make_feedback_doc("test@inbox.testmail.app", 3, id="id-2")
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
# Make is_test_email return True for the test email
|
||||
mock_is_test.side_effect = lambda e: "testmail" in e
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=True,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
assert result.items[0].user_email == "alice@example.com"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_pagination(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test pagination with offset and limit."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
docs = [
|
||||
self._make_feedback_doc(f"user{i}@example.com", 4, id=f"id-{i}")
|
||||
for i in range(5)
|
||||
]
|
||||
mock_db.collection.return_value.stream.return_value = docs
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=2, offset=2, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 5
|
||||
assert len(result.items) == 2
|
||||
assert result.has_more is True
|
||||
assert result.offset == 2
|
||||
assert result.limit == 2
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_aggregate_stats(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that aggregate rating averages are computed correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc1 = self._make_feedback_doc("a@x.com", 5, id="id-1", ease_of_use=4, lyrics_accuracy=3, correction_experience=2)
|
||||
doc2 = self._make_feedback_doc("b@x.com", 3, id="id-2", ease_of_use=2, lyrics_accuracy=5, correction_experience=4)
|
||||
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.avg_overall_rating == 4.0
|
||||
assert result.avg_ease_of_use_rating == 3.0
|
||||
assert result.avg_lyrics_accuracy_rating == 4.0
|
||||
assert result.avg_correction_experience_rating == 3.0
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_empty(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test empty results."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
|
||||
mock_db.collection.return_value.stream.return_value = []
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.total == 0
|
||||
assert len(result.items) == 0
|
||||
assert result.avg_overall_rating is None
|
||||
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_handles_string_created_at(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that string timestamps (not datetime objects) are handled correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc = self._make_feedback_doc("a@x.com", 5, id="id-1", created_at="2026-03-01T12:00:00")
|
||||
mock_db.collection.return_value.stream.return_value = [doc]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.items[0].created_at == "2026-03-01T12:00:00"
|
||||
|
||||
@patch("backend.api.routes.admin.get_user_service")
|
||||
@patch("backend.api.routes.admin.is_test_email")
|
||||
def test_list_feedback_handles_none_created_at(self, mock_is_test, mock_get_user_svc):
|
||||
"""Test that None created_at is handled correctly."""
|
||||
from backend.api.routes.admin import list_user_feedback
|
||||
|
||||
mock_db = Mock()
|
||||
mock_user_svc = Mock()
|
||||
mock_user_svc.db = mock_db
|
||||
mock_get_user_svc.return_value = mock_user_svc
|
||||
mock_is_test.return_value = False
|
||||
|
||||
doc = self._make_feedback_doc("a@x.com", 5, id="id-1", created_at=None)
|
||||
mock_db.collection.return_value.stream.return_value = [doc]
|
||||
|
||||
result = list_user_feedback(
|
||||
limit=50, offset=0, search=None, exclude_test=False,
|
||||
auth_result=("admin@test.com", "admin", 1),
|
||||
)
|
||||
|
||||
assert result.items[0].created_at is None
|
||||
|
||||
|
||||
class TestSubmitFeedbackEmailIntegration:
|
||||
"""Test that submit_user_feedback correctly calls send_feedback_notification."""
|
||||
|
||||
@patch("backend.services.email_service.get_email_service")
|
||||
@patch("backend.services.auth_service.get_auth_service")
|
||||
def test_submit_feedback_sends_admin_notification(self, mock_get_auth, mock_get_email):
|
||||
"""Verify the caller (submit_user_feedback) passes correct args to email service."""
|
||||
import asyncio
|
||||
import uuid as uuid_mod
|
||||
from backend.api.routes.users import submit_user_feedback
|
||||
from backend.models.user import UserFeedbackRequest
|
||||
|
||||
# Mock auth
|
||||
mock_auth_svc = Mock()
|
||||
mock_auth_result = Mock()
|
||||
mock_auth_result.is_valid = True
|
||||
mock_auth_result.user_email = "alice@example.com"
|
||||
mock_auth_svc.validate_token_full.return_value = mock_auth_result
|
||||
mock_get_auth.return_value = mock_auth_svc
|
||||
|
||||
# Mock email service
|
||||
mock_email_svc = Mock()
|
||||
mock_email_svc.send_feedback_notification.return_value = True
|
||||
mock_get_email.return_value = mock_email_svc
|
||||
|
||||
# Mock user service with a db that has a collection mock
|
||||
mock_user_svc = Mock()
|
||||
mock_user = Mock()
|
||||
mock_user.email = "alice@example.com"
|
||||
mock_user.total_jobs_completed = 5
|
||||
mock_user.has_submitted_feedback = False
|
||||
mock_user_svc.get_or_create_user.return_value = mock_user
|
||||
mock_user_svc.update_user.return_value = None
|
||||
mock_user_svc.add_credits.return_value = None
|
||||
|
||||
went_well = "The lyrics synchronization was incredibly accurate and impressive overall"
|
||||
could_improve = "Speed could be faster for longer songs in the processing queue"
|
||||
|
||||
request = UserFeedbackRequest(
|
||||
overall_rating=4,
|
||||
ease_of_use_rating=3,
|
||||
lyrics_accuracy_rating=5,
|
||||
correction_experience_rating=2,
|
||||
what_went_well=went_well,
|
||||
what_could_improve=could_improve,
|
||||
additional_comments=None,
|
||||
would_recommend=True,
|
||||
would_use_again=False,
|
||||
)
|
||||
|
||||
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# Verify email notification was called with matching args
|
||||
mock_email_svc.send_feedback_notification.assert_called_once_with(
|
||||
user_email="alice@example.com",
|
||||
overall_rating=4,
|
||||
ease_of_use_rating=3,
|
||||
lyrics_accuracy_rating=5,
|
||||
correction_experience_rating=2,
|
||||
what_went_well=went_well,
|
||||
what_could_improve=could_improve,
|
||||
additional_comments=None,
|
||||
would_recommend=True,
|
||||
would_use_again=False,
|
||||
)
|
||||
|
||||
assert result.credits_granted == 2
|
||||
|
||||
@patch("backend.services.email_service.get_email_service")
|
||||
@patch("backend.services.auth_service.get_auth_service")
|
||||
def test_submit_feedback_continues_on_email_failure(self, mock_get_auth, mock_get_email):
|
||||
"""Verify feedback submission succeeds even if email notification fails."""
|
||||
import asyncio
|
||||
import uuid as uuid_mod
|
||||
from backend.api.routes.users import submit_user_feedback
|
||||
from backend.models.user import UserFeedbackRequest
|
||||
|
||||
mock_auth_svc = Mock()
|
||||
mock_auth_result = Mock()
|
||||
mock_auth_result.is_valid = True
|
||||
mock_auth_result.user_email = "bob@example.com"
|
||||
mock_auth_svc.validate_token_full.return_value = mock_auth_result
|
||||
mock_get_auth.return_value = mock_auth_svc
|
||||
|
||||
# Email service throws an exception
|
||||
mock_email_svc = Mock()
|
||||
mock_email_svc.send_feedback_notification.side_effect = Exception("SendGrid down")
|
||||
mock_get_email.return_value = mock_email_svc
|
||||
|
||||
mock_user_svc = Mock()
|
||||
mock_user = Mock()
|
||||
mock_user.email = "bob@example.com"
|
||||
mock_user.total_jobs_completed = 3
|
||||
mock_user.has_submitted_feedback = False
|
||||
mock_user_svc.get_or_create_user.return_value = mock_user
|
||||
|
||||
request = UserFeedbackRequest(
|
||||
overall_rating=5,
|
||||
ease_of_use_rating=5,
|
||||
lyrics_accuracy_rating=5,
|
||||
correction_experience_rating=5,
|
||||
what_went_well="Everything was perfect and I really enjoyed the experience a lot",
|
||||
)
|
||||
|
||||
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
|
||||
)
|
||||
|
||||
# User still gets credits even though email failed
|
||||
assert result.status == "success"
|
||||
assert result.credits_granted == 2
|
||||
|
||||
|
||||
class TestFeedbackEmailNotification:
|
||||
"""Tests for send_feedback_notification email method."""
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
def test_send_feedback_notification_calls_provider(self, mock_get_provider):
|
||||
"""Test that feedback notification sends email via provider."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = True
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
result = service.send_feedback_notification(
|
||||
user_email="alice@example.com",
|
||||
overall_rating=5,
|
||||
ease_of_use_rating=4,
|
||||
lyrics_accuracy_rating=3,
|
||||
correction_experience_rating=4,
|
||||
what_went_well="Great lyrics sync",
|
||||
what_could_improve="More song variety",
|
||||
additional_comments=None,
|
||||
would_recommend=True,
|
||||
would_use_again=True,
|
||||
)
|
||||
|
||||
assert result is True
|
||||
mock_provider.send_email.assert_called_once()
|
||||
call_args = mock_provider.send_email.call_args
|
||||
|
||||
# Check email is sent to admin
|
||||
to_email = call_args.kwargs.get("to_email") or call_args[0][0]
|
||||
assert to_email == "admin@nomadkaraoke.com"
|
||||
|
||||
# Check subject contains user email and rating
|
||||
subject = call_args.kwargs.get("subject") or call_args[0][1]
|
||||
assert "alice@example.com" in subject
|
||||
assert "5/5" in subject
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
def test_send_feedback_notification_content(self, mock_get_provider):
|
||||
"""Test that feedback notification email contains all feedback fields."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = True
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
service.send_feedback_notification(
|
||||
user_email="bob@example.com",
|
||||
overall_rating=3,
|
||||
ease_of_use_rating=2,
|
||||
lyrics_accuracy_rating=4,
|
||||
correction_experience_rating=5,
|
||||
what_went_well="Easy to use",
|
||||
what_could_improve="Better mobile support",
|
||||
additional_comments="Love it overall",
|
||||
would_recommend=False,
|
||||
would_use_again=True,
|
||||
)
|
||||
|
||||
call_args = mock_provider.send_email.call_args
|
||||
html_content = call_args.kwargs.get("html_content") or call_args[0][2]
|
||||
text_content = call_args.kwargs.get("text_content") or call_args[0][3]
|
||||
|
||||
# Check HTML contains feedback text
|
||||
assert "Easy to use" in html_content
|
||||
assert "Better mobile support" in html_content
|
||||
assert "Love it overall" in html_content
|
||||
assert "bob@example.com" in html_content
|
||||
|
||||
# Check plain text also contains feedback
|
||||
assert "Easy to use" in text_content
|
||||
assert "Better mobile support" in text_content
|
||||
assert "3/5" in text_content
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
@patch.dict("os.environ", {"ADMIN_NOTIFICATION_EMAIL": "custom@admin.com"})
|
||||
def test_send_feedback_notification_custom_admin_email(self, mock_get_provider):
|
||||
"""Test that admin email can be configured via env var."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = True
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
service.send_feedback_notification(
|
||||
user_email="test@example.com",
|
||||
overall_rating=4,
|
||||
ease_of_use_rating=4,
|
||||
lyrics_accuracy_rating=4,
|
||||
correction_experience_rating=4,
|
||||
)
|
||||
|
||||
call_args = mock_provider.send_email.call_args
|
||||
to_email = call_args.kwargs.get("to_email") or call_args[0][0]
|
||||
assert to_email == "custom@admin.com"
|
||||
|
||||
@patch.object(EmailService, '_get_provider')
|
||||
def test_send_feedback_notification_returns_false_on_failure(self, mock_get_provider):
|
||||
"""Test that failure is returned when provider fails."""
|
||||
mock_provider = Mock()
|
||||
mock_provider.send_email.return_value = False
|
||||
mock_get_provider.return_value = mock_provider
|
||||
|
||||
service = EmailService()
|
||||
result = service.send_feedback_notification(
|
||||
user_email="test@example.com",
|
||||
overall_rating=1,
|
||||
ease_of_use_rating=1,
|
||||
lyrics_accuracy_rating=1,
|
||||
correction_experience_rating=1,
|
||||
)
|
||||
|
||||
assert result is False
|
||||
@@ -45,6 +45,7 @@ from backend.services.tracing import job_span, add_span_event, add_span_attribut
|
||||
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
|
||||
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
|
||||
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
|
||||
# Import from the unified style loader
|
||||
@@ -161,30 +162,32 @@ async def process_render_video(job_id: str) -> bool:
|
||||
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}
|
||||
# 3. Load base CorrectionResult from original data
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# 4. Apply user corrections if available (from review UI)
|
||||
# Uses the same method as preview generation to ensure
|
||||
# identical CorrectionResult construction (DRY).
|
||||
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")
|
||||
job_log.info("Found updated corrections from review, applying via shared method")
|
||||
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
|
||||
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)
|
||||
|
||||
# Same construction path as preview — prevents divergence
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
job_log.info("Applied user corrections via CorrectionOperations")
|
||||
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
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")
|
||||
|
||||
|
||||
+42
@@ -1699,6 +1699,48 @@ Called by Cloud Tasks 5 minutes after a job enters a blocking state (primarily `
|
||||
|
||||
**Note**: With the combined review flow, users complete both lyrics review and instrumental selection in one session. The `awaiting_instrumental_selection` state is only used for finalise-only jobs.
|
||||
|
||||
### Admin Feedback
|
||||
|
||||
```http
|
||||
GET /api/admin/feedback
|
||||
GET /api/admin/feedback?search=user@example.com&exclude_test=true&limit=50&offset=0
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Lists all user feedback submissions with pagination, search, and aggregate stats.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "uuid",
|
||||
"user_email": "user@example.com",
|
||||
"created_at": "2026-03-01T12:00:00",
|
||||
"overall_rating": 4,
|
||||
"ease_of_use_rating": 5,
|
||||
"lyrics_accuracy_rating": 3,
|
||||
"correction_experience_rating": 4,
|
||||
"what_went_well": "...",
|
||||
"what_could_improve": "...",
|
||||
"additional_comments": null,
|
||||
"would_recommend": true,
|
||||
"would_use_again": true
|
||||
}
|
||||
],
|
||||
"total": 2,
|
||||
"offset": 0,
|
||||
"limit": 50,
|
||||
"has_more": false,
|
||||
"avg_overall_rating": 4.0,
|
||||
"avg_ease_of_use_rating": 4.5,
|
||||
"avg_lyrics_accuracy_rating": 3.5,
|
||||
"avg_correction_experience_rating": 4.0
|
||||
}
|
||||
```
|
||||
|
||||
An email notification is also sent to `admin@nomadkaraoke.com` (configurable via `ADMIN_NOTIFICATION_EMAIL` env var) whenever a user submits new feedback.
|
||||
|
||||
## Rate Limits & Abuse Prevention
|
||||
|
||||
### Usage Control
|
||||
|
||||
@@ -58,6 +58,16 @@ Audio separation and lyrics transcription run in parallel. Both can fail indepen
|
||||
### GCE Instance Selection for FFmpeg
|
||||
AMD EPYC (C4D series) significantly outperforms Intel Xeon (C4 series) for CPU-bound FFmpeg encoding with libass. C4D-highcpu-32 is ~5x faster than C4-standard-8. C4D requires `hyperdisk-balanced` disk type.
|
||||
|
||||
### Data Types Must Enforce Their Own Invariants (Mar 2026)
|
||||
When a data type has constraints on its fields (e.g., "word text must not contain newlines"), enforce them in the type's constructor (`__post_init__`), not in callers. This bug was caused by `Word` objects being constructed via two different code paths — one that stripped newlines (preview) and one that didn't (final render). The preview accidentally worked while final renders had corrupted subtitles with silently dropped lyrics. The fix: `Word.__post_init__` strips whitespace so ALL construction paths are safe, plus a defensive strip at the ASS output boundary.
|
||||
|
||||
**Key principles:**
|
||||
- **Single source of truth for data invariants** — the type, not the caller, is responsible for field constraints
|
||||
- **Defensive output boundaries** — even with clean inputs, validate at system boundaries (ASS file writing) as a safety net
|
||||
- **Two code paths doing "the same thing" will diverge** — if preview and render both construct CorrectionResult, they must use the same method, not reimplementations
|
||||
|
||||
**Detection clue:** If `corrected.txt` shows correct lyrics but the video is missing words, check for embedded newlines in Word text corrupting ASS dialogue events.
|
||||
|
||||
### Large Documents: GCS + Firestore Metadata (Mar 2026)
|
||||
When a document's payload can exceed Firestore's 1MB limit (e.g., CorrectionData at 100KB+ per session), store the payload in GCS and keep only metadata in Firestore. Use SHA-256 hash deduplication to avoid re-uploading identical data. For cross-document queries (e.g., searching sessions across jobs), use Firestore collection group queries on the metadata subcollection with Python-side text filtering — Firestore doesn't support LIKE/substring queries natively.
|
||||
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
# Fix ASS Preview/Render Divergence — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Eliminate the divergence between preview and final render by unifying Word text sanitization and CorrectionResult construction, preventing embedded newlines from corrupting ASS subtitle output.
|
||||
|
||||
**Architecture:** Strip whitespace in `Word.__post_init__` (single source of truth for Word invariants), add defensive strip in ASS output, refactor render worker to use the shared `update_correction_result_with_data()` method, and document the lesson learned.
|
||||
|
||||
**Tech Stack:** Python dataclasses, ASS subtitle format, FastAPI workers
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-03-22-fix-ass-preview-render-divergence-design.md`
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| File | Responsibility | Change |
|
||||
|------|---------------|--------|
|
||||
| `karaoke_gen/lyrics_transcriber/types.py` | Word/Segment data types | Add `__post_init__` to strip text |
|
||||
| `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py` | ASS dialogue event generation | Defensive strip in `_create_ass_text()` |
|
||||
| `backend/workers/render_video_worker.py` | Final video render orchestration | Use `update_correction_result_with_data()` |
|
||||
| `karaoke_gen/lyrics_transcriber/correction/operations.py` | Shared correction operations | Remove redundant `.strip()` calls |
|
||||
| `docs/LESSONS-LEARNED.md` | Project knowledge base | Document this bug class |
|
||||
| `tests/unit/test_word_text_sanitization.py` | New test file | Word stripping + ASS output tests |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add `__post_init__` to Word dataclass
|
||||
|
||||
**Files:**
|
||||
- Modify: `karaoke_gen/lyrics_transcriber/types.py:7-37`
|
||||
- Create: `tests/unit/test_word_text_sanitization.py`
|
||||
|
||||
- [ ] **Step 1: Create test file with failing tests for Word text stripping**
|
||||
|
||||
Create `tests/unit/test_word_text_sanitization.py`:
|
||||
|
||||
```python
|
||||
"""Tests for Word text sanitization — ensures embedded newlines never reach ASS output."""
|
||||
|
||||
import pytest
|
||||
from karaoke_gen.lyrics_transcriber.types import Word, LyricsSegment
|
||||
|
||||
|
||||
class TestWordTextSanitization:
|
||||
"""Word.__post_init__ must strip whitespace/newlines from text."""
|
||||
|
||||
def test_trailing_newline_stripped(self):
|
||||
word = Word(id="w1", text="spell\n", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "spell"
|
||||
|
||||
def test_trailing_double_newline_stripped(self):
|
||||
word = Word(id="w1", text="end\n\n", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "end"
|
||||
|
||||
def test_leading_whitespace_stripped(self):
|
||||
word = Word(id="w1", text=" hello", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "hello"
|
||||
|
||||
def test_mixed_whitespace_stripped(self):
|
||||
word = Word(id="w1", text="\n spell \n", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "spell"
|
||||
|
||||
def test_clean_text_unchanged(self):
|
||||
word = Word(id="w1", text="hello", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "hello"
|
||||
|
||||
def test_from_dict_strips_text(self):
|
||||
"""from_dict must also strip — this was the original bug."""
|
||||
word = Word.from_dict({
|
||||
"id": "w1",
|
||||
"text": "spell\n",
|
||||
"start_time": 1.0,
|
||||
"end_time": 2.0,
|
||||
})
|
||||
assert word.text == "spell"
|
||||
|
||||
def test_from_dict_with_double_newline(self):
|
||||
word = Word.from_dict({
|
||||
"id": "w1",
|
||||
"text": "broken\n\n",
|
||||
"start_time": 1.0,
|
||||
"end_time": 2.0,
|
||||
})
|
||||
assert word.text == "broken"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to verify they fail**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v`
|
||||
|
||||
Expected: 5 FAIL (trailing newlines not stripped), 2 PASS (clean text, leading whitespace might pass by accident)
|
||||
|
||||
- [ ] **Step 3: Add `__post_init__` to Word dataclass**
|
||||
|
||||
In `karaoke_gen/lyrics_transcriber/types.py`, add after line 17 (after `created_during_correction` field):
|
||||
|
||||
```python
|
||||
def __post_init__(self):
|
||||
"""Strip whitespace/newlines from text.
|
||||
|
||||
Word text from transcription pipelines may contain embedded newline
|
||||
characters at segment boundaries (e.g., "spell\\n"). These corrupt ASS
|
||||
subtitle output by splitting dialogue events across file lines, causing
|
||||
words after the newline to be silently dropped by video renderers.
|
||||
"""
|
||||
self.text = self.text.strip()
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests to verify they pass**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v`
|
||||
|
||||
Expected: All 7 PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add karaoke_gen/lyrics_transcriber/types.py tests/unit/test_word_text_sanitization.py
|
||||
git commit -m "fix: strip whitespace/newlines from Word text in __post_init__
|
||||
|
||||
Embedded newlines in word text (e.g. 'spell\n') corrupt ASS subtitle
|
||||
dialogue events by splitting them across file lines. Words after the
|
||||
newline are silently dropped by the video renderer.
|
||||
|
||||
This was the root cause of lyrics missing in final renders but
|
||||
appearing correctly in previews (job 0d4b550c)."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Add defensive strip in ASS output
|
||||
|
||||
**Files:**
|
||||
- Modify: `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py:237-262`
|
||||
- Modify: `tests/unit/test_word_text_sanitization.py`
|
||||
|
||||
- [ ] **Step 1: Add test for ASS text generation with newline words**
|
||||
|
||||
Append to `tests/unit/test_word_text_sanitization.py`:
|
||||
|
||||
```python
|
||||
from karaoke_gen.lyrics_transcriber.output.ass.lyrics_line import LyricsLine
|
||||
from karaoke_gen.lyrics_transcriber.output.ass.config import ScreenConfig
|
||||
|
||||
|
||||
class TestASSOutputSanitization:
|
||||
"""ASS output must never contain literal newlines in dialogue text."""
|
||||
|
||||
def _make_segment(self, words_data):
|
||||
"""Helper to create a LyricsSegment from word tuples (text, start, end)."""
|
||||
words = [
|
||||
Word(id=f"w{i}", text=text, start_time=start, end_time=end)
|
||||
for i, (text, start, end) in enumerate(words_data)
|
||||
]
|
||||
text = " ".join(w.text for w in words)
|
||||
return LyricsSegment(
|
||||
id="seg1", text=text, words=words,
|
||||
start_time=words[0].start_time, end_time=words[-1].end_time,
|
||||
)
|
||||
|
||||
def test_ass_text_no_literal_newlines(self):
|
||||
"""Even if Word.__post_init__ were bypassed, ASS output must not contain newlines."""
|
||||
segment = self._make_segment([
|
||||
("the", 54.11, 54.26),
|
||||
("spell", 54.30, 55.14),
|
||||
("we're", 55.18, 55.83),
|
||||
("under", 55.93, 57.24),
|
||||
])
|
||||
config = ScreenConfig(line_height=50)
|
||||
line = LyricsLine(segment=segment, screen_config=config)
|
||||
# Access the private method to test ASS text generation
|
||||
from datetime import timedelta
|
||||
ass_text = line._create_ass_text(timedelta(seconds=54.0))
|
||||
assert "\n" not in ass_text, f"ASS text contains literal newline: {repr(ass_text)}"
|
||||
assert "the" in ass_text
|
||||
assert "spell" in ass_text
|
||||
assert "we're" in ass_text
|
||||
assert "under" in ass_text
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it passes (Word.__post_init__ already strips)**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py::TestASSOutputSanitization -v`
|
||||
|
||||
Expected: PASS (Word.__post_init__ already strips newlines, so this test passes with current code)
|
||||
|
||||
- [ ] **Step 3: Add defensive strip in `_create_ass_text()`**
|
||||
|
||||
In `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py`, change line 257-258 from:
|
||||
|
||||
```python
|
||||
# Apply case transformation to the word text
|
||||
transformed_text = self._apply_case_transform(word.text)
|
||||
```
|
||||
|
||||
to:
|
||||
|
||||
```python
|
||||
# Apply case transformation to the word text
|
||||
# Defensive strip: Word.__post_init__ should already handle this,
|
||||
# but embedded newlines in ASS dialogue events cause silent word
|
||||
# loss so we guard against it at the output boundary too.
|
||||
clean_word_text = word.text.replace("\n", "").strip()
|
||||
transformed_text = self._apply_case_transform(clean_word_text)
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run all sanitization tests**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v`
|
||||
|
||||
Expected: All PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py tests/unit/test_word_text_sanitization.py
|
||||
git commit -m "fix: defensive strip in ASS output as safety net
|
||||
|
||||
Belt-and-suspenders guard at the ASS output boundary. Even though
|
||||
Word.__post_init__ strips newlines, this prevents any future bypass
|
||||
from producing corrupted ASS dialogue events."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Refactor render worker to use shared CorrectionResult construction
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/workers/render_video_worker.py:153-188`
|
||||
|
||||
- [ ] **Step 1: Refactor the merge logic**
|
||||
|
||||
In `backend/workers/render_video_worker.py`, add the import at the top (after existing lyrics_transcriber imports around line 47):
|
||||
|
||||
```python
|
||||
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
|
||||
```
|
||||
|
||||
Then replace the merge logic at lines 164-188. Change from:
|
||||
|
||||
```python
|
||||
# 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")
|
||||
```
|
||||
|
||||
to:
|
||||
|
||||
```python
|
||||
# 3. Load base CorrectionResult from original data
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# 4. Apply user corrections if available (from review UI)
|
||||
# Uses the same method as preview generation to ensure
|
||||
# identical CorrectionResult construction (DRY).
|
||||
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, applying via shared method")
|
||||
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
|
||||
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)
|
||||
|
||||
# Same construction path as preview — prevents divergence
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
job_log.info("Applied user corrections via CorrectionOperations")
|
||||
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
|
||||
else:
|
||||
correction_result = base_result
|
||||
|
||||
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")
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run existing tests to check for regressions**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/ -v --timeout=60 -x -q 2>&1 | tail -30`
|
||||
|
||||
Expected: All existing tests pass
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add backend/workers/render_video_worker.py
|
||||
git commit -m "refactor: use shared CorrectionResult construction in render worker
|
||||
|
||||
Replace manual dict merge + from_dict() with the same
|
||||
update_correction_result_with_data() method used by preview generation.
|
||||
This eliminates the code path divergence that caused the preview/render
|
||||
ASS subtitle discrepancy."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Clean up redundant `.strip()` in `update_correction_result_with_data()`
|
||||
|
||||
**Files:**
|
||||
- Modify: `karaoke_gen/lyrics_transcriber/correction/operations.py:39-99`
|
||||
|
||||
- [ ] **Step 1: Remove redundant `.strip()` from Word text construction only**
|
||||
|
||||
In `karaoke_gen/lyrics_transcriber/correction/operations.py`, the `update_correction_result_with_data` method (lines 39-99) has `.strip()` on several text fields. Only the `Word` text strip (line 74) is now redundant thanks to `Word.__post_init__`. The others operate on `WordCorrection` fields or `LyricsSegment` text which don't have `__post_init__` — those must stay.
|
||||
|
||||
Change line 74 from:
|
||||
```python
|
||||
text=w["text"].strip(),
|
||||
```
|
||||
to:
|
||||
```python
|
||||
text=w["text"],
|
||||
```
|
||||
|
||||
**Keep** `.strip()` on lines 47, 48, and 70 — those are `WordCorrection.original_word`, `WordCorrection.corrected_word`, and `LyricsSegment.text` respectively, which are not protected by `Word.__post_init__`.
|
||||
|
||||
- [ ] **Step 2: Run all tests**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/unit/test_word_text_sanitization.py -v && poetry run pytest tests/ -v --timeout=60 -x -q 2>&1 | tail -30`
|
||||
|
||||
Expected: All PASS
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add karaoke_gen/lyrics_transcriber/correction/operations.py
|
||||
git commit -m "refactor: remove redundant .strip() from update_correction_result_with_data
|
||||
|
||||
Word.__post_init__ now handles text stripping. Removing the redundant
|
||||
calls makes it clear that sanitization is Word's responsibility, not
|
||||
the caller's."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Document lesson learned
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/LESSONS-LEARNED.md`
|
||||
|
||||
- [ ] **Step 1: Add the lesson to the Architecture Decisions section**
|
||||
|
||||
In `docs/LESSONS-LEARNED.md`, add a new subsection after the existing "Architecture Decisions" entries (after line ~58). Insert:
|
||||
|
||||
```markdown
|
||||
### Data Types Must Enforce Their Own Invariants (Mar 2026)
|
||||
When a data type has constraints on its fields (e.g., "word text must not contain newlines"), enforce them in the type's constructor (`__post_init__`), not in callers. This bug was caused by `Word` objects being constructed via two different code paths — one that stripped newlines (preview) and one that didn't (final render). The preview accidentally worked while final renders had corrupted subtitles with silently dropped lyrics. The fix: `Word.__post_init__` strips whitespace so ALL construction paths are safe, plus a defensive strip at the ASS output boundary.
|
||||
|
||||
**Key principles:**
|
||||
- **Single source of truth for data invariants** — the type, not the caller, is responsible for field constraints
|
||||
- **Defensive output boundaries** — even with clean inputs, validate at system boundaries (ASS file writing) as a safety net
|
||||
- **Two code paths doing "the same thing" will diverge** — if preview and render both construct CorrectionResult, they must use the same method, not reimplementations
|
||||
|
||||
**Detection clue:** If `corrected.txt` shows correct lyrics but the video is missing words, check for embedded newlines in Word text corrupting ASS dialogue events.
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add docs/LESSONS-LEARNED.md
|
||||
git commit -m "docs: document data type invariant enforcement lesson
|
||||
|
||||
Records the Word text newline bug, the architectural principle it
|
||||
violated, and detection clues for similar issues."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Run full test suite and verify
|
||||
|
||||
- [ ] **Step 1: Run the full test suite**
|
||||
|
||||
Run: `cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run pytest tests/ -v --timeout=120 -q 2>&1 | tail -40`
|
||||
|
||||
Expected: All tests pass, no regressions
|
||||
|
||||
- [ ] **Step 2: Verify the fix would solve the original bug**
|
||||
|
||||
Run a quick sanity check that Word objects with the problematic data from job `0d4b550c` are now clean:
|
||||
|
||||
```python
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-fix-ass-preview-render-divergence && poetry run python -c "
|
||||
from karaoke_gen.lyrics_transcriber.types import Word
|
||||
# Simulate the exact data from the buggy job
|
||||
w1 = Word(id='test', text='spell\n', start_time=54.30, end_time=55.14)
|
||||
w2 = Word.from_dict({'id': 'test', 'text': 'broken\n\n', 'start_time': 59.98, 'end_time': 61.54})
|
||||
assert w1.text == 'spell', f'Expected spell, got {repr(w1.text)}'
|
||||
assert w2.text == 'broken', f'Expected broken, got {repr(w2.text)}'
|
||||
print('PASS: Word text sanitization works correctly')
|
||||
"
|
||||
```
|
||||
|
||||
Expected: `PASS: Word text sanitization works correctly`
|
||||
|
||||
- [ ] **Step 3: Bump version**
|
||||
|
||||
In `pyproject.toml`, bump the patch version (this is a bugfix).
|
||||
|
||||
- [ ] **Step 4: Final commit with version bump**
|
||||
|
||||
```bash
|
||||
git add pyproject.toml
|
||||
git commit -m "chore: bump version for ASS preview/render divergence fix"
|
||||
```
|
||||
@@ -0,0 +1,99 @@
|
||||
# Fix ASS Preview/Render Divergence
|
||||
|
||||
**Date:** 2026-03-22
|
||||
**Status:** Approved
|
||||
**Job that exposed bug:** `0d4b550c` (The Ataris - All Souls Day)
|
||||
|
||||
## Problem
|
||||
|
||||
Lyrics that render correctly in the preview video are missing words in the final (with_vocals / final) video output. The root cause is that Word objects contain embedded newline characters (e.g., `"spell\n"`, `"broken\n"`) inherited from the transcription pipeline's segment boundary markers. These newlines corrupt ASS subtitle dialogue events by splitting them across file lines, causing the video renderer to silently drop words after the newline.
|
||||
|
||||
The preview path accidentally avoids this bug because `CorrectionOperations.update_correction_result_with_data()` calls `.strip()` on word text, while the final render path uses `Word.from_dict()` which does not strip.
|
||||
|
||||
## Root Cause Analysis
|
||||
|
||||
### Two divergent CorrectionResult construction paths
|
||||
|
||||
**Preview** (`review.py` → `CorrectionOperations.generate_preview_video()`):
|
||||
1. Downloads `corrections.json` → `CorrectionResult.from_dict()`
|
||||
2. Calls `update_correction_result_with_data(result, updated_data)` which constructs new Word objects with `text=w["text"].strip()` — newlines removed
|
||||
|
||||
**Final render** (`render_video_worker.py`):
|
||||
1. Downloads `corrections.json` + `corrections_updated.json`
|
||||
2. Manually merges dicts: replaces `corrections` and `corrected_segments` keys
|
||||
3. Calls `CorrectionResult.from_dict(merged_data)` which constructs Word objects with `text=data["text"]` — newlines preserved
|
||||
4. Newlines in word text corrupt ASS output in `LyricsLine._create_ass_text()`
|
||||
|
||||
### Why only some segments are affected
|
||||
|
||||
Newlines appear on words at segment boundaries from the original transcription (e.g., `"spell\n"` where a line break was detected). When the segment resizer splits a long segment, a word with an embedded newline may end up in the middle of a resized segment rather than at the end. When it's at the end, the newline is harmless trailing whitespace. When it's in the middle, it splits the ASS dialogue event.
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Strip in `Word.__post_init__`
|
||||
|
||||
Add text stripping to the Word dataclass `__post_init__` so ALL Word objects are guaranteed clean regardless of construction method:
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class Word:
|
||||
...
|
||||
def __post_init__(self):
|
||||
# Strip whitespace/newlines — embedded newlines corrupt ASS subtitle output
|
||||
self.text = self.text.strip()
|
||||
```
|
||||
|
||||
This is the single-responsibility fix: Word is responsible for its own invariants.
|
||||
|
||||
### 2. Defensive strip in `_create_ass_text()`
|
||||
|
||||
Belt-and-suspenders safety net in the ASS output layer:
|
||||
|
||||
```python
|
||||
# In LyricsLine._create_ass_text():
|
||||
transformed_text = self._apply_case_transform(word.text.replace("\n", "").strip())
|
||||
```
|
||||
|
||||
### 3. Refactor render_video_worker to use shared construction method
|
||||
|
||||
Replace the manual dict merge + `from_dict()` with `CorrectionOperations.update_correction_result_with_data()` — the same method the preview uses:
|
||||
|
||||
```python
|
||||
# Before (render_video_worker.py):
|
||||
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']
|
||||
correction_result = CorrectionResult.from_dict(original_data)
|
||||
|
||||
# After:
|
||||
base_result = CorrectionResult.from_dict(original_data)
|
||||
correction_result = CorrectionOperations.update_correction_result_with_data(
|
||||
base_result, updated_data
|
||||
)
|
||||
```
|
||||
|
||||
### 4. Clean up redundant `.strip()` in `update_correction_result_with_data()`
|
||||
|
||||
Since `Word.__post_init__` now handles stripping, remove the explicit `.strip()` calls in `update_correction_result_with_data()` to avoid giving the impression that stripping is the caller's responsibility.
|
||||
|
||||
### 5. Document the lesson learned
|
||||
|
||||
Add to `docs/LESSONS-LEARNED.md` documenting this class of bug and the architectural principle that prevented its recurrence.
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `karaoke_gen/lyrics_transcriber/types.py` | Add `__post_init__` to Word, strip text |
|
||||
| `karaoke_gen/lyrics_transcriber/output/ass/lyrics_line.py` | Defensive strip in `_create_ass_text()` |
|
||||
| `backend/workers/render_video_worker.py` | Use `update_correction_result_with_data()` instead of manual merge |
|
||||
| `karaoke_gen/lyrics_transcriber/correction/operations.py` | Remove redundant `.strip()` calls |
|
||||
| `docs/LESSONS-LEARNED.md` | Document the bug and fix |
|
||||
| Tests | Unit tests for Word stripping, integration test for ASS output |
|
||||
|
||||
## What This Does NOT Change
|
||||
|
||||
- The preview and final render still generate separate ASS files (necessary due to resolution-dependent positioning: 360p vs 4K)
|
||||
- The data flow: frontend → GCS → worker remains the same
|
||||
- No changes to the frontend
|
||||
@@ -0,0 +1,320 @@
|
||||
"use client"
|
||||
|
||||
import { Fragment, useEffect, useState, useCallback } from "react"
|
||||
import { adminApi, AdminFeedbackItem, AdminFeedbackListResponse } from "@/lib/api"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Search,
|
||||
Loader2,
|
||||
RefreshCw,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Star,
|
||||
ThumbsUp,
|
||||
ThumbsDown,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
function StarRating({ rating }: { rating: number }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-0.5" title={`${rating}/5`}>
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
<Star
|
||||
key={i}
|
||||
className={`w-3.5 h-3.5 ${
|
||||
i <= rating
|
||||
? "fill-yellow-400 text-yellow-400"
|
||||
: "text-muted-foreground/30"
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function formatDate(dateStr: string | null) {
|
||||
if (!dateStr) return "—"
|
||||
try {
|
||||
return new Date(dateStr).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
})
|
||||
} catch {
|
||||
return dateStr
|
||||
}
|
||||
}
|
||||
|
||||
function ExpandableText({ label, text }: { label: string; text: string | null }) {
|
||||
if (!text) return null
|
||||
return (
|
||||
<div className="mb-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">{label}</span>
|
||||
<p className="text-sm whitespace-pre-wrap">{text}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function AdminFeedbackPage() {
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [data, setData] = useState<AdminFeedbackListResponse | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [search, setSearch] = useState("")
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null)
|
||||
|
||||
const fetchFeedback = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const result = await adminApi.listFeedback({
|
||||
limit: PAGE_SIZE,
|
||||
offset,
|
||||
search: search || undefined,
|
||||
exclude_test: !showTestData,
|
||||
})
|
||||
setData(result)
|
||||
} catch (err) {
|
||||
toast.error("Failed to load feedback")
|
||||
console.error(err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [offset, search, showTestData])
|
||||
|
||||
useEffect(() => {
|
||||
fetchFeedback()
|
||||
}, [fetchFeedback])
|
||||
|
||||
const handleSearch = () => {
|
||||
setOffset(0)
|
||||
setSearch(searchInput)
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter") handleSearch()
|
||||
}
|
||||
|
||||
const toggleExpand = (id: string) => {
|
||||
setExpandedId(expandedId === id ? null : id)
|
||||
}
|
||||
|
||||
const hasTextContent = (item: AdminFeedbackItem) =>
|
||||
item.what_went_well || item.what_could_improve || item.additional_comments
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">User Feedback</h1>
|
||||
<Button variant="outline" size="sm" onClick={fetchFeedback} disabled={loading}>
|
||||
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Aggregate stats */}
|
||||
{data && data.total > 0 && (
|
||||
<div className="grid grid-cols-2 md:grid-cols-5 gap-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
Total Responses
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">{data.total}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{[
|
||||
{ label: "Overall", value: data.avg_overall_rating },
|
||||
{ label: "Ease of Use", value: data.avg_ease_of_use_rating },
|
||||
{ label: "Lyrics Accuracy", value: data.avg_lyrics_accuracy_rating },
|
||||
{ label: "Correction Exp.", value: data.avg_correction_experience_rating },
|
||||
].map(({ label, value }) => (
|
||||
<Card key={label}>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
Avg {label}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-2xl font-bold">
|
||||
{value != null ? value.toFixed(1) : "—"}
|
||||
</p>
|
||||
<span className="text-muted-foreground text-sm">/ 5</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search */}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Search by email..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
<Button variant="outline" onClick={handleSearch}>
|
||||
<Search className="w-4 h-4 mr-2" />
|
||||
Search
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : !data || data.items.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
No feedback submissions found.
|
||||
</div>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-8"></TableHead>
|
||||
<TableHead>User</TableHead>
|
||||
<TableHead>Date</TableHead>
|
||||
<TableHead>Overall</TableHead>
|
||||
<TableHead>Ease of Use</TableHead>
|
||||
<TableHead>Lyrics</TableHead>
|
||||
<TableHead>Correction</TableHead>
|
||||
<TableHead>Recommend</TableHead>
|
||||
<TableHead>Use Again</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.items.map((item) => (
|
||||
<Fragment key={item.id}>
|
||||
<TableRow
|
||||
className={`cursor-pointer hover:bg-muted/50 ${
|
||||
expandedId === item.id ? "bg-muted/30" : ""
|
||||
}`}
|
||||
onClick={() => toggleExpand(item.id)}
|
||||
>
|
||||
<TableCell className="w-8">
|
||||
{hasTextContent(item) && (
|
||||
expandedId === item.id
|
||||
? <ChevronUp className="w-4 h-4 text-muted-foreground" />
|
||||
: <ChevronDown className="w-4 h-4 text-muted-foreground" />
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-sm">
|
||||
{item.user_email}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{formatDate(item.created_at)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StarRating rating={item.overall_rating} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StarRating rating={item.ease_of_use_rating} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StarRating rating={item.lyrics_accuracy_rating} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StarRating rating={item.correction_experience_rating} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{item.would_recommend ? (
|
||||
<Badge variant="secondary" className="bg-green-500/10 text-green-600">
|
||||
<ThumbsUp className="w-3 h-3 mr-1" />
|
||||
Yes
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="bg-red-500/10 text-red-600">
|
||||
<ThumbsDown className="w-3 h-3 mr-1" />
|
||||
No
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{item.would_use_again ? (
|
||||
<Badge variant="secondary" className="bg-green-500/10 text-green-600">
|
||||
<ThumbsUp className="w-3 h-3 mr-1" />
|
||||
Yes
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="bg-red-500/10 text-red-600">
|
||||
<ThumbsDown className="w-3 h-3 mr-1" />
|
||||
No
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{expandedId === item.id && hasTextContent(item) && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={9} className="bg-muted/20 px-8 py-4">
|
||||
<ExpandableText label="What went well" text={item.what_went_well} />
|
||||
<ExpandableText label="What could improve" text={item.what_could_improve} />
|
||||
<ExpandableText label="Additional comments" text={item.additional_comments} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Pagination */}
|
||||
{data && data.total > PAGE_SIZE && (
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, data.total)} of {data.total}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={offset === 0}
|
||||
onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4 mr-1" />
|
||||
Previous
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!data.has_more}
|
||||
onClick={() => setOffset(offset + PAGE_SIZE)}
|
||||
>
|
||||
Next
|
||||
<ChevronRight className="w-4 h-4 ml-1" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
BookOpenCheck,
|
||||
Scissors,
|
||||
Fingerprint,
|
||||
MessageSquare,
|
||||
} from "lucide-react"
|
||||
|
||||
import {
|
||||
@@ -71,6 +72,11 @@ const navItems = [
|
||||
href: "/admin/audio-edits",
|
||||
icon: Scissors,
|
||||
},
|
||||
{
|
||||
title: "Feedback",
|
||||
href: "/admin/feedback",
|
||||
icon: MessageSquare,
|
||||
},
|
||||
{
|
||||
title: "Abuse Investigation",
|
||||
href: "/admin/abuse",
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, EncodingWorkerHealth, FlacfetchHealth } from "@/lib/api";
|
||||
import { api, EncodingWorkerHealth, FlacfetchHealth, AudioSeparatorHealth } from "@/lib/api";
|
||||
|
||||
export function VersionFooter() {
|
||||
const [backendVersion, setBackendVersion] = useState<string | null>(null);
|
||||
const [encodingWorker, setEncodingWorker] = useState<EncodingWorkerHealth | null>(null);
|
||||
const [flacfetch, setFlacfetch] = useState<FlacfetchHealth | null>(null);
|
||||
const [audioSeparator, setAudioSeparator] = useState<AudioSeparatorHealth | null>(null);
|
||||
// Frontend version is injected at build time from pyproject.toml
|
||||
const frontendVersion = process.env.NEXT_PUBLIC_APP_VERSION || "dev";
|
||||
|
||||
@@ -41,9 +42,20 @@ export function VersionFooter() {
|
||||
}
|
||||
};
|
||||
|
||||
const fetchAudioSeparatorHealth = async () => {
|
||||
try {
|
||||
const health = await api.getAudioSeparatorHealth();
|
||||
setAudioSeparator(health);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch audio separator health:", error);
|
||||
setAudioSeparator(null);
|
||||
}
|
||||
};
|
||||
|
||||
fetchBackendVersion();
|
||||
fetchEncodingWorkerHealth();
|
||||
fetchFlacfetchHealth();
|
||||
fetchAudioSeparatorHealth();
|
||||
}, []);
|
||||
|
||||
// Render encoding worker status indicator
|
||||
@@ -113,6 +125,36 @@ export function VersionFooter() {
|
||||
);
|
||||
};
|
||||
|
||||
// Render audio separator status indicator
|
||||
const renderAudioSeparatorStatus = () => {
|
||||
if (!audioSeparator) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (audioSeparator.status === "not_configured") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isHealthy = audioSeparator.available && audioSeparator.status === "ok";
|
||||
const statusColor = isHealthy ? "text-green-500" : "text-red-500";
|
||||
const statusDot = isHealthy ? "●" : "○";
|
||||
|
||||
let statusText = isHealthy ? "Separator" : "Separator offline";
|
||||
if (isHealthy && audioSeparator.version) {
|
||||
statusText = `Separator: v${audioSeparator.version}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{" | "}
|
||||
<span className={statusColor} title={isHealthy ? "Audio separator healthy" : audioSeparator.error || "Audio separator offline"}>
|
||||
{statusDot}
|
||||
</span>{" "}
|
||||
{statusText}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<footer className="border-t mt-12 py-6" style={{ borderColor: 'var(--card-border)' }}>
|
||||
<div className="px-4 text-center text-sm" style={{ color: 'var(--text-muted)' }}>
|
||||
@@ -132,6 +174,7 @@ export function VersionFooter() {
|
||||
)}
|
||||
{renderEncodingWorkerStatus()}
|
||||
{renderFlacfetchStatus()}
|
||||
{renderAudioSeparatorStatus()}
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
@@ -297,6 +297,13 @@ export interface FlacfetchHealth {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface AudioSeparatorHealth {
|
||||
available: boolean;
|
||||
status: string; // 'ok' | 'offline' | 'not_configured'
|
||||
version?: string | null;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// Signed URL upload types
|
||||
export interface SignedUploadUrl {
|
||||
file_type: string;
|
||||
@@ -1305,6 +1312,14 @@ export const api = {
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get audio separator service health status
|
||||
*/
|
||||
async getAudioSeparatorHealth(): Promise<AudioSeparatorHealth> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/health/audio-separator`);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
// ==========================================================================
|
||||
// Credits/Payment API endpoints
|
||||
// ==========================================================================
|
||||
@@ -2400,6 +2415,25 @@ export const adminApi = {
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async listFeedback(params?: {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
search?: string;
|
||||
exclude_test?: boolean;
|
||||
}): Promise<AdminFeedbackListResponse> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.limit) searchParams.set('limit', String(params.limit));
|
||||
if (params?.offset) searchParams.set('offset', String(params.offset));
|
||||
if (params?.search) searchParams.set('search', params.search);
|
||||
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
|
||||
|
||||
const url = `${API_BASE_URL}/api/admin/feedback${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
};
|
||||
|
||||
export interface EditReviewSummary {
|
||||
@@ -3249,5 +3283,33 @@ export interface IpGeoInfo {
|
||||
cached_at?: string;
|
||||
}
|
||||
|
||||
// Admin feedback types
|
||||
export interface AdminFeedbackItem {
|
||||
id: string;
|
||||
user_email: string;
|
||||
created_at: string | null;
|
||||
overall_rating: number;
|
||||
ease_of_use_rating: number;
|
||||
lyrics_accuracy_rating: number;
|
||||
correction_experience_rating: number;
|
||||
what_went_well: string | null;
|
||||
what_could_improve: string | null;
|
||||
additional_comments: string | null;
|
||||
would_recommend: boolean;
|
||||
would_use_again: boolean;
|
||||
}
|
||||
|
||||
export interface AdminFeedbackListResponse {
|
||||
items: AdminFeedbackItem[];
|
||||
total: number;
|
||||
offset: number;
|
||||
limit: number;
|
||||
has_more: boolean;
|
||||
avg_overall_rating: number | null;
|
||||
avg_ease_of_use_rating: number | null;
|
||||
avg_lyrics_accuracy_rating: number | null;
|
||||
avg_correction_experience_rating: number | null;
|
||||
}
|
||||
|
||||
export { ApiError };
|
||||
|
||||
@@ -311,7 +311,8 @@ def _get_instance_age_hours(instance: compute_v1.Instance) -> float:
|
||||
|
||||
def check_github_for_pending_jobs() -> bool:
|
||||
"""
|
||||
Check GitHub API for any pending/queued/in-progress workflow runs.
|
||||
Check GitHub API for any pending/queued/in-progress workflow runs
|
||||
across all org repos that use self-hosted runners.
|
||||
|
||||
Returns True if there are runs that might need our self-hosted runners.
|
||||
"""
|
||||
@@ -320,25 +321,29 @@ def check_github_for_pending_jobs() -> bool:
|
||||
pat = get_github_pat()
|
||||
org = "nomadkaraoke"
|
||||
|
||||
for status in ["queued", "in_progress"]:
|
||||
url = f"https://api.github.com/repos/{org}/karaoke-gen/actions/runs?status={status}"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"Authorization": f"Bearer {pat}",
|
||||
"Accept": "application/vnd.github+json",
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
)
|
||||
# All repos that have workflows using self-hosted runners
|
||||
repos = ["karaoke-gen", "python-audio-separator"]
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
if data.get("total_count", 0) > 0:
|
||||
print(f"Found {data['total_count']} {status} runs in karaoke-gen")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error checking GitHub API ({status}): {e}")
|
||||
for repo in repos:
|
||||
for status in ["queued", "in_progress"]:
|
||||
url = f"https://api.github.com/repos/{org}/{repo}/actions/runs?status={status}"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"Authorization": f"Bearer {pat}",
|
||||
"Accept": "application/vnd.github+json",
|
||||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
if data.get("total_count", 0) > 0:
|
||||
print(f"Found {data['total_count']} {status} runs in {repo}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error checking GitHub API ({repo}/{status}): {e}")
|
||||
|
||||
return False
|
||||
|
||||
|
||||
@@ -214,10 +214,10 @@ def create_audio_separation_job(
|
||||
name="GCP_REGION",
|
||||
value=REGION,
|
||||
),
|
||||
# Modal API URL for GPU audio separation
|
||||
# Audio separator API (Cloud Run GPU service in us-east4)
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
name="AUDIO_SEPARATOR_API_URL",
|
||||
value="https://nomadkaraoke--audio-separator-api.modal.run",
|
||||
value="https://audio-separator-718638054799.us-east4.run.app",
|
||||
),
|
||||
# Cloud Run service URL for Cloud Tasks targeting
|
||||
cloudrunv2.JobTemplateTemplateContainerEnvArgs(
|
||||
|
||||
@@ -71,7 +71,7 @@ class CorrectionOperations:
|
||||
words=[
|
||||
Word(
|
||||
id=w["id"],
|
||||
text=w["text"].strip(),
|
||||
text=w["text"],
|
||||
start_time=w["start_time"],
|
||||
end_time=w["end_time"],
|
||||
confidence=w.get("confidence"),
|
||||
|
||||
@@ -254,7 +254,11 @@ class LyricsLine:
|
||||
# Add the word with its duration
|
||||
duration = int(round((word.end_time - word.start_time) * 100))
|
||||
# Apply case transformation to the word text
|
||||
transformed_text = self._apply_case_transform(word.text)
|
||||
# Defensive strip: Word.__post_init__ should already handle this,
|
||||
# but embedded newlines in ASS dialogue events cause silent word
|
||||
# loss so we guard against it at the output boundary too.
|
||||
clean_word_text = word.text.replace("\n", "").strip()
|
||||
transformed_text = self._apply_case_transform(clean_word_text)
|
||||
text += r"{\kf" + str(duration) + r"}" + transformed_text + " "
|
||||
|
||||
prev_end_time = word.end_time # Track the actual end time of the word
|
||||
|
||||
@@ -16,6 +16,16 @@ class Word:
|
||||
# New: Track if this word was created during correction
|
||||
created_during_correction: bool = False
|
||||
|
||||
def __post_init__(self):
|
||||
"""Strip whitespace/newlines from text.
|
||||
|
||||
Word text from transcription pipelines may contain embedded newline
|
||||
characters at segment boundaries (e.g., "spell\\n"). These corrupt ASS
|
||||
subtitle output by splitting dialogue events across file lines, causing
|
||||
words after the newline to be silently dropped by video renderers.
|
||||
"""
|
||||
self.text = self.text.strip()
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Convert Word to dictionary for JSON serialization."""
|
||||
d = asdict(self)
|
||||
|
||||
Generated
+4
-4
@@ -350,14 +350,14 @@ files = [
|
||||
|
||||
[[package]]
|
||||
name = "audio-separator"
|
||||
version = "0.40.0"
|
||||
version = "0.43.0"
|
||||
description = "Easy to use audio stem separation, using various models from UVR trained primarily by @Anjok07"
|
||||
optional = false
|
||||
python-versions = ">=3.10"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "audio_separator-0.40.0-py3-none-any.whl", hash = "sha256:aa67f6bc5625b7c5362f6fd5a4faba2d5b8a5ab8aff1205c0b4f06d35c2f7ac9"},
|
||||
{file = "audio_separator-0.40.0.tar.gz", hash = "sha256:956dceb7f3eba342ca2278c241ca7b86a04c015afd890b7c580d74af00226363"},
|
||||
{file = "audio_separator-0.43.0-py3-none-any.whl", hash = "sha256:7315f26fd0715e5cb3ddd02532565f2b63f77f208391463ad6bccd7cf4583454"},
|
||||
{file = "audio_separator-0.43.0.tar.gz", hash = "sha256:4628c2f1c43fc2d17a93e5451921bd6f5f720791d2bbf4bb6b70bda7114ac633"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
@@ -10705,4 +10705,4 @@ local-whisper = ["whisper-timestamped"]
|
||||
[metadata]
|
||||
lock-version = "2.1"
|
||||
python-versions = ">=3.10,<3.14"
|
||||
content-hash = "7acf9e306a9ac7b7a4547eb130be6747cb522cb80f16b0c914467e4a252d3dcd"
|
||||
content-hash = "6f4c1aa73c0b4adecdc901fdec83dea48a9c431056c4b8fd04da5461469d3095"
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.148.0"
|
||||
version = "0.149.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
@@ -36,7 +36,7 @@ google-auth-oauthlib = "*"
|
||||
google-auth-httplib2 = "*"
|
||||
thefuzz = ">=0.22"
|
||||
numpy = ">=2"
|
||||
audio-separator = { version = ">=0.34.0", extras = ["cpu"] }
|
||||
audio-separator = { version = ">=0.43.0", extras = ["cpu"] }
|
||||
lyrics-converter = ">=0.2.1"
|
||||
# lyrics_transcriber is now a subpackage of karaoke_gen (karaoke_gen/lyrics_transcriber/)
|
||||
# Dependencies from vendored lyrics_transcriber:
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Tests for Word text sanitization — ensures embedded newlines never reach ASS output."""
|
||||
|
||||
import pytest
|
||||
from karaoke_gen.lyrics_transcriber.types import Word, LyricsSegment
|
||||
from karaoke_gen.lyrics_transcriber.output.ass.lyrics_line import LyricsLine
|
||||
from karaoke_gen.lyrics_transcriber.output.ass.config import ScreenConfig
|
||||
|
||||
|
||||
class TestWordTextSanitization:
|
||||
"""Word.__post_init__ must strip whitespace/newlines from text."""
|
||||
|
||||
def test_trailing_newline_stripped(self):
|
||||
word = Word(id="w1", text="spell\n", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "spell"
|
||||
|
||||
def test_trailing_double_newline_stripped(self):
|
||||
word = Word(id="w1", text="end\n\n", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "end"
|
||||
|
||||
def test_leading_whitespace_stripped(self):
|
||||
word = Word(id="w1", text=" hello", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "hello"
|
||||
|
||||
def test_mixed_whitespace_stripped(self):
|
||||
word = Word(id="w1", text="\n spell \n", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "spell"
|
||||
|
||||
def test_clean_text_unchanged(self):
|
||||
word = Word(id="w1", text="hello", start_time=1.0, end_time=2.0)
|
||||
assert word.text == "hello"
|
||||
|
||||
def test_from_dict_strips_text(self):
|
||||
"""from_dict must also strip — this was the original bug."""
|
||||
word = Word.from_dict({
|
||||
"id": "w1",
|
||||
"text": "spell\n",
|
||||
"start_time": 1.0,
|
||||
"end_time": 2.0,
|
||||
})
|
||||
assert word.text == "spell"
|
||||
|
||||
def test_from_dict_with_double_newline(self):
|
||||
word = Word.from_dict({
|
||||
"id": "w1",
|
||||
"text": "broken\n\n",
|
||||
"start_time": 1.0,
|
||||
"end_time": 2.0,
|
||||
})
|
||||
assert word.text == "broken"
|
||||
|
||||
|
||||
class TestASSOutputSanitization:
|
||||
"""ASS output must never contain literal newlines in dialogue text."""
|
||||
|
||||
def _make_segment(self, words_data):
|
||||
"""Helper to create a LyricsSegment from word tuples (text, start, end)."""
|
||||
words = [
|
||||
Word(id=f"w{i}", text=text, start_time=start, end_time=end)
|
||||
for i, (text, start, end) in enumerate(words_data)
|
||||
]
|
||||
text = " ".join(w.text for w in words)
|
||||
return LyricsSegment(
|
||||
id="seg1", text=text, words=words,
|
||||
start_time=words[0].start_time, end_time=words[-1].end_time,
|
||||
)
|
||||
|
||||
def test_ass_text_no_literal_newlines(self):
|
||||
"""Defensive strip in _create_ass_text catches newlines that bypass __post_init__.
|
||||
|
||||
Word.__post_init__ normally strips newlines, but this test verifies the
|
||||
defensive strip at the ASS output boundary by injecting newlines directly
|
||||
into Word.text after construction (bypassing __post_init__).
|
||||
"""
|
||||
from datetime import timedelta
|
||||
|
||||
# Build words normally first (clean text)
|
||||
words = [
|
||||
Word(id="w0", text="the", start_time=54.11, end_time=54.26),
|
||||
Word(id="w1", text="spell", start_time=54.30, end_time=55.14),
|
||||
Word(id="w2", text="we're", start_time=55.18, end_time=55.83),
|
||||
Word(id="w3", text="under", start_time=55.93, end_time=57.24),
|
||||
]
|
||||
# Inject newlines directly, bypassing __post_init__
|
||||
object.__setattr__(words[1], "text", "spell\n")
|
||||
object.__setattr__(words[3], "text", "under\n")
|
||||
|
||||
segment = LyricsSegment(
|
||||
id="seg1", text="the spell we're under",
|
||||
words=words, start_time=54.11, end_time=57.24,
|
||||
)
|
||||
config = ScreenConfig(line_height=50)
|
||||
line = LyricsLine(segment=segment, screen_config=config)
|
||||
ass_text = line._create_ass_text(timedelta(seconds=54.0))
|
||||
assert "\n" not in ass_text, f"ASS text contains literal newline: {repr(ass_text)}"
|
||||
assert "the" in ass_text
|
||||
assert "spell" in ass_text
|
||||
assert "we're" in ass_text
|
||||
assert "under" in ass_text
|
||||
Reference in new issue
Block a user