Lesterchia174 commited on
Commit
3d4be7f
·
verified ·
1 Parent(s): c8b491b

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +222 -0
  2. apt.txt +1 -0
  3. requirements.txt +20 -0
app.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """App
3
+
4
+ Automatically generated by Colab.
5
+ """
6
+
7
+ # Note: The eSpeak installation code has been removed.
8
+ # Instead, ensure that "espeak" is listed in your apt.txt file for Hugging Face Spaces.
9
+
10
+ import gradio as gr
11
+ import numpy as np
12
+ from transformers import pipeline
13
+ import os
14
+ import groq
15
+
16
+ # Updated imports to address LangChain deprecation warnings:
17
+ from langchain_groq import ChatGroq
18
+ from langchain.schema import HumanMessage
19
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
20
+ from langchain_community.vectorstores import Chroma
21
+ from langchain_community.embeddings import HuggingFaceEmbeddings
22
+ from langchain.docstore.document import Document
23
+
24
+ # Importing chardet (make sure to add chardet to your requirements.txt)
25
+ import chardet
26
+
27
+ import fitz # PyMuPDF for PDFs
28
+ import docx # python-docx for Word files
29
+ import gtts # Google Text-to-Speech library
30
+ from pptx import Presentation # python-pptx for PowerPoint files
31
+ import re
32
+
33
+ # Initialize Whisper model for speech-to-text
34
+ transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-base.en")
35
+
36
+ # Set API Key (Ensure it's stored securely in an environment variable)
37
+ groq.api_key = os.getenv("GROQ_API_KEY") # Replace with a valid API key
38
+
39
+ # Initialize Chat Model
40
+ chat_model = ChatGroq(model_name="DeepSeek-R1-Distill-Llama-70b", api_key=groq.api_key)
41
+
42
+ # Initialize Embeddings
43
+ embedding_model = HuggingFaceEmbeddings()
44
+
45
+ # Initialize ChromaDB
46
+ vectorstore = Chroma(embedding_function=embedding_model)
47
+
48
+ # Prompt for quiz generation with added remark
49
+ quiz_prompt = """
50
+ 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.
51
+ 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.
52
+
53
+ For each question:
54
+
55
+ - Provide 4 answer choices (for MCQs), with only one correct answer.
56
+ - Ensure fill-in-the-blank questions focus on key terms, phrases, or concepts from the document.
57
+ - Include an answer key for all questions.
58
+ - Ensure questions vary in difficulty and encourage comprehension rather than memorization.
59
+ - Additionally, implement an instant feedback mechanism:
60
+ - When a user selects an answer, indicate whether it is correct or incorrect.
61
+ - If incorrect, provide a brief explanation from the document to guide learning.
62
+ - Ensure responses are concise and educational to enhance understanding.
63
+
64
+ Output Example:
65
+ 1. Fill in the blank: The LLM Agent framework has a central decision-making unit called the _______________________.
66
+
67
+ Answer: Agent Core
68
+
69
+ 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.
70
+
71
+ 2. What is the main limitation of LLM-based applications?
72
+ a) Limited token capacity
73
+ b) Lack of domain expertise
74
+ c) Prone to hallucination
75
+ d) All of the above
76
+
77
+ Answer: d) All of the above
78
+
79
+ Feedback: LLM-based applications have several limitations, including limited token capacity, lack of domain expertise, and being prone to hallucination, among others.
80
+ """
81
+
82
+ # Function to clean AI response by removing unwanted formatting
83
+ def clean_response(response):
84
+ """Removes <think> tags, asterisks, and markdown formatting."""
85
+ cleaned_text = re.sub(r"<think>.*?</think>", "", response, flags=re.DOTALL)
86
+ cleaned_text = re.sub(r"(\*\*|\*)", "", cleaned_text)
87
+ cleaned_text = re.sub(r"^#+\s*", "", cleaned_text, flags=re.MULTILINE)
88
+ return cleaned_text.strip()
89
+
90
+ # Function to generate quiz based on content
91
+ def generate_quiz(content):
92
+ prompt = f"{quiz_prompt}\n\nDocument content:\n{content}"
93
+ response = chat_model([HumanMessage(content=prompt)])
94
+ cleaned_response = clean_response(response.content)
95
+ return cleaned_response
96
+
97
+ # Function to retrieve relevant documents from vectorstore based on user query
98
+ def retrieve_documents(query):
99
+ results = vectorstore.similarity_search(query, k=3)
100
+ return [doc.page_content for doc in results]
101
+
102
+ # Function to handle chatbot interactions
103
+ def chat_with_groq(user_input):
104
+ try:
105
+ relevant_docs = retrieve_documents(user_input)
106
+ context = "\n".join(relevant_docs)
107
+ response = chat_model([HumanMessage(content=user_input + "\n\nContext:\n" + context)])
108
+ cleaned_response_text = clean_response(response.content)
109
+ audio_file = speech_playback(cleaned_response_text)
110
+ return cleaned_response_text, audio_file
111
+ except Exception as e:
112
+ return f"Error: {str(e)}", None
113
+
114
+ # Function to play response as speech using gTTS
115
+ def speech_playback(text):
116
+ tts = gtts.gTTS(text, lang='en')
117
+ audio_file = "output_audio.mp3"
118
+ tts.save(audio_file)
119
+ return audio_file
120
+
121
+ # Function to detect encoding safely
122
+ def detect_encoding(file_path):
123
+ try:
124
+ with open(file_path, "rb") as f:
125
+ raw_data = f.read(4096)
126
+ detected = chardet.detect(raw_data)
127
+ encoding = detected["encoding"]
128
+ return encoding if encoding else "utf-8"
129
+ except Exception:
130
+ return "utf-8"
131
+
132
+ # Function to extract text from PDF
133
+ def extract_text_from_pdf(pdf_path):
134
+ try:
135
+ doc = fitz.open(pdf_path)
136
+ text = "\n".join([page.get_text("text") for page in doc])
137
+ return text if text.strip() else "No extractable text found."
138
+ except Exception as e:
139
+ return f"Error extracting text from PDF: {str(e)}"
140
+
141
+ # Function to extract text from Word files (.docx)
142
+ def extract_text_from_docx(docx_path):
143
+ try:
144
+ doc = docx.Document(docx_path)
145
+ text = "\n".join([para.text for para in doc.paragraphs])
146
+ return text if text.strip() else "No extractable text found."
147
+ except Exception as e:
148
+ return f"Error extracting text from Word document: {str(e)}"
149
+
150
+ # Function to extract text from PowerPoint files (.pptx)
151
+ def extract_text_from_pptx(pptx_path):
152
+ try:
153
+ presentation = Presentation(pptx_path)
154
+ text = ""
155
+ for slide in presentation.slides:
156
+ for shape in slide.shapes:
157
+ if hasattr(shape, "text"):
158
+ text += shape.text + "\n"
159
+ return text if text.strip() else "No extractable text found."
160
+ except Exception as e:
161
+ return f"Error extracting text from PowerPoint: {str(e)}"
162
+
163
+ # Function to process documents safely
164
+ def process_document(file):
165
+ try:
166
+ file_extension = os.path.splitext(file.name)[-1].lower()
167
+ if file_extension in [".png", ".jpg", ".jpeg"]:
168
+ return "Error: Images cannot be processed for text extraction."
169
+ if file_extension == ".pdf":
170
+ content = extract_text_from_pdf(file.name)
171
+ elif file_extension == ".docx":
172
+ content = extract_text_from_docx(file.name)
173
+ elif file_extension == ".pptx":
174
+ content = extract_text_from_pptx(file.name)
175
+ else:
176
+ encoding = detect_encoding(file.name)
177
+ with open(file.name, "r", encoding=encoding, errors="replace") as f:
178
+ content = f.read()
179
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
180
+ documents = [Document(page_content=chunk) for chunk in text_splitter.split_text(content)]
181
+ vectorstore.add_documents(documents)
182
+ quiz = generate_quiz(content)
183
+ return f"Document processed successfully (File Type: {file_extension}). Quiz generated:\n{quiz}"
184
+ except Exception as e:
185
+ return f"Error processing document: {str(e)}"
186
+
187
+ # Function to handle speech-to-text conversion
188
+ def transcribe_audio(audio):
189
+ sr, y = audio
190
+ if y.ndim > 1:
191
+ y = y.mean(axis=1)
192
+ y = y.astype(np.float32)
193
+ y /= np.max(np.abs(y))
194
+ return transcriber({"sampling_rate": sr, "raw": y})["text"]
195
+
196
+ # Gradio UI
197
+ with gr.Blocks() as demo:
198
+ gr.HTML("<h2 style='text-align: center;'>AI Tutor</h2>")
199
+ gr.HTML("""
200
+ <div style="text-align: center; margin-bottom: 20px;">
201
+ <img src="https://img.freepik.com/premium-photo/little-girl-is-seen-sitting-front-laptop-computer-engaged-with-nearby-robot-robot-assistant-helping-child-with-homework-ai-generated_585735-12266.jpg" style="max-width: 60%; height: auto; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.2);" />
202
+ </div>
203
+ """)
204
+ with gr.Row():
205
+ with gr.Column():
206
+ audio_input = gr.Audio(type="numpy", label="Record Audio")
207
+ transcription_output = gr.Textbox(label="Transcription")
208
+ user_input = gr.Textbox(label="Ask a question")
209
+ chat_output = gr.Textbox(label="Response")
210
+ audio_output = gr.Audio(label="Audio Playback")
211
+ submit_btn = gr.Button("Ask")
212
+ with gr.Column():
213
+ file_upload = gr.File(label="Upload a document")
214
+ process_status = gr.Textbox(label="Processing Status", interactive=False)
215
+ process_btn = gr.Button("Process Document")
216
+ audio_input.change(fn=transcribe_audio, inputs=audio_input, outputs=transcription_output)
217
+ transcription_output.change(fn=lambda x: x, inputs=transcription_output, outputs=user_input)
218
+ submit_btn.click(chat_with_groq, inputs=user_input, outputs=[chat_output, audio_output])
219
+ process_btn.click(process_document, inputs=file_upload, outputs=process_status)
220
+
221
+ # Launch the Gradio app
222
+ demo.launch()
apt.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ espeak
requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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