File size: 19,464 Bytes
4368f96
 
 
 
 
 
 
 
 
6191c40
4214099
 
0f50d71
4368f96
6191c40
 
 
 
 
 
 
 
9c66c5f
 
4368f96
17f9f26
0285b1b
faf39dd
d4e1309
faf39dd
 
 
 
17f9f26
 
 
 
 
 
 
 
 
 
 
 
 
0285b1b
faf39dd
919f81c
 
17f9f26
 
 
 
faf39dd
17f9f26
919f81c
 
17f9f26
0285b1b
faf39dd
919f81c
17f9f26
 
 
 
 
0285b1b
919f81c
17f9f26
 
6148c3d
 
17f9f26
 
6148c3d
 
17f9f26
 
 
919f81c
17f9f26
6148c3d
17f9f26
 
 
6148c3d
919f81c
 
17f9f26
 
 
 
919f81c
 
 
17f9f26
0285b1b
919f81c
 
17f9f26
 
0285b1b
d4e1309
919f81c
17f9f26
 
 
 
 
 
 
 
 
 
 
d4e1309
 
919f81c
17f9f26
 
 
919f81c
17f9f26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4e1309
0285b1b
 
 
4368f96
 
 
 
 
 
 
0285b1b
 
4368f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fbb8bd
4368f96
8fbb8bd
 
4368f96
 
ce79e89
4368f96
 
 
ce79e89
7dd5b9d
 
 
 
 
 
 
8fbb8bd
 
 
209ed30
 
 
 
8fbb8bd
209ed30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4368f96
 
 
006b455
 
 
ce79e89
6148c3d
4368f96
 
 
 
 
ce79e89
6148c3d
4368f96
 
 
 
ce79e89
4368f96
 
6148c3d
4368f96
 
 
 
 
 
 
 
 
 
 
 
ce79e89
6148c3d
4368f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6148c3d
4368f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d8736d
 
 
4368f96
e7dfb7a
4368f96
 
3e83fd3
 
e7dfb7a
4368f96
4d8736d
 
4368f96
4214099
 
 
 
 
 
 
 
 
 
 
4368f96
4214099
4368f96
0f50d71
6b9dfec
 
 
 
0f50d71
 
 
 
 
 
 
 
 
6b9dfec
 
4d8736d
 
 
4214099
4368f96
4214099
4368f96
3e83fd3
 
4214099
 
4368f96
e7dfb7a
 
4214099
4368f96
3150019
 
 
 
 
 
 
 
6148c3d
919f81c
6148c3d
17f9f26
4214099
6148c3d
4368f96
4214099
1f24f10
4214099
38b5884
3150019
 
 
 
 
919f81c
4214099
 
 
17f9f26
8fbb8bd
 
3150019
8fbb8bd
 
 
 
 
 
 
3150019
 
 
 
 
 
 
 
 
 
 
 
 
c30135d
53c1d8d
0285b1b
3e83fd3
 
 
 
0285b1b
4368f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e83fd3
 
4368f96
 
 
 
 
 
33982da
6191c40
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import os
import tempfile
import gradio as gr
import openai
from typing import Optional, List
import hashlib
import base64
import json
import time
from dotenv import load_dotenv
from gtts import gTTS
import io
import numpy as np

# Load environment variables
load_dotenv()

# Initialize OpenAI client with error handling
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
    raise ValueError("OPENAI_API_KEY environment variable is not set")

# Initialize OpenAI client with older API syntax
openai.api_key = api_key

