@@ -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+
117162def _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
0 commit comments