File size: 12,604 Bytes
ff052c3
9c59947
 
 
0a44afc
 
 
 
ff052c3
0a44afc
 
 
ff052c3
0a44afc
16d852f
9c59947
 
 
 
 
 
 
 
 
16d852f
 
 
 
 
 
 
 
 
 
 
 
 
ff052c3
9c59947
 
 
 
 
 
ff052c3
9c59947
 
 
 
 
ff052c3
 
 
 
 
9c59947
 
 
 
 
 
 
 
 
 
 
 
ff052c3
 
 
 
 
 
 
 
9c59947
 
ff052c3
 
 
 
 
 
9c59947
ff052c3
 
 
 
9c59947
ff052c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c59947
ff052c3
 
 
 
 
 
 
 
9c59947
 
 
ff052c3
 
 
 
 
9c59947
 
 
 
 
 
ff052c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c59947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff052c3
9c59947
 
 
 
 
 
 
 
 
ff052c3
9c59947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff052c3
9c59947
 
 
 
 
ff052c3
9c59947
 
 
 
 
 
 
 
 
 
 
 
 
ff052c3
 
9c59947
 
 
ff052c3
9c59947
 
 
ff052c3
 
9c59947
 
 
 
 
 
ff052c3
9c59947
 
 
 
 
 
 
 
 
ff052c3
9c59947
 
 
ff052c3
9c59947
 
 
 
 
ff052c3
9c59947
 
 
ff052c3
 
9c59947
 
 
ff052c3
 
 
 
 
 
 
 
 
 
 
 
9c59947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b46e10d
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
"""MrrrMe Backend WebSocket Server - Web-Accessible Emotion AI"""
import os
import sys

# ===== SET CACHE DIRECTORIES FIRST =====
os.environ['HF_HOME'] = '/tmp/huggingface'
os.environ['TRANSFORMERS_CACHE'] = '/tmp/transformers'
os.environ['HF_HUB_CACHE'] = '/tmp/huggingface/hub'
os.environ['TORCH_HOME'] = '/tmp/torch'
os.makedirs('/tmp/huggingface', exist_ok=True)
os.makedirs('/tmp/transformers', exist_ok=True)
os.makedirs('/tmp/huggingface/hub', exist_ok=True)
os.makedirs('/tmp/torch', exist_ok=True)

# ===== GPU FIX: Patch TensorBoard =====
class DummySummaryWriter:
    def __init__(self, *args, **kwargs): pass
    def __getattr__(self, name): return lambda *args, **kwargs: None

try:
    import tensorboardX
    tensorboardX.SummaryWriter = DummySummaryWriter
except: pass

# ===== GPU FIX: Patch Logging to redirect /work paths =====
import logging
_original_FileHandler = logging.FileHandler

class RedirectingFileHandler(_original_FileHandler):
    def __init__(self, filename, mode='a', encoding=None, delay=False, errors=None):
        if isinstance(filename, str) and filename.startswith('/work'):
            filename = '/tmp/openface_log.txt'
        os.makedirs(os.path.dirname(filename) if os.path.dirname(filename) else '/tmp', exist_ok=True)
        super().__init__(filename, mode, encoding, delay, errors)

logging.FileHandler = RedirectingFileHandler

# Now import everything else
import asyncio
import json
import base64
import numpy as np
import cv2
import io
import torch
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
import requests
from PIL import Image

# Check GPU
if not torch.cuda.is_available():
    print("[Backend] ⚠️ No GPU detected - using CPU mode")
else:
    print(f"[Backend] βœ… GPU available: {torch.cuda.get_device_name(0)}")

app = FastAPI()

# CORS for browser access
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Global model variables (will be loaded after startup)
face_processor = None
text_analyzer = None
whisper_worker = None
voice_worker = None
llm_generator = None
fusion_engine = None
models_ready = False

# Avatar backend URL
AVATAR_API = "http://localhost:8765"