# Custom CSS for a beautiful, modern look
custom_css = """
html, body, .gradio-container {
    height: 100vh !important;
    min-height: 100vh !important;
    max-width: 100vw !important;
    margin: 0 !important;
    padding: 0 !important;
    font-family: 'Inter', 'Segoe UI', Arial, sans-serif;
    background: #f4f7fb;
    color: #222;
}

.centered-main {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    min-height: 100vh;
    width: 100vw;
    padding-top: 32px;
}

.compact-box {
    background: #fff;
    border-radius: 18px;
    box-shadow: 0 4px 24px rgba(0, 60, 180, 0.07), 0 1.5px 4px rgba(0,0,0,0.04);
    padding: 32px 32px 20px 32px;
    margin-bottom: 32px;
    width: 100%;
    max-width: 600px;
    margin-left: auto;
    margin-right: auto;
    border: 1.5px solid #e3e8f0;
}

.section-title {
    font-size: 1.25rem;
    font-weight: 700;
    margin-bottom: 18px;
    color: #1a237e;
    letter-spacing: 0.01em;
}

.upload-btn, .send-btn, .audio-btn, .reset-btn {
    background: linear-gradient(135deg, #1976D2 0%, #00bcd4 100%);
    color: white;
    border: none;
    padding: 12px 28px;
    border-radius: 24px;
    cursor: pointer;
    font-weight: 600;
    font-size: 16px;
    margin-top: 10px;
    margin-bottom: 10px;
    transition: all 0.2s;
    box-shadow: 0 2px 8px rgba(25, 118, 210, 0.08);
}
.upload-btn:hover, .send-btn:hover, .audio-btn:hover, .reset-btn:hover {
    background: linear-gradient(135deg, #00bcd4 0%, #1976D2 100%);
    box-shadow: 0 4px 16px rgba(0, 188, 212, 0.13);
}

.gradio-chatbot {
    border-radius: 14px !important;
    border: 1.5px solid #e3e8f0 !important;
    background: #f8fafc !important;
    padding: 12px !important;
    min-height: 350px !important;
    max-height: 400px !important;
    overflow-y: auto !important;
    margin-bottom: 10px;
}

.gradio-audio {
    margin-top: 12px;
    margin-bottom: 12px;
}

.textbox {
    border-radius: 12px !important;
    border: 1.5px solid #e3e8f0 !important;
    padding: 12px !important;
    font-size: 16px !important;
    margin-bottom: 10px;
    background: #f8fafc !important;
    color: #222 !important;
}
.textbox:focus {
    border-color: #1976D2 !important;
    box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.13) !important;
}

.status-text {
    color: #1976D2;
    font-size: 15px;
    margin-top: 10px;
    font-weight: 500;
    background: #e3f2fd;
    border-radius: 8px;
    padding: 8px 12px;
}

/* File upload area */
input[type="file"]::-webkit-file-upload-button {
    background: #1976D2;
    color: #fff;
    border: none;
    border-radius: 8px;
    padding: 8px 18px;
    font-weight: 600;
    cursor: pointer;
}
input[type="file"]::-webkit-file-upload-button:hover {
    background: #00bcd4;
}

/* Only one main scroll */
body, .gradio-container, #root, #app {
    overflow: auto !important;
    height: 100vh !important;
}
#component-0, #component-1, #component-2, .chatbot, .chat-container {
    overflow: visible !important;
    height: auto !important;
    max-height: none !important;
}
"""

