Chia Woon Yap commited on
Commit
fc3c6d7
·
verified ·
1 Parent(s): de44ca9

Create App_R3.py

Browse files
Files changed (1) hide show
  1. App_R3.py +366 -0
App_R3.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def transcribe_audio(audio):
268
+ sr, y = audio
269
+ if y.ndim > 1:
270
+ y = y.mean(axis=1)
271
+ y = y.astype(np.float32)
272
+ y /= np.max(np.abs(y))
273
+ return transcriber({"sampling_rate": sr, "raw": y})["text"]
274
+
275
+ # Clear chat history function
276
+ def clear_chat_history():
277
+ chat_memory.clear()
278
+ return [], None
279
+
280
+ def tutor_ai_chatbot():
281
+ """Main Gradio interface for the Tutor AI Chatbot."""
282
+ with gr.Blocks() as app:
283
+ gr.Markdown("# 📚 AI Tutor - We.(POC)")
284
+ gr.Markdown("An interactive Personal AI Tutor chatbot to help with your learning needs.")
285
+
286
+ # Chatbot Tab
287
+ with gr.Tab("AI Chatbot"):
288
+ with gr.Row():
289
+ with gr.Column(scale=3):
290
+ chatbot = gr.Chatbot(height=500, type="messages")
291
+ with gr.Row():
292
+ msg = gr.Textbox(label="Ask a question", placeholder="Type your question here...")
293
+ submit = gr.Button("Send")
294
+
295
+ with gr.Column(scale=1):
296
+ audio_input = gr.Audio(type="numpy", label="Record or Upload Audio")
297
+
298
+ with gr.Column(scale=1):
299
+ audio_playback = gr.Audio(label="Audio Response", type="filepath")
300
+
301
+ # Clear chat history button
302
+ clear_btn = gr.Button("Clear Chat")
303
+
304
+ # Handle chat interaction
305
+ submit.click(
306
+ chat_with_groq,
307
+ inputs=[msg, chatbot],
308
+ outputs=[chatbot, msg, audio_playback]
309
+ )
310
+
311
+ # Clear chat history function
312
+ clear_btn.click(
313
+ lambda: [], # Return empty list in message format
314
+ inputs=None,
315
+ outputs=[chatbot]
316
+ )
317
+
318
+ # Also allow Enter key to submit
319
+ msg.submit(
320
+ chat_with_groq,
321
+ inputs=[msg, chatbot],
322
+ outputs=[chatbot, msg, audio_playback]
323
+ )
324
+
325
+ # Add some examples of questions students might ask
326
+ with gr.Accordion("Example Questions", open=False):
327
+ gr.Examples(
328
+ examples=[
329
+ "Can you explain the concept of RLHF AI?",
330
+ "What are AI transformers?",
331
+ "What is MoE AI?",
332
+ "What's gate networks AI?",
333
+ "I am making a switch, please generating baking recipe?"
334
+ ],
335
+ inputs=msg
336
+ )
337
+
338
+ # Connect audio input to transcription
339
+ audio_input.change(fn=transcribe_audio, inputs=audio_input, outputs=msg)
340
+
341
+ # Upload Notes & Generate Quiz Tab
342
+ with gr.Tab("Upload Notes & Generate Quiz"):
343
+ with gr.Row():
344
+ with gr.Column(scale=2):
345
+ file_input = gr.File(label="Upload Lecture Notes (PDF, DOCX, PPTX)")
346
+ with gr.Column(scale=3):
347
+ quiz_output = gr.Textbox(label="Generated Quiz", lines=10)
348
+
349
+ # Connect file input to document processing
350
+ file_input.change(process_document, inputs=file_input, outputs=quiz_output)
351
+
352
+ # Introduction Video Tab - Now with the working video
353
+ with gr.Tab("Introduction Video"):
354
+ with gr.Row():
355
+ with gr.Column(scale=1):
356
+ gr.Markdown("### Welcome to the Introduction Video")
357
+ gr.Markdown("Music from Xu Mengyuan - China-O, musician Xu Mengyuan YUAN! | 徐梦圆 - China-O 音乐人徐梦圆YUAN!")
358
+ # Use the local video file that's stored in your Space
359
+ gr.Video("We_not_me_video.mp4", label="Introduction Video")
360
+
361
+ # Launch the application
362
+ app.launch(share=False)
363
+
364
+ # Launch the AI chatbot
365
+ if __name__ == "__main__":
366
+ tutor_ai_chatbot()