@app.on_event("startup")
async def startup_event():
    """Start loading models in background after server is ready"""
    asyncio.create_task(load_models())

async def load_models():
    """Load all AI models asynchronously"""
    global face_processor, text_analyzer, whisper_worker, voice_worker
    global llm_generator, fusion_engine, models_ready
    
    print("[Backend] πŸš€ Initializing MrrrMe AI models in background...")
    
    try:
        # Import modules
        from mrrrme.vision.face_processor import FaceProcessor
        from mrrrme.audio.voice_emotion import VoiceEmotionWorker
        from mrrrme.audio.whisper_transcription import WhisperTranscriptionWorker
        from mrrrme.nlp.text_sentiment import TextSentimentAnalyzer
        from mrrrme.nlp.llm_generator_groq import LLMResponseGenerator
        from mrrrme.config import FUSE4
        
        # Load models
        print("[Backend] Loading FaceProcessor...")
        face_processor = FaceProcessor()
        
        print("[Backend] Loading TextSentiment...")
        text_analyzer = TextSentimentAnalyzer()
        
        print("[Backend] Loading Whisper...")
        whisper_worker = WhisperTranscriptionWorker(text_analyzer)
        
        print("[Backend] Loading VoiceEmotion...")
        voice_worker = VoiceEmotionWorker(whisper_worker=whisper_worker)
        
        print("[Backend] Initializing LLM...")
        groq_api_key = os.getenv("GROQ_API_KEY", "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")
        llm_generator = LLMResponseGenerator(api_key=groq_api_key)
        
        # Initialize fusion engine
        class FusionEngine:
            def __init__(self):
                self.alpha_face = 0.5
                self.alpha_voice = 0.3
                self.alpha_text = 0.2
            
            def fuse(self, face_probs, voice_probs, text_probs):
                fused = (
                    self.alpha_face * face_probs +
                    self.alpha_voice * voice_probs +
                    self.alpha_text * text_probs
                )
                fused = fused / (np.sum(fused) + 1e-8)
                fused_idx = int(np.argmax(fused))
                fused_emotion = FUSE4[fused_idx]
                intensity = float(np.max(fused))
                return fused_emotion, intensity
        
        fusion_engine = FusionEngine()
        models_ready = True
        
        print("[Backend] βœ… All models loaded!")
        
    except Exception as e:
        print(f"[Backend] ❌ Error loading models: {e}")
        import traceback
        traceback.print_exc()

@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "status": "running",
        "models_ready": models_ready,
        "message": "MrrrMe AI Backend"
    }

