import os import sys import logging import gradio as gr import openai import requests import shutil import pandas as pd from docx import Document as DocxDocument import fitz # PyMuPDF from pinecone import Pinecone, ServerlessSpec from llama_index.core import VectorStoreIndex, StorageContext, Document,SimpleDirectoryReader from llama_index.vector_stores.pinecone import PineconeVectorStore import uuid # --- Logging --- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # --- Set API Keys from Environment Variables --- openai.api_key = os.environ.get("OPENAI_API_KEY") pinecone_api_key = os.environ.get("PINECONE_API_KEY") if not openai.api_key or not pinecone_api_key: raise ValueError("OPENAI_API_KEY and PINECONE_API_KEY must be set in environment variables.") # --- Initialize Pinecone --- try: pc = Pinecone(api_key=pinecone_api_key) index_name = "hf-doc-qa" dimension = 1536 # Create the index if it doesn't exist if index_name not in [idx['name'] for idx in pc.list_indexes()]: logger.info(f"Creating Pinecone index: {index_name}") pc.create_index( name=index_name, dimension=dimension, metric="euclidean", spec=ServerlessSpec(cloud="aws", region="us-east-1"), ) pinecone_index = pc.Index(index_name) vector_store = PineconeVectorStore(pinecone_index=pinecone_index) storage_context = StorageContext.from_defaults(vector_store=vector_store) except Exception as e: logger.error(f"Failed to initialize Pinecone: {str(e)}") raise # --- Global Index --- index = None # --- Document Processing Functions --- def extract_text_from_pdf(file_path): """Extract text from a PDF file using PyMuPDF.""" try: doc = fitz.open(file_path) text = "" for page in doc: text += page.get_text() doc.close() return text except Exception as e: logger.error(f"Error processing PDF {file_path}: {str(e)}") return None def extract_text_from_docx(file_path): """Extract text from a DOCX file.""" try: doc = DocxDocument(file_path) text = "\n".join([para.text for para in doc.paragraphs if para.text]) return text except Exception as e: logger.error(f"Error processing DOCX {file_path}: {str(e)}") return None def extract_text_from_csv(file_path): """Extract text from a CSV file using pandas.""" try: df = pd.read_csv(file_path) # Convert DataFrame to a string representation text = df.to_string(index=False) return text except Exception as e: logger.error(f"Error processing CSV {file_path}: {str(e)}") return None def extract_text_from_txt(file_path): """Extract text from a TXT file.""" try: with open(file_path, "r", encoding="utf-8") as f: return f.read() except Exception as e: logger.error(f"Error processing TXT {file_path}: {str(e)}") return None def process_documents(files): global index data_dir = "./.data" os.makedirs(data_dir, exist_ok=True) try: for file in files: # Gradio gives a temporary file path file_ext = os.path.splitext(file.name)[1].lower() dest_path = os.path.join(data_dir, os.path.basename(file.name)) shutil.copy(file.name, dest_path) # Load files using SimpleDirectoryReader documents = SimpleDirectoryReader(input_dir=data_dir).load_data() # Create vector index vector_store = PineconeVectorStore(pinecone_index=pinecone_index) storage_context = StorageContext.from_defaults(vector_store=vector_store) index = VectorStoreIndex.from_documents(documents, storage_context=storage_context) logger.info("Documents indexed successfully") return "✅ Documents indexed successfully. You can now ask questions." except Exception as e: logger.error(f"Error processing documents: {str(e)}") return f"Error: {str(e)}" finally: # Optionally clean up .data folder after indexing shutil.rmtree(data_dir) def query_doc(prompt): """Query the indexed documents.""" if index is None: return "⚠️ Please upload and index documents first." try: response = index.as_query_engine().query(prompt) return str(response) except Exception as e: logger.error(f"Error querying documents: {str(e)}") return f"Error: {str(e)}" # --- Gradio Interface --- with gr.Blocks(title="Document QA with LlamaIndex + Pinecone") as demo: # Add company logo gr.HTML( """
Zain Logo
""" ) gr.Markdown("## 📄 Document QA Chatbot\nUpload your .txt, .pdf, .docx, or .csv files and ask questions based on the content.") with gr.Row(): file_input = gr.File( label="Upload Documents", file_types=[".txt", ".pdf", ".docx", ".csv"], file_count="multiple" ) upload_button = gr.Button("📥 Index Documents") status_output = gr.Textbox(label="Indexing Status", interactive=False) upload_button.click(fn=process_documents, inputs=[file_input], outputs=[status_output]) gr.Markdown("---") question_input = gr.Textbox(label="Ask a Question", placeholder="What is the document about?") answer_output = gr.Textbox(label="Answer") ask_button = gr.Button("💬 Get Answer") ask_button.click(fn=query_doc, inputs=question_input, outputs=answer_output) demo.launch()