# Custom audio recorder component with improved styling
def create_audio_recorder():
    return gr.HTML("""
        <div class="audio-recorder">
            <button id="recordButton" class="record-button">
                <span class="record-icon">🎀</span>
                <span class="record-text">Start Recording</span>
            </button>
            <div id="recordingStatus" class="status-text"></div>
            <audio id="audioPlayback" controls style="display: none; margin-top: 10px;"></audio>
        </div>
        <script>
            let mediaRecorder;
            let audioChunks = [];
            let isRecording = false;
            const recordButton = document.getElementById('recordButton');
            const recordingStatus = document.getElementById('recordingStatus');
            const audioPlayback = document.getElementById('audioPlayback');

            recordButton.addEventListener('click', async () => {
                if (!isRecording) {
                    try {
                        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                        mediaRecorder = new MediaRecorder(stream);
                        audioChunks = [];
                        
                        mediaRecorder.ondataavailable = (event) => {
                            audioChunks.push(event.data);
                        };
                        
                        mediaRecorder.onstop = () => {
                            const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                            const audioUrl = URL.createObjectURL(audioBlob);
                            audioPlayback.src = audioUrl;
                            audioPlayback.style.display = 'block';
                            
                            const reader = new FileReader();
                            reader.readAsDataURL(audioBlob);
                            reader.onloadend = () => {
                                const base64Audio = reader.result;
                                window.parent.postMessage({
                                    type: 'audio_data',
                                    data: base64Audio
                                }, '*');
                            };
                        };
                        
                        mediaRecorder.start();
                        isRecording = true;
                        recordButton.classList.add('recording');
                        recordButton.querySelector('.record-text').textContent = 'Stop Recording';
                        recordingStatus.textContent = 'Recording...';
                    } catch (err) {
                        console.error('Error accessing microphone:', err);
                        recordingStatus.textContent = 'Error accessing microphone';
                    }
                } else {
                    mediaRecorder.stop();
                    isRecording = false;
                    recordButton.classList.remove('recording');
                    recordButton.querySelector('.record-text').textContent = 'Start Recording';
                    recordingStatus.textContent = 'Recording saved';
                }
            });
        </script>
    """)

class AdvancedRAG:
    def __init__(self):
        self.thread_id: Optional[str] = None
        self.file_ids: List[str] = []
        self.assistant_id: Optional[str] = os.getenv("ASSISTANT_ID")
        if hasattr(self, 'vector_store_id'):
            self.vector_store_id = None

    def create_thread(self) -> str:
        thread = openai.beta.threads.create()
        self.thread_id = thread.id
        return self.thread_id

    def upload_document(self, file) -> str:
        # Delete previous file from OpenAI if it exists
        if self.file_ids:
            for file_id in self.file_ids:
                try:
                    openai.files.delete(file_id)
                except Exception as e:
                    print(f"Warning: Could not delete file {file_id}: {e}")
        self.thread_id = None
        self.file_ids = []
        if hasattr(self, 'vector_store_id'):
            try:
                openai.beta.vector_stores.delete(self.vector_store_id)
            except Exception as e:
                print(f"Warning: Could not delete vector store: {e}")
            self.vector_store_id = None

        # Wait a moment to ensure deletion is processed
        time.sleep(2)

        # Upload new file
        if not file:
            raise Exception("No file uploaded.")
        filename = 'uploaded_file.pdf'
        with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(filename)[1]) as tmp:
            tmp.write(file)
            tmp.flush()
            with open(tmp.name, "rb") as file_obj:
                file_obj = openai.files.create(
                    file=file_obj,
                    purpose="assistants"
                )
                self.file_ids = [file_obj.id]

        # Create a new thread for the new document
        thread = openai.beta.threads.create()
        self.thread_id = thread.id

        # Send a message in the new thread with only the new file as an attachment
        openai.beta.threads.messages.create(
            thread_id=self.thread_id,
            role="user",
            content="I have uploaded a document. Please analyze it.",
            attachments=[{"file_id": self.file_ids[0], "tools": [{"type": "file_search"}]}]
        )
        return self.file_ids[0]

    def ask_question(self, question: str) -> str:
        try:
            if not self.thread_id:
                self.create_thread()

            # Add the question to the thread
            openai.beta.threads.messages.create(
                thread_id=self.thread_id,
                role="user",
                content=question
            )
            
            # Create a run
            run = openai.beta.threads.runs.create(
                thread_id=self.thread_id,
                assistant_id=self.assistant_id
            )
            
            # Wait for the run to complete
            waited = 0
            while True:
                run_status = openai.beta.threads.runs.retrieve(
                    thread_id=self.thread_id,
                    run_id=run.id
                )
                if run_status.status == 'completed':
                    break
                elif run_status.status == 'failed':
                    raise Exception("Run failed")
                time.sleep(0.2)
                waited += 0.2
                if waited > 60:
                    raise Exception("Run timed out after 60 seconds.")

            # Get the latest message
            messages = openai.beta.threads.messages.list(
                thread_id=self.thread_id,
                order='desc',
                limit=1
            )
            if not messages.data:
                return "No response received from the assistant."
            return messages.data[0].content[0].text.value
        except Exception as e:
            return f"[Error: {str(e)}]"

    def transcribe_audio(self, audio_file):
        try:
            with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
                tmp.write(audio_file.read())
                tmp.flush()
                tmp_path = tmp.name
            with open(tmp_path, "rb") as audio:
                transcript = openai.audio.transcriptions.create(
                    model="whisper-1",
                    file=audio,
                    language="en"
                )
            os.remove(tmp_path)
            return transcript.text
        except Exception as e:
            return f"[Error transcribing audio: {str(e)}]"