@app.get("/health")
async def health():
    """Health check - responds immediately"""
    return {
        "status": "healthy",
        "models_ready": models_ready
    }

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    print("[WebSocket] βœ… Client connected!")
    
    # Wait for models to load if needed
    if not models_ready:
        await websocket.send_json({
            "type": "status",
            "message": "AI models are loading, please wait..."
        })
        
        # Wait up to 15 minutes for models
        for _ in range(900):
            if models_ready:
                await websocket.send_json({
                    "type": "status",
                    "message": "Models loaded! Ready to chat."
                })
                break
            await asyncio.sleep(1)
        
        if not models_ready:
            await websocket.send_json({
                "type": "error",
                "message": "Models failed to load. Please refresh."
            })
            return
    
    # Session state
    audio_buffer = []
    
    try:
        while True:
            data = await websocket.receive_json()
            msg_type = data.get("type")
            
            # ============ VIDEO FRAME ============
            if msg_type == "video_frame":
                try:
                    # Decode base64 image
                    img_data = base64.b64decode(data["frame"].split(",")[1])
                    img = Image.open(io.BytesIO(img_data))
                    frame = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
                    
                    # Process face emotion
                    try:
                        processed_frame, result = face_processor.process_frame(frame)
                        face_emotion = face_processor.get_last_emotion() or "Neutral"
                        face_confidence = face_processor.get_last_confidence() or 0.0
                    except Exception as proc_err:
                        print(f"[FaceProcessor] Error: {proc_err}")
                        face_emotion = "Neutral"
                        face_confidence = 0.0
                    
                    # Send face emotion to frontend
                    await websocket.send_json({
                        "type": "face_emotion",
                        "emotion": face_emotion,
                        "confidence": face_confidence
                    })
                    
                except Exception as e:
                    print(f"[Video] Error: {e}")
            
            # ============ AUDIO CHUNK ============
            elif msg_type == "audio_chunk":
                try:
                    audio_data = base64.b64decode(data["audio"])
                    audio_buffer.append(audio_data)
                    
                    if len(audio_buffer) >= 5:
                        voice_probs, voice_emotion = voice_worker.get_probs()
                        await websocket.send_json({
                            "type": "voice_emotion",
                            "emotion": voice_emotion
                        })
                        audio_buffer = audio_buffer[-3:]
                    
                except Exception as e:
                    print(f"[Audio] Error: {e}")
            
            # ============ USER FINISHED SPEAKING ============
            elif msg_type == "speech_end":
                transcription = data.get("text", "").strip()
                print(f"\n[Speech End] User said: '{transcription}'")
                
                # Filter short/meaningless transcriptions
                if len(transcription) < 2:
                    continue
                
                hallucinations = {"thank you", "thanks", "okay", "ok", "you", "yeah", "yep"}
                if transcription.lower().strip('.,!?') in hallucinations:
                    continue
                
                try:
                    # Get face emotion
                    face_emotion = face_processor.get_last_emotion()
                    face_confidence = face_processor.get_last_confidence()
                    
                    # Create emotion probabilities
                    emotion_map = {'Neutral': 0, 'Happy': 1, 'Sad': 2, 'Angry': 3}
                    face_probs = np.array([0.25, 0.25, 0.25, 0.25], dtype=np.float32)
                    if face_emotion in emotion_map:
                        face_idx = emotion_map[face_emotion]
                        face_probs[face_idx] = face_confidence
                        face_probs = face_probs / face_probs.sum()
                    
                    # Get voice and text emotions
                    voice_probs, voice_emotion = voice_worker.get_probs()
                    text_analyzer.analyze(transcription)
                    text_probs, _ = text_analyzer.get_probs()
                    
                    # Fuse emotions
                    fused_emotion, intensity = fusion_engine.fuse(
                        face_probs, voice_probs, text_probs
                    )
                    
                    print(f"[Fusion] Face: {face_emotion}, Voice: {voice_emotion}, Fused: {fused_emotion}")
                    
                    # Generate LLM response
                    response_text = llm_generator.generate_response(
                        fused_emotion, face_emotion, voice_emotion,
                        transcription, force=True, intensity=intensity
                    )
                    
                    print(f"[LLM] Response: '{response_text}'")
                    
                    # Send to avatar for TTS
                    try:
                        avatar_response = requests.post(
                            f"{AVATAR_API}/speak",
                            data={"text": response_text},
                            timeout=45
                        )
                        avatar_response.raise_for_status()
                        avatar_data = avatar_response.json()
                        
                        await websocket.send_json({
                            "type": "llm_response",
                            "text": response_text,
                            "emotion": fused_emotion,
                            "intensity": intensity,
                            "audio_url": avatar_data.get("audio_url"),
                            "visemes": avatar_data.get("visemes")
                        })
                        
                    except Exception as avatar_err:
                        print(f"[Avatar] Error: {avatar_err}")
                        await websocket.send_json({
                            "type": "llm_response",
                            "text": response_text,
                            "emotion": fused_emotion,
                            "intensity": intensity,
                            "error": "Avatar TTS failed"
                        })
                    
                except Exception as e:
                    print(f"[Speech Processing] Error: {e}")
                    import traceback
                    traceback.print_exc()
    
    except WebSocketDisconnect:
        print("[WebSocket] ❌ Client disconnected")
    except Exception as e:
        print(f"[WebSocket] Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)