Skip to content

Commit b476182

Browse files
Apolo151cursoragent
andcommitted
Add source-speaker ref audio trimming for ephemeral voice cloning.
Let users pick a short clip from uploaded media as dubbing reference audio via voice=source, with backend ffmpeg extraction and existing TTS clone path. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 2ae0ab8 commit b476182

22 files changed

Lines changed: 1050 additions & 27 deletions

‎backend/app/api/media_routers.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ async def upload_video(
6060
target_lang: str = Form(DEFAULT_TARGET_LANG),
6161
trim_start: Optional[float] = Form(None),
6262
trim_end: Optional[float] = Form(None),
63+
ref_clip_start: Optional[float] = Form(None),
64+
ref_clip_end: Optional[float] = Form(None),
6365
service: VideoService = Depends(get_video_service),
6466
current_user: User = Depends(get_current_user)
6567
):
@@ -75,6 +77,8 @@ async def upload_video(
7577
)
7678
options["trim_start"] = trim_start
7779
options["trim_end"] = trim_end
80+
options["ref_clip_start"] = ref_clip_start
81+
options["ref_clip_end"] = ref_clip_end
7882
video = await service.upload_video(current_user.user_id, file, background_tasks, options=options)
7983
return VideoUploadResponse(id=video.id, status=video.status)
8084

