Spaces:
Running
Running
Commit
·
be22066
1
Parent(s):
0ba063f
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,270 +1,535 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import tempfile
|
| 3 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
-
import faiss
|
| 6 |
from sentence_transformers import SentenceTransformer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
faiss_index = None
|
| 21 |
-
embedding_dimension = 384 # all-MiniLM-L6-v2 embedding dimension
|
| 22 |
-
|
| 23 |
-
def extract_text_from_pdf(pdf_file_path, start_page=None, end_page=None):
|
| 24 |
-
"""Extract text from PDF file, optionally from a specific page range."""
|
| 25 |
-
doc = fitz.open(pdf_file_path)
|
| 26 |
-
text = ""
|
| 27 |
-
num_pages_in_doc = doc.page_count
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
def chunk_text(text, chunk_size=
|
| 46 |
"""Split text into overlapping chunks"""
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
# Normalize embeddings for cosine similarity
|
| 59 |
faiss.normalize_L2(embeddings)
|
| 60 |
-
|
| 61 |
-
# Create index - using IndexFlatIP for cosine similarity
|
| 62 |
-
index = faiss.IndexFlatIP(embedding_dimension)
|
| 63 |
-
index.add(embeddings)
|
| 64 |
|
| 65 |
return index
|
| 66 |
|
| 67 |
-
def
|
| 68 |
-
"""
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
if not GEMINI_API_KEY:
|
| 72 |
-
return None, [["System", "⚠️ GAPI environment variable not set. Please configure your Gemini API key."]]
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
try:
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
tmp_path = tmp.name
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
if not current_chunks:
|
| 94 |
-
return None, [["System", "⚠️ Could not create text chunks from the PDF."]]
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
current_embeddings = np.array(current_embeddings, dtype=np.float32)
|
| 99 |
-
|
| 100 |
-
# Create FAISS index
|
| 101 |
-
current_index = create_faiss_index(current_embeddings)
|
| 102 |
-
|
| 103 |
-
# Update global storage
|
| 104 |
-
chunks = current_chunks
|
| 105 |
-
faiss_index = current_index
|
| 106 |
|
| 107 |
-
|
| 108 |
-
success_msg = f"✅ Successfully processed '{pdf_name}' ({total_pages} pages, {len(chunks)} chunks). FAISS index created! You can now ask questions!"
|
| 109 |
-
|
| 110 |
-
# Clean up
|
| 111 |
-
if os.path.exists(tmp_path):
|
| 112 |
-
os.unlink(tmp_path)
|
| 113 |
-
|
| 114 |
-
return None, [["System", success_msg]]
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
except Exception as e:
|
| 117 |
-
|
| 118 |
-
faiss_index = None
|
| 119 |
-
error_msg = f"❌ Error processing PDF: {str(e)}"
|
| 120 |
-
return None, [["System", error_msg]]
|
| 121 |
|
| 122 |
-
def
|
| 123 |
-
"""
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
try:
|
| 130 |
-
#
|
| 131 |
-
|
| 132 |
-
|
|
|
|
| 133 |
|
| 134 |
-
#
|
| 135 |
-
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
| 139 |
|
| 140 |
-
#
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
top_chunks.append(chunks[idx])
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
return history, ""
|
| 163 |
-
|
| 164 |
-
if not chunks or faiss_index is None:
|
| 165 |
-
history[-1][1] = "📄 Please upload and process a PDF document first."
|
| 166 |
-
return history, ""
|
| 167 |
-
|
| 168 |
-
try:
|
| 169 |
-
# Configure Gemini
|
| 170 |
-
genai.configure(api_key=GEMINI_API_KEY)
|
| 171 |
-
|
| 172 |
-
# Get relevant context using FAISS
|
| 173 |
-
context_chunks = retrieve_relevant_chunks(message, top_k=5)
|
| 174 |
-
if not context_chunks:
|
| 175 |
-
history[-1][1] = "❌ Could not find relevant information in the document."
|
| 176 |
-
return history, ""
|
| 177 |
-
|
| 178 |
-
# Generate response
|
| 179 |
-
context = "\n\n".join(context_chunks)
|
| 180 |
-
prompt = f"""Based on the following context from the document, answer the user's question.
|
| 181 |
-
|
| 182 |
-
Context:
|
| 183 |
-
{context}
|
| 184 |
-
|
| 185 |
-
Question: {message}
|
| 186 |
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
-
|
| 190 |
-
|
|
|
|
| 191 |
|
| 192 |
-
history[-1][1] = response.text
|
| 193 |
-
|
| 194 |
except Exception as e:
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
return history, ""
|
| 198 |
-
|
| 199 |
-
# Custom CSS for better chat appearance
|
| 200 |
-
css = """
|
| 201 |
-
.gradio-container {
|
| 202 |
-
max-width: 800px !important;
|
| 203 |
-
margin: auto !important;
|
| 204 |
-
}
|
| 205 |
-
.chat-message {
|
| 206 |
-
padding: 10px !important;
|
| 207 |
-
margin: 5px 0 !important;
|
| 208 |
-
border-radius: 10px !important;
|
| 209 |
-
}
|
| 210 |
-
"""
|
| 211 |
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
Upload a PDF document and chat with it naturally. Now with FAISS for faster vector search!
|
| 217 |
|
| 218 |
-
|
| 219 |
-
""
|
| 220 |
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
label="💬 Chat",
|
| 229 |
-
height=500,
|
| 230 |
-
show_label=False,
|
| 231 |
-
bubble_full_width=False
|
| 232 |
-
)
|
| 233 |
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
-
#
|
| 246 |
-
|
| 247 |
-
fn=process_pdf,
|
| 248 |
-
inputs=[pdf_input],
|
| 249 |
-
outputs=[msg_input, chatbot]
|
| 250 |
-
)
|
| 251 |
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
inputs=[msg_input, chatbot],
|
| 255 |
-
outputs=[chatbot, msg_input]
|
| 256 |
-
)
|
| 257 |
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
outputs=[chatbot, msg_input]
|
| 262 |
-
)
|
| 263 |
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
)
|
| 268 |
|
| 269 |
if __name__ == "__main__":
|
| 270 |
-
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Hindi RAG Voice Demo - Gradio Implementation (No OCR Version)
|
| 4 |
+
A streamlined voice-enabled RAG system for Hindi content using Gradio
|
| 5 |
+
Assumes PDFs have selectable text - no OCR processing
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import gradio as gr
|
| 9 |
import os
|
| 10 |
import tempfile
|
| 11 |
+
import time
|
| 12 |
+
import uuid
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
import fitz # PyMuPDF
|
| 15 |
+
import requests
|
| 16 |
+
import json
|
| 17 |
import numpy as np
|
|
|
|
| 18 |
from sentence_transformers import SentenceTransformer
|
| 19 |
+
import faiss
|
| 20 |
+
import whisper
|
| 21 |
+
from gtts import gTTS
|
| 22 |
+
import warnings
|
| 23 |
+
warnings.filterwarnings("ignore")
|
| 24 |
+
|
| 25 |
+
# Global configuration
|
| 26 |
+
CONFIG = {
|
| 27 |
+
'PASSCODE': os.getenv('PASSCODE'),
|
| 28 |
+
'MAX_FILE_SIZE': 10 * 1024 * 1024, # 10MB
|
| 29 |
+
'MAX_QUERIES_PER_SESSION': 5,
|
| 30 |
+
'MAX_AUDIO_DURATION': 120, # 2 minutes
|
| 31 |
+
'GROQ_API_KEY': os.getenv('GAPI'),
|
| 32 |
+
}
|
| 33 |
|
| 34 |
+
# Global session storage
|
| 35 |
+
SESSION_DATA = {
|
| 36 |
+
'authenticated': False,
|
| 37 |
+
'session_id': str(uuid.uuid4()),
|
| 38 |
+
'query_count': 0,
|
| 39 |
+
'document_chunks': [],
|
| 40 |
+
'faiss_index': None,
|
| 41 |
+
'author_name': '',
|
| 42 |
+
'book_title': '',
|
| 43 |
+
'embedding_model': None,
|
| 44 |
+
'whisper_model': None
|
| 45 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
# Initialize models (cached)
|
| 48 |
+
def load_models():
|
| 49 |
+
"""Load and cache models"""
|
| 50 |
+
if SESSION_DATA['embedding_model'] is None:
|
| 51 |
+
print("Loading embedding model...")
|
| 52 |
+
SESSION_DATA['embedding_model'] = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
|
| 53 |
+
|
| 54 |
+
if SESSION_DATA['whisper_model'] is None:
|
| 55 |
+
print("Loading Whisper model...")
|
| 56 |
+
SESSION_DATA['whisper_model'] = whisper.load_model("base")
|
| 57 |
+
|
| 58 |
+
return SESSION_DATA['embedding_model'], SESSION_DATA['whisper_model']
|
| 59 |
|
| 60 |
+
# Text extraction functions
|
| 61 |
+
def extract_text_from_pdf(pdf_path):
|
| 62 |
+
"""Extract text from PDF using PyMuPDF (assumes selectable text)"""
|
| 63 |
+
text_content = ""
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
pdf_document = fitz.open(pdf_path)
|
| 67 |
+
total_pages = len(pdf_document)
|
| 68 |
+
|
| 69 |
+
print(f"Processing PDF with {total_pages} pages...")
|
| 70 |
+
|
| 71 |
+
# Process all pages (removed page limit for production use)
|
| 72 |
+
for page_num in range(total_pages):
|
| 73 |
+
page = pdf_document.load_page(page_num)
|
| 74 |
+
page_text = page.get_text()
|
| 75 |
+
|
| 76 |
+
# Add page text if it exists
|
| 77 |
+
if page_text.strip():
|
| 78 |
+
text_content += page_text + "\n"
|
| 79 |
+
else:
|
| 80 |
+
print(f"Warning: Page {page_num + 1} appears to have no selectable text")
|
| 81 |
+
|
| 82 |
+
pdf_document.close()
|
| 83 |
+
|
| 84 |
+
if not text_content.strip():
|
| 85 |
+
return "Error: No selectable text found in PDF. Please ensure the PDF contains selectable text, not just images."
|
| 86 |
+
|
| 87 |
+
return text_content
|
| 88 |
+
|
| 89 |
+
except Exception as e:
|
| 90 |
+
return f"Error extracting text: {str(e)}"
|
| 91 |
|
| 92 |
+
def extract_metadata(text):
|
| 93 |
+
"""Extract author name and book title from text"""
|
| 94 |
+
lines = [line.strip() for line in text.split('\n')[:25] if line.strip()]
|
| 95 |
+
|
| 96 |
+
author_name = "अज्ञात लेखक"
|
| 97 |
+
book_title = "अनाम पुस्तक"
|
| 98 |
+
|
| 99 |
+
# Simple heuristics for metadata extraction
|
| 100 |
+
for i, line in enumerate(lines):
|
| 101 |
+
# Look for author patterns
|
| 102 |
+
if any(word in line.lower() for word in ['लेखक', 'author', 'by', 'द्वारा', 'रचयिता']):
|
| 103 |
+
author_name = line
|
| 104 |
+
# First substantial line might be title
|
| 105 |
+
elif 10 < len(line) < 100 and not any(char.isdigit() for char in line[:20]):
|
| 106 |
+
if book_title == "अनाम पुस्तक":
|
| 107 |
+
book_title = line
|
| 108 |
+
|
| 109 |
+
return author_name, book_title
|
| 110 |
|
| 111 |
+
def chunk_text(text, chunk_size=400, overlap=50):
|
| 112 |
"""Split text into overlapping chunks"""
|
| 113 |
+
words = text.split()
|
| 114 |
+
chunks = []
|
| 115 |
+
|
| 116 |
+
for i in range(0, len(words), chunk_size - overlap):
|
| 117 |
+
chunk = ' '.join(words[i:i + chunk_size])
|
| 118 |
+
if chunk.strip():
|
| 119 |
+
chunks.append(chunk)
|
| 120 |
+
|
| 121 |
+
return chunks
|
| 122 |
|
| 123 |
+
# Vector search functions
|
| 124 |
+
def create_embeddings(chunks):
|
| 125 |
+
"""Create embeddings and FAISS index"""
|
| 126 |
+
embedding_model, _ = load_models()
|
| 127 |
+
embeddings = embedding_model.encode(chunks, show_progress_bar=False)
|
| 128 |
+
|
| 129 |
+
# Create FAISS index
|
| 130 |
+
dimension = embeddings.shape[1]
|
| 131 |
+
index = faiss.IndexFlatIP(dimension)
|
| 132 |
|
| 133 |
# Normalize embeddings for cosine similarity
|
| 134 |
faiss.normalize_L2(embeddings)
|
| 135 |
+
index.add(embeddings.astype('float32'))
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
return index
|
| 138 |
|
| 139 |
+
def search_similar_chunks(query, top_k=3):
|
| 140 |
+
"""Search for similar chunks"""
|
| 141 |
+
if SESSION_DATA['faiss_index'] is None or not SESSION_DATA['document_chunks']:
|
| 142 |
+
return []
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
embedding_model, _ = load_models()
|
| 145 |
+
query_embedding = embedding_model.encode([query], show_progress_bar=False)
|
| 146 |
+
faiss.normalize_L2(query_embedding)
|
| 147 |
+
|
| 148 |
+
scores, indices = SESSION_DATA['faiss_index'].search(query_embedding.astype('float32'), top_k)
|
| 149 |
+
|
| 150 |
+
results = []
|
| 151 |
+
for i, idx in enumerate(indices[0]):
|
| 152 |
+
if idx >= 0 and idx < len(SESSION_DATA['document_chunks']):
|
| 153 |
+
results.append({
|
| 154 |
+
'text': SESSION_DATA['document_chunks'][idx],
|
| 155 |
+
'score': float(scores[0][i])
|
| 156 |
+
})
|
| 157 |
+
|
| 158 |
+
return results
|
| 159 |
|
| 160 |
+
# LLM functions
|
| 161 |
+
def call_groq_api(prompt, model="llama-3.1-8b-instant"):
|
| 162 |
+
"""Call Groq API for LLM inference"""
|
| 163 |
+
if not CONFIG['GROQ_API_KEY'] or CONFIG['GROQ_API_KEY'] == 'your_groq_api_key_here':
|
| 164 |
+
return "⚠️ Groq API key not configured. Please set GROQ_API_KEY environment variable."
|
| 165 |
+
|
| 166 |
+
url = "https://api.groq.com/openai/v1/chat/completions"
|
| 167 |
+
headers = {
|
| 168 |
+
"Authorization": f"Bearer {CONFIG['GROQ_API_KEY']}",
|
| 169 |
+
"Content-Type": "application/json"
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
data = {
|
| 173 |
+
"model": model,
|
| 174 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 175 |
+
"temperature": 0.7,
|
| 176 |
+
"max_tokens": 800
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
try:
|
| 180 |
+
response = requests.post(url, headers=headers, json=data, timeout=30)
|
| 181 |
+
response.raise_for_status()
|
| 182 |
+
return response.json()['choices'][0]['message']['content']
|
| 183 |
+
except Exception as e:
|
| 184 |
+
return f"Error calling LLM: {str(e)}"
|
|
|
|
| 185 |
|
| 186 |
+
def generate_rag_response(query, context_chunks):
|
| 187 |
+
"""Generate response using RAG"""
|
| 188 |
+
if not context_chunks:
|
| 189 |
+
return "मुझे इस प्रश्न का उत्तर देने के लिए पर्याप्त जानकारी नहीं मिली।"
|
| 190 |
+
|
| 191 |
+
context = "\n\n".join([chunk['text'] for chunk in context_chunks])
|
| 192 |
+
|
| 193 |
+
prompt = f"""आप एक हिंदी पुस्तक सहायक हैं। निम्नलिखित जानकारी के आधार पर प्रश्न का उत्तर दें:
|
| 194 |
|
| 195 |
+
पुस्तक: {SESSION_DATA['book_title']}
|
| 196 |
+
लेखक: {SESSION_DATA['author_name']}
|
|
|
|
|
|
|
| 197 |
|
| 198 |
+
संदर्भ:
|
| 199 |
+
{context}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
+
प्रश्न: {query}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
+
निर्देश:
|
| 204 |
+
- हिंदी में संक्षिप्त और सटीक उत्तर दें
|
| 205 |
+
- उत्तर की शुरुआत में पुस्तक और लेखक का संदर्भ शामिल करें
|
| 206 |
+
- केवल दिए गए संदर्भ के आधार पर ही उत्तर दें
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
response = call_groq_api(prompt)
|
| 210 |
+
return response
|
| 211 |
+
|
| 212 |
+
# Audio processing functions
|
| 213 |
+
def transcribe_audio(audio_file):
|
| 214 |
+
"""Transcribe audio using Whisper"""
|
| 215 |
+
if audio_file is None:
|
| 216 |
+
return ""
|
| 217 |
+
|
| 218 |
+
try:
|
| 219 |
+
_, whisper_model = load_models()
|
| 220 |
+
result = whisper_model.transcribe(audio_file, language="hi")
|
| 221 |
+
return result["text"]
|
| 222 |
except Exception as e:
|
| 223 |
+
return f"Transcription error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
| 224 |
|
| 225 |
+
def text_to_speech(text):
|
| 226 |
+
"""Convert text to speech in Hindi"""
|
| 227 |
+
if not text or len(text.strip()) == 0:
|
| 228 |
+
return None
|
| 229 |
+
|
| 230 |
+
try:
|
| 231 |
+
tts = gTTS(text=text, lang='hi', slow=False)
|
| 232 |
+
|
| 233 |
+
# Save to temporary file
|
| 234 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
| 235 |
+
tts.save(tmp_file.name)
|
| 236 |
+
return tmp_file.name
|
| 237 |
+
except Exception as e:
|
| 238 |
+
print(f"TTS Error: {str(e)}")
|
| 239 |
+
return None
|
| 240 |
+
|
| 241 |
+
# Authentication function
|
| 242 |
+
def authenticate(passcode):
|
| 243 |
+
"""Check passcode authentication"""
|
| 244 |
+
if passcode == CONFIG['PASSCODE']:
|
| 245 |
+
SESSION_DATA['authenticated'] = True
|
| 246 |
+
return gr.update(visible=False), gr.update(visible=True), "✅ Access granted! / पहुंच मिली!"
|
| 247 |
+
else:
|
| 248 |
+
return gr.update(visible=True), gr.update(visible=False), "❌ Invalid passcode / गलत पासकोड"
|
| 249 |
|
| 250 |
+
# Document processing function
|
| 251 |
+
def process_document(pdf_file):
|
| 252 |
+
"""Process uploaded PDF document"""
|
| 253 |
+
if pdf_file is None:
|
| 254 |
+
return "कृपया एक PDF फ़ाइल अपलोड करें।", "", "", gr.update(visible=False)
|
| 255 |
+
|
| 256 |
try:
|
| 257 |
+
# Check file size
|
| 258 |
+
file_size = os.path.getsize(pdf_file.name)
|
| 259 |
+
if file_size > CONFIG['MAX_FILE_SIZE']:
|
| 260 |
+
return f"फ़ाइल बहुत बड़ी है! अधिकतम आकार: {CONFIG['MAX_FILE_SIZE'] // (1024*1024)}MB", "", "", gr.update(visible=False)
|
| 261 |
|
| 262 |
+
# Extract text (no OCR - assumes selectable text)
|
| 263 |
+
text_content = extract_text_from_pdf(pdf_file.name)
|
| 264 |
|
| 265 |
+
if not text_content.strip() or "Error" in text_content:
|
| 266 |
+
return text_content, "", "", gr.update(visible=False)
|
| 267 |
|
| 268 |
+
# Extract metadata
|
| 269 |
+
author_name, book_title = extract_metadata(text_content)
|
| 270 |
+
SESSION_DATA['author_name'] = author_name
|
| 271 |
+
SESSION_DATA['book_title'] = book_title
|
|
|
|
| 272 |
|
| 273 |
+
# Create chunks
|
| 274 |
+
chunks = chunk_text(text_content)
|
| 275 |
+
SESSION_DATA['document_chunks'] = chunks
|
| 276 |
+
|
| 277 |
+
# Create embeddings and index
|
| 278 |
+
print("Creating embeddings and search index...")
|
| 279 |
+
SESSION_DATA['faiss_index'] = create_embeddings(chunks)
|
| 280 |
+
|
| 281 |
+
# Reset query count
|
| 282 |
+
SESSION_DATA['query_count'] = 0
|
| 283 |
+
|
| 284 |
+
# Calculate statistics
|
| 285 |
+
word_count = len(text_content.split())
|
| 286 |
+
char_count = len(text_content)
|
| 287 |
+
|
| 288 |
+
success_msg = f"""✅ दस्तावेज़ सफलतापूर्वक प्रसंस्करित!
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
+
📖 पुस्तक: {book_title}
|
| 291 |
+
✍️ लेखक: {author_name}
|
| 292 |
+
📄 टेक्स्ट खंड: {len(chunks)}
|
| 293 |
+
📊 शब्द संख्या: {word_count:,}
|
| 294 |
+
📝 अक्षर संख्या: {char_count:,}
|
| 295 |
|
| 296 |
+
अब आप प्रश्न पूछ सकते हैं।"""
|
| 297 |
+
|
| 298 |
+
return success_msg, book_title, author_name, gr.update(visible=True)
|
| 299 |
|
|
|
|
|
|
|
| 300 |
except Exception as e:
|
| 301 |
+
return f"दस्तावेज़ प्रसंस्करण में त्रुटि: {str(e)}", "", "", gr.update(visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
+
# Query processing function
|
| 304 |
+
def process_query(audio_input, text_input):
|
| 305 |
+
"""Process user query (audio or text)"""
|
| 306 |
+
if SESSION_DATA['query_count'] >= CONFIG['MAX_QUERIES_PER_SESSION']:
|
| 307 |
+
return "⚠️ प्रश्न सीमा समाप्त (5 प्रश्न प्रति सत्र)", None, f"प्रश्न: {SESSION_DATA['query_count']}/{CONFIG['MAX_QUERIES_PER_SESSION']}"
|
| 308 |
|
| 309 |
+
if not SESSION_DATA['document_chunks']:
|
| 310 |
+
return "कृपया पहले एक PDF दस्तावेज़ अपलोड करें।", None, f"प्रश्न: {SESSION_DATA['query_count']}/{CONFIG['MAX_QUERIES_PER_SESSION']}"
|
|
|
|
| 311 |
|
| 312 |
+
# Get query text
|
| 313 |
+
query_text = ""
|
| 314 |
|
| 315 |
+
if audio_input:
|
| 316 |
+
query_text = transcribe_audio(audio_input)
|
| 317 |
+
if "error" in query_text.lower():
|
| 318 |
+
query_text = ""
|
| 319 |
|
| 320 |
+
if not query_text.strip() and text_input.strip():
|
| 321 |
+
query_text = text_input.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
|
| 323 |
+
if not query_text.strip():
|
| 324 |
+
return "कृपया आवाज़ या टेक्स्ट के माध्यम से प्रश्न दें।", None, f"प्रश्न: {SESSION_DATA['query_count']}/{CONFIG['MAX_QUERIES_PER_SESSION']}"
|
| 325 |
+
|
| 326 |
+
try:
|
| 327 |
+
# Search similar chunks
|
| 328 |
+
similar_chunks = search_similar_chunks(query_text)
|
| 329 |
+
|
| 330 |
+
# Generate response
|
| 331 |
+
response_text = generate_rag_response(query_text, similar_chunks)
|
| 332 |
+
|
| 333 |
+
# Generate TTS
|
| 334 |
+
audio_response = text_to_speech(response_text)
|
| 335 |
+
|
| 336 |
+
# Update query count
|
| 337 |
+
SESSION_DATA['query_count'] += 1
|
| 338 |
+
|
| 339 |
+
# Format response with context
|
| 340 |
+
formatted_response = f"""**प्रश्न:** {query_text}
|
| 341 |
+
|
| 342 |
+
**उत्तर:**
|
| 343 |
+
{response_text}
|
| 344 |
+
|
| 345 |
+
**संदर्भ स्रोत:**
|
| 346 |
+
"""
|
| 347 |
+
|
| 348 |
+
for i, chunk in enumerate(similar_chunks):
|
| 349 |
+
formatted_response += f"\n{i+1}. {chunk['text'][:150]}... (स्कोर: {chunk['score']:.3f})"
|
| 350 |
+
|
| 351 |
+
return formatted_response, audio_response, f"प्रश्न: {SESSION_DATA['query_count']}/{CONFIG['MAX_QUERIES_PER_SESSION']}"
|
| 352 |
+
|
| 353 |
+
except Exception as e:
|
| 354 |
+
return f"प्रश्न प्रसंस्कर�� में त्रुटि: {str(e)}", None, f"प्रश्न: {SESSION_DATA['query_count']}/{CONFIG['MAX_QUERIES_PER_SESSION']}"
|
| 355 |
+
|
| 356 |
+
def reset_session():
|
| 357 |
+
"""Reset the session"""
|
| 358 |
+
SESSION_DATA.update({
|
| 359 |
+
'query_count': 0,
|
| 360 |
+
'document_chunks': [],
|
| 361 |
+
'faiss_index': None,
|
| 362 |
+
'author_name': '',
|
| 363 |
+
'book_title': '',
|
| 364 |
+
'session_id': str(uuid.uuid4())
|
| 365 |
+
})
|
| 366 |
+
return "✅ नया सत्र शुरू किया गया!", "", "", gr.update(visible=False), "प्रश्न: 0/5"
|
| 367 |
+
|
| 368 |
+
# Create Gradio interface
|
| 369 |
+
def create_interface():
|
| 370 |
+
"""Create the Gradio interface"""
|
| 371 |
+
|
| 372 |
+
with gr.Blocks(
|
| 373 |
+
title="Hindi RAG Voice Demo",
|
| 374 |
+
theme=gr.themes.Soft(),
|
| 375 |
+
css="""
|
| 376 |
+
.main-header { text-align: center; color: #2E86AB; margin-bottom: 2rem; }
|
| 377 |
+
.section-header { color: #A23B72; font-weight: bold; margin: 1rem 0; }
|
| 378 |
+
.info-box { background: #F18F01; color: white; padding: 1rem; border-radius: 8px; margin: 1rem 0; }
|
| 379 |
+
"""
|
| 380 |
+
) as demo:
|
| 381 |
+
|
| 382 |
+
gr.HTML("""
|
| 383 |
+
<div class="main-header">
|
| 384 |
+
<h1>📚 Hindi RAG Voice Demo</h1>
|
| 385 |
+
<h3>हिंदी पुस्तक आवाज़ सहायक</h3>
|
| 386 |
+
<p>AI-powered interactive book assistant for Indian authors</p>
|
| 387 |
+
<p><em>Optimized for PDFs with selectable text</em></p>
|
| 388 |
+
</div>
|
| 389 |
+
""")
|
| 390 |
+
|
| 391 |
+
# Authentication section
|
| 392 |
+
with gr.Group(visible=True) as auth_section:
|
| 393 |
+
gr.Markdown("### 🔐 Access Control / पहुंच नियंत्रण")
|
| 394 |
+
gr.Markdown("Please enter the passcode to access the demo / कृपया डेमो एक्सेस करने के लिए पासकोड दर्ज करें")
|
| 395 |
+
|
| 396 |
+
passcode_input = gr.Textbox(
|
| 397 |
+
label="Passcode / पासकोड",
|
| 398 |
+
type="password",
|
| 399 |
+
placeholder="Enter passcode here..."
|
| 400 |
+
)
|
| 401 |
+
auth_button = gr.Button("🔓 Access Demo / डेमो एक्सेस करें", variant="primary")
|
| 402 |
+
auth_status = gr.Textbox(label="Status", interactive=False)
|
| 403 |
+
|
| 404 |
+
# Main application section
|
| 405 |
+
with gr.Group(visible=False) as main_section:
|
| 406 |
+
|
| 407 |
+
# Session info
|
| 408 |
+
with gr.Row():
|
| 409 |
+
with gr.Column(scale=3):
|
| 410 |
+
gr.Markdown("### 📊 Session Information")
|
| 411 |
+
with gr.Column(scale=1):
|
| 412 |
+
query_counter = gr.Textbox(
|
| 413 |
+
label="Query Usage",
|
| 414 |
+
value="प्रश्न: 0/5",
|
| 415 |
+
interactive=False
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# Document upload section
|
| 419 |
+
gr.Markdown("### 📁 Step 1: Upload Your Book / अपनी पुस्तक अपलोड करें")
|
| 420 |
+
gr.Markdown("**Note:** Please ensure your PDF contains selectable text (not scanned images)")
|
| 421 |
+
|
| 422 |
+
with gr.Row():
|
| 423 |
+
pdf_upload = gr.File(
|
| 424 |
+
label="Upload PDF / PDF अपलोड करें",
|
| 425 |
+
file_types=[".pdf"],
|
| 426 |
+
type="filepath"
|
| 427 |
+
)
|
| 428 |
+
process_btn = gr.Button("📖 Process Document / दस्तावेज़ प्रसंस्करित करें", variant="primary")
|
| 429 |
+
|
| 430 |
+
doc_status = gr.Textbox(label="Processing Status / प्रसंस्करण स्थिति", interactive=False)
|
| 431 |
+
|
| 432 |
+
with gr.Row():
|
| 433 |
+
book_title_display = gr.Textbox(label="Book Title / पुस्तक शीर्षक", interactive=False)
|
| 434 |
+
author_display = gr.Textbox(label="Author / लेखक", interactive=False)
|
| 435 |
+
|
| 436 |
+
# Query section
|
| 437 |
+
with gr.Group(visible=False) as query_section:
|
| 438 |
+
gr.Markdown("### 🎤 Step 2: Ask Questions / प्रश्न पूछें")
|
| 439 |
+
|
| 440 |
+
with gr.Row():
|
| 441 |
+
with gr.Column():
|
| 442 |
+
audio_input = gr.Audio(
|
| 443 |
+
label="🎙️ Record Voice Question / आवाज़ प्रश्न रिकॉर्ड करें",
|
| 444 |
+
sources=["microphone"],
|
| 445 |
+
type="filepath"
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
with gr.Column():
|
| 449 |
+
text_input = gr.Textbox(
|
| 450 |
+
label="💬 Or Type Question / या प्रश्न टाइप करें",
|
| 451 |
+
placeholder="उदाहरण: इस पुस्तक में मुख्य विषय क्या है?",
|
| 452 |
+
lines=3
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
ask_button = gr.Button("🔍 Get Answer / उत्तर पाएं", variant="primary", size="lg")
|
| 456 |
+
|
| 457 |
+
# Response section
|
| 458 |
+
with gr.Column():
|
| 459 |
+
response_text = gr.Textbox(
|
| 460 |
+
label="📝 Response / उत्तर",
|
| 461 |
+
lines=8,
|
| 462 |
+
interactive=False
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
response_audio = gr.Audio(
|
| 466 |
+
label="🔊 Audio Response / आवाज़ उत्तर",
|
| 467 |
+
interactive=False
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
# Reset section
|
| 471 |
+
gr.Markdown("---")
|
| 472 |
+
with gr.Row():
|
| 473 |
+
reset_btn = gr.Button("🔄 Start New Session / नया सत्र शुरू करें", variant="secondary")
|
| 474 |
+
|
| 475 |
+
with gr.Column():
|
| 476 |
+
gr.Markdown("""
|
| 477 |
+
**Requirements & Limits / आवश्यकताएं और सीमा:**
|
| 478 |
+
- PDF with selectable text (no scanned images)
|
| 479 |
+
- Max file size: 10MB
|
| 480 |
+
- Max queries: 5 per session
|
| 481 |
+
- Supported: Hindi & English text
|
| 482 |
+
""")
|
| 483 |
+
|
| 484 |
+
# Event handlers
|
| 485 |
+
auth_button.click(
|
| 486 |
+
authenticate,
|
| 487 |
+
inputs=[passcode_input],
|
| 488 |
+
outputs=[auth_section, main_section, auth_status]
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
process_btn.click(
|
| 492 |
+
process_document,
|
| 493 |
+
inputs=[pdf_upload],
|
| 494 |
+
outputs=[doc_status, book_title_display, author_display, query_section]
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
ask_button.click(
|
| 498 |
+
process_query,
|
| 499 |
+
inputs=[audio_input, text_input],
|
| 500 |
+
outputs=[response_text, response_audio, query_counter]
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
reset_btn.click(
|
| 504 |
+
reset_session,
|
| 505 |
+
outputs=[doc_status, book_title_display, author_display, query_section, query_counter]
|
| 506 |
+
)
|
| 507 |
+
|
| 508 |
+
# Load models on startup
|
| 509 |
+
demo.load(load_models)
|
| 510 |
|
| 511 |
+
return demo
|
| 512 |
+
|
| 513 |
+
# Main function
|
| 514 |
+
def main():
|
| 515 |
+
"""Main function to launch the application"""
|
| 516 |
+
print("🚀 Starting Hindi RAG Voice Demo (No OCR Version)...")
|
| 517 |
+
print("📋 Loading AI models (this may take a moment)...")
|
| 518 |
|
| 519 |
+
# Pre-load models
|
| 520 |
+
load_models()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 521 |
|
| 522 |
+
# Create and launch interface
|
| 523 |
+
demo = create_interface()
|
|
|
|
|
|
|
|
|
|
| 524 |
|
| 525 |
+
print("✅ Models loaded successfully!")
|
| 526 |
+
print(f"🔑 Demo passcode: {CONFIG['PASSCODE']}")
|
| 527 |
+
print("🌐 Launching web interface...")
|
|
|
|
|
|
|
| 528 |
|
| 529 |
+
demo.launch(
|
| 530 |
+
share=True,
|
| 531 |
+
show_error=True,
|
| 532 |
)
|
| 533 |
|
| 534 |
if __name__ == "__main__":
|
| 535 |
+
main()
|