J Z commited on
Commit
399c8e8
·
verified ·
1 Parent(s): 2d42963

Upload app_hf.py

Browse files
Files changed (1) hide show
  1. app_hf.py +186 -0
app_hf.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+
3
+ import threading
4
+ import time
5
+ import os, json
6
+ import glob
7
+ import atexit
8
+ from nicegui import ui, app
9
+
10
+ from LivePortraitIdle import generate_fixed_chunks
11
+ from LatentSync import run_latentsync_inference
12
+ from SparkTTS import run_tts
13
+ from Dual_LLM import generate_darwin_response
14
+ from PlaylistManager import idle_playlist_maker, response_playlist_maker, create_lipsync_playlist
15
+ from ui import build_ui # Import build_ui from the ui.py file
16
+
17
+ REPO_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
18
+ STREAM_LIVE_DIR = os.path.join(REPO_DIR, "stream", "live")
19
+ STREAM_SPEECH_DIR = os.path.join(REPO_DIR, "stream", "speech")
20
+ PLAYLIST_PATH = os.path.join("stream", "playlist", "playlist.json")
21
+
22
+ # === Thread management ===
23
+ _main_thread = None
24
+ _thread_lock = threading.Lock()
25
+ _shutdown_flag = False
26
+
27
+ # === State Flags ===
28
+ awaiting_response = False
29
+ user_prompt = "" # Store the user's prompt
30
+
31
+ # Expose media folder
32
+ app.add_static_files('/stream', os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'stream')))
33
+
34
+ def get_latest_video_from_live_dir():
35
+ """Get the most recent video from the live directory"""
36
+ video_files = glob.glob(os.path.join(STREAM_LIVE_DIR, "*.mp4"))
37
+ if not video_files:
38
+ return None
39
+ return max(video_files, key=os.path.getctime)
40
+
41
+ def update_playlist_with_single_video(video_path):
42
+ """Create a playlist with just the specified video"""
43
+ # Convert absolute path to relative path for playlist
44
+ try:
45
+ # Get the path relative to the REPO_DIR
46
+ relative_path = os.path.relpath(video_path, os.path.join(REPO_DIR))
47
+
48
+ # Important fix: Remove any "stream" prefix to avoid path duplication
49
+ if relative_path.startswith("stream\\") or relative_path.startswith("stream/"):
50
+ relative_path = relative_path[7:] # Skip past "stream/" or "stream\"
51
+
52
+ # Convert backslashes to forward slashes for web paths
53
+ web_path = relative_path.replace("\\", "/")
54
+
55
+ # Create a playlist with just this video
56
+ playlist = [web_path]
57
+
58
+ # Save the playlist
59
+ with open(PLAYLIST_PATH, "w") as f:
60
+ json.dump(playlist, f)
61
+
62
+ print(f"[PLAYLIST] Updated playlist with single video: {web_path}")
63
+ return True
64
+ except Exception as e:
65
+ print(f"[ERROR] Failed to update playlist: {e}")
66
+ return False
67
+
68
+ def idle_mode():
69
+ print("[MAIN] Starting idle mode...")
70
+ idle_playlist_maker()
71
+ #generate_fixed_chunks(mode="talking", chunks_per_video=1, video_limit=1)
72
+
73
+ print("[MAIN] Idle mode finished, waiting for response trigger...")
74
+ return
75
+
76
+ def response_mode():
77
+ global user_prompt
78
+ print("[MAIN] Starting response mode...")
79
+
80
+ # Step 1: Generate response from the LLM
81
+ print("[LLM] Generating Darwin's response...")
82
+ if not user_prompt:
83
+ print("[WARNING] No user prompt provided, using default")
84
+ user_prompt = "Tell me about your theory of evolution."
85
+
86
+ llm_response = generate_darwin_response(user_prompt)
87
+ print(f"[LLM] Response generated: {llm_response[:500]}...")
88
+
89
+ # Step 2: Convert response to speech using TTS
90
+ print("[TTS] Converting text to speech...")
91
+ speech_file = run_tts(text=llm_response)
92
+ print(f"[TTS] Speech generated: {speech_file}")
93
+
94
+ # Step 3: Generate lip-synced video
95
+ print("[SYNC] Running lip sync...")
96
+ success = run_latentsync_inference()
97
+ print(f"[SYNC] Lip sync completed with status: {success}")
98
+
99
+ # Step 4: If successful, get the latest video and make it the only item in the playlist
100
+ if success:
101
+ # Get the latest video from the LIVE_DIR
102
+ latest_video = get_latest_video_from_live_dir()
103
+ if latest_video:
104
+ print(f"[PLAYBACK] Found latest video: {latest_video}")
105
+ # Update playlist to only include this video, forcing playback
106
+ update_playlist_with_single_video(latest_video)
107
+ # The updated UI will automatically detect playlist changes and play the video
108
+ else:
109
+ print("[ERROR] No video found in live directory after sync completion")
110
+
111
+ # Reset the user prompt for next interaction
112
+ user_prompt = ""
113
+
114
+ return success
115
+
116
+ def main_loop():
117
+ global awaiting_response
118
+ thread_id = threading.get_ident()
119
+ print(f"[THREAD] Main loop running in thread {thread_id}")
120
+
121
+ while not _shutdown_flag:
122
+ awaiting_response = False
123
+ idle_mode()
124
+
125
+ # Wait here for response button to be pressed
126
+ print("[MAIN] Idle finished, waiting for trigger")
127
+ while not awaiting_response and not _shutdown_flag:
128
+ time.sleep(1) # Sleep without printing to reduce log spam
129
+
130
+ # Check if we got shutdown while waiting
131
+ if _shutdown_flag:
132
+ break
133
+
134
+ print("[MAIN] Response triggered, starting response processing")
135
+ response_mode()
136
+
137
+ # Add a delay to ensure the video has time to play (the response video)
138
+ time.sleep(10)
139
+
140
+ # After showing the response video, update the playlist to include other videos too
141
+ print("[MAIN] Updating playlist with additional videos")
142
+ create_lipsync_playlist()
143
+
144
+ print("[MAIN] Response mode completed, ready for next interaction")
145
+
146
+ print(f"[THREAD] Thread {thread_id} shutting down")
147
+
148
+ def trigger_response_with_prompt(prompt):
149
+ global awaiting_response, user_prompt
150
+ user_prompt = prompt
151
+ awaiting_response = True
152
+ print(f"[UI] Response triggered by user with prompt: {prompt[:50]}...")
153
+
154
+ def start_main_thread():
155
+ global _main_thread
156
+ with _thread_lock:
157
+ if _main_thread is None or not _main_thread.is_alive():
158
+ _main_thread = threading.Thread(target=main_loop, daemon=True)
159
+ _main_thread.start()
160
+ print(f"[INIT] Main thread started with ID {_main_thread.ident}")
161
+ return True
162
+ else:
163
+ print(f"[INIT] Main thread already running with ID {_main_thread.ident}")
164
+ return False
165
+
166
+ def shutdown():
167
+ global _shutdown_flag
168
+ _shutdown_flag = True
169
+ print("[APP] Shutdown initiated, waiting for threads to terminate...")
170
+ if _main_thread and _main_thread.is_alive():
171
+ _main_thread.join(timeout=5)
172
+ print("[APP] Shutdown complete")
173
+
174
+ # Register shutdown handler
175
+ atexit.register(shutdown)
176
+
177
+ # Only run this block when the file is executed directly
178
+ if __name__ in {"__main__", "__mp_main__"}: # Support multiprocessing
179
+ # Build the UI with our response callback
180
+ build_ui(trigger_response_callback=trigger_response_with_prompt)
181
+
182
+ # Start the main thread
183
+ start_main_thread()
184
+
185
+ # Start the NiceGUI server
186
+ ui.run(host='0.0.0.0', port=7860)