Lesterchia174 commited on
Commit
0ff6f8a
·
verified ·
1 Parent(s): c373a8e

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +376 -0
  2. apt.txt +1 -0
  3. requirements.txt +27 -0
app.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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") # Replace with a valid API key
40
+
41
+ #___________________________________
42
+
43
+ # Authenticate with Hugging Face API using the token
44
+ #hf_token = os.getenv("HF_TOKEN") # Replace with the environment variable containing your Hugging Face token
45
+ #login(token=hf_token)
46
+
47
+ # Load the LLaVA model
48
+ #model_id = "liuhaotian/LLaVA-7B" # You can change the model ID based on what is available
49
+ #processor = AutoProcessor.from_pretrained(model_id)
50
+ #model = AutoModelForVision2Seq.from_pretrained(model_id, torch_dtype=torch.float16).cuda()
51
+
52
+ # Load and preprocess an image
53
+ #image = Image.open("your_image.jpg") # Replace with the path to your image
54
+ #inputs = processor(text="Describe this image", images=image, return_tensors="pt").to("cuda")
55
+
56
+ # Generate output from LLaVA model
57
+ #output = model.generate(**inputs)
58
+
59
+ # Decode and print the output
60
+ #print(processor.decode(output[0]))
61
+
62
+ #___________________________________
63
+
64
+ # Initialize Chat Model
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
+
74
+ # Prompt for quiz generation with added remark
75
+ quiz_prompt = """
76
+ 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.
77
+ Generate 20 Questions.
78
+ 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.
79
+ For each question:
80
+ - Provide 4 answer choices (for MCQs), with only one correct answer.
81
+ - Ensure fill-in-the-blank questions focus on key terms, phrases, or concepts from the document.
82
+ - Include an answer key for all questions.
83
+ - Ensure questions vary in difficulty and encourage comprehension rather than memorization.
84
+ - Additionally, implement an instant feedback mechanism:
85
+ - When a user selects an answer, indicate whether it is correct or incorrect.
86
+ - If incorrect, provide a brief explanation from the document to guide learning.
87
+ - Ensure responses are concise and educational to enhance understanding.
88
+ Output Example:
89
+ 1. Fill in the blank: The LLM Agent framework has a central decision-making unit called the _______________________.
90
+ Answer: Agent Core
91
+ 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.
92
+ 2. What is the main limitation of LLM-based applications?
93
+ a) Limited token capacity
94
+ b) Lack of domain expertise
95
+ c) Prone to hallucination
96
+ d) All of the above
97
+ Answer: d) All of the above
98
+ Feedback: LLM-based applications have several limitations, including limited token capacity, lack of domain expertise, and being prone to hallucination, among others.
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 handle chatbot interactions with short-term memory
124
+ def chat_with_groq(user_input):
125
+ try:
126
+ # Retrieve relevant documents for additional context
127
+ relevant_docs = retrieve_documents(user_input)
128
+ context = "\n".join(relevant_docs) if relevant_docs else "No relevant documents found."
129
+
130
+ # Construct proper prompting with conversation history
131
+ system_prompt = "You are a helpful AI assistant. Answer questions accurately and concisely."
132
+ conversation_history = "\n".join(chat_memory[-10:]) # Keep the last 10 exchanges
133
+ prompt = f"{system_prompt}\n\nConversation History:\n{conversation_history}\n\nUser Input: {user_input}\n\nContext:\n{context}"
134
+
135
+ # Call the chat model
136
+ response = chat_model([HumanMessage(content=prompt)])
137
+
138
+ # Clean response to remove any unwanted formatting
139
+ cleaned_response_text = clean_response(response.content)
140
+
141
+ # Append conversation history
142
+ chat_memory.append(f"User: {user_input}")
143
+ chat_memory.append(f"AI: {cleaned_response_text}")
144
+
145
+ # Convert response to speech
146
+ audio_file = speech_playback(cleaned_response_text)
147
+
148
+ # Ensure the return format is a list of tuples
149
+ return [(user_input, cleaned_response_text)], audio_file
150
+ except Exception as e:
151
+ return [("Error", str(e))], None
152
+
153
+
154
+ # Function to play response as speech using gTTS
155
+ def speech_playback(text):
156
+ try:
157
+ # Generate a unique filename for each audio file
158
+ unique_id = str(uuid.uuid4())
159
+ audio_file = f"output_audio_{unique_id}.mp3"
160
+
161
+ # Convert text to speech
162
+ tts = gtts.gTTS(text, lang='en')
163
+ tts.save(audio_file)
164
+
165
+ # Return the path to the audio file
166
+ return audio_file
167
+ except Exception as e:
168
+ print(f"Error in speech_playback: {e}")
169
+ return None
170
+
171
+ # Function to detect encoding safely
172
+ def detect_encoding(file_path):
173
+ try:
174
+ with open(file_path, "rb") as f:
175
+ raw_data = f.read(4096)
176
+ detected = chardet.detect(raw_data)
177
+ encoding = detected["encoding"]
178
+ return encoding if encoding else "utf-8"
179
+ except Exception:
180
+ return "utf-8"
181
+
182
+ # Function to extract text from PDF
183
+ def extract_text_from_pdf(pdf_path):
184
+ try:
185
+ doc = fitz.open(pdf_path)
186
+ text = "\n".join([page.get_text("text") for page in doc])
187
+ return text if text.strip() else "No extractable text found."
188
+ except Exception as e:
189
+ return f"Error extracting text from PDF: {str(e)}"
190
+
191
+ # Function to extract text from Word files (.docx)
192
+ def extract_text_from_docx(docx_path):
193
+ try:
194
+ doc = docx.Document(docx_path)
195
+ text = "\n".join([para.text for para in doc.paragraphs])
196
+ return text if text.strip() else "No extractable text found."
197
+ except Exception as e:
198
+ return f"Error extracting text from Word document: {str(e)}"
199
+
200
+ # Function to extract text from PowerPoint files (.pptx)
201
+ def extract_text_from_pptx(pptx_path):
202
+ try:
203
+ presentation = Presentation(pptx_path)
204
+ text = ""
205
+ for slide in presentation.slides:
206
+ for shape in slide.shapes:
207
+ if hasattr(shape, "text"):
208
+ text += shape.text + "\n"
209
+ return text if text.strip() else "No extractable text found."
210
+ except Exception as e:
211
+ return f"Error extracting text from PowerPoint: {str(e)}"
212
+
213
+ # Function to process documents safely
214
+ def process_document(file):
215
+ try:
216
+ file_extension = os.path.splitext(file.name)[-1].lower()
217
+ if file_extension in [".png", ".jpg", ".jpeg"]:
218
+ return "Error: Images cannot be processed for text extraction."
219
+ if file_extension == ".pdf":
220
+ content = extract_text_from_pdf(file.name)
221
+ elif file_extension == ".docx":
222
+ content = extract_text_from_docx(file.name)
223
+ elif file_extension == ".pptx":
224
+ content = extract_text_from_pptx(file.name)
225
+ else:
226
+ encoding = detect_encoding(file.name)
227
+ with open(file.name, "r", encoding=encoding, errors="replace") as f:
228
+ content = f.read()
229
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
230
+ documents = [Document(page_content=chunk) for chunk in text_splitter.split_text(content)]
231
+ vectorstore.add_documents(documents)
232
+ quiz = generate_quiz(content)
233
+ return f"Document processed successfully (File Type: {file_extension}). Quiz generated:\n{quiz}"
234
+ except Exception as e:
235
+ return f"Error processing document: {str(e)}"
236
+
237
+ # Function to handle speech-to-text conversion
238
+ def transcribe_audio(audio):
239
+ sr, y = audio
240
+ if y.ndim > 1:
241
+ y = y.mean(axis=1)
242
+ y = y.astype(np.float32)
243
+ y /= np.max(np.abs(y))
244
+ return transcriber({"sampling_rate": sr, "raw": y})["text"]
245
+
246
+ # Modify chat_with_groq function to return audio file for playback
247
+ def chat_with_groq(user_input):
248
+ try:
249
+ # Retrieve relevant documents for additional context
250
+ relevant_docs = retrieve_documents(user_input)
251
+ context = "\n".join(relevant_docs) if relevant_docs else "No relevant documents found."
252
+
253
+ # Construct proper prompting with conversation history
254
+ system_prompt = "You are a helpful AI assistant. Answer questions accurately and concisely."
255
+ conversation_history = "\n".join(chat_memory[-10:]) # Keep the last 10 exchanges
256
+ prompt = f"{system_prompt}\n\nConversation History:\n{conversation_history}\n\nUser Input: {user_input}\n\nContext:\n{context}"
257
+
258
+ # Call the chat model
259
+ response = chat_model([HumanMessage(content=prompt)])
260
+
261
+ # Clean response to remove any unwanted formatting
262
+ cleaned_response_text = clean_response(response.content)
263
+
264
+ # Append conversation history
265
+ chat_memory.append(f"User: {user_input}")
266
+ chat_memory.append(f"AI: {cleaned_response_text}")
267
+
268
+ # Convert response to speech
269
+ audio_file = speech_playback(cleaned_response_text)
270
+
271
+ # Return both chat response and audio file path
272
+ return [(user_input, cleaned_response_text)], audio_file # Return as a tuple
273
+ except Exception as e:
274
+ return [("Error", str(e))], None
275
+
276
+ #__________________________________________________________________________________________________________________________
277
+
278
+
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) # Chatbot display area
291
+ with gr.Row():
292
+ msg = gr.Textbox(label="Ask a question", placeholder="Type your question here...")
293
+ submit = gr.Button("Send")
294
+ # Create the chat interface
295
+ #msg = gr.ChatInterface(fn=chat_with_groq, type="messages", autofocus=False) #test
296
+
297
+ #with gr.Row():
298
+ with gr.Column(scale=1):
299
+ audio_input = gr.Audio(type="numpy", label="Record or Upload Audio") # Audio input for speech-to-text
300
+
301
+
302
+ with gr.Column(scale=1):
303
+ audio_playback = gr.Audio(label="Audio Response", type="filepath")
304
+
305
+ # Clear chat history button
306
+ clear_btn = gr.Button("Clear Chat")
307
+
308
+ # Handle chat interaction
309
+ submit.click(
310
+ chat_with_groq,
311
+ inputs=[msg],
312
+ outputs=[chatbot, audio_playback]
313
+ )
314
+
315
+ # Clear chat history function
316
+ def clear_chat_history():
317
+ return None, None
318
+
319
+ clear_btn.click(clear_chat_history, inputs=None, outputs=[chatbot, audio_playback]) #,audio_input
320
+
321
+ # Also allow Enter key to submit
322
+ msg.submit(
323
+ chat_with_groq,
324
+ inputs=[msg],
325
+ outputs=[chatbot, audio_playback]
326
+ )
327
+
328
+ # Add some examples of questions students might ask
329
+ with gr.Accordion("Example Questions", open=False):
330
+ gr.Examples(
331
+ examples=[
332
+ "Can you explain the concept of RLHF AI?",
333
+ "What are AI transformers?",
334
+ "What is MoE AI?",
335
+ "What's gate networks AI?",
336
+ "I am making a switch, please generating baking recipe?"
337
+ ],
338
+ inputs=msg
339
+ )
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
+ #generate_btn = gr.Button("Generate Quiz")
347
+ with gr.Column(scale=3):
348
+ quiz_output = gr.Textbox(label="Generated Quiz", lines=10)
349
+
350
+
351
+ # Introduction Video
352
+ with gr.Tab("Introduction Video"):
353
+ with gr.Row():
354
+ with gr.Column(scale=1):
355
+ #with gr.Column(scale=1): # Adjust scale for equal width
356
+ gr.Markdown("### Welcome to the Introduction Video") # Adding a heading
357
+ gr.Markdown("Music from Xu Mengyuan - China-O, musician Xu Mengyuan YUAN! | 徐梦圆 - China-O 音乐人徐梦圆YUAN! ") # Adding descriptive text
358
+ gr.Video("https://github.com/lesterchia1/AI_tutor/raw/main/We%20not%20me%20video.mp4", label="Introduction Video")
359
+
360
+
361
+
362
+ # Connect the button to the document processing function
363
+ audio_input.change(fn=transcribe_audio, inputs=audio_input, outputs=msg) # transcribe and fill the msg textbox
364
+ file_input.change(process_document, inputs=file_input, outputs=quiz_output)
365
+
366
+
367
+ # Launch the application
368
+ app.launch(share=True) # Set share=True to create a public link
369
+
370
+ # Add cleanup function to be triggered periodically (e.g., every time a button is clicked or after certain actions)
371
+ #demo.load(lambda: cleanup_old_files(directory="./", age_limit=60), inputs=[], outputs=[])
372
+
373
+
374
+ # Launch the AI chatbot
375
+ if __name__ == "__main__":
376
+ tutor_ai_chatbot()
apt.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ espeak
requirements.txt ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ groq
3
+ gtts
4
+ langchain
5
+ langchain-core
6
+ langchain-community
7
+ langchain-text-splitters
8
+ langgraph
9
+ chromadb
10
+ langsmith
11
+ llama-cpp-python
12
+ langchain_huggingface
13
+ pymupdf
14
+ sentence_transformers
15
+ langchain-groq
16
+ langchain-docling
17
+ langchain-chroma
18
+ pyttsx3
19
+ chardet
20
+ torchaudio
21
+ numpy
22
+ transformers
23
+ uuid
24
+ pymupdf # for fitz (PyMuPDF)
25
+ python-docx # for docx
26
+ gtts
27
+ python-pptx