# Initialize RAG system
rag = AdvancedRAG()

def process_file(file):
    if file is None:
        return "Please upload a file first."
    try:
        rag.upload_document(file)
        return "File uploaded successfully! You can now ask questions about the document."
    except Exception as e:
        return f"Error uploading file: {str(e)}"

def process_question(question, history):
    # Prevent sending empty messages
    if not question or not question.strip():
        return "", history, "", None
    if not rag.thread_id:
        return "Please upload a document first.", history, "", None
    try:
        response = rag.ask_question(question)
        history.append({"role": "user", "content": question})
        history.append({"role": "assistant", "content": response})
        return "", history, "", None
    except Exception as e:
        history.append({"role": "assistant", "content": f"Error: {str(e)}"})
        return "", history, "", None

def synthesize_text(text):
    try:
        tts = gTTS(text)
        fp = io.BytesIO()
        tts.write_to_fp(fp)
        fp.seek(0)
        return fp.read()
    except Exception as e:
        return None

def process_voice_note(audio_file, history):
    if audio_file is None:
        return "Please record or upload an audio file.", history, "", None, None
    try:
        transcript = None
        # If audio_file is a string (filepath), open it as a file
        if isinstance(audio_file, str):
            with open(audio_file, "rb") as f:
                transcript = rag.transcribe_audio(f)
        # If audio_file is a tuple (sample_rate, np.ndarray), save as temp WAV and open
        elif isinstance(audio_file, tuple) and isinstance(audio_file[1], np.ndarray):
            import soundfile as sf
            sample_rate, audio_data = audio_file
            with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
                sf.write(tmp.name, audio_data, sample_rate)
                tmp.flush()
                with open(tmp.name, "rb") as f:
                    transcript = rag.transcribe_audio(f)
        else:
            transcript = rag.transcribe_audio(audio_file)
        if not transcript or not str(transcript).strip():
            history.append({"role": "user", "content": "🎀 [No audio detected or transcription failed]"})
            history.append({"role": "assistant", "content": "Sorry, I couldn't understand the audio. Please try again."})
            return "", history, "", None, None
        if not rag.thread_id:
            return "Please upload a document first.", history, "", None, None
        response = rag.ask_question(transcript)
        history.append({"role": "user", "content": f"🎀 {transcript}"})
        history.append({"role": "assistant", "content": response})
        tts_audio = synthesize_text(response)
        return "", history, "", None, tts_audio
    except Exception as e:
        history.append({"role": "user", "content": f"🎀 [Error transcribing audio: {str(e)}]"})
        history.append({"role": "assistant", "content": "It seems there was an error while transcribing audio due to a technical issue. If there's anything specific from the document or any other questions you have regarding the content, please let me know, and I can assist you with that information."})
        return "", history, "", None, None

def reset_all():
    rag.thread_id = None
    if hasattr(rag, 'file_ids'):
        rag.file_ids = []
    if hasattr(rag, 'vector_store_id'):
        rag.vector_store_id = None
    return "", [], "", None, None

