import os import re import wave import asyncio import tempfile import subprocess from datetime import datetime from collections import deque import json from typing import Optional from fastapi import FastAPI, Request, HTTPException, UploadFile, File, Form from fastapi.responses import HTMLResponse, FileResponse, StreamingResponse from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware import numpy as np import torch import librosa import imageio import edge_tts from groq import Groq from loguru import logger # Import SoulX inference modules from flash_head.inference import ( get_pipeline, get_base_data, get_infer_params, get_audio_embedding, run_pipeline, ) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) IDLE_VIDEO_PATH = os.path.join(BASE_DIR, "idle_animation", "idlecombined.mp4") app = FastAPI(title="SoulX Avatar Assistant API") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Mount static folders app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "static")), name="static") app.mount("/idle_animation", StaticFiles(directory=os.path.join(BASE_DIR, "idle_animation")), name="idle") # Output Directories GRADIO_RESULTS_DIR = os.path.join(BASE_DIR, "gradio_results") RESULTS_DIR = os.path.join(GRADIO_RESULTS_DIR, "stream_preview") os.makedirs(RESULTS_DIR, exist_ok=True) app.mount("/gradio_results", StaticFiles(directory=GRADIO_RESULTS_DIR), name="gradio_results") app.mount("/stream_preview", StaticFiles(directory=RESULTS_DIR), name="stream_preview") # Global pipeline caches pipeline = None loaded_ckpt_dir = None loaded_wav2vec_dir = None loaded_model_type = None groq_client = None def get_groq_client(): global groq_client if groq_client is None: api_key = os.environ.get("GROQ_API_KEY") if not api_key: raise HTTPException(status_code=500, detail="GROQ_API_KEY environment variable not set.") groq_client = Groq(api_key=api_key) return groq_client def sanitize_text(text: str) -> str: if not text: return "" text = re.sub(r'[*:#`_~\[\](){}>•\-—]', ' ', text) text = re.sub(r'\s+', ' ', text).strip() return text async def generate_cloud_tts_audio(text: str, voice_name: str, target_sr=16000): with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file: tmp_path = tmp_file.name try: communicate = edge_tts.Communicate(text, voice_name) await communicate.save(tmp_path) wav_array, _ = await asyncio.to_thread(librosa.load, tmp_path, sr=target_sr, mono=True) return wav_array finally: if os.path.exists(tmp_path): os.remove(tmp_path) def _write_frames_to_mp4(frames_list, video_path, fps): os.makedirs(os.path.dirname(video_path) or ".", exist_ok=True) with imageio.get_writer( video_path, format="mp4", mode="I", fps=fps, codec="h264", ffmpeg_params=["-bf", "0"] ) as writer: for frames in frames_list: frames_np = frames.numpy().astype(np.uint8) if isinstance(frames, torch.Tensor) else frames.astype(np.uint8) for i in range(frames_np.shape[0]): writer.append_data(frames_np[i, :, :, :]) return video_path def save_video_with_audio(frames_list, video_path, audio_path, fps): temp_path = video_path.replace(".mp4", "_temp.mp4") _write_frames_to_mp4(frames_list, temp_path, fps) try: cmd = [ "ffmpeg", "-y", "-i", temp_path, "-i", audio_path, "-c:v", "copy", "-c:a", "aac", "-strict", "experimental", video_path, ] subprocess.run(cmd, check=True, capture_output=True) finally: if os.path.exists(temp_path): os.remove(temp_path) return video_path def _save_chunk_audio_to_wav(audio_array, wav_path, sample_rate=16000): os.makedirs(os.path.dirname(wav_path) or ".", exist_ok=True) samples = (np.clip(audio_array, -1.0, 1.0) * 32767).astype(np.int16) with wave.open(wav_path, "wb") as wav_file: wav_file.setnchannels(1) wav_file.setsampwidth(2) wav_file.setframerate(sample_rate) wav_file.writeframes(samples.tobytes()) return wav_path # ------------------------------------------------------------------- # Refactored Helper Functions (Zero Duplicate Inference!) # ------------------------------------------------------------------- def save_chunk_files(accumulated_frames, accumulated_audio, chunk_wav, chunk_mp4, sample_rate=16000, tgt_fps=25): """Encodes accumulated video and audio frames to WAV and MP4 without running PyTorch inference.""" _save_chunk_audio_to_wav(np.array(accumulated_audio), chunk_wav, sample_rate=sample_rate) save_video_with_audio(accumulated_frames, chunk_mp4, chunk_wav, fps=tgt_fps) return chunk_mp4 def save_full_video(all_frames, full_audio_array, output_mp4_path, sample_rate=16000, fps=25): """Encodes all frame tensors and full audio track into one complete MP4 video.""" os.makedirs(os.path.dirname(output_mp4_path) or ".", exist_ok=True) temp_wav_path = output_mp4_path.replace(".mp4", "_temp.wav") _save_chunk_audio_to_wav(np.array(full_audio_array), temp_wav_path, sample_rate=sample_rate) save_video_with_audio(all_frames, output_mp4_path, temp_wav_path, fps=fps) if os.path.exists(temp_wav_path): os.remove(temp_wav_path) return output_mp4_path @app.get("/") async def get_index(): return FileResponse(os.path.join(BASE_DIR, "static", "index.html")) @app.post("/api/transcribe") async def transcribe_audio( file: UploadFile = File(...), language: Optional[str] = Form(None) ): """Speech-to-Text endpoint using Groq Whisper-large-v3 linked to selected language.""" client = get_groq_client() with tempfile.NamedTemporaryFile(delete=False, suffix=".webm") as tmp: tmp.write(await file.read()) tmp_path = tmp.name try: with open(tmp_path, "rb") as audio_file: transcription = await asyncio.to_thread( client.audio.transcriptions.create, file=(file.filename or "recording.webm", audio_file.read()), model="whisper-large-v3", language=language if language else None, temperature=0.0, response_format="text", ) return {"text": sanitize_text(transcription)} except Exception as e: logger.error(f"Whisper STT Error: {e}") raise HTTPException(status_code=500, detail=str(e)) finally: if os.path.exists(tmp_path): os.remove(tmp_path) @app.post("/api/chat") async def chat_stream(request: Request): """Event-Stream (SSE) endpoint with perfectly synchronized audio/video streaming and full export.""" body = await request.json() prompt_text = body.get("prompt", "").strip() voice_name = body.get("voice", "en-US-JennyNeural") ckpt_dir = body.get("ckpt_dir", "models/SoulX-FlashHead-1_3B") wav2vec_dir = body.get("wav2vec_dir", "models/wav2vec2-base-960h") model_type = body.get("model_type", "lite") cond_image = body.get("cond_image", "examples/girl.png") seed = int(body.get("seed", 9999)) use_face_crop = bool(body.get("use_face_crop", False)) if not prompt_text: raise HTTPException(status_code=400, detail="Prompt text cannot be empty.") async def event_generator(): global pipeline, loaded_ckpt_dir, loaded_wav2vec_dir, loaded_model_type # 1. Call Groq AI in background thread client = get_groq_client() messages = [ { "role": "system", "content": "You are an interactive AI avatar. Keep responses natural, direct, concise, and without special characters or markdown. Generate appropriate answer length when prompted. Make sure your answers are complete, not half way.", }, {"role": "user", "content": prompt_text}, ] completion = await asyncio.to_thread( client.chat.completions.create, model="llama-3.3-70b-versatile", messages=messages, temperature=0.6, max_tokens=4000, ) ai_response = sanitize_text(completion.choices[0].message.content) yield f"data: {json.dumps({'type': 'text', 'text': ai_response})}\n\n" await asyncio.sleep(0.01) # 2. TTS Audio Generation human_speech_all = await generate_cloud_tts_audio(ai_response, voice_name) # 3. Initialize SoulX pipeline if needed if (pipeline is None or loaded_ckpt_dir != ckpt_dir or loaded_wav2vec_dir != wav2vec_dir or loaded_model_type != model_type): pipeline = await asyncio.to_thread(get_pipeline, world_size=1, ckpt_dir=ckpt_dir, model_type=model_type, wav2vec_dir=wav2vec_dir) loaded_ckpt_dir, loaded_wav2vec_dir, loaded_model_type = ckpt_dir, wav2vec_dir, model_type await asyncio.to_thread(get_base_data, pipeline, cond_image_path_or_dir=cond_image, base_seed=seed, use_face_crop=use_face_crop) # 4. Prepare Slices infer_params = get_infer_params() sample_rate = infer_params.get("sample_rate", 16000) tgt_fps = infer_params.get("tgt_fps", 25) cached_audio_duration = infer_params.get("cached_audio_duration", 3) frame_num = infer_params.get("frame_num", 25) motion_frames_num = infer_params.get("motion_frames_num", getattr(pipeline, "motion_frames_num", 1)) slice_len = frame_num - motion_frames_num human_speech_slice_len = slice_len * sample_rate // tgt_fps timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")[:-3] cached_audio_length_sum = sample_rate * cached_audio_duration audio_end_idx = cached_audio_duration * tgt_fps audio_start_idx = audio_end_idx - frame_num remainder = len(human_speech_all) % human_speech_slice_len if remainder > 0: pad = human_speech_slice_len - remainder human_speech_all = np.concatenate([human_speech_all, np.zeros(pad, dtype=human_speech_all.dtype)]) slices = human_speech_all.reshape(-1, human_speech_slice_len) audio_dq = deque([0.0] * cached_audio_length_sum, maxlen=cached_audio_length_sum) slice_duration_secs = slice_len / float(tgt_fps) target_slices_per_chunk = max(1, round(3.0 / slice_duration_secs)) accumulated_frames, accumulated_audio = [], [] all_frames = [] emitted_count = 0 # 5. Perfectly Synchronized Generation Loop for chunk_idx, human_speech_array in enumerate(slices): audio_dq.extend(human_speech_array.tolist()) audio_array = np.array(audio_dq) accumulated_audio.extend(human_speech_array) # Run PyTorch GPU inference strictly ONCE per slice def run_single_slice(pipe, aud_arr): aud_emb = get_audio_embedding(pipe, aud_arr, audio_start_idx, audio_end_idx) torch.cuda.synchronize() vid = run_pipeline(pipe, aud_emb)[motion_frames_num:] torch.cuda.synchronize() return vid.cpu() slice_frames = await asyncio.to_thread(run_single_slice, pipeline, audio_array) # Append cleanly without duplicates! accumulated_frames.append(slice_frames) all_frames.append(slice_frames) is_last = (chunk_idx + 1) == len(slices) # Emit chunk when target slice count is reached or on final slice if len(accumulated_frames) >= target_slices_per_chunk or is_last: chunk_wav = os.path.join(RESULTS_DIR, f"chunk_{timestamp}_{emitted_count}.wav") chunk_mp4 = os.path.join(RESULTS_DIR, f"chunk_{timestamp}_{emitted_count}.mp4") # Encode files in background thread (NO INFERENCE CALLED HERE!) await asyncio.to_thread( save_chunk_files, accumulated_frames, accumulated_audio, chunk_wav, chunk_mp4, sample_rate, tgt_fps ) rel_url = f"/stream_preview/chunk_{timestamp}_{emitted_count}.mp4" yield f"data: {json.dumps({'type': 'video_chunk', 'url': rel_url})}\n\n" await asyncio.sleep(0.01) accumulated_frames, accumulated_audio = [], [] emitted_count += 1 # 6. Auto-Save Synchronized Full Video to gradio_results/ if all_frames: full_mp4_path = os.path.join(GRADIO_RESULTS_DIR, f"full_{timestamp}.mp4") await asyncio.to_thread( save_full_video, all_frames, human_speech_all, full_mp4_path, sample_rate, tgt_fps ) logger.info(f"Full synchronized video saved to: {full_mp4_path}") yield f"data: {json.dumps({'type': 'done', 'full_video_url': f'/gradio_results/full_{timestamp}.mp4'})}\n\n" else: yield f"data: {json.dumps({'type': 'done'})}\n\n" await asyncio.sleep(0.01) return StreamingResponse(event_generator(), media_type="text/event-stream") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="127.0.0.1", port=8000)