@@ -88,6 +92,8 @@ async def upload_audio(
8892
translation_style: str = Form("neutral"),
8993
source_lang: str = Form(...),
9094
target_lang: str = Form(DEFAULT_TARGET_LANG),
95+
ref_clip_start: Optional[float] = Form(None),
96+
ref_clip_end: Optional[float] = Form(None),
9197
service: VideoService = Depends(get_video_service),
9298
current_user: User = Depends(get_current_user)
9399
):
@@ -97,6 +103,8 @@ async def upload_audio(
97103
options = _upload_options(
98104
output_type, domain, voice, translation_style, source_lang, target_lang
99105
)
106+
options["ref_clip_start"] = ref_clip_start
107+
options["ref_clip_end"] = ref_clip_end
100108
audio = await service.upload_audio(current_user.user_id, file, background_tasks, options=options)
101109
return VideoUploadResponse(id=audio.id, status=audio.status)
102110

@@ -146,6 +154,8 @@ async def upload_from_youtube(
146154
target_lang: str = Form(DEFAULT_TARGET_LANG),
147155
trim_start: Optional[float] = Form(None),
148156
trim_end: Optional[float] = Form(None),
157+
ref_clip_start: Optional[float] = Form(None),
158+
ref_clip_end: Optional[float] = Form(None),
149159
service: VideoService = Depends(get_video_service),
150160
current_user: User = Depends(get_current_user)
151161
):
@@ -160,6 +170,8 @@ async def upload_from_youtube(
160170
)
161171
options["trim_start"] = trim_start
162172
options["trim_end"] = trim_end
173+
options["ref_clip_start"] = ref_clip_start
174+
options["ref_clip_end"] = ref_clip_end
163175
video = await service.upload_from_youtube(
164176
current_user.user_id, youtube_url, format, quality, background_tasks, options=options
165177
)

‎backend/app/media/ffmpeg_service.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,62 @@ async def get_audio_duration(self, file_path: str) -> float:
112112
logger.warning("Failed to read audio duration for %s: %s", file_path, exc)
113113
return 0.0
114114

115+
async def extract_audio_segment(
116+
self,
117+
input_path: str,
118+
output_path: str,
119+
start_sec: float,
120+
end_sec: float,
121+
*,
122+
sample_rate: int = 24000,
123+
) -> bool:
124+
"""Extract [start_sec, end_sec) as 24 kHz mono PCM WAV for voice cloning."""
125+
if end_sec <= start_sec:
126+
logger.error(
127+
"extract_audio_segment: invalid range start=%s end=%s", start_sec, end_sec
128+
)
129+
return False
130+
131+
cmd = [
132+
self.ffmpeg_path,
133+
"-y",
134+
"-hide_banner",
135+
"-loglevel",
136+
"error",
137+
"-ss",
138+
str(start_sec),
139+
"-to",
140+
str(end_sec),
141+
"-i",
142+
input_path,
143+
"-vn",
144+
"-ac",
145+
"1",
146+
"-ar",
147+
str(sample_rate),
148+
"-c:a",
149+
"pcm_s16le",
150+
output_path,
151+
]
152+
153+
try:
154+
process = await asyncio.create_subprocess_exec(
155+
*cmd,
156+
stdout=asyncio.subprocess.PIPE,
157+
stderr=asyncio.subprocess.PIPE,
158+
)
159+
_stdout, stderr = await process.communicate()
160+
161+
if process.returncode != 0:
162+
logger.error("ffmpeg extract_audio_segment failed: %s", stderr.decode())
163+
return False
164+
165+
out = Path(output_path)
166+
return out.exists() and out.stat().st_size > 0
167+
except Exception as e:
168+
logger.error("Error extracting audio segment: %s", e)
169+
return False
170+
115171
async def extract_audio(self, input_path: str, output_path: str) -> bool:
116172
"""Extract audio to MP3/AAC."""
117173
# Force overwrite (-y)

‎backend/app/media/schemas.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,8 @@ class ProcessingOptions(BaseModel):
106106
translation_style: str = "neutral"
107107
source_lang: str
108108
target_lang: str = DEFAULT_TARGET_LANG
109+
ref_clip_start: Optional[float] = None
110+
ref_clip_end: Optional[float] = None
109111

110112
@field_validator("source_lang")
111113
@classmethod

‎backend/app/media/service.py‎

Lines changed: 148 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,51 @@ def _normalize_processing_options(options: dict | None) -> dict:
114114
return normalized
115115

116116

117+
async def _resolve_pipeline_voice_fields(
118+
db: AsyncSession,
119+
user_id: int,
120+
options: dict | None,
121+
*,
122+
storage,
123+
ffmpeg: FFmpegService,
124+
video_id: str,
125+
local_media_path: str | None = None,
126+
) -> dict:
127+
"""Map voice selection (incl. ephemeral source speaker) to TTS input_data fields."""
128+
opts = options or {}
129+
voice = opts.get("voice", "male1")
130+
if voice == "source":
131+
if local_media_path is None:
132+
raise ValueError(
133+
"Source speaker voice requires local media for reference extraction."
134+
)
135+
ref_start = opts.get("ref_clip_start")
136+
ref_end = opts.get("ref_clip_end")
137+
if ref_start is None or ref_end is None:
138+
raise ValueError(
139+
"Source speaker requires ref_clip_start and ref_clip_end."
140+
)
141+
from app.voices.source_ref import resolve_source_speaker_ref
142+
143+
try:
144+
return await resolve_source_speaker_ref(
145+
storage=storage,
146+
ffmpeg=ffmpeg,
147+
user_id=user_id,
148+
video_id=video_id,
149+
local_media_path=local_media_path,
150+
ref_clip_start=ref_start,
151+
ref_clip_end=ref_end,
152+
)
153+
except HTTPException as exc:
154+
detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
155+
raise ValueError(detail) from exc
156+
157+
from app.voices.resolver import resolve_voice_selection
158+
159+
return await resolve_voice_selection(db, user_id, voice)
160+
161+
117162
def _build_pipeline_input_data(normalized: dict, task_id: str) -> dict:
118163
return {
119164
"output_type": normalized.get("output_type", "fullDubbing"),
@@ -256,8 +301,13 @@ async def process_text_task(video_id: str, text_content: str, options: dict = No
256301
processing_mode = _resolve_processing_mode(output_type)
257302

258303
from app.voices.resolver import resolve_voice_selection
304+
voice_choice = (options or {}).get("voice", "male1")
305+
if voice_choice == "source":
306+
raise ValueError(
307+
"Source speaker voice is not available for text uploads."
308+
)
259309
voice_fields = await resolve_voice_selection(
260-
db, video.user_id, (options or {}).get("voice", "male1")
310+
db, video.user_id, voice_choice
261311
)
262312

263313
from app.tasks.models import VideoTask, TaskStatus
@@ -441,9 +491,8 @@ async def process_video_task(video_id: str, file_path_key: str, options: dict =
441491
video.thumbnail_path = thumbnail_key
442492

443493
elif video.media_type == MediaType.AUDIO:
444-
# Audio specific steps if any
445-
# If it's pure audio, we might want to skip extraction but maybe validate?
446494
logger.info("Processing AUDIO type")
495+
video.audio_path = file_path_key
447496

448497
elif video.media_type == MediaType.TEXT:
449498
logger.info("Processing TEXT type")
@@ -502,14 +551,47 @@ async def process_video_task(video_id: str, file_path_key: str, options: dict =
502551
await db.commit()
503552
return
504553

505-
# Resolve the requested voice into pipeline-ready fields
506-
# (instruct / ref_audio_key) — this dict rides on the
507-
# parent job's input_data and is copied verbatim down to
508-
# the TTS job by the orchestrator.
509-
from app.voices.resolver import resolve_voice_selection
510-
voice_fields = await resolve_voice_selection(
511-
db, video.user_id, options.get("voice", "male1")
512-
)
554+
voice_choice = normalized.get("voice", "male1")
555+
if voice_choice == "source" and video.media_type == MediaType.VIDEO and not metadata.audio_present:
556+
db.add(Job(
557+
id=str(uuid.uuid4()),
558+
video_id=video_id,
559+
user_id=video.user_id,
560+
job_type=JobType.DUBBING_PIPELINE,
561+
status=JobStatus.FAILED,
562+
progress=0.0,
563+
error_message="Source speaker voice requires an audio track in the video.",
564+
completed_at=datetime.utcnow(),
565+
))
566+
await db.commit()
567+
return
568+
569+
try:
570+
voice_fields = await _resolve_pipeline_voice_fields(
571+
db,
572+
video.user_id,
573+
normalized,
574+
storage=storage,
575+
ffmpeg=ffmpeg,
576+
video_id=video_id,
577+
local_media_path=str(local_video_path),
578+
)
579+
except ValueError as exc:
580+
logger.warning(
581+
"Voice resolution failed for %s: %s", video_id, exc
582+
)
583+
db.add(Job(
584+
id=str(uuid.uuid4()),
585+
video_id=video_id,
586+
user_id=video.user_id,
587+
job_type=JobType.DUBBING_PIPELINE,
588+
status=JobStatus.FAILED,
589+
progress=0.0,
590+
error_message=str(exc),
591+
completed_at=datetime.utcnow(),
592+
))
593+
await db.commit()
594+
return
513595

514596
# Create VideoTask as single source-of-truth for this pipeline run
515597
from app.tasks.models import VideoTask, TaskStatus
@@ -1069,6 +1151,59 @@ async def upload_from_youtube(
10691151
)
10701152
return new_video
10711153

1154+
async def _resolve_reprocess_voice_fields(
1155+
self, media: Video, user_id: int, selected_options: dict
1156+
) -> dict:
1157+
voice = selected_options.get("voice", "male1")
1158+
if voice != "source":
1159+
from app.voices.resolver import resolve_voice_selection
1160+
1161+
return await resolve_voice_selection(self.db, user_id, voice)
1162+
1163+
ref_start = selected_options.get("ref_clip_start")
1164+
ref_end = selected_options.get("ref_clip_end")
1165+
if ref_start is None or ref_end is None:
1166+
raise HTTPException(
1167+
status_code=400,
1168+
detail="Source speaker requires ref_clip_start and ref_clip_end.",
1169+
)
1170+
1171+
ffmpeg = FFmpegService()
1172+
source_key = media.audio_path or media.file_path
1173+
if not source_key:
1174+
raise HTTPException(
1175+
status_code=400,
1176+
detail="Source media has no audio available for reference extraction.",
1177+
)
1178+
1179+
with tempfile.TemporaryDirectory() as temp_dir:
1180+
local_path = Path(temp_dir) / "source_media"
1181+
downloaded = await self.storage.download(source_key, str(local_path))
1182+
if not downloaded:
1183+
local_path = Path(self.storage.get_absolute_path(source_key))
1184+
1185+
if media.media_type == MediaType.VIDEO and not media.audio_path:
1186+
audio_local = Path(temp_dir) / "extracted.mp3"
1187+
ok = await ffmpeg.extract_audio(str(local_path), str(audio_local))
1188+
if not ok or not audio_local.exists():
1189+
raise HTTPException(
1190+
status_code=400,
1191+
detail="Could not extract audio from video for source speaker reference.",
1192+
)
1193+
local_path = audio_local
1194+
1195+
from app.voices.source_ref import resolve_source_speaker_ref
1196+
1197+
return await resolve_source_speaker_ref(
1198+
storage=self.storage,
1199+
ffmpeg=ffmpeg,
1200+
user_id=user_id,
1201+
video_id=media.id,
1202+
local_media_path=str(local_path),
1203+
ref_clip_start=ref_start,
1204+
ref_clip_end=ref_end,
1205+
)
1206+
10721207
async def reprocess_existing_media(self, user_id: int, video_id: str, options: dict | None = None):
10731208
"""Create a fresh STT pipeline job for an existing uploaded media file."""
10741209

@@ -1103,9 +1238,8 @@ async def reprocess_existing_media(self, user_id: int, video_id: str, options: d
11031238
detail=f"Insufficient credits: need {cost}, have {balance}",
11041239
)
11051240

1106-
from app.voices.resolver import resolve_voice_selection
1107-
voice_fields = await resolve_voice_selection(
1108-
self.db, user_id, selected_options.get("voice", "male1")
1241+
voice_fields = await self._resolve_reprocess_voice_fields(
1242+
media, user_id, selected_options
11091243
)
11101244

11111245
# Create VideoTask as single source-of-truth for this reprocess run

‎backend/app/voices/resolver.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,15 @@ async def resolve_voice_selection(db: AsyncSession, user_id: int, voice: Optiona
3939
"""
4040
voice = voice or DEFAULT_PRESET_ID
4141

42+
if voice == "source":
43+
raise HTTPException(
44+
status_code=400,
45+
detail=(
46+
"Source speaker requires ref_clip_start and ref_clip_end; "
47+
"use resolve_source_speaker_ref during media processing."
48+
),
49+
)
50+
4251
if voice in PRESET_VOICES:
4352
preset = PRESET_VOICES[voice]
4453
if preset["instruct"] is None:

0 commit comments

Comments
 (0)