Chia Woon Yap commited on
Commit
c5cef76
·
verified ·
1 Parent(s): 15bfc80

Create app0.py

Browse files
Files changed (1) hide show
  1. app0.py +413 -0
app0.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """app
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1pwwcBb5Zlw1DA3u5K8W8mjrwBTBWXc1L
8
+ """
9
+
10
+ import gradio as gr
11
+ import numpy as np
12
+ from transformers import pipeline
13
+ import os
14
+ import time
15
+ import groq
16
+ import uuid # For generating unique filenames
17
+
18
+ # Updated imports to address LangChain deprecation warnings:
19
+ from langchain_groq import ChatGroq
20
+ from langchain.schema import HumanMessage
21
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
22
+ from langchain_community.vectorstores import Chroma
23
+ from langchain_community.embeddings import HuggingFaceEmbeddings
24
+ from langchain.docstore.document import Document
25
+
26
+ # Importing chardet (make sure to add chardet to your requirements.txt)
27
+ import chardet
28
+
29
+ import fitz # PyMuPDF for PDFs
30
+ import docx # python-docx for Word files
31
+ import gtts # Google Text-to-Speech library
32
+ from pptx import Presentation # python-pptx for PowerPoint files
33
+ import re
34
+
35
+ # Initialize Whisper model for speech-to-text
36
+ transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-base.en")
37
+
38
+ # Set API Key (Ensure it's stored securely in an environment variable)
39
+ groq.api_key = os.getenv("GROQ_API_KEY")
40
+
41
+ # Initialize Chat Model
42
+ chat_model = ChatGroq(model_name="llama-3.3-70b-versatile", api_key=groq.api_key)
43
+
44
+ # Initialize Embeddings and chromaDB
45
+ os.makedirs("chroma_db", exist_ok=True)
46
+ embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
47
+ vectorstore = Chroma(
48
+ embedding_function=embedding_model,
49
+ persist_directory="chroma_db"
50
+ )
51
+
52
+ # Short-term memory for the LLM
53
+ chat_memory = []
54
+
55
+ # Prompt for quiz generation with added remark
56
+ quiz_prompt = """
57
+ You are an AI assistant specialized in education and assessment creation. Given an uploaded document or text, generate a quiz with a mix of multiple-choice questions (MCQs) and fill-in-the-blank questions. The quiz should be directly based on the key concepts, facts, and details from the provided material.
58
+ Generate 20 Questions.
59
+ Remove all unnecessary formatting generated by the LLM, including <think> tags, asterisks, markdown formatting, and any bold or italic text, as well as **, ###, ##, and # tags.
60
+ For each question:
61
+ - Provide 4 answer choices (for MCQs), with only one correct answer.
62
+ - Ensure fill-in-the-blank questions focus on key terms, phrases, or concepts from the document.
63
+ - Include an answer key for all questions.
64
+ - Ensure questions vary in difficulty and encourage comprehension rather than memorization.
65
+ - Additionally, implement an instant feedback mechanism:
66
+ - When a user selects an answer, indicate whether it is correct or incorrect.
67
+ - If incorrect, provide a brief explanation from the document to guide learning.
68
+ - Ensure responses are concise and educational to enhance understanding.
69
+ Output Example:
70
+ 1. Fill in the blank: The LLM Agent framework has a central decision-making unit called the _______________________.
71
+
72
+ Answer: Agent Core
73
+
74
+ Feedback: The Agent Core is the central component of the LLM Agent framework, responsible for managing goals, tool instructions, planning modules, memory integration, and agent persona.
75
+
76
+ 2. What is the main limitation of LLM-based applications?
77
+ a) Limited token capacity
78
+ b) Lack of domain expertise
79
+ c) Prone to hallucination
80
+ d) All of the above
81
+
82
+ Answer: d) All of the above
83
+
84
+ Feedback: LLM-based applications have several limitations, including limited token capacity, lack of domain expertise, and being prone to hallucination, among others.
85
+
86
+ 3. Given the following info, what is the value of P(jam|Rain)?
87
+ P(no Rain) = 0.8;
88
+ P(no Jam) = 0.2;
89
+ P(Rain|Jam) = 0.1
90
+
91
+ a) 0.016
92
+ b) 0.025
93
+ c) 0.1
94
+ d) 0.4
95
+
96
+ Answer: d) 0.4
97
+
98
+ Feedback: This question tests understanding of Bayes' Theorem by requiring the calculation of conditional probability using the given values.
99
+ """
100
+
101
+ # Function to clean AI response by removing unwanted formatting
102
+ def clean_response(response):
103
+ """Removes <think> tags, asterisks, and markdown formatting."""
104
+ cleaned_text = re.sub(r"<think>.*?</think>", "", response, flags=re.DOTALL)
105
+ cleaned_text = re.sub(r"(\*\*|\*|\[|\])", "", cleaned_text)
106
+ cleaned_text = re.sub(r"^##+\s*", "", cleaned_text, flags=re.MULTILINE)
107
+ cleaned_text = re.sub(r"\\", "", cleaned_text)
108
+ cleaned_text = re.sub(r"---", "", cleaned_text)
109
+ return cleaned_text.strip()
110
+
111
+ # Function to generate quiz based on content
112
+ def generate_quiz(content):
113
+ prompt = f"{quiz_prompt}\n\nDocument content:\n{content}"
114
+ response = chat_model([HumanMessage(content=prompt)])
115
+ cleaned_response = clean_response(response.content)
116
+ return cleaned_response
117
+
118
+ # Function to retrieve relevant documents from vectorstore based on user query
119
+ def retrieve_documents(query):
120
+ results = vectorstore.similarity_search(query, k=3)
121
+ return [doc.page_content for doc in results]
122
+
123
+ # Function to convert tuple format to message format
124
+ def convert_to_message_format(chat_history):
125
+ """Convert from [(user, bot)] format to [{"role": "user", "content": user}, {"role": "assistant", "content": bot}] format"""
126
+ message_format = []
127
+ for user_msg, bot_msg in chat_history:
128
+ message_format.append({"role": "user", "content": user_msg})
129
+ message_format.append({"role": "assistant", "content": bot_msg})
130
+ return message_format
131
+
132
+ # Function to convert message format to tuple format for processing
133
+ def convert_to_tuple_format(chat_history):
134
+ """Convert from message format back to tuple format for processing"""
135
+ tuple_format = []
136
+ for i in range(0, len(chat_history), 2):
137
+ if i+1 < len(chat_history):
138
+ user_msg = chat_history[i]["content"]
139
+ bot_msg = chat_history[i+1]["content"]
140
+ tuple_format.append((user_msg, bot_msg))
141
+ return tuple_format
142
+
143
+ # Function to handle chatbot interactions with short-term memory
144
+ def chat_with_groq(user_input, chat_history):
145
+ try:
146
+ # Convert message format to tuple format for processing
147
+ tuple_history = convert_to_tuple_format(chat_history)
148
+
149
+ # Retrieve relevant documents for additional context
150
+ relevant_docs = retrieve_documents(user_input)
151
+ context = "\n".join(relevant_docs) if relevant_docs else "No relevant documents found."
152
+
153
+ # Construct proper prompting with conversation history
154
+ system_prompt = "You are a helpful AI assistant. Answer questions accurately and concisely."
155
+ conversation_history = "\n".join(chat_memory[-10:]) # Keep the last 10 exchanges
156
+ prompt = f"{system_prompt}\n\nConversation History:\n{conversation_history}\n\nUser Input: {user_input}\n\nContext:\n{context}"
157
+
158
+ # Call the chat model
159
+ response = chat_model([HumanMessage(content=prompt)])
160
+
161
+ # Clean response to remove any unwanted formatting
162
+ cleaned_response_text = clean_response(response.content)
163
+
164
+ # Append conversation history
165
+ chat_memory.append(f"User: {user_input}")
166
+ chat_memory.append(f"AI: {cleaned_response_text}")
167
+
168
+ # Update chat history - add new messages in the correct format
169
+ chat_history.append({"role": "user", "content": user_input})
170
+ chat_history.append({"role": "assistant", "content": cleaned_response_text})
171
+
172
+ # Convert response to speech
173
+ audio_file = speech_playback(cleaned_response_text)
174
+
175
+ return chat_history, "", audio_file
176
+ except Exception as e:
177
+ error_msg = f"Error: {str(e)}"
178
+ chat_history.append({"role": "user", "content": user_input})
179
+ chat_history.append({"role": "assistant", "content": error_msg})
180
+ return chat_history, "", None
181
+
182
+ # Function to play response as speech using gTTS
183
+ def speech_playback(text):
184
+ try:
185
+ # Generate a unique filename for each audio file
186
+ unique_id = str(uuid.uuid4())
187
+ audio_file = f"output_audio_{unique_id}.mp3"
188
+
189
+ # Convert text to speech
190
+ tts = gtts.gTTS(text, lang='en')
191
+ tts.save(audio_file)
192
+
193
+ # Return the path to the audio file
194
+ return audio_file
195
+ except Exception as e:
196
+ print(f"Error in speech_playback: {e}")
197
+ return None
198
+
199
+ # Function to detect encoding safely
200
+ def detect_encoding(file_path):
201
+ try:
202
+ with open(file_path, "rb") as f:
203
+ raw_data = f.read(4096)
204
+ detected = chardet.detect(raw_data)
205
+ encoding = detected["encoding"]
206
+ return encoding if encoding else "utf-8"
207
+ except Exception:
208
+ return "utf-8"
209
+
210
+ # Function to extract text from PDF
211
+ def extract_text_from_pdf(pdf_path):
212
+ try:
213
+ doc = fitz.open(pdf_path)
214
+ text = "\n".join([page.get_text("text") for page in doc])
215
+ return text if text.strip() else "No extractable text found."
216
+ except Exception as e:
217
+ return f"Error extracting text from PDF: {str(e)}"
218
+
219
+ # Function to extract text from Word files (.docx)
220
+ def extract_text_from_docx(docx_path):
221
+ try:
222
+ doc = docx.Document(docx_path)
223
+ text = "\n".join([para.text for para in doc.paragraphs])
224
+ return text if text.strip() else "No extractable text found."
225
+ except Exception as e:
226
+ return f"Error extracting text from Word document: {str(e)}"
227
+
228
+ # Function to extract text from PowerPoint files (.pptx)
229
+ def extract_text_from_pptx(pptx_path):
230
+ try:
231
+ presentation = Presentation(pptx_path)
232
+ text = ""
233
+ for slide in presentation.slides:
234
+ for shape in slide.shapes:
235
+ if hasattr(shape, "text"):
236
+ text += shape.text + "\n"
237
+ return text if text.strip() else "No extractable text found."
238
+ except Exception as e:
239
+ return f"Error extracting text from PowerPoint: {str(e)}"
240
+
241
+ # Function to process documents safely
242
+ def process_document(file):
243
+ try:
244
+ file_extension = os.path.splitext(file.name)[-1].lower()
245
+ if file_extension in [".png", ".jpg", ".jpeg"]:
246
+ return "Error: Images cannot be processed for text extraction."
247
+ if file_extension == ".pdf":
248
+ content = extract_text_from_pdf(file.name)
249
+ elif file_extension == ".docx":
250
+ content = extract_text_from_docx(file.name)
251
+ elif file_extension == ".pptx":
252
+ content = extract_text_from_pptx(file.name)
253
+ else:
254
+ encoding = detect_encoding(file.name)
255
+ with open(file.name, "r", encoding=encoding, errors="replace") as f:
256
+ content = f.read()
257
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
258
+ documents = [Document(page_content=chunk) for chunk in text_splitter.split_text(content)]
259
+ vectorstore.add_documents(documents)
260
+
261
+ quiz = generate_quiz(content)
262
+ return f"Document processed successfully (File Type: {file_extension}). Quiz generated:\n{quiz}"
263
+ except Exception as e:
264
+ return f"Error processing document: {str(e)}"
265
+
266
+ # Function to handle speech-to-text conversion
267
+
268
+ #def transcribe_audio(audio):
269
+ # sr, y = audio
270
+ # if y.ndim > 1:
271
+ # y = y.mean(axis=1)
272
+ # y = y.astype(np.float32)
273
+ # y /= np.max(np.abs(y))
274
+ # return transcriber({"sampling_rate": sr, "raw": y})["text"]
275
+
276
+ #Quick Fixes You Can Try First:
277
+
278
+ def transcribe_audio(audio):
279
+ sr, y = audio
280
+ if y.ndim > 1:
281
+ y = y.mean(axis=1)
282
+ y = y.astype(np.float32)
283
+
284
+ # Improved normalization
285
+ max_val = np.max(np.abs(y))
286
+ if max_val > 0:
287
+ y /= max_val
288
+
289
+ # Use better model
290
+ better_transcriber = pipeline(
291
+ "automatic-speech-recognition",
292
+ model="openai/whisper-small.en", # More accurate
293
+ chunk_length_s=30
294
+ )
295
+
296
+ return better_transcriber({"sampling_rate": sr, "raw": y})["text"]
297
+
298
+ # the remaining is the same
299
+
300
+
301
+
302
+
303
+ # Clear chat history function
304
+ def clear_chat_history():
305
+ chat_memory.clear()
306
+ return [], None
307
+
308
+ def tutor_ai_chatbot():
309
+ """Main Gradio interface for the Tutor AI Chatbot."""
310
+ with gr.Blocks() as app:
311
+ gr.Markdown("# 📚 AI Tutor - We.(POC)")
312
+ gr.Markdown("An interactive Personal AI Tutor chatbot to help with your learning needs.")
313
+
314
+ # Chatbot Tab
315
+ with gr.Tab("AI Chatbot"):
316
+ with gr.Row():
317
+ with gr.Column(scale=3):
318
+ chatbot = gr.Chatbot(height=500, type="messages")
319
+
320
+ with gr.Column(scale=1):
321
+ audio_playback = gr.Audio(label="Audio Response", type="filepath")
322
+
323
+ # Move the input controls here to span full width
324
+ with gr.Row():
325
+ msg = gr.Textbox(
326
+ label="Ask a question",
327
+ placeholder="Type your question here...",
328
+ container=False # Removes the default container styling
329
+ )
330
+ submit = gr.Button("Send")
331
+
332
+ with gr.Row():
333
+ with gr.Column(scale=1):
334
+ audio_input = gr.Audio(type="numpy", label="Record or Upload Audio")
335
+
336
+ # Voice recording tips - ONLY in AI Chatbot tab
337
+ with gr.Accordion("🎤 Voice Recording Tips", open=False):
338
+ gr.Markdown("""
339
+ **For better speech recognition accuracy:**
340
+ - 🎙️ Speak clearly and at a moderate pace
341
+ - 🔇 Record in a quiet environment
342
+ - 📍 Keep the microphone close to your mouth (10-15 cm)
343
+ - 🎧 Use a good quality microphone if possible
344
+ - 📝 Review the transcribed text before sending
345
+ - 🔄 If transcription is poor, try recording again or type manually
346
+ """)
347
+
348
+ # Clear chat history button
349
+ clear_btn = gr.Button("Clear Chat")
350
+
351
+ # Handle chat interaction
352
+ submit.click(
353
+ chat_with_groq,
354
+ inputs=[msg, chatbot],
355
+ outputs=[chatbot, msg, audio_playback]
356
+ )
357
+
358
+ # Clear chat history function
359
+ clear_btn.click(
360
+ lambda: [], # Return empty list in message format
361
+ inputs=None,
362
+ outputs=[chatbot]
363
+ )
364
+
365
+ # Also allow Enter key to submit
366
+ msg.submit(
367
+ chat_with_groq,
368
+ inputs=[msg, chatbot],
369
+ outputs=[chatbot, msg, audio_playback]
370
+ )
371
+
372
+ # Add some examples of questions students might ask
373
+ with gr.Accordion("Example Questions", open=False):
374
+ gr.Examples(
375
+ examples=[
376
+ "Can you explain the concept of RLHF AI?",
377
+ "What are AI transformers?",
378
+ "What is MoE AI?",
379
+ "What's gate networks AI?",
380
+ "I am making a switch, please generating baking recipe?"
381
+ ],
382
+ inputs=msg
383
+ )
384
+
385
+ # Connect audio input to transcription
386
+ audio_input.change(fn=transcribe_audio, inputs=audio_input, outputs=msg)
387
+
388
+ # Upload Notes & Generate Quiz Tab
389
+ with gr.Tab("Upload Notes & Generate Quiz"):
390
+ with gr.Row():
391
+ with gr.Column(scale=2):
392
+ file_input = gr.File(label="Upload Lecture Notes (PDF, DOCX, PPTX)")
393
+ with gr.Column(scale=3):
394
+ quiz_output = gr.Textbox(label="Generated Quiz", lines=10)
395
+
396
+ # Connect file input to document processing
397
+ file_input.change(process_document, inputs=file_input, outputs=quiz_output)
398
+
399
+ # Introduction Video Tab - Now with the working video
400
+ with gr.Tab("Introduction Video"):
401
+ with gr.Row():
402
+ with gr.Column(scale=1):
403
+ gr.Markdown("### Welcome to the Introduction Video")
404
+ gr.Markdown("Music from Xu Mengyuan - China-O, musician Xu Mengyuan YUAN! | 徐梦圆 - China-O 音乐人徐梦圆YUAN!")
405
+ # Use the local video file that's stored in your Space
406
+ gr.Video("We_not_me_video.mp4", label="Introduction Video")
407
+
408
+ # Launch the application
409
+ app.launch(share=False)
410
+
411
+ # Launch the AI chatbot
412
+ if __name__ == "__main__":
413
+ tutor_ai_chatbot()