# Create Gradio interface with improved layout
with gr.Blocks(css=custom_css, title="Document Q&A System") as demo:
    gr.Markdown("""
    # <span style='color:#1976D2;'>Document Q&A System</span>
    <div style='text-align:center; color:#1976D2; margin-bottom:18px;'>Upload a document, record your voice, and chat!</div>
    """)

    chatbot = gr.Chatbot(height=400, elem_classes="gradio-chatbot", label=None, type="messages")
    audio_input = gr.Audio(type="filepath", label="Record or Upload Audio", elem_classes="gradio-audio", visible=False)
    tts_output = gr.Audio(label="Assistant Voice Reply", interactive=False, visible=False)

    with gr.Row():
        # Left: Document Q&A controls
        with gr.Column(scale=1, min_width=350):
            with gr.Group(elem_classes="compact-box"):
                gr.Markdown("<div class='section-title'>Document Q&A Controls</div>")
                file_input = gr.File(label="Upload Document", file_types=[".pdf", ".txt", ".doc", ".docx"], file_count="single", type="binary", elem_classes="upload-btn")
                mic_btn = gr.Button("🎀 Record Voice", elem_classes="audio-btn")
                audio_input
                send_voice_btn = gr.Button("Send Voice Note", elem_classes="send-btn", visible=False)
                reset_btn = gr.Button("Reset Chat & Upload New Document", elem_classes="reset-btn")
                file_output = gr.Textbox(label="Upload Status", interactive=False, elem_classes="textbox")
                question = gr.Textbox(label="Type your question and press Enter", placeholder="Ask a question about your document...", elem_classes="textbox")
                file_input.change(process_file, file_input, file_output)
                def reset_all():
                    rag.thread_id = None
                    if hasattr(rag, 'file_ids'):
                        rag.file_ids = []
                    if hasattr(rag, 'vector_store_id'):
                        rag.vector_store_id = None
                    return "", [], "", None, None
                reset_btn.click(reset_all, None, [file_output, chatbot, question, audio_input, tts_output])
                def show_audio():
                    return {audio_input: gr.update(visible=True), send_voice_btn: gr.update(visible=True)}
                mic_btn.click(show_audio, None, [audio_input, send_voice_btn])
                def hide_audio():
                    return {audio_input: gr.update(visible=False), send_voice_btn: gr.update(visible=False)}
                send_voice_btn.click(process_voice_note, [audio_input, chatbot], [file_output, chatbot, question, audio_input, tts_output])
                send_voice_btn.click(hide_audio, None, [audio_input, send_voice_btn])
                question.submit(process_question, [question, chatbot], [question, chatbot, question, audio_input])
                tts_output
        # Right: Chatbot screen
        with gr.Column(scale=2, min_width=500):
            with gr.Group(elem_classes="compact-box"):
                chatbot

    # Add JavaScript for audio handling
    demo.load(
        fn=None,
        inputs=None,
        outputs=None,
        js="""
        function() {
            window.addEventListener('message', function(event) {
                if (event.data.type === 'audio_data') {
                    const audioData = event.data.data;
                    const byteString = atob(audioData.split(',')[1]);
                    const mimeString = audioData.split(',')[0].split(':')[1].split(';')[0];
                    const ab = new ArrayBuffer(byteString.length);
                    const ia = new Uint8Array(ab);
                    for (let i = 0; i < byteString.length; i++) {
                        ia[i] = byteString.charCodeAt(i);
                    }
                    const blob = new Blob([ab], {type: mimeString});
                    const file = new File([blob], "recording.wav", {type: mimeString});
                    
                    const audioInput = document.querySelector('input[type="file"]');
                    const dataTransfer = new DataTransfer();
                    dataTransfer.items.add(file);
                    audioInput.files = dataTransfer.files;
                    audioInput.dispatchEvent(new Event('change', { bubbles: true }));
                }
            });
        }
        """
    )

if __name__ == "__main__":
    demo.launch(
        share=True,
        server_name="0.0.0.0",
        server_port=7860,
        show_error=True
    )