Lesterchia174 commited on
Commit
5ff1e17
·
verified ·
1 Parent(s): ed112eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +367 -0
app.py CHANGED
@@ -65,9 +65,376 @@ groq.api_key = os.getenv("GROQ_API_KEY") # Replace with a valid API key
65
  chat_model = ChatGroq(model_name="deepseek-r1-distill-qwen-32b", api_key=groq.api_key) #DeepSeek-R1-Distill-Llama-70b
66
 
67
  # Initialize Embeddings and chromaDB
 
68
  embedding_model = HuggingFaceEmbeddings()
69
  vectorstore = Chroma(embedding_function=embedding_model)
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  # Short-term memory for the LLM
72
  chat_memory = []
73
 
 
65
  chat_model = ChatGroq(model_name="deepseek-r1-distill-qwen-32b", api_key=groq.api_key) #DeepSeek-R1-Distill-Llama-70b
66
 
67
  # Initialize Embeddings and chromaDB
68
+
69
  embedding_model = HuggingFaceEmbeddings()
70
  vectorstore = Chroma(embedding_function=embedding_model)
71
 
72
+
73
+ # -*- coding: utf-8 -*-
74
+ """app
75
+
76
+ Automatically generated by Colab.
77
+
78
+ Original file is located at
79
+ https://colab.research.google.com/drive/1jdKA4WQJcLb0_aQ3vtGVM46B1wriSsDv
80
+ """
81
+
82
+ import gradio as gr
83
+ import numpy as np
84
+ from transformers import pipeline
85
+ import os
86
+ import time
87
+ import groq
88
+ import uuid # For generating unique filenames
89
+
90
+ # Updated imports to address LangChain deprecation warnings:
91
+ from langchain_groq import ChatGroq
92
+ from langchain.schema import HumanMessage
93
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
94
+ from langchain_community.vectorstores import Chroma
95
+ from langchain_community.embeddings import HuggingFaceEmbeddings
96
+ from langchain.docstore.document import Document
97
+
98
+ # Importing chardet (make sure to add chardet to your requirements.txt)
99
+ import chardet
100
+
101
+ import fitz # PyMuPDF for PDFs
102
+ import docx # python-docx for Word files
103
+ import gtts # Google Text-to-Speech library
104
+ from pptx import Presentation # python-pptx for PowerPoint files
105
+ import re
106
+
107
+
108
+ # Initialize Whisper model for speech-to-text
109
+ transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-base.en")
110
+
111
+ # Set API Key (Ensure it's stored securely in an environment variable)
112
+ groq.api_key = os.getenv("GROQ_API_KEY", "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") # Replace with a valid API key
113
+
114
+ # Initialize Chat Model
115
+ chat_model = ChatGroq(model_name="deepseek-r1-distill-qwen-32b", api_key=groq.api_key) #DeepSeek-R1-Distill-Llama-70b | deepseek-r1-distill-qwen-32b
116
+
117
+ # Initialize Embeddings and chromaDB
118
+ os.makedirs("chroma_db", exist_ok=True)
119
+ embedding_model = HuggingFaceEmbeddings()
120
+ #new
121
+ vectorstore = Chroma(
122
+ embedding_function=embedding_model,
123
+ persist_directory="chroma_db" # Set a valid folder name or path
124
+ )
125
+ vectorstore.persist()
126
+ #end New
127
+
128
+ # Short-term memory for the LLM
129
+ chat_memory = []
130
+
131
+ # Prompt for quiz generation with added remark
132
+ quiz_prompt = """
133
+ 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.
134
+ Generate 20 Questions.
135
+ 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.
136
+ For each question:
137
+ - Provide 4 answer choices (for MCQs), with only one correct answer.
138
+ - Ensure fill-in-the-blank questions focus on key terms, phrases, or concepts from the document.
139
+ - Include an answer key for all questions.
140
+ - Ensure questions vary in difficulty and encourage comprehension rather than memorization.
141
+ - Additionally, implement an instant feedback mechanism:
142
+ - When a user selects an answer, indicate whether it is correct or incorrect.
143
+ - If incorrect, provide a brief explanation from the document to guide learning.
144
+ - Ensure responses are concise and educational to enhance understanding.
145
+ Output Example:
146
+ 1. Fill in the blank: The LLM Agent framework has a central decision-making unit called the _______________________.
147
+
148
+ Answer: Agent Core
149
+
150
+ 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.
151
+
152
+ 2. What is the main limitation of LLM-based applications?
153
+ a) Limited token capacity
154
+ b) Lack of domain expertise
155
+ c) Prone to hallucination
156
+ d) All of the above
157
+
158
+ Answer: d) All of the above
159
+
160
+ Feedback: LLM-based applications have several limitations, including limited token capacity, lack of domain expertise, and being prone to hallucination, among others.
161
+ """
162
+
163
+ # Function to clean AI response by removing unwanted formatting
164
+ def clean_response(response):
165
+ """Removes <think> tags, asterisks, and markdown formatting."""
166
+ cleaned_text = re.sub(r"<think>.*?</think>", "", response, flags=re.DOTALL)
167
+ cleaned_text = re.sub(r"(\*\*|\*|\[|\])", "", cleaned_text)
168
+ cleaned_text = re.sub(r"^##+\s*", "", cleaned_text, flags=re.MULTILINE)
169
+ cleaned_text = re.sub(r"\\", "", cleaned_text)
170
+ cleaned_text = re.sub(r"---", "", cleaned_text)
171
+ return cleaned_text.strip()
172
+
173
+ # Function to generate quiz based on content
174
+ def generate_quiz(content):
175
+ prompt = f"{quiz_prompt}\n\nDocument content:\n{content}"
176
+ response = chat_model([HumanMessage(content=prompt)])
177
+ cleaned_response = clean_response(response.content)
178
+ return cleaned_response
179
+
180
+ # Function to retrieve relevant documents from vectorstore based on user query
181
+ def retrieve_documents(query):
182
+ results = vectorstore.similarity_search(query, k=3)
183
+ return [doc.page_content for doc in results]
184
+
185
+ # Function to handle chatbot interactions with short-term memory
186
+ def chat_with_groq(user_input):
187
+ try:
188
+ # Retrieve relevant documents for additional context
189
+ relevant_docs = retrieve_documents(user_input)
190
+ context = "\n".join(relevant_docs) if relevant_docs else "No relevant documents found."
191
+
192
+ # Construct proper prompting with conversation history
193
+ system_prompt = "You are a helpful AI assistant. Answer questions accurately and concisely."
194
+ conversation_history = "\n".join(chat_memory[-10:]) # Keep the last 10 exchanges
195
+ prompt = f"{system_prompt}\n\nConversation History:\n{conversation_history}\n\nUser Input: {user_input}\n\nContext:\n{context}"
196
+
197
+ # Call the chat model
198
+ response = chat_model([HumanMessage(content=prompt)])
199
+
200
+ # Clean response to remove any unwanted formatting
201
+ cleaned_response_text = clean_response(response.content)
202
+
203
+ # Append conversation history
204
+ chat_memory.append(f"User: {user_input}")
205
+ chat_memory.append(f"AI: {cleaned_response_text}")
206
+
207
+ # Convert response to speech
208
+ audio_file = speech_playback(cleaned_response_text)
209
+
210
+ # Ensure the return format is a list of tuples
211
+ return [(user_input, cleaned_response_text)], audio_file
212
+ except Exception as e:
213
+ return [("Error", str(e))], None
214
+
215
+
216
+ # Function to play response as speech using gTTS
217
+ def speech_playback(text):
218
+ try:
219
+ # Generate a unique filename for each audio file
220
+ unique_id = str(uuid.uuid4())
221
+ audio_file = f"output_audio_{unique_id}.mp3"
222
+
223
+ # Convert text to speech
224
+ tts = gtts.gTTS(text, lang='en')
225
+ tts.save(audio_file)
226
+
227
+ # Return the path to the audio file
228
+ return audio_file
229
+ except Exception as e:
230
+ print(f"Error in speech_playback: {e}")
231
+ return None
232
+
233
+ # Function to detect encoding safely
234
+ def detect_encoding(file_path):
235
+ try:
236
+ with open(file_path, "rb") as f:
237
+ raw_data = f.read(4096)
238
+ detected = chardet.detect(raw_data)
239
+ encoding = detected["encoding"]
240
+ return encoding if encoding else "utf-8"
241
+ except Exception:
242
+ return "utf-8"
243
+
244
+ # Function to extract text from PDF
245
+ def extract_text_from_pdf(pdf_path):
246
+ try:
247
+ doc = fitz.open(pdf_path)
248
+ text = "\n".join([page.get_text("text") for page in doc])
249
+ return text if text.strip() else "No extractable text found."
250
+ except Exception as e:
251
+ return f"Error extracting text from PDF: {str(e)}"
252
+
253
+ # Function to extract text from Word files (.docx)
254
+ def extract_text_from_docx(docx_path):
255
+ try:
256
+ doc = docx.Document(docx_path)
257
+ text = "\n".join([para.text for para in doc.paragraphs])
258
+ return text if text.strip() else "No extractable text found."
259
+ except Exception as e:
260
+ return f"Error extracting text from Word document: {str(e)}"
261
+
262
+ # Function to extract text from PowerPoint files (.pptx)
263
+ def extract_text_from_pptx(pptx_path):
264
+ try:
265
+ presentation = Presentation(pptx_path)
266
+ text = ""
267
+ for slide in presentation.slides:
268
+ for shape in slide.shapes:
269
+ if hasattr(shape, "text"):
270
+ text += shape.text + "\n"
271
+ return text if text.strip() else "No extractable text found."
272
+ except Exception as e:
273
+ return f"Error extracting text from PowerPoint: {str(e)}"
274
+
275
+ # Function to process documents safely
276
+ def process_document(file):
277
+ try:
278
+ file_extension = os.path.splitext(file.name)[-1].lower()
279
+ if file_extension in [".png", ".jpg", ".jpeg"]:
280
+ return "Error: Images cannot be processed for text extraction."
281
+ if file_extension == ".pdf":
282
+ content = extract_text_from_pdf(file.name)
283
+ elif file_extension == ".docx":
284
+ content = extract_text_from_docx(file.name)
285
+ elif file_extension == ".pptx":
286
+ content = extract_text_from_pptx(file.name)
287
+ else:
288
+ encoding = detect_encoding(file.name)
289
+ with open(file.name, "r", encoding=encoding, errors="replace") as f:
290
+ content = f.read()
291
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
292
+ documents = [Document(page_content=chunk) for chunk in text_splitter.split_text(content)]
293
+ vectorstore.add_documents(documents)
294
+ vectorstore.persist() # <-- Persist changes after adding documents
295
+
296
+ quiz = generate_quiz(content)
297
+ return f"Document processed successfully (File Type: {file_extension}). Quiz generated:\n{quiz}"
298
+ except Exception as e:
299
+ return f"Error processing document: {str(e)}"
300
+
301
+ # Function to handle speech-to-text conversion
302
+ def transcribe_audio(audio):
303
+ sr, y = audio
304
+ if y.ndim > 1:
305
+ y = y.mean(axis=1)
306
+ y = y.astype(np.float32)
307
+ y /= np.max(np.abs(y))
308
+ return transcriber({"sampling_rate": sr, "raw": y})["text"]
309
+
310
+ # Modify chat_with_groq function to return audio file for playback
311
+ def chat_with_groq(user_input):
312
+ try:
313
+ # Retrieve relevant documents for additional context
314
+ relevant_docs = retrieve_documents(user_input)
315
+ context = "\n".join(relevant_docs) if relevant_docs else "No relevant documents found."
316
+
317
+ # Construct proper prompting with conversation history
318
+ system_prompt = "You are a helpful AI assistant. Answer questions accurately and concisely."
319
+ conversation_history = "\n".join(chat_memory[-10:]) # Keep the last 10 exchanges
320
+ prompt = f"{system_prompt}\n\nConversation History:\n{conversation_history}\n\nUser Input: {user_input}\n\nContext:\n{context}"
321
+
322
+ # Call the chat model
323
+ response = chat_model([HumanMessage(content=prompt)])
324
+
325
+ # Clean response to remove any unwanted formatting
326
+ cleaned_response_text = clean_response(response.content)
327
+
328
+ # Append conversation history
329
+ chat_memory.append(f"User: {user_input}")
330
+ chat_memory.append(f"AI: {cleaned_response_text}")
331
+
332
+ # Convert response to speech
333
+ audio_file = speech_playback(cleaned_response_text)
334
+
335
+ # Return both chat response and audio file path
336
+ return [(user_input, cleaned_response_text)], audio_file # Return as a tuple
337
+ except Exception as e:
338
+ return [("Error", str(e))], None
339
+
340
+ #__________________________________________________________________________________________________________________________
341
+
342
+ def tutor_ai_chatbot():
343
+ """Main Gradio interface for the Tutor AI Chatbot."""
344
+ with gr.Blocks() as app:
345
+ gr.Markdown("# 📚 AI Tutor - We.(POC)")
346
+ gr.Markdown("An interactive Personal AI Tutor chatbot to help with your learning needs.")
347
+
348
+ # Chatbot Tab
349
+ with gr.Tab("AI Chatbot"):
350
+ with gr.Row():
351
+ with gr.Column(scale=3):
352
+ chatbot = gr.Chatbot(height=500) # Chatbot display area
353
+ with gr.Row():
354
+ msg = gr.Textbox(label="Ask a question", placeholder="Type your question here...")
355
+ submit = gr.Button("Send")
356
+
357
+ #with gr.Row():
358
+ with gr.Column(scale=1):
359
+ audio_input = gr.Audio(type="numpy", label="Record or Upload Audio") # Audio input for speech-to-text
360
+
361
+
362
+ with gr.Column(scale=1):
363
+ audio_playback = gr.Audio(label="Audio Response", type="filepath")
364
+
365
+ # Clear chat history button
366
+ clear_btn = gr.Button("Clear Chat")
367
+
368
+ # Handle chat interaction
369
+ submit.click(
370
+ chat_with_groq,
371
+ inputs=[msg],
372
+ outputs=[chatbot, audio_playback]
373
+ )
374
+
375
+ # Clear chat history function
376
+ def clear_chat_history():
377
+ return None, None
378
+
379
+ clear_btn.click(clear_chat_history, inputs=None, outputs=[chatbot, audio_playback]) #,audio_input
380
+
381
+ # Also allow Enter key to submit
382
+ msg.submit(
383
+ chat_with_groq,
384
+ inputs=[msg],
385
+ outputs=[chatbot, audio_playback]
386
+ )
387
+
388
+ # Add some examples of questions students might ask
389
+ with gr.Accordion("Example Questions", open=False):
390
+ gr.Examples(
391
+ examples=[
392
+ "Can you explain the concept of RLHF AI?",
393
+ "What are AI transformers?",
394
+ "What is MoE AI?",
395
+ "What's gate networks AI?",
396
+ "I am making a switch, please generating baking recipe?"
397
+ ],
398
+ inputs=msg
399
+ )
400
+
401
+ # Upload Notes & Generate Quiz Tab
402
+ with gr.Tab("Upload Notes & Generate Quiz"):
403
+ with gr.Row():
404
+ with gr.Column(scale=2):
405
+ file_input = gr.File(label="Upload Lecture Notes (PDF, DOCX, PPTX)")
406
+ #generate_btn = gr.Button("Generate Quiz")
407
+ with gr.Column(scale=3):
408
+ quiz_output = gr.Textbox(label="Generated Quiz", lines=10)
409
+
410
+
411
+ # Introduction Video
412
+ with gr.Tab("Introduction Video"):
413
+ with gr.Row():
414
+ with gr.Column(scale=1):
415
+ #with gr.Column(scale=1): # Adjust scale for equal width
416
+ gr.Markdown("### Welcome to the Introduction Video") # Adding a heading
417
+ gr.Markdown("Music from Xu Mengyuan - China-O, musician Xu Mengyuan YUAN! | 徐梦圆 - China-O 音乐人徐梦圆YUAN! ") # Adding descriptive text
418
+ gr.Video("https://github.com/lesterchia1/AI_tutor/raw/main/We%20not%20me%20video.mp4", label="Introduction Video")
419
+
420
+
421
+ # Connect the button to the document processing function
422
+ audio_input.change(fn=transcribe_audio, inputs=audio_input, outputs=msg) # transcribe and fill the msg textbox
423
+ file_input.change(process_document, inputs=file_input, outputs=quiz_output)
424
+
425
+
426
+ # Launch the application
427
+ app.launch(share=True) # Set share=True to create a public link
428
+
429
+
430
+ # Launch the AI chatbot
431
+ if __name__ == "__main__":
432
+ tutor_ai_chatbot()
433
+
434
+
435
+
436
+
437
+
438
  # Short-term memory for the LLM
439
  chat_memory = []
440