Spaces:
Sleeping
Sleeping
Commit ·
be22066
1
Parent(s): 0ba063f
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270import osimport tempfileimport gradio as grimport numpy as npimport faissfrom sentence_transformers import SentenceTransformerimport google.generativeai as genaiimport fitz # PyMuPDFimport traceback# Initialize embedding modelsbert_model = SentenceTransformer('all-MiniLM-L6-v2')# Get API key from environmentGEMINI_API_KEY = os.getenv('GAPI')# Data storagechunks = []faiss_index = Noneembedding_dimension = 384 # all-MiniLM-L6-v2 embedding dimensiondef extract_text_from_pdf(pdf_file_path, start_page=None, end_page=None):"""Extract text from PDF file, optionally from a specific page range."""doc = fitz.open(pdf_file_path)text = ""num_pages_in_doc = doc.page_countif start_page is not None and end_page is not None:start_idx = start_page - 1end_idx = end_page - 1if 0 <= start_idx <= end_idx < num_pages_in_doc:pages_to_process = range(start_idx, end_idx + 1)else:pages_to_process = range(num_pages_in_doc)else:pages_to_process = range(num_pages_in_doc)for i in pages_to_process:text += doc.load_page(i).get_text()doc.close()return text, num_pages_in_docdef chunk_text(text, chunk_size=1000, overlap=200):"""Split text into overlapping chunks"""doc_chunks = []for i in range(0, len(text), chunk_size - overlap):chunk = text[i:i + chunk_size]if len(chunk) > 100:doc_chunks.append(chunk)return doc_chunksdef create_faiss_index(embeddings):"""Create FAISS index for fast similarity search."""global embedding_dimension# Normalize embeddings for cosine similarityfaiss.normalize_L2(embeddings)# Create index - using IndexFlatIP for cosine similarityindex = faiss.IndexFlatIP(embedding_dimension)index.add(embeddings)return indexdef process_pdf(pdf_file_obj):"""Process PDF and create FAISS index."""global chunks, faiss_indexif not GEMINI_API_KEY:return None, [["System", "⚠️ GAPI environment variable not set. Please configure your Gemini API key."]]if pdf_file_obj is None:return None, [["System", "📄 Please upload a PDF file."]]try:# Save uploaded file temporarilywith open(pdf_file_obj.name, "rb") as f_in:pdf_bytes = f_in.read()with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp:tmp.write(pdf_bytes)tmp_path = tmp.name# Extract texttext, total_pages = extract_text_from_pdf(tmp_path)if not text.strip():return None, [["System", "⚠️ No text found in the PDF. Please try a different file."]]# Create chunkscurrent_chunks = chunk_text(text)if not current_chunks:return None, [["System", "⚠️ Could not create text chunks from the PDF."]]# Generate embeddingscurrent_embeddings = sbert_model.encode(current_chunks)current_embeddings = np.array(current_embeddings, dtype=np.float32)# Create FAISS indexcurrent_index = create_faiss_index(current_embeddings)# Update global storagechunks = current_chunksfaiss_index = current_indexpdf_name = os.path.basename(pdf_file_obj.name)success_msg = f"✅ Successfully processed '{pdf_name}' ({total_pages} pages, {len(chunks)} chunks). FAISS index created! You can now ask questions!"# Clean upif os.path.exists(tmp_path):os.unlink(tmp_path)return None, [["System", success_msg]]except Exception as e:chunks = []faiss_index = Noneerror_msg = f"❌ Error processing PDF: {str(e)}"return None, [["System", error_msg]]def retrieve_relevant_chunks(query, top_k=3):"""Retrieve most relevant chunks using FAISS search."""global chunks, faiss_indexif not chunks or faiss_index is None:return []try:# Encode queryquery_embedding = sbert_model.encode([query])query_embedding = np.array(query_embedding, dtype=np.float32)# Normalize for cosine similarityfaiss.normalize_L2(query_embedding)# Search using FAISSscores, indices = faiss_index.search(query_embedding, top_k)# Get top chunkstop_chunks = []for idx in indices[0]:if idx < len(chunks): # Safety checktop_chunks.append(chunks[idx])return top_chunksexcept Exception as e:print(f"Error in FAISS search: {str(e)}")return []def chat_fn(message, history):"""Handle chat interaction."""if not message.strip():return history, ""# Add user message to historyhistory = history + [[message, None]]if not GEMINI_API_KEY:history[-1][1] = "⚠️ GAPI environment variable not set. Please configure your Gemini API key."return history, ""if not chunks or faiss_index is None:history[-1][1] = "📄 Please upload and process a PDF document first."return history, ""try:# Configure Geminigenai.configure(api_key=GEMINI_API_KEY)# Get relevant context using FAISScontext_chunks = retrieve_relevant_chunks(message, top_k=5)if not context_chunks:history[-1][1] = "❌ Could not find relevant information in the document."return history, ""# Generate responsecontext = "\n\n".join(context_chunks)prompt = f"""Based on the following context from the document, answer the user's question.Context:{context}Question: {message}Please provide a clear, accurate answer based only on the information in the context. If the context doesn't contain enough information to answer the question, say so."""model = genai.GenerativeModel('gemini-1.5-flash-latest')response = model.generate_content(prompt)history[-1][1] = response.textexcept Exception as e:history[-1][1] = f"❌ Error: {str(e)}"return history, ""# Custom CSS for better chat appearancecss = """.gradio-container {max-width: 800px !important;margin: auto !important;}.chat-message {padding: 10px !important;margin: 5px 0 !important;border-radius: 10px !important;}"""with gr.Blocks(css=css, title="📚 Chat with Your PDF") as demo:gr.Markdown(f"""# 📚 Chat with Your PDF (FAISS-Powered)Upload a PDF document and chat with it naturally. Now with FAISS for faster vector search!{"✅ API Key: Configured from environment" if GEMINI_API_KEY else "❌ API Key: Not found in GAPI environment variable"}""")pdf_input = gr.File(label="📄 Upload PDF",file_types=['.pdf'])# Chat interfacechatbot = gr.Chatbot(label="💬 Chat",height=500,show_label=False,bubble_full_width=False)msg_input = gr.Textbox(label="Message",placeholder="Ask anything about your PDF...",show_label=False,container=False)with gr.Row():submit_btn = gr.Button("Send 💬", variant="primary")clear_btn = gr.Button("Clear Chat 🗑️")# Event handlerspdf_input.upload(fn=process_pdf,inputs=[pdf_input],outputs=[msg_input, chatbot])submit_btn.click(fn=chat_fn,inputs=[msg_input, chatbot],outputs=[chatbot, msg_input])msg_input.submit(fn=chat_fn,inputs=[msg_input, chatbot],outputs=[chatbot, msg_input])clear_btn.click(fn=lambda: ([], ""),outputs=[chatbot, msg_input])if __name__ == "__main__":demo.launch(share=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535#!/usr/bin/env python3"""Hindi RAG Voice Demo - Gradio Implementation (No OCR Version)A streamlined voice-enabled RAG system for Hindi content using GradioAssumes PDFs have selectable text - no OCR processing"""import gradio as grimport osimport tempfileimport timeimport uuidfrom datetime import datetimeimport fitz # PyMuPDFimport requestsimport jsonimport numpy as npfrom sentence_transformers import SentenceTransformerimport faissimport whisperfrom gtts import gTTSimport warningswarnings.filterwarnings("ignore")# Global configurationCONFIG = {'PASSCODE': os.getenv('PASSCODE'),'MAX_FILE_SIZE': 10 * 1024 * 1024, # 10MB'MAX_QUERIES_PER_SESSION': 5,'MAX_AUDIO_DURATION': 120, # 2 minutes'GROQ_API_KEY': os.getenv('GAPI'),}# Global session storageSESSION_DATA = {'authenticated': False,'session_id': str(uuid.uuid4()),'query_count': 0,'document_chunks': [],'faiss_index': None,'author_name': '','book_title': '','embedding_model': None,'whisper_model': None}# Initialize models (cached)def load_models():"""Load and cache models"""if SESSION_DATA['embedding_model'] is None:print("Loading embedding model...")SESSION_DATA['embedding_model'] = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')if SESSION_DATA['whisper_model'] is None:print("Loading Whisper model...")SESSION_DATA['whisper_model'] = whisper.load_model("base")return SESSION_DATA['embedding_model'], SESSION_DATA['whisper_model']# Text extraction functionsdef extract_text_from_pdf(pdf_path):"""Extract text from PDF using PyMuPDF (assumes selectable text)"""text_content = ""try:pdf_document = fitz.open(pdf_path)total_pages = len(pdf_document)print(f"Processing PDF with {total_pages} pages...")# Process all pages (removed page limit for production use)for page_num in range(total_pages):page = pdf_document.load_page(page_num)page_text = page.get_text()# Add page text if it existsif page_text.strip():text_content += page_text + "\n"else:print(f"Warning: Page {page_num + 1} appears to have no selectable text")pdf_document.close()if not text_content.strip():return "Error: No selectable text found in PDF. Please ensure the PDF contains selectable text, not just images."return text_contentexcept Exception as e:return f"Error extracting text: {str(e)}"def extract_metadata(text):"""Extract author name and book title from text"""lines = [line.strip() for line in text.split('\n')[:25] if line.strip()]author_name = "अज्ञात लेखक"book_title = "अनाम पुस्तक"# Simple heuristics for metadata extractionfor i, line in enumerate(lines):# Look for author patternsif any(word in line.lower() for word in ['लेखक', 'author', 'by', 'द्वारा', 'रचयिता']):author_name = line# First substantial line might be titleelif 10 < len(line) < 100 and not any(char.isdigit() for char in line[:20]):if book_title == "अनाम पुस्तक":book_title = linereturn author_name, book_titledef chunk_text(text, chunk_size=400, overlap=50):"""Split text into overlapping chunks"""words = text.split()chunks = []for i in range(0, len(words), chunk_size - overlap):chunk = ' '.join(words[i:i + chunk_size])if chunk.strip():chunks.append(chunk)return chunks# Vector search functionsdef create_embeddings(chunks):"""Create embeddings and FAISS index"""embedding_model, _ = load_models()embeddings = embedding_model.encode(chunks, show_progress_bar=False)# Create FAISS indexdimension = embeddings.shape[1]index = faiss.IndexFlatIP(dimension)# Normalize embeddings for cosine similarityfaiss.normalize_L2(embeddings)index.add(embeddings.astype('float32'))return indexdef search_similar_chunks(query, top_k=3):"""Search for similar chunks"""if SESSION_DATA['faiss_index'] is None or not SESSION_DATA['document_chunks']:return []embedding_model, _ = load_models()query_embedding = embedding_model.encode([query], show_progress_bar=False)faiss.normalize_L2(query_embedding)scores, indices = SESSION_DATA['faiss_index'].search(query_embedding.astype('float32'), top_k)results = []for i, idx in enumerate(indices[0]):if idx >= 0 and idx < len(SESSION_DATA['document_chunks']):results.append({'text': SESSION_DATA['document_chunks'][idx],'score': float(scores[0][i])})return results# LLM functionsdef call_groq_api(prompt, model="llama-3.1-8b-instant"):"""Call Groq API for LLM inference"""if not CONFIG['GROQ_API_KEY'] or CONFIG['GROQ_API_KEY'] == 'your_groq_api_key_here':return "⚠️ Groq API key not configured. Please set GROQ_API_KEY environment variable."url = "https://api.groq.com/openai/v1/chat/completions"headers = {"Authorization": f"Bearer {CONFIG['GROQ_API_KEY']}","Content-Type": "application/json"}data = {"model": model,"messages": [{"role": "user", "content": prompt}],"temperature": 0.7,"max_tokens": 800}try:response = requests.post(url, headers=headers, json=data, timeout=30)response.raise_for_status()return response.json()['choices'][0]['message']['content']except Exception as e:return f"Error calling LLM: {str(e)}"def generate_rag_response(query, context_chunks):"""Generate response using RAG"""if not context_chunks:return "मुझे इस प्रश्न का उत्तर देने के लिए पर्याप्त जानकारी नहीं मिली।"context = "\n\n".join([chunk['text'] for chunk in context_chunks])prompt = f"""आप एक हिंदी पुस्तक सहायक हैं। निम्नलिखित जानकारी के आधार पर प्रश्न का उत्तर दें:पुस्तक: {SESSION_DATA['book_title']}लेखक: {SESSION_DATA['author_name']}संदर्भ:{context}प्रश्न: {query}निर्देश:- हिंदी में संक्षिप्त और सटीक उत्तर दें- उत्तर की शुरुआत में पुस्तक और लेखक का संदर्भ शामिल करें- केवल दिए गए संदर्भ के आधार पर ही उत्तर दें"""response = call_groq_api(prompt)return response# Audio processing functionsdef transcribe_audio(audio_file):"""Transcribe audio using Whisper"""if audio_file is None:return ""try:_, whisper_model = load_models()result = whisper_model.transcribe(audio_file, language="hi")return result["text"]except Exception as e:return f"Transcription error: {str(e)}"def text_to_speech(text):"""Convert text to speech in Hindi"""if not text or len(text.strip()) == 0:return Nonetry:tts = gTTS(text=text, lang='hi', slow=False)# Save to temporary filewith tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:tts.save(tmp_file.name)return tmp_file.nameexcept Exception as e:print(f"TTS Error: {str(e)}")return None# Authentication functiondef authenticate(passcode):"""Check passcode authentication"""if passcode == CONFIG['PASSCODE']:SESSION_DATA['authenticated'] = Truereturn gr.update(visible=False), gr.update(visible=True), "✅ Access granted! / पहुंच मिली!"else:return gr.update(visible=True), gr.update(visible=False), "❌ Invalid passcode / गलत पासकोड"# Document processing functiondef process_document(pdf_file):"""Process uploaded PDF document"""if pdf_file is None:return "कृपया एक PDF फ़ाइल अपलोड करें।", "", "", gr.update(visible=False)try:# Check file sizefile_size = os.path.getsize(pdf_file.name)if file_size > CONFIG['MAX_FILE_SIZE']:return f"फ़ाइल बहुत बड़ी है! अधिकतम आकार: {CONFIG['MAX_FILE_SIZE'] // (1024*1024)}MB", "", "", gr.update(visible=False)# Extract text (no OCR - assumes selectable text)text_content = extract_text_from_pdf(pdf_file.name)if not text_content.strip() or "Error" in text_content:return text_content, "", "", gr.update(visible=False)# Extract metadataauthor_name, book_title = extract_metadata(text_content)SESSION_DATA['author_name'] = author_nameSESSION_DATA['book_title'] = book_title# Create chunkschunks = chunk_text(text_content)SESSION_DATA['document_chunks'] = chunks# Create embeddings and indexprint("Creating embeddings and search index...")SESSION_DATA['faiss_index'] = create_embeddings(chunks)# Reset query countSESSION_DATA['query_count'] = 0# Calculate statisticsword_count = len(text_content.split())char_count = len(text_content)success_msg = f"""✅ दस्तावेज़ सफलतापूर्वक प्रसंस्करित!📖 पुस्तक: {book_title}✍️ लेखक: {author_name}📄 टेक्स्ट खंड: {len(chunks)}📊 शब्द संख्या: {word_count:,}📝 अक्षर संख्या: {char_count:,}अब आप प्रश्न पूछ सकते हैं।"""return success_msg, book_title, author_name, gr.update(visible=True)except Exception as e:return f"दस्तावेज़ प्रसंस्करण में त्रुटि: {str(e)}", "", "", gr.update(visible=False)# Query processing functiondef process_query(audio_input, text_input):"""Process user query (audio or text)"""if SESSION_DATA['query_count'] >= CONFIG['MAX_QUERIES_PER_SESSION']:return "⚠️ प्रश्न सीमा समाप्त (5 प्रश्न प्रति सत्र)", None, f"प्रश्न: {SESSION_DATA['query_count']}/{CONFIG['MAX_QUERIES_PER_SESSION']}"if not SESSION_DATA['document_chunks']:return "कृपया पहले एक PDF दस्तावेज़ अपलोड करें।", None, f"प्रश्न: {SESSION_DATA['query_count']}/{CONFIG['MAX_QUERIES_PER_SESSION']}"# Get query textquery_text = ""if audio_input:query_text = transcribe_audio(audio_input)if "error" in query_text.lower():query_text = ""if not query_text.strip() and text_input.strip():query_text = text_input.strip()if not query_text.strip():return "कृपया आवाज़ या टेक्स्ट के माध्यम से प्रश्न दें।", None, f"प्रश्न: {SESSION_DATA['query_count']}/{CONFIG['MAX_QUERIES_PER_SESSION']}"try:# Search similar chunkssimilar_chunks = search_similar_chunks(query_text)# Generate responseresponse_text = generate_rag_response(query_text, similar_chunks)# Generate TTSaudio_response = text_to_speech(response_text)# Update query countSESSION_DATA['query_count'] += 1# Format response with contextformatted_response = f"""**प्रश्न:** {query_text}**उत्तर:**{response_text}**संदर्भ स्रोत:**"""for i, chunk in enumerate(similar_chunks):formatted_response += f"\n{i+1}. {chunk['text'][:150]}... (स्कोर: {chunk['score']:.3f})"return formatted_response, audio_response, f"प्रश्न: {SESSION_DATA['query_count']}/{CONFIG['MAX_QUERIES_PER_SESSION']}"except Exception as e:return f"प्रश्न प्रसंस्कर�� में त्रुटि: {str(e)}", None, f"प्रश्न: {SESSION_DATA['query_count']}/{CONFIG['MAX_QUERIES_PER_SESSION']}"def reset_session():"""Reset the session"""SESSION_DATA.update({'query_count': 0,'document_chunks': [],'faiss_index': None,'author_name': '','book_title': '','session_id': str(uuid.uuid4())})return "✅ नया सत्र शुरू किया गया!", "", "", gr.update(visible=False), "प्रश्न: 0/5"# Create Gradio interfacedef create_interface():"""Create the Gradio interface"""with gr.Blocks(title="Hindi RAG Voice Demo",theme=gr.themes.Soft(),css=""".main-header { text-align: center; color: #2E86AB; margin-bottom: 2rem; }.section-header { color: #A23B72; font-weight: bold; margin: 1rem 0; }.info-box { background: #F18F01; color: white; padding: 1rem; border-radius: 8px; margin: 1rem 0; }""") as demo:gr.HTML("""<div class="main-header"><h1>📚 Hindi RAG Voice Demo</h1><h3>हिंदी पुस्तक आवाज़ सहायक</h3><p>AI-powered interactive book assistant for Indian authors</p><p><em>Optimized for PDFs with selectable text</em></p></div>""")# Authentication sectionwith gr.Group(visible=True) as auth_section:gr.Markdown("### 🔐 Access Control / पहुंच नियंत्रण")gr.Markdown("Please enter the passcode to access the demo / कृपया डेमो एक्सेस करने के लिए पासकोड दर्ज करें")passcode_input = gr.Textbox(label="Passcode / पासकोड",type="password",placeholder="Enter passcode here...")auth_button = gr.Button("🔓 Access Demo / डेमो एक्सेस करें", variant="primary")auth_status = gr.Textbox(label="Status", interactive=False)# Main application sectionwith gr.Group(visible=False) as main_section:# Session infowith gr.Row():with gr.Column(scale=3):gr.Markdown("### 📊 Session Information")with gr.Column(scale=1):query_counter = gr.Textbox(label="Query Usage",value="प्रश्न: 0/5",interactive=False)# Document upload sectiongr.Markdown("### 📁 Step 1: Upload Your Book / अपनी पुस्तक अपलोड करें")gr.Markdown("**Note:** Please ensure your PDF contains selectable text (not scanned images)")with gr.Row():pdf_upload = gr.File(label="Upload PDF / PDF अपलोड करें",file_types=[".pdf"],type="filepath")process_btn = gr.Button("📖 Process Document / दस्तावेज़ प्रसंस्करित करें", variant="primary")doc_status = gr.Textbox(label="Processing Status / प्रसंस्करण स्थिति", interactive=False)with gr.Row():book_title_display = gr.Textbox(label="Book Title / पुस्तक शीर्षक", interactive=False)author_display = gr.Textbox(label="Author / लेखक", interactive=False)# Query sectionwith gr.Group(visible=False) as query_section:gr.Markdown("### 🎤 Step 2: Ask Questions / प्रश्न पूछें")with gr.Row():with gr.Column():audio_input = gr.Audio(label="🎙️ Record Voice Question / आवाज़ प्रश्न रिकॉर्ड करें",sources=["microphone"],type="filepath")with gr.Column():text_input = gr.Textbox(label="💬 Or Type Question / या प्रश्न टाइप करें",placeholder="उदाहरण: इस पुस्तक में मुख्य विषय क्या है?",lines=3)ask_button = gr.Button("🔍 Get Answer / उत्तर पाएं", variant="primary", size="lg")# Response sectionwith gr.Column():response_text = gr.Textbox(label="📝 Response / उत्तर",lines=8,interactive=False)response_audio = gr.Audio(label="🔊 Audio Response / आवाज़ उत्तर",interactive=False)# Reset sectiongr.Markdown("---")with gr.Row():reset_btn = gr.Button("🔄 Start New Session / नया सत्र शुरू करें", variant="secondary")with gr.Column():gr.Markdown("""**Requirements & Limits / आवश्यकताएं और सीमा:**- PDF with selectable text (no scanned images)- Max file size: 10MB- Max queries: 5 per session- Supported: Hindi & English text""")# Event handlersauth_button.click(authenticate,inputs=[passcode_input],outputs=[auth_section, main_section, auth_status])process_btn.click(process_document,inputs=[pdf_upload],outputs=[doc_status, book_title_display, author_display, query_section])ask_button.click(process_query,inputs=[audio_input, text_input],outputs=[response_text, response_audio, query_counter])reset_btn.click(reset_session,outputs=[doc_status, book_title_display, author_display, query_section, query_counter])# Load models on startupdemo.load(load_models)return demo# Main functiondef main():"""Main function to launch the application"""print("🚀 Starting Hindi RAG Voice Demo (No OCR Version)...")print("📋 Loading AI models (this may take a moment)...")# Pre-load modelsload_models()# Create and launch interfacedemo = create_interface()print("✅ Models loaded successfully!")print(f"🔑 Demo passcode: {CONFIG['PASSCODE']}")print("🌐 Launching web interface...")demo.launch(share=True,show_error=True,)if __name__ == "__main__":main()
app.py+484-219