File size: 10,832 Bytes
cf427d1
 
daf7e26
322ba51
cf427d1
1c51010
cf427d1
322ba51
998a350
daf7e26
 
cf427d1
1c51010
 
322ba51
 
 
 
 
 
1c51010
cf427d1
 
 
 
 
 
 
 
 
 
 
 
 
322ba51
cf427d1
322ba51
 
cf427d1
 
 
 
 
322ba51
cf427d1
322ba51
cf427d1
 
322ba51
cf427d1
322ba51
 
cf427d1
322ba51
 
cf427d1
 
322ba51
 
 
cf427d1
 
 
 
 
 
 
 
 
 
322ba51
 
cf427d1
322ba51
cf427d1
322ba51
 
cf427d1
 
322ba51
cf427d1
 
 
 
 
 
 
322ba51
cf427d1
 
322ba51
cf427d1
 
322ba51
cf427d1
 
 
 
 
 
322ba51
cf427d1
 
 
 
 
 
322ba51
 
 
cf427d1
322ba51
 
cf427d1
322ba51
 
 
cf427d1
 
 
 
 
 
 
 
322ba51
 
 
cf427d1
 
 
322ba51
 
 
cf427d1
 
 
 
 
322ba51
cf427d1
 
 
 
 
322ba51
cf427d1
 
 
322ba51
cf427d1
 
 
 
 
 
322ba51
cf427d1
 
 
 
322ba51
cf427d1
 
 
 
322ba51
 
 
 
 
 
 
cf427d1
 
322ba51
cf427d1
 
322ba51
cf427d1
 
322ba51
cf427d1
322ba51
 
cf427d1
322ba51
cf427d1
 
2c1a7ab
cf427d1
322ba51
cf427d1
2c1a7ab
322ba51
cf427d1
322ba51
 
 
 
 
 
 
 
 
 
 
cf427d1
 
322ba51
 
 
 
 
 
 
 
 
 
 
 
 
cf427d1
 
322ba51
 
cf427d1
322ba51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf427d1
 
 
 
322ba51
 
 
 
cf427d1
 
322ba51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf427d1
 
2c1a7ab
322ba51
cf427d1
322ba51
cf427d1
322ba51
 
 
 
 
 
 
 
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
import os, torch, numpy as np, soundfile as sf, gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig, pipeline
import nemo.collections.asr as nemo_asr
from TTS.api import TTS
from sklearn.linear_model import LogisticRegression
from datasets import load_dataset
import tempfile
import gc

# Configuration
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
SEED = 42; SAMPLE_RATE = 22050; TEMPERATURE = 0.7
torch.manual_seed(SEED); np.random.seed(SEED)

print(f"πŸš€ System Info:")
print(f"Device: {DEVICE}")
print(f"NumPy: {np.__version__}")
print(f"PyTorch: {torch.__version__}")
if torch.cuda.is_available():
    print(f"CUDA: {torch.version.cuda}")

class ConversationalAI:
    def __init__(self):
        print("πŸ”„ Initializing Conversational AI...")
        self.setup_models()
        print("βœ… All models loaded successfully!")
    
    def setup_models(self):
        # 1. ASR: Parakeet RNNT
        print("πŸ“’ Loading ASR model...")
        try:
            self.asr_model = nemo_asr.models.EncDecRNNTBPEModel.from_pretrained(
                "nvidia/parakeet-rnnt-1.1b"
            ).to(DEVICE).eval()
            print("βœ… Parakeet ASR loaded")
        except Exception as e:
            print(f"⚠️ Parakeet failed: {e}")
            print("πŸ”„ Loading Whisper fallback...")
            self.asr_pipeline = pipeline(
                "automatic-speech-recognition",
                model="openai/whisper-base.en",
                device=0 if DEVICE == "cuda" else -1
            )
            print("βœ… Whisper ASR loaded")
        
        # 2. SER: Emotion classifier (simplified for demo)
        print("🎭 Setting up emotion recognition...")
        X_demo = np.random.rand(100, 128)
        y_demo = np.random.randint(0, 5, 100)  # 5 emotions: neutral, happy, sad, angry, surprised
        self.ser_clf = LogisticRegression().fit(X_demo, y_demo)
        self.emotion_labels = ["neutral", "happy", "sad", "angry", "surprised"]
        print("βœ… SER model ready")
        
        # 3. LLM: Conversational model
        print("🧠 Loading LLM...")
        bnb_cfg = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_compute_dtype=torch.float16,
            bnb_4bit_use_double_quant=True,
            bnb_4bit_quant_type="nf4"
        )
        
        model_name = "microsoft/DialoGPT-medium"
        self.tokenizer = AutoTokenizer.from_pretrained(model_name)
        self.tokenizer.pad_token = self.tokenizer.eos_token
        
        self.llm_model = AutoModelForCausalLM.from_pretrained(
            model_name,
            quantization_config=bnb_cfg,
            device_map="auto",
            torch_dtype=torch.float16,
            low_cpu_mem_usage=True
        )
        print("βœ… LLM loaded")
        
        # 4. TTS: Text-to-Speech
        print("πŸ—£οΈ Loading TTS...")
        try:
            self.tts = TTS("tts_models/en/ljspeech/tacotron2-DDC").to(DEVICE)
            print("βœ… TTS loaded")
        except Exception as e:
            print(f"⚠️ TTS error: {e}")
            self.tts = None
        
        # Memory cleanup
        if DEVICE == "cuda":
            torch.cuda.empty_cache()
            gc.collect()
    
    def transcribe(self, audio):
        """Convert speech to text"""
        try:
            if hasattr(self, 'asr_model'):
                # Use Parakeet
                temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
                sf.write(temp_file.name, audio[1], audio[0])
                transcription = self.asr_model.transcribe([temp_file.name])[0]
                os.unlink(temp_file.name)
                return transcription.text if hasattr(transcription, 'text') else str(transcription)
            else:
                # Use Whisper
                return self.asr_pipeline({"sampling_rate": audio[0], "raw": audio[1]})["text"]
        except Exception as e:
            print(f"ASR Error: {e}")
            return "Sorry, I couldn't understand the audio."
    
    def predict_emotion(self):
        """Predict emotion from audio (simplified demo)"""
        emotion_idx = self.ser_clf.predict(np.random.rand(1, 128))[0]
        return self.emotion_labels[emotion_idx]
    
    def generate_response(self, text, emotion):
        """Generate conversational response"""
        try:
            # Create emotion-aware prompt
            prompt = f"Human: {text}\nAssistant (feeling {emotion}):"
            
            inputs = self.tokenizer.encode(prompt, return_tensors="pt", max_length=512, truncation=True).to(DEVICE)
            
            with torch.no_grad():
                outputs = self.llm_model.generate(
                    inputs,
                    max_length=inputs.shape[1] + 100,
                    temperature=TEMPERATURE,
                    do_sample=True,
                    pad_token_id=self.tokenizer.eos_token_id,
                    no_repeat_ngram_size=2,
                    top_p=0.9
                )
            
            response = self.tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
            response = response.split("Human:")[0].strip()
            
            return response if response else "I understand. Please tell me more."
        except Exception as e:
            print(f"LLM Error: {e}")
            return "I'm having trouble processing that. Could you please rephrase?"
    
    def synthesize(self, text):
        """Convert text to speech"""
        try:
            if self.tts:
                wav = self.tts.tts(text=text)
                if isinstance(wav, list):
                    wav = np.array(wav, dtype=np.float32)
                # Normalize audio
                wav = wav / np.max(np.abs(wav)) if np.max(np.abs(wav)) > 0 else wav
                return (SAMPLE_RATE, (wav * 32767).astype(np.int16))
            else:
                # Return silence if TTS fails
                return (SAMPLE_RATE, np.zeros(SAMPLE_RATE, dtype=np.int16))
        except Exception as e:
            print(f"TTS Error: {e}")
            return (SAMPLE_RATE, np.zeros(SAMPLE_RATE, dtype=np.int16))
    
    def process_conversation(self, audio_input, chat_history):
        """Main pipeline: Speech -> Emotion -> LLM -> Speech"""
        if audio_input is None:
            return chat_history, None, ""
        
        try:
            # Step 1: Speech to Text
            user_text = self.transcribe(audio_input)
            if not user_text.strip():
                return chat_history, None, "No speech detected."
            
            # Step 2: Emotion Recognition
            emotion = self.predict_emotion()
            
            # Step 3: Generate Response
            ai_response = self.generate_response(user_text, emotion)
            
            # Step 4: Text to Speech
            audio_response = self.synthesize(ai_response)
            
            # Update chat history
            chat_history.append([user_text, ai_response])
            
            # Memory cleanup
            if DEVICE == "cuda":
                torch.cuda.empty_cache()
                gc.collect()
            
            return chat_history, audio_response, f"You said: {user_text} (detected emotion: {emotion})"
        
        except Exception as e:
            error_msg = f"Error processing conversation: {e}"
            print(error_msg)
            return chat_history, None, error_msg

# Initialize AI system
print("πŸš€ Starting Conversational AI...")
ai_system = ConversationalAI()

# Gradio Interface
def create_interface():
    with gr.Blocks(
        title="Emotion-Aware Conversational AI",
        theme=gr.themes.Soft()
    ) as demo:
        
        gr.HTML("""
            <div style="text-align: center; margin-bottom: 2rem;">
                <h1>πŸ€– Emotion-Aware Conversational AI</h1>
                <p>Speak naturally and get intelligent responses with emotion recognition</p>
            </div>
        """)
        
        with gr.Row():
            with gr.Column(scale=2):
                chatbot = gr.Chatbot(
                    label="Conversation History",
                    height=400,
                    show_copy_button=True
                )
                
                audio_input = gr.Audio(
                    label="🎀 Speak to AI",
                    sources=["microphone"],
                    type="numpy",
                    format="wav"
                )
                
                with gr.Row():
                    submit_btn = gr.Button("πŸ’¬ Process Speech", variant="primary", scale=2)
                    clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary", scale=1)
            
            with gr.Column(scale=1):
                audio_output = gr.Audio(
                    label="πŸ”Š AI Response",
                    type="numpy",
                    autoplay=True
                )
                
                status_display = gr.Textbox(
                    label="πŸ“Š Status",
                    lines=3,
                    interactive=False
                )
                
                gr.HTML(f"""
                    <div style="padding: 1rem; background: #f0f9ff; border-radius: 0.5rem;">
                        <h3>πŸ”§ System Info</h3>
                        <p><strong>Device:</strong> {DEVICE.upper()}</p>
                        <p><strong>PyTorch:</strong> {torch.__version__}</p>
                        <p><strong>Models:</strong> Parakeet + DialoGPT + TTS</p>
                        <p><strong>Features:</strong> Emotion Recognition</p>
                    </div>
                """)
        
        def process_audio(audio, history):
            return ai_system.process_conversation(audio, history)
        
        def clear_conversation():
            if DEVICE == "cuda":
                torch.cuda.empty_cache()
                gc.collect()
            return [], None, "Conversation cleared."
        
        # Event handlers
        submit_btn.click(
            fn=process_audio,
            inputs=[audio_input, chatbot],
            outputs=[chatbot, audio_output, status_display]
        )
        
        clear_btn.click(
            fn=clear_conversation,
            outputs=[chatbot, audio_output, status_display]
        )
        
        audio_input.change(
            fn=process_audio,
            inputs=[audio_input, chatbot],
            outputs=[chatbot, audio_output, status_display]
        )
    
    return demo

# Launch application
if __name__ == "__main__":
    print("🌟 Creating interface...")
    demo = create_interface()
    
    print("πŸš€ Launching application...")
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        show_error=True
    )