Spaces:
Sleeping
Sleeping
Chia Woon Yap
commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,597 +16,539 @@ import time
|
|
| 16 |
import groq
|
| 17 |
import uuid # For generating unique filenames
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
from
|
| 22 |
-
from
|
| 23 |
-
from
|
| 24 |
-
from langchain_community.
|
| 25 |
-
from
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
import chardet
|
| 29 |
-
|
| 30 |
import fitz # PyMuPDF for PDFs
|
| 31 |
import docx # python-docx for Word files
|
| 32 |
import gtts # Google Text-to-Speech library
|
| 33 |
from pptx import Presentation # python-pptx for PowerPoint files
|
| 34 |
import re
|
| 35 |
|
| 36 |
-
|
| 37 |
-
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
|
| 38 |
-
from fastapi.responses import JSONResponse, FileResponse
|
| 39 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 40 |
-
import uvicorn
|
| 41 |
-
from typing import Optional
|
| 42 |
-
import io
|
| 43 |
-
import soundfile as sf
|
| 44 |
-
import librosa
|
| 45 |
|
| 46 |
-
#
|
| 47 |
try:
|
| 48 |
transcriber = pipeline(
|
| 49 |
-
"automatic-speech-recognition",
|
| 50 |
-
model="openai/whisper-
|
| 51 |
-
device=-1, # Use CPU (-1) or GPU (0)
|
| 52 |
-
chunk_length_s=30,
|
| 53 |
-
stride_length_s=5,
|
| 54 |
-
batch_size=8
|
| 55 |
)
|
|
|
|
| 56 |
except Exception as e:
|
| 57 |
-
print(f"
|
| 58 |
-
|
| 59 |
-
transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-base.en")
|
| 60 |
-
|
| 61 |
-
# Set API Key (Ensure it's stored securely in an environment variable)
|
| 62 |
-
groq.api_key = os.getenv("GROQ_API_KEY")
|
| 63 |
|
| 64 |
-
# Initialize
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
# Initialize
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
#
|
| 76 |
chat_memory = []
|
| 77 |
|
| 78 |
-
#
|
| 79 |
-
AUDIO_SAMPLE_RATE = 16000 # Whisper works best with 16kHz
|
| 80 |
-
|
| 81 |
-
# Prompt for quiz generation with added remark
|
| 82 |
quiz_prompt = """
|
| 83 |
-
You are an AI assistant specialized in education
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
- If incorrect, provide a brief explanation from the document to guide learning.
|
| 97 |
-
- Ensure responses are concise and educational to enhance understanding.
|
| 98 |
-
|
| 99 |
-
Output Example:
|
| 100 |
-
1. Fill in the blank: The LLM Agent framework has a central decision-making unit called the _______________________.
|
| 101 |
-
|
| 102 |
-
Answer: Agent Core
|
| 103 |
-
|
| 104 |
-
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.
|
| 105 |
-
|
| 106 |
-
2. What is the main limitation of LLM-based applications?
|
| 107 |
-
a) Limited token capacity
|
| 108 |
-
b) Lack of domain expertise
|
| 109 |
-
c) Prone to hallucination
|
| 110 |
-
d) All of the above
|
| 111 |
-
|
| 112 |
-
Answer: d) All of the above
|
| 113 |
-
|
| 114 |
-
Feedback: LLM-based applications have several limitations, including limited token capacity, lack of domain expertise, and being prone to hallucination, among others.
|
| 115 |
-
|
| 116 |
-
3. Given the following info, what is the value of P(jam|Rain)?
|
| 117 |
-
P(no Rain) = 0.8;
|
| 118 |
-
P(no Jam) = 0.2;
|
| 119 |
-
P(Rain|Jam) = 0.1
|
| 120 |
-
|
| 121 |
-
a) 0.016
|
| 122 |
-
b) 0.025
|
| 123 |
-
c) 0.1
|
| 124 |
-
d) 0.4
|
| 125 |
-
|
| 126 |
-
Answer: d) 0.4
|
| 127 |
-
|
| 128 |
-
Feedback: This question tests understanding of Bayes' Theorem by requiring the calculation of conditional probability using the given values.
|
| 129 |
"""
|
| 130 |
|
| 131 |
-
# Function to clean AI response by removing unwanted formatting
|
| 132 |
def clean_response(response):
|
| 133 |
-
"""
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
return
|
| 140 |
|
| 141 |
-
# Function to generate quiz based on content
|
| 142 |
def generate_quiz(content):
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
-
# Function to retrieve relevant documents from vectorstore based on user query
|
| 149 |
def retrieve_documents(query):
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
return message_format
|
| 161 |
-
|
| 162 |
-
# Function to convert message format to tuple format for processing
|
| 163 |
-
def convert_to_tuple_format(chat_history):
|
| 164 |
-
"""Convert from message format back to tuple format for processing"""
|
| 165 |
-
tuple_format = []
|
| 166 |
-
for i in range(0, len(chat_history), 2):
|
| 167 |
-
if i+1 < len(chat_history):
|
| 168 |
-
user_msg = chat_history[i]["content"]
|
| 169 |
-
bot_msg = chat_history[i+1]["content"]
|
| 170 |
-
tuple_format.append((user_msg, bot_msg))
|
| 171 |
-
return tuple_format
|
| 172 |
|
| 173 |
-
# Function to handle chatbot interactions with short-term memory
|
| 174 |
def chat_with_groq(user_input, chat_history):
|
|
|
|
| 175 |
try:
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
system_prompt = "You are a helpful AI assistant. Answer questions accurately and concisely."
|
| 185 |
-
conversation_history = "\n".join(chat_memory[-10:]) # Keep the last 10 exchanges
|
| 186 |
-
prompt = f"{system_prompt}\n\nConversation History:\n{conversation_history}\n\nUser Input: {user_input}\n\nContext:\n{context}"
|
| 187 |
|
| 188 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
response = chat_model([HumanMessage(content=prompt)])
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
# Append conversation history
|
| 195 |
-
chat_memory.append(f"User: {user_input}")
|
| 196 |
-
chat_memory.append(f"AI: {cleaned_response_text}")
|
| 197 |
-
|
| 198 |
-
# Update chat history - add new messages in the correct format
|
| 199 |
chat_history.append({"role": "user", "content": user_input})
|
| 200 |
-
chat_history.append({"role": "assistant", "content":
|
| 201 |
-
|
| 202 |
-
#
|
| 203 |
-
audio_file = speech_playback(
|
| 204 |
-
|
| 205 |
return chat_history, "", audio_file
|
|
|
|
| 206 |
except Exception as e:
|
| 207 |
-
error_msg = f"Error: {str(e)}"
|
| 208 |
chat_history.append({"role": "user", "content": user_input})
|
| 209 |
chat_history.append({"role": "assistant", "content": error_msg})
|
| 210 |
return chat_history, "", None
|
| 211 |
|
| 212 |
-
# Function to play response as speech using gTTS
|
| 213 |
def speech_playback(text):
|
|
|
|
| 214 |
try:
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
tts.save(audio_file)
|
| 222 |
-
|
| 223 |
-
# Return the path to the audio file
|
| 224 |
return audio_file
|
| 225 |
except Exception as e:
|
| 226 |
-
print(f"
|
| 227 |
return None
|
| 228 |
|
| 229 |
-
# Function to detect encoding safely
|
| 230 |
def detect_encoding(file_path):
|
|
|
|
| 231 |
try:
|
| 232 |
with open(file_path, "rb") as f:
|
| 233 |
raw_data = f.read(4096)
|
| 234 |
detected = chardet.detect(raw_data)
|
| 235 |
-
|
| 236 |
-
return encoding if encoding else "utf-8"
|
| 237 |
except Exception:
|
| 238 |
return "utf-8"
|
| 239 |
|
| 240 |
-
# Function to extract text from PDF
|
| 241 |
def extract_text_from_pdf(pdf_path):
|
|
|
|
| 242 |
try:
|
| 243 |
doc = fitz.open(pdf_path)
|
| 244 |
-
text = "
|
| 245 |
-
|
|
|
|
|
|
|
| 246 |
except Exception as e:
|
| 247 |
-
return f"
|
| 248 |
|
| 249 |
-
# Function to extract text from Word files (.docx)
|
| 250 |
def extract_text_from_docx(docx_path):
|
|
|
|
| 251 |
try:
|
| 252 |
doc = docx.Document(docx_path)
|
| 253 |
-
text = "\n".join([para.text for para in doc.paragraphs])
|
| 254 |
-
return text if text.strip() else "No
|
| 255 |
except Exception as e:
|
| 256 |
-
return f"
|
| 257 |
|
| 258 |
-
# Function to extract text from PowerPoint files (.pptx)
|
| 259 |
def extract_text_from_pptx(pptx_path):
|
|
|
|
| 260 |
try:
|
| 261 |
-
|
| 262 |
text = ""
|
| 263 |
-
for slide in
|
| 264 |
for shape in slide.shapes:
|
| 265 |
-
if hasattr(shape, "text"):
|
| 266 |
text += shape.text + "\n"
|
| 267 |
-
return text if text.strip() else "No
|
| 268 |
except Exception as e:
|
| 269 |
-
return f"
|
| 270 |
|
| 271 |
-
# Function to process documents safely
|
| 272 |
def process_document(file):
|
|
|
|
| 273 |
try:
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
content = f.read()
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
vectorstore.add_documents(documents)
|
| 290 |
-
|
| 291 |
-
quiz = generate_quiz(content)
|
| 292 |
-
return f"Document processed successfully (File Type: {file_extension}). Quiz generated:\n{quiz}"
|
| 293 |
-
except Exception as e:
|
| 294 |
-
return f"Error processing document: {str(e)}"
|
| 295 |
-
|
| 296 |
-
# Enhanced function to handle speech-to-text conversion with audio preprocessing
|
| 297 |
-
def preprocess_audio(audio_data, sample_rate):
|
| 298 |
-
"""
|
| 299 |
-
Enhanced audio preprocessing for better STT accuracy
|
| 300 |
-
"""
|
| 301 |
-
try:
|
| 302 |
-
# Convert to mono if stereo
|
| 303 |
-
if audio_data.ndim > 1:
|
| 304 |
-
audio_data = np.mean(audio_data, axis=1)
|
| 305 |
|
| 306 |
-
|
| 307 |
-
|
| 308 |
|
| 309 |
-
#
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
-
#
|
| 315 |
-
|
| 316 |
-
audio_data = librosa.resample(audio_data, orig_sr=sample_rate, target_sr=AUDIO_SAMPLE_RATE)
|
| 317 |
-
sample_rate = AUDIO_SAMPLE_RATE
|
| 318 |
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
-
return audio_data, sample_rate
|
| 327 |
-
|
| 328 |
except Exception as e:
|
| 329 |
-
|
| 330 |
-
# Return original audio if preprocessing fails
|
| 331 |
-
return audio_data, sample_rate
|
| 332 |
|
| 333 |
def transcribe_audio(audio):
|
| 334 |
-
"""
|
| 335 |
-
Enhanced speech-to-text transcription with better error handling and preprocessing
|
| 336 |
-
"""
|
| 337 |
try:
|
| 338 |
if audio is None:
|
| 339 |
-
return "No audio
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
sample_rate, audio_data = audio
|
| 342 |
|
| 343 |
-
#
|
| 344 |
-
audio_data
|
| 345 |
-
|
| 346 |
-
# Ensure audio is not too short
|
| 347 |
-
if len(audio_data) / sample_rate < 0.5: # Less than 0.5 seconds
|
| 348 |
-
return "Audio too short. Please record at least 1 second of audio."
|
| 349 |
-
|
| 350 |
-
# Ensure audio is not too long (to prevent timeouts)
|
| 351 |
-
max_duration = 30 # seconds
|
| 352 |
-
if len(audio_data) / sample_rate > max_duration:
|
| 353 |
-
# Truncate audio
|
| 354 |
-
max_samples = max_duration * sample_rate
|
| 355 |
-
audio_data = audio_data[:max_samples]
|
| 356 |
-
|
| 357 |
-
# Use Whisper with better configuration
|
| 358 |
-
result = transcriber({
|
| 359 |
-
"sampling_rate": sample_rate,
|
| 360 |
-
"raw": audio_data
|
| 361 |
-
})
|
| 362 |
-
|
| 363 |
-
transcription = result["text"].strip()
|
| 364 |
-
|
| 365 |
-
if not transcription:
|
| 366 |
-
return "No speech detected. Please try again with clearer audio."
|
| 367 |
-
|
| 368 |
-
return transcription
|
| 369 |
|
| 370 |
-
|
| 371 |
-
error_msg = f"Transcription error: {str(e)}"
|
| 372 |
-
print(error_msg)
|
| 373 |
-
return f"Sorry, I couldn't process the audio. Please try again. Error: {str(e)}"
|
| 374 |
-
|
| 375 |
-
# FastAPI Application
|
| 376 |
-
app = FastAPI(title="Tutor AI API", description="Enhanced Speech-to-Text Tutor AI API")
|
| 377 |
-
|
| 378 |
-
# CORS middleware
|
| 379 |
-
app.add_middleware(
|
| 380 |
-
CORSMiddleware,
|
| 381 |
-
allow_origins=["*"],
|
| 382 |
-
allow_credentials=True,
|
| 383 |
-
allow_methods=["*"],
|
| 384 |
-
allow_headers=["*"],
|
| 385 |
-
)
|
| 386 |
-
|
| 387 |
-
# FastAPI Routes
|
| 388 |
-
@app.get("/")
|
| 389 |
-
async def root():
|
| 390 |
-
return {"message": "Tutor AI API is running", "version": "1.0"}
|
| 391 |
-
|
| 392 |
-
@app.post("/api/transcribe")
|
| 393 |
-
async def api_transcribe_audio(file: UploadFile = File(...)):
|
| 394 |
-
"""
|
| 395 |
-
Enhanced API endpoint for speech-to-text transcription
|
| 396 |
-
"""
|
| 397 |
-
try:
|
| 398 |
-
# Check if file is audio
|
| 399 |
-
if not file.content_type.startswith('audio/'):
|
| 400 |
-
raise HTTPException(status_code=400, detail="File must be an audio file")
|
| 401 |
|
| 402 |
-
#
|
| 403 |
-
|
|
|
|
|
|
|
| 404 |
|
| 405 |
-
#
|
| 406 |
-
|
| 407 |
-
|
|
|
|
|
|
|
|
|
|
| 408 |
|
| 409 |
# Transcribe
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
return JSONResponse({
|
| 413 |
-
"success": True,
|
| 414 |
-
"transcription": transcription,
|
| 415 |
-
"audio_duration": len(audio_data) / sample_rate if audio_data is not None else 0
|
| 416 |
-
})
|
| 417 |
-
|
| 418 |
-
except Exception as e:
|
| 419 |
-
return JSONResponse({
|
| 420 |
-
"success": False,
|
| 421 |
-
"error": str(e)
|
| 422 |
-
}, status_code=500)
|
| 423 |
-
|
| 424 |
-
@app.post("/api/chat")
|
| 425 |
-
async def api_chat(message: str = Form(...)):
|
| 426 |
-
"""
|
| 427 |
-
API endpoint for chat interactions
|
| 428 |
-
"""
|
| 429 |
-
try:
|
| 430 |
-
# Simple chat response without memory for API
|
| 431 |
-
prompt = f"You are a helpful AI tutor. Answer the following question accurately and concisely: {message}"
|
| 432 |
-
response = chat_model([HumanMessage(content=prompt)])
|
| 433 |
-
cleaned_response = clean_response(response.content)
|
| 434 |
-
|
| 435 |
-
return JSONResponse({
|
| 436 |
-
"success": True,
|
| 437 |
-
"response": cleaned_response
|
| 438 |
-
})
|
| 439 |
-
|
| 440 |
-
except Exception as e:
|
| 441 |
-
return JSONResponse({
|
| 442 |
-
"success": False,
|
| 443 |
-
"error": str(e)
|
| 444 |
-
}, status_code=500)
|
| 445 |
-
|
| 446 |
-
@app.post("/api/process-document")
|
| 447 |
-
async def api_process_document(file: UploadFile = File(...)):
|
| 448 |
-
"""
|
| 449 |
-
API endpoint for document processing
|
| 450 |
-
"""
|
| 451 |
-
try:
|
| 452 |
-
# Save uploaded file temporarily
|
| 453 |
-
file_extension = os.path.splitext(file.filename)[-1].lower()
|
| 454 |
-
temp_path = f"temp_{uuid.uuid4()}{file_extension}"
|
| 455 |
-
|
| 456 |
-
with open(temp_path, "wb") as f:
|
| 457 |
-
f.write(await file.read())
|
| 458 |
-
|
| 459 |
-
# Process document based on type
|
| 460 |
-
if file_extension == ".pdf":
|
| 461 |
-
content = extract_text_from_pdf(temp_path)
|
| 462 |
-
elif file_extension == ".docx":
|
| 463 |
-
content = extract_text_from_docx(temp_path)
|
| 464 |
-
elif file_extension == ".pptx":
|
| 465 |
-
content = extract_text_from_pptx(temp_path)
|
| 466 |
-
else:
|
| 467 |
-
# Try text file
|
| 468 |
-
encoding = detect_encoding(temp_path)
|
| 469 |
-
with open(temp_path, "r", encoding=encoding, errors="replace") as f:
|
| 470 |
-
content = f.read()
|
| 471 |
-
|
| 472 |
-
# Clean up temp file
|
| 473 |
-
os.remove(temp_path)
|
| 474 |
|
| 475 |
-
|
| 476 |
-
|
| 477 |
|
| 478 |
-
return
|
| 479 |
-
"success": True,
|
| 480 |
-
"content_preview": content[:500] + "..." if len(content) > 500 else content,
|
| 481 |
-
"quiz": quiz
|
| 482 |
-
})
|
| 483 |
|
| 484 |
except Exception as e:
|
| 485 |
-
return
|
| 486 |
-
"success": False,
|
| 487 |
-
"error": str(e)
|
| 488 |
-
}, status_code=500)
|
| 489 |
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
"""Health check endpoint"""
|
| 493 |
-
return {"status": "healthy", "timestamp": time.time()}
|
| 494 |
-
|
| 495 |
-
# Clear chat history function
|
| 496 |
-
def clear_chat_history():
|
| 497 |
chat_memory.clear()
|
| 498 |
return [], None
|
| 499 |
|
| 500 |
-
def
|
| 501 |
-
"""
|
| 502 |
-
with gr.Blocks(
|
| 503 |
-
gr.
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
with gr.Row():
|
| 509 |
with gr.Column(scale=3):
|
| 510 |
-
chatbot = gr.Chatbot(
|
| 511 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
with gr.Column(scale=1):
|
| 513 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 514 |
|
| 515 |
-
# Move the input controls here to span full width
|
| 516 |
with gr.Row():
|
| 517 |
msg = gr.Textbox(
|
| 518 |
-
label="
|
| 519 |
-
placeholder="Type your question here...",
|
| 520 |
-
|
|
|
|
|
|
|
| 521 |
)
|
| 522 |
-
|
| 523 |
|
| 524 |
with gr.Row():
|
| 525 |
with gr.Column(scale=1):
|
| 526 |
-
audio_input = gr.Audio(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 527 |
|
| 528 |
-
|
| 529 |
-
with gr.Accordion("π€ Voice Recording Tips", open=False):
|
| 530 |
gr.Markdown("""
|
| 531 |
-
|
| 532 |
-
-
|
| 533 |
-
-
|
| 534 |
-
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
""")
|
| 539 |
|
| 540 |
-
# Clear chat history button
|
| 541 |
-
clear_btn = gr.Button("Clear Chat")
|
| 542 |
-
|
| 543 |
-
# Handle chat interaction
|
| 544 |
-
submit.click(
|
| 545 |
-
chat_with_groq,
|
| 546 |
-
inputs=[msg, chatbot],
|
| 547 |
-
outputs=[chatbot, msg, audio_playback]
|
| 548 |
-
)
|
| 549 |
-
|
| 550 |
-
# Clear chat history function
|
| 551 |
-
clear_btn.click(
|
| 552 |
-
lambda: [], # Return empty list in message format
|
| 553 |
-
inputs=None,
|
| 554 |
-
outputs=[chatbot]
|
| 555 |
-
)
|
| 556 |
-
|
| 557 |
-
# Also allow Enter key to submit
|
| 558 |
-
msg.submit(
|
| 559 |
-
chat_with_groq,
|
| 560 |
-
inputs=[msg, chatbot],
|
| 561 |
-
outputs=[chatbot, msg, audio_playback]
|
| 562 |
-
)
|
| 563 |
-
|
| 564 |
-
# Add some examples of questions students might ask
|
| 565 |
-
with gr.Accordion("Example Questions", open=False):
|
| 566 |
-
gr.Examples(
|
| 567 |
-
examples=[
|
| 568 |
-
"Can you explain the concept of RLHF AI?",
|
| 569 |
-
"What are AI transformers?",
|
| 570 |
-
"What is MoE AI?",
|
| 571 |
-
"What's gate networks AI?",
|
| 572 |
-
"I am making a switch, please generating baking recipe?"
|
| 573 |
-
],
|
| 574 |
-
inputs=msg
|
| 575 |
-
)
|
| 576 |
-
|
| 577 |
-
# Connect audio input to transcription
|
| 578 |
-
audio_input.change(fn=transcribe_audio, inputs=audio_input, outputs=msg)
|
| 579 |
-
|
| 580 |
-
# Upload Notes & Generate Quiz Tab
|
| 581 |
-
with gr.Tab("Upload Notes & Generate Quiz"):
|
| 582 |
with gr.Row():
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
#
|
| 592 |
-
with gr.Tab("
|
|
|
|
|
|
|
| 593 |
with gr.Row():
|
| 594 |
with gr.Column(scale=1):
|
| 595 |
-
gr.
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 602 |
|
| 603 |
-
#
|
| 604 |
if __name__ == "__main__":
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
|
|
|
|
|
| 16 |
import groq
|
| 17 |
import uuid # For generating unique filenames
|
| 18 |
|
| 19 |
+
# LangChain imports with compatibility handling
|
| 20 |
+
try:
|
| 21 |
+
from langchain_groq import ChatGroq
|
| 22 |
+
from langchain_core.messages import HumanMessage
|
| 23 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 24 |
+
from langchain_community.vectorstores import Chroma
|
| 25 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 26 |
+
from langchain_core.documents import Document
|
| 27 |
+
except ImportError:
|
| 28 |
+
# Fallback for older versions
|
| 29 |
+
try:
|
| 30 |
+
from langchain_groq import ChatGroq
|
| 31 |
+
from langchain.schema import HumanMessage
|
| 32 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 33 |
+
from langchain_community.vectorstores import Chroma
|
| 34 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 35 |
+
from langchain.docstore.document import Document
|
| 36 |
+
except ImportError as e:
|
| 37 |
+
print(f"Import warning: {e}")
|
| 38 |
+
# Define fallback classes
|
| 39 |
+
class HumanMessage:
|
| 40 |
+
def __init__(self, content):
|
| 41 |
+
self.content = content
|
| 42 |
+
class Document:
|
| 43 |
+
def __init__(self, page_content):
|
| 44 |
+
self.page_content = page_content
|
| 45 |
+
|
| 46 |
+
# Basic imports
|
| 47 |
import chardet
|
|
|
|
| 48 |
import fitz # PyMuPDF for PDFs
|
| 49 |
import docx # python-docx for Word files
|
| 50 |
import gtts # Google Text-to-Speech library
|
| 51 |
from pptx import Presentation # python-pptx for PowerPoint files
|
| 52 |
import re
|
| 53 |
|
| 54 |
+
print("π Initializing AI Tutor Application...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
# Initialize Whisper for speech-to-text
|
| 57 |
try:
|
| 58 |
transcriber = pipeline(
|
| 59 |
+
"automatic-speech-recognition",
|
| 60 |
+
model="openai/whisper-base.en"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
)
|
| 62 |
+
print("β
Whisper model loaded successfully")
|
| 63 |
except Exception as e:
|
| 64 |
+
print(f"β Error loading Whisper: {e}")
|
| 65 |
+
transcriber = None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
# Initialize Groq
|
| 68 |
+
groq_api_key = os.getenv("GROQ_API_KEY")
|
| 69 |
+
if groq_api_key:
|
| 70 |
+
try:
|
| 71 |
+
chat_model = ChatGroq(
|
| 72 |
+
model_name="llama-3.3-70b-versatile",
|
| 73 |
+
api_key=groq_api_key,
|
| 74 |
+
temperature=0.7
|
| 75 |
+
)
|
| 76 |
+
CHAT_MODEL_AVAILABLE = True
|
| 77 |
+
print("β
Groq chat model initialized")
|
| 78 |
+
except Exception as e:
|
| 79 |
+
print(f"β Error initializing Groq: {e}")
|
| 80 |
+
CHAT_MODEL_AVAILABLE = False
|
| 81 |
+
else:
|
| 82 |
+
print("β οΈ GROQ_API_KEY not found in environment variables")
|
| 83 |
+
CHAT_MODEL_AVAILABLE = False
|
| 84 |
|
| 85 |
+
# Initialize Vector Store
|
| 86 |
+
try:
|
| 87 |
+
os.makedirs("chroma_db", exist_ok=True)
|
| 88 |
+
embedding_model = HuggingFaceEmbeddings(
|
| 89 |
+
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
| 90 |
+
)
|
| 91 |
+
vectorstore = Chroma(
|
| 92 |
+
embedding_function=embedding_model,
|
| 93 |
+
persist_directory="chroma_db"
|
| 94 |
+
)
|
| 95 |
+
VECTORSTORE_AVAILABLE = True
|
| 96 |
+
print("β
Vector store initialized")
|
| 97 |
+
except Exception as e:
|
| 98 |
+
print(f"β Error initializing vector store: {e}")
|
| 99 |
+
VECTORSTORE_AVAILABLE = False
|
| 100 |
|
| 101 |
+
# Application state
|
| 102 |
chat_memory = []
|
| 103 |
|
| 104 |
+
# Quiz generation prompt
|
|
|
|
|
|
|
|
|
|
| 105 |
quiz_prompt = """
|
| 106 |
+
You are an AI assistant specialized in education. Given document content, generate a quiz with 10 questions mixing multiple-choice and fill-in-the-blank.
|
| 107 |
+
|
| 108 |
+
Requirements:
|
| 109 |
+
- 10 total questions
|
| 110 |
+
- Mix of MCQs and fill-in-the-blank
|
| 111 |
+
- Based on key concepts from the document
|
| 112 |
+
- Include answer key
|
| 113 |
+
- Remove all markdown formatting
|
| 114 |
+
|
| 115 |
+
Output format:
|
| 116 |
+
1. [Question text]
|
| 117 |
+
Options (if MCQ): a) b) c) d)
|
| 118 |
+
Answer: [Correct answer]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
"""
|
| 120 |
|
|
|
|
| 121 |
def clean_response(response):
|
| 122 |
+
"""Clean AI response from unwanted formatting."""
|
| 123 |
+
if not response:
|
| 124 |
+
return ""
|
| 125 |
+
|
| 126 |
+
cleaned = re.sub(r"<think>.*?</think>", "", response, flags=re.DOTALL)
|
| 127 |
+
cleaned = re.sub(r"(\*\*|\*|\[|\]|#+|\\)", "", cleaned)
|
| 128 |
+
return cleaned.strip()
|
| 129 |
|
|
|
|
| 130 |
def generate_quiz(content):
|
| 131 |
+
"""Generate quiz from document content."""
|
| 132 |
+
if not CHAT_MODEL_AVAILABLE:
|
| 133 |
+
return "β Chat model not available. Please check GROQ_API_KEY configuration."
|
| 134 |
+
|
| 135 |
+
# Limit content length to avoid token limits
|
| 136 |
+
if len(content) > 8000:
|
| 137 |
+
content = content[:8000] + "... [content truncated for efficiency]"
|
| 138 |
+
|
| 139 |
+
try:
|
| 140 |
+
prompt = f"{quiz_prompt}\n\nDocument content:\n{content}"
|
| 141 |
+
response = chat_model([HumanMessage(content=prompt)])
|
| 142 |
+
return clean_response(response.content)
|
| 143 |
+
except Exception as e:
|
| 144 |
+
return f"β Error generating quiz: {str(e)}"
|
| 145 |
|
|
|
|
| 146 |
def retrieve_documents(query):
|
| 147 |
+
"""Retrieve relevant documents for context."""
|
| 148 |
+
if not VECTORSTORE_AVAILABLE or not query.strip():
|
| 149 |
+
return []
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
results = vectorstore.similarity_search(query, k=2)
|
| 153 |
+
return [doc.page_content for doc in results]
|
| 154 |
+
except Exception as e:
|
| 155 |
+
print(f"Document retrieval error: {e}")
|
| 156 |
+
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
|
|
|
| 158 |
def chat_with_groq(user_input, chat_history):
|
| 159 |
+
"""Handle chat interactions with the AI."""
|
| 160 |
try:
|
| 161 |
+
if not user_input.strip():
|
| 162 |
+
return chat_history, "", None
|
| 163 |
+
|
| 164 |
+
if not CHAT_MODEL_AVAILABLE:
|
| 165 |
+
error_msg = "π€ Chat service is currently unavailable. Please check your API configuration."
|
| 166 |
+
chat_history.append({"role": "user", "content": user_input})
|
| 167 |
+
chat_history.append({"role": "assistant", "content": error_msg})
|
| 168 |
+
return chat_history, "", None
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
# Get relevant context from documents
|
| 171 |
+
relevant_docs = retrieve_documents(user_input)
|
| 172 |
+
context = "\n".join(relevant_docs) if relevant_docs else "No specific context available."
|
| 173 |
+
|
| 174 |
+
# Build enhanced prompt
|
| 175 |
+
system_msg = "You are a helpful AI tutor. Provide accurate, educational, and concise responses. If you don't know something, admit it honestly."
|
| 176 |
+
prompt = f"{system_msg}\n\nRelevant Context:\n{context}\n\nUser Question: {user_input}\n\nAssistant Response:"
|
| 177 |
+
|
| 178 |
+
# Get AI response
|
| 179 |
response = chat_model([HumanMessage(content=prompt)])
|
| 180 |
+
cleaned_response = clean_response(response.content)
|
| 181 |
+
|
| 182 |
+
# Update chat history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
chat_history.append({"role": "user", "content": user_input})
|
| 184 |
+
chat_history.append({"role": "assistant", "content": cleaned_response})
|
| 185 |
+
|
| 186 |
+
# Generate speech output
|
| 187 |
+
audio_file = speech_playback(cleaned_response)
|
| 188 |
+
|
| 189 |
return chat_history, "", audio_file
|
| 190 |
+
|
| 191 |
except Exception as e:
|
| 192 |
+
error_msg = f"β Error processing your request: {str(e)}"
|
| 193 |
chat_history.append({"role": "user", "content": user_input})
|
| 194 |
chat_history.append({"role": "assistant", "content": error_msg})
|
| 195 |
return chat_history, "", None
|
| 196 |
|
|
|
|
| 197 |
def speech_playback(text):
|
| 198 |
+
"""Convert text to speech using gTTS."""
|
| 199 |
try:
|
| 200 |
+
if not text or len(text.strip()) < 10:
|
| 201 |
+
return None
|
| 202 |
+
|
| 203 |
+
# Limit text length for audio generation
|
| 204 |
+
if len(text) > 400:
|
| 205 |
+
text = text[:400] + "..."
|
| 206 |
+
|
| 207 |
+
unique_id = str(uuid.uuid4())[:8]
|
| 208 |
+
audio_file = f"audio_{unique_id}.mp3"
|
| 209 |
+
|
| 210 |
+
tts = gtts.gTTS(text=text, lang='en', slow=False)
|
| 211 |
tts.save(audio_file)
|
| 212 |
+
|
|
|
|
| 213 |
return audio_file
|
| 214 |
except Exception as e:
|
| 215 |
+
print(f"π TTS Error: {e}")
|
| 216 |
return None
|
| 217 |
|
|
|
|
| 218 |
def detect_encoding(file_path):
|
| 219 |
+
"""Detect file encoding."""
|
| 220 |
try:
|
| 221 |
with open(file_path, "rb") as f:
|
| 222 |
raw_data = f.read(4096)
|
| 223 |
detected = chardet.detect(raw_data)
|
| 224 |
+
return detected.get("encoding", "utf-8")
|
|
|
|
| 225 |
except Exception:
|
| 226 |
return "utf-8"
|
| 227 |
|
|
|
|
| 228 |
def extract_text_from_pdf(pdf_path):
|
| 229 |
+
"""Extract text from PDF files."""
|
| 230 |
try:
|
| 231 |
doc = fitz.open(pdf_path)
|
| 232 |
+
text = ""
|
| 233 |
+
for page in doc:
|
| 234 |
+
text += page.get_text()
|
| 235 |
+
return text.strip() if text.strip() else "No extractable text found in PDF."
|
| 236 |
except Exception as e:
|
| 237 |
+
return f"PDF extraction error: {str(e)}"
|
| 238 |
|
|
|
|
| 239 |
def extract_text_from_docx(docx_path):
|
| 240 |
+
"""Extract text from Word documents."""
|
| 241 |
try:
|
| 242 |
doc = docx.Document(docx_path)
|
| 243 |
+
text = "\n".join([para.text for para in doc.paragraphs if para.text.strip()])
|
| 244 |
+
return text.strip() if text.strip() else "No text found in Word document."
|
| 245 |
except Exception as e:
|
| 246 |
+
return f"Word extraction error: {str(e)}"
|
| 247 |
|
|
|
|
| 248 |
def extract_text_from_pptx(pptx_path):
|
| 249 |
+
"""Extract text from PowerPoint files."""
|
| 250 |
try:
|
| 251 |
+
prs = Presentation(pptx_path)
|
| 252 |
text = ""
|
| 253 |
+
for slide in prs.slides:
|
| 254 |
for shape in slide.shapes:
|
| 255 |
+
if hasattr(shape, "text") and shape.text:
|
| 256 |
text += shape.text + "\n"
|
| 257 |
+
return text.strip() if text.strip() else "No text found in PowerPoint."
|
| 258 |
except Exception as e:
|
| 259 |
+
return f"PowerPoint extraction error: {str(e)}"
|
| 260 |
|
|
|
|
| 261 |
def process_document(file):
|
| 262 |
+
"""Process uploaded document and generate quiz."""
|
| 263 |
try:
|
| 264 |
+
if not file:
|
| 265 |
+
return "π Please upload a document file first."
|
| 266 |
+
|
| 267 |
+
filename = file.name
|
| 268 |
+
file_ext = os.path.splitext(filename)[-1].lower()
|
| 269 |
+
|
| 270 |
+
print(f"Processing {file_ext} file: {filename}")
|
| 271 |
+
|
| 272 |
+
# Extract text based on file type
|
| 273 |
+
if file_ext == ".pdf":
|
| 274 |
+
content = extract_text_from_pdf(filename)
|
| 275 |
+
elif file_ext == ".docx":
|
| 276 |
+
content = extract_text_from_docx(filename)
|
| 277 |
+
elif file_ext == ".pptx":
|
| 278 |
+
content = extract_text_from_pptx(filename)
|
| 279 |
+
elif file_ext in [".txt", ".md"]:
|
| 280 |
+
encoding = detect_encoding(filename)
|
| 281 |
+
with open(filename, "r", encoding=encoding, errors="ignore") as f:
|
| 282 |
content = f.read()
|
| 283 |
+
else:
|
| 284 |
+
return f"β Unsupported file type: {file_ext}. Please upload PDF, Word, PowerPoint, or text files."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
+
if not content or "error" in content.lower() or "no text" in content.lower():
|
| 287 |
+
return f"β Could not extract meaningful content from this file. Error: {content}"
|
| 288 |
|
| 289 |
+
# Store in vector database for future queries
|
| 290 |
+
if VECTORSTORE_AVAILABLE and len(content) > 100:
|
| 291 |
+
try:
|
| 292 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 293 |
+
chunk_size=500,
|
| 294 |
+
chunk_overlap=50
|
| 295 |
+
)
|
| 296 |
+
texts = text_splitter.split_text(content)
|
| 297 |
+
documents = [Document(page_content=text) for text in texts]
|
| 298 |
+
vectorstore.add_documents(documents)
|
| 299 |
+
except Exception as e:
|
| 300 |
+
print(f"Vector store addition warning: {e}")
|
| 301 |
|
| 302 |
+
# Generate quiz from content
|
| 303 |
+
quiz = generate_quiz(content)
|
|
|
|
|
|
|
| 304 |
|
| 305 |
+
success_msg = f"""
|
| 306 |
+
β
**Document Processed Successfully!**
|
| 307 |
+
|
| 308 |
+
π **File Type**: {file_ext.upper()}
|
| 309 |
+
π **Content Preview**: {content[:200]}...
|
| 310 |
+
|
| 311 |
+
π **Generated Quiz**:
|
| 312 |
+
{quiz}
|
| 313 |
+
"""
|
| 314 |
+
|
| 315 |
+
return success_msg
|
| 316 |
|
|
|
|
|
|
|
| 317 |
except Exception as e:
|
| 318 |
+
return f"β Error processing document: {str(e)}"
|
|
|
|
|
|
|
| 319 |
|
| 320 |
def transcribe_audio(audio):
|
| 321 |
+
"""Transcribe audio to text using Whisper."""
|
|
|
|
|
|
|
| 322 |
try:
|
| 323 |
if audio is None:
|
| 324 |
+
return "π€ No audio detected. Please record or upload audio."
|
| 325 |
+
|
| 326 |
+
if transcriber is None:
|
| 327 |
+
return "π Speech-to-text service is currently unavailable."
|
| 328 |
|
| 329 |
sample_rate, audio_data = audio
|
| 330 |
|
| 331 |
+
# Basic audio preprocessing
|
| 332 |
+
if audio_data.ndim > 1:
|
| 333 |
+
audio_data = np.mean(audio_data, axis=1) # Convert to mono
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
|
| 335 |
+
audio_data = audio_data.astype(np.float32)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
+
# Normalize audio
|
| 338 |
+
max_val = np.max(np.abs(audio_data))
|
| 339 |
+
if max_val > 0:
|
| 340 |
+
audio_data = audio_data / max_val
|
| 341 |
|
| 342 |
+
# Check audio length
|
| 343 |
+
audio_duration = len(audio_data) / sample_rate
|
| 344 |
+
if audio_duration < 0.5:
|
| 345 |
+
return "β±οΈ Audio too short. Please record at least 1 second."
|
| 346 |
+
if audio_duration > 30:
|
| 347 |
+
return "β±οΈ Audio too long. Please keep under 30 seconds."
|
| 348 |
|
| 349 |
# Transcribe
|
| 350 |
+
result = transcriber({"sampling_rate": sample_rate, "raw": audio_data})
|
| 351 |
+
text = result.get("text", "").strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
+
if not text:
|
| 354 |
+
return "π No speech detected. Please try again with clearer audio."
|
| 355 |
|
| 356 |
+
return f"π€ Transcribed: {text}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
|
| 358 |
except Exception as e:
|
| 359 |
+
return f"β Transcription error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
| 360 |
|
| 361 |
+
def clear_chat():
|
| 362 |
+
"""Clear chat history."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
chat_memory.clear()
|
| 364 |
return [], None
|
| 365 |
|
| 366 |
+
def create_interface():
|
| 367 |
+
"""Create and configure the Gradio interface."""
|
| 368 |
+
with gr.Blocks(
|
| 369 |
+
theme=gr.themes.Soft(),
|
| 370 |
+
title="AI Tutor - Learning Assistant",
|
| 371 |
+
css="""
|
| 372 |
+
.gradio-container {
|
| 373 |
+
max-width: 1200px !important;
|
| 374 |
+
}
|
| 375 |
+
"""
|
| 376 |
+
) as app:
|
| 377 |
+
gr.Markdown("""
|
| 378 |
+
# π AI Tutor Assistant
|
| 379 |
+
*Your personal learning companion with speech-to-text capabilities*
|
| 380 |
+
""")
|
| 381 |
+
|
| 382 |
+
# Main chat interface
|
| 383 |
+
with gr.Tab("π¬ AI Chatbot"):
|
| 384 |
+
gr.Markdown("Chat with your AI tutor using text or voice input!")
|
| 385 |
+
|
| 386 |
with gr.Row():
|
| 387 |
with gr.Column(scale=3):
|
| 388 |
+
chatbot = gr.Chatbot(
|
| 389 |
+
label="Conversation History",
|
| 390 |
+
height=500,
|
| 391 |
+
type="messages",
|
| 392 |
+
show_copy_button=True,
|
| 393 |
+
avatar_images=("π€", "π€")
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
with gr.Column(scale=1):
|
| 397 |
+
audio_output = gr.Audio(
|
| 398 |
+
label="Audio Response",
|
| 399 |
+
type="filepath",
|
| 400 |
+
visible=True,
|
| 401 |
+
autoplay=True
|
| 402 |
+
)
|
| 403 |
|
|
|
|
| 404 |
with gr.Row():
|
| 405 |
msg = gr.Textbox(
|
| 406 |
+
label="Your message",
|
| 407 |
+
placeholder="Type your question here or use voice input below...",
|
| 408 |
+
scale=4,
|
| 409 |
+
container=False,
|
| 410 |
+
max_lines=3
|
| 411 |
)
|
| 412 |
+
send_btn = gr.Button("π Send", scale=1, variant="primary")
|
| 413 |
|
| 414 |
with gr.Row():
|
| 415 |
with gr.Column(scale=1):
|
| 416 |
+
audio_input = gr.Audio(
|
| 417 |
+
sources=["microphone"],
|
| 418 |
+
type="numpy",
|
| 419 |
+
label="π€ Record Audio Question",
|
| 420 |
+
show_download_button=False
|
| 421 |
+
)
|
| 422 |
|
| 423 |
+
with gr.Accordion("π‘ Tips for Better Experience", open=False):
|
|
|
|
| 424 |
gr.Markdown("""
|
| 425 |
+
**π€ Voice Input Tips:**
|
| 426 |
+
- Speak clearly in a quiet environment
|
| 427 |
+
- Keep microphone 10-15 cm from your mouth
|
| 428 |
+
- Record for 2-5 seconds for best results
|
| 429 |
+
|
| 430 |
+
**π Document Tips:**
|
| 431 |
+
- Upload PDF, Word, or PowerPoint files
|
| 432 |
+
- Clear text documents work best
|
| 433 |
+
- Process documents before asking questions about them
|
| 434 |
+
|
| 435 |
+
**π¬ Chat Tips:**
|
| 436 |
+
- Ask specific questions for better answers
|
| 437 |
+
- Use the clear button to start fresh conversations
|
| 438 |
+
- The AI remembers context from uploaded documents
|
| 439 |
""")
|
| 440 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
with gr.Row():
|
| 442 |
+
clear_btn = gr.Button("π§Ή Clear Chat History", variant="secondary")
|
| 443 |
+
gr.Button("π Refresh Page").click(
|
| 444 |
+
lambda: None,
|
| 445 |
+
None,
|
| 446 |
+
None,
|
| 447 |
+
js="() => window.location.reload()"
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
# Document processing tab
|
| 451 |
+
with gr.Tab("π Upload & Generate Quiz"):
|
| 452 |
+
gr.Markdown("Upload your study materials and generate custom quizzes automatically!")
|
| 453 |
+
|
| 454 |
with gr.Row():
|
| 455 |
with gr.Column(scale=1):
|
| 456 |
+
file_upload = gr.File(
|
| 457 |
+
label="π Upload Study Materials",
|
| 458 |
+
file_types=[".pdf", ".docx", ".pptx", ".txt", ".md"],
|
| 459 |
+
file_count="single",
|
| 460 |
+
height=100
|
| 461 |
+
)
|
| 462 |
+
process_btn = gr.Button("β‘ Process & Generate Quiz", variant="primary")
|
| 463 |
+
|
| 464 |
+
gr.Markdown("""
|
| 465 |
+
**Supported Formats:**
|
| 466 |
+
- PDF documents
|
| 467 |
+
- Word documents (.docx)
|
| 468 |
+
- PowerPoint (.pptx)
|
| 469 |
+
- Text files (.txt, .md)
|
| 470 |
+
""")
|
| 471 |
+
|
| 472 |
+
with gr.Column(scale=2):
|
| 473 |
+
quiz_display = gr.Textbox(
|
| 474 |
+
label="π Generated Quiz",
|
| 475 |
+
lines=20,
|
| 476 |
+
max_lines=25,
|
| 477 |
+
show_copy_button=True,
|
| 478 |
+
placeholder="Your generated quiz will appear here after processing a document..."
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
# Instructions tab
|
| 482 |
+
with gr.Tab("βΉοΈ How to Use"):
|
| 483 |
+
gr.Markdown("""
|
| 484 |
+
## π Getting Started with AI Tutor
|
| 485 |
+
|
| 486 |
+
### π€ Using Voice Input
|
| 487 |
+
1. Go to the **AI Chatbot** tab
|
| 488 |
+
2. Click the microphone button
|
| 489 |
+
3. Allow microphone access in your browser
|
| 490 |
+
4. Speak clearly and wait for transcription
|
| 491 |
+
5. Review the text and click Send
|
| 492 |
+
|
| 493 |
+
### π Processing Documents
|
| 494 |
+
1. Go to the **Upload & Generate Quiz** tab
|
| 495 |
+
2. Upload your study materials (PDF, Word, PowerPoint)
|
| 496 |
+
3. Click "Process & Generate Quiz"
|
| 497 |
+
4. Get instant quiz questions based on your content
|
| 498 |
+
5. Use the chat to ask questions about your documents
|
| 499 |
+
|
| 500 |
+
### π¬ Chat Features
|
| 501 |
+
- Ask questions about uploaded documents
|
| 502 |
+
- Get detailed explanations
|
| 503 |
+
- Receive audio responses
|
| 504 |
+
- Clear chat when needed
|
| 505 |
+
|
| 506 |
+
### π§ Technical Requirements
|
| 507 |
+
- Modern web browser with microphone access
|
| 508 |
+
- Stable internet connection
|
| 509 |
+
- Groq API key (set as environment variable)
|
| 510 |
+
""")
|
| 511 |
+
|
| 512 |
+
# Event handlers
|
| 513 |
+
send_btn.click(
|
| 514 |
+
fn=chat_with_groq,
|
| 515 |
+
inputs=[msg, chatbot],
|
| 516 |
+
outputs=[chatbot, msg, audio_output]
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
msg.submit(
|
| 520 |
+
fn=chat_with_groq,
|
| 521 |
+
inputs=[msg, chatbot],
|
| 522 |
+
outputs=[chatbot, msg, audio_output]
|
| 523 |
+
)
|
| 524 |
+
|
| 525 |
+
audio_input.change(
|
| 526 |
+
fn=transcribe_audio,
|
| 527 |
+
inputs=[audio_input],
|
| 528 |
+
outputs=[msg]
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
process_btn.click(
|
| 532 |
+
fn=process_document,
|
| 533 |
+
inputs=[file_upload],
|
| 534 |
+
outputs=[quiz_display]
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
clear_btn.click(
|
| 538 |
+
fn=clear_chat,
|
| 539 |
+
outputs=[chatbot, audio_output]
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
return app
|
| 543 |
|
| 544 |
+
# Launch the application
|
| 545 |
if __name__ == "__main__":
|
| 546 |
+
print("π Starting AI Tutor Application...")
|
| 547 |
+
app = create_interface()
|
| 548 |
+
app.launch(
|
| 549 |
+
server_name="0.0.0.0",
|
| 550 |
+
server_port=7860,
|
| 551 |
+
share=False,
|
| 552 |
+
show_error=True,
|
| 553 |
+
debug=True
|
| 554 |
+
)
|