Spaces:
Runtime error
Runtime error
File size: 7,394 Bytes
229897d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | import gradio as gr
import asyncio
import numpy as np
import os
import warnings
import cv2
# --- NEW ESSENTIAL IMPORTS ---
from LLM.GeminiLive import GeminiLiveClient
from TFG.Streamer import AudioBuffer
# -----------------------------
warnings.filterwarnings('ignore')
# --- CONFIGURATION ---
DEFAULT_AVATAR = "./Musetalk/data/video/yongen_musev.mp4"
WSS_URL = "wss://gemini-live-bridge-production.up.railway.app/ws"
BBOX_SHIFT = 5
# --- GLOBAL STATE ---
client = GeminiLiveClient(websocket_url=WSS_URL)
# 200ms buffer for tight lip-sync latency
audio_buffer = AudioBuffer(sample_rate=16000, context_size_seconds=0.2)
musetalker = None
avatar_prepared = False
current_avatar_path = None
# --- INITIALIZATION & LOGIC ---
def init_model():
"""Lazy load MuseTalk to save resources"""
global musetalker
if musetalker is None:
print("π Loading MuseTalk Engine...")
from TFG import MuseTalk_RealTime
musetalker = MuseTalk_RealTime()
musetalker.init_model()
print("β
MuseTalk Loaded")
def prepare_avatar(avatar_source, bbox_shift):
"""
Pre-calculates avatar latents for real-time inference.
Handles both Video (Looping) and Image (Static) inputs.
"""
global avatar_prepared, current_avatar_path, musetalker
init_model()
# 1. Reset State
if avatar_prepared:
avatar_prepared = False
audio_buffer.clear()
if hasattr(musetalker, 'input_latent_list_cycle'):
musetalker.input_latent_list_cycle = None
if hasattr(musetalker, 'stream_idx'):
delattr(musetalker, 'stream_idx')
# 2. Validate Input
if avatar_source is None:
# Fallback to default if nothing provided
if os.path.exists(DEFAULT_AVATAR):
avatar_path = DEFAULT_AVATAR
print(f"πΈ Using Default Avatar: {avatar_path}")
else:
return "β Error: Default avatar not found and no file uploaded."
else:
avatar_path = avatar_source
print(f"πΈ Using Custom Avatar: {avatar_path}")
# 3. Process
try:
print("π Processing Avatar Materials...")
musetalker.prepare_material(avatar_path, bbox_shift)
current_avatar_path = avatar_path
avatar_prepared = True
audio_buffer.clear()
return f"β
Ready! Using: {os.path.basename(avatar_path)}"
except Exception as e:
print(f"β Error: {e}")
return f"β Preparation Failed: {str(e)}"
async def start_session():
"""Connects to the Railway Bridge"""
init_model()
print(f"π Dialing {WSS_URL}...")
success = await client.connect()
if success:
return "β
Gemini Connected (Listening...)"
return "β Connection Failed"
async def process_stream(audio_data):
"""
The Heartbeat Loop:
Mic -> Bridge -> Gemini -> Audio -> MuseTalk -> Video Frame
"""
ret_frame = None
ret_audio = None
if not client.running or not avatar_prepared:
return None, None
# 1. Send User Audio
if audio_data is not None:
sr, y = audio_data
await client.send_audio(y, original_sr=sr)
# 2. Receive Gemini Audio
new_chunks = []
while not client.output_queue.empty():
try:
chunk = client.output_queue.get_nowait()
audio_buffer.push(chunk)
new_chunks.append(chunk)
except asyncio.QueueEmpty:
break
# 3. Playback Audio (if any)
if new_chunks:
# Concatenate for Gradio Output (16kHz)
ret_audio = (16000, np.concatenate(new_chunks))
# 4. Generate Video Frame
current_window = audio_buffer.get_window()
if current_window is not None:
try:
ret_frame = musetalker.inference_streaming(
audio_buffer_16k=current_window,
return_frame_only=False
)
except:
pass # Skip dropped frames to maintain sync
return ret_frame, ret_audio
# --- GRADIO UI ---
def main():
with gr.Blocks(title="Linly-Talker Multi-Turn", theme=gr.themes.Soft()) as inference:
gr.Markdown(
"""
# π£οΈ Linly-Talker Multi-Turn Interaction
**Powered by Gemini Live** | Continuous Conversation Mode
"""
)
with gr.Row():
# --- Left Column: The Avatar ---
with gr.Column(scale=3):
avatar_output = gr.Image(
label="Digital Human",
streaming=True,
interactive=False,
height=500
)
# Hidden audio output for browser playback
speaker_output = gr.Audio(
label="Gemini Voice",
autoplay=True,
streaming=True,
visible=False
)
# --- Right Column: Controls & Setup ---
with gr.Column(scale=2, variant="panel"):
gr.Markdown("### βοΈ Configuration")
with gr.Tab("Avatar"):
avatar_upload = gr.File(
label="Upload Image/Video (Optional)",
file_types=["image", "video"],
type="filepath"
)
bbox_shift = gr.Slider(
label="Mouth Alignment (BBox Shift)",
minimum=-20, maximum=20, value=5, step=1
)
btn_prepare = gr.Button("1. Load Avatar", variant="secondary")
status_prepare = gr.Textbox(label="Status", value="Idle", interactive=False)
with gr.Tab("Connection"):
btn_connect = gr.Button("2. Connect to Gemini", variant="primary")
status_connect = gr.Textbox(label="Status", value="Disconnected", interactive=False)
gr.Markdown("### ποΈ Conversation")
mic_input = gr.Audio(
sources=["microphone"],
type="numpy",
label="Microphone Input",
streaming=True
)
gr.Markdown("*Speak naturally. You can interrupt the avatar at any time.*")
# --- Event Wiring ---
# 1. Prepare Avatar
btn_prepare.click(
fn=prepare_avatar,
inputs=[avatar_upload, bbox_shift],
outputs=[status_prepare]
)
# 2. Connect
btn_connect.click(
fn=start_session,
inputs=[],
outputs=[status_connect]
)
# 3. Streaming Loop
mic_input.stream(
fn=process_stream,
inputs=[mic_input],
outputs=[avatar_output, speaker_output],
stream_every=0.04, # 25 FPS
time_limit=300
)
return inference
if __name__ == "__main__":
demo = main()
demo.queue().launch(
server_name="0.0.0.0",
server_port=7860,
quiet=True
) |