Spaces:
Sleeping
Sleeping
Download app.py from COLONEL-HERE/Prompt-PDF: direct link, hf CLI and curl.
- Browser
- Download file 19.5 kB
-
https://huggingface.co/spaces/COLONEL-HERE/Prompt-PDF/resolve/main/app.py
- Command line
-
hf download hf://spaces/COLONEL-HERE/Prompt-PDF/app.py
-
curl -L -o app.py https://huggingface.co/spaces/COLONEL-HERE/Prompt-PDF/resolve/main/app.py
19.5 kB
| import os | |
| import sys | |
| from langchain_community.vectorstores.pgvector import PGVector | |
| from langchain_core.vectorstores import VectorStore | |
| from langchain.text_splitter import RecursiveCharacterTextSplitter | |
| from langchain_core.documents import Document | |
| import streamlit as st | |
| import google.generativeai as genai | |
| from dotenv import load_dotenv | |
| import psycopg2 | |
| import datetime | |
| import nest_asyncio | |
| from llama_cloud_services import LlamaParse | |
| import logging | |
| import uuid | |
| import time | |
| # Configure logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
| handlers=[ | |
| logging.FileHandler("app.log"), | |
| logging.StreamHandler(sys.stdout) | |
| ] | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Apply nest_asyncio to allow nested event loops | |
| nest_asyncio.apply() | |
| load_dotenv() | |
| supabase_user = os.environ.get("user") | |
| supabase_password = os.environ.get("password") | |
| supabase_host = os.environ.get("host") | |
| # postgresql://{supabase_user}:{supabase_password}@{supabase_host}:6543/postgres | |
| connection_string = f"postgresql://{supabase_user}:{supabase_password}@{supabase_host}:6543/postgres" #connection string | |
| genai.configure(api_key=os.environ.get("GEMINI_API_KEY")) | |
| def ensure_pgvector(): | |
| logger.info("Checking PGVector extension") | |
| try: | |
| conn = psycopg2.connect(connection_string) | |
| cur = conn.cursor() | |
| cur.execute("CREATE EXTENSION IF NOT EXISTS vector;") | |
| conn.commit() | |
| cur.close() | |
| conn.close() | |
| logger.info("PGVector extension check successful") | |
| except Exception as e: | |
| logger.error(f"Failed to create vector extension: {str(e)}", exc_info=True) | |
| st.error(f"Failed to create vector extension: {str(e)}") | |
| raise e | |
| class GeminiEmbeddings: | |
| def __init__(self, status_callback=None): | |
| logger.info("Initializing GeminiEmbeddings") | |
| self.status_callback = status_callback | |
| def _update_status(self, message): | |
| logger.info(message) | |
| if self.status_callback: | |
| self.status_callback(message) | |
| def embed_documents(self, texts): | |
| self._update_status(f"Embedding {len(texts)} documents") | |
| start_time = time.time() | |
| embeddings = [] | |
| for i, text in enumerate(texts): | |
| try: | |
| embedding = genai.embed_content( | |
| model="models/embedding-001", | |
| content=text, | |
| task_type="retrieval_document" | |
| ) | |
| embeddings.append(embedding['embedding']) | |
| if i % 10 == 0 and i > 0: | |
| self._update_status(f"Embedded {i}/{len(texts)} documents") | |
| except Exception as e: | |
| logger.error(f"Error generating embedding for document {i}: {str(e)}", exc_info=True) | |
| st.error(f"Error generating embedding: {str(e)}") | |
| raise e | |
| processing_time = time.time() - start_time | |
| self._update_status(f"Embedded {len(texts)} documents in {processing_time:.2f} seconds") | |
| return embeddings | |
| def embed_query(self, text): | |
| self._update_status("Embedding query") | |
| start_time = time.time() | |
| try: | |
| response = genai.embed_content( | |
| model="models/embedding-001", | |
| content=text, | |
| task_type="retrieval_query" | |
| ) | |
| processing_time = time.time() - start_time | |
| self._update_status(f"Query embedded in {processing_time:.2f} seconds") | |
| return response['embedding'] | |
| except Exception as e: | |
| logger.error(f"Error generating query embedding: {str(e)}", exc_info=True) | |
| st.error(f"Error generating query embedding: {str(e)}") | |
| raise e | |
| def process_document(pdf, status_callback=None) -> VectorStore: | |
| """ | |
| Process a PDF document and store it in a vector database. | |
| Args: | |
| pdf: The PDF file to process | |
| status_callback: Optional callback function to report processing status | |
| Returns: | |
| VectorStore: The vector store containing the processed document | |
| """ | |
| logger.info("Starting document processing") | |
| start_time = time.time() | |
| # Helper function to log and update status | |
| def update_status(message): | |
| logger.info(message) | |
| if status_callback: | |
| status_callback(message) | |
| try: | |
| update_status("Initializing LlamaParse") | |
| parser = LlamaParse( | |
| api_key=os.environ.get("LLAMA_CLOUD_API_KEY"), | |
| result_type="markdown", | |
| use_vendor_multimodal_model=True, | |
| vendor_multimodal_model_name="anthropic-sonnet-3.7", | |
| ) | |
| # Get the file name from the uploaded file object | |
| file_name = pdf.name if hasattr(pdf, 'name') else "uploaded_document.pdf" | |
| update_status(f"Processing document: {file_name}") | |
| # Read the file content as bytes | |
| pdf_bytes = pdf.read() | |
| update_status(f"Read {len(pdf_bytes)} bytes from PDF file") | |
| # Parse with file name included | |
| update_status("Parsing PDF with LlamaParse (this may take a while)...") | |
| parse_start_time = time.time() | |
| result = parser.parse(pdf_bytes, extra_info={"file_name": file_name}) | |
| parse_time = time.time() - parse_start_time | |
| update_status(f"LlamaParse parsing completed in {parse_time:.2f} seconds") | |
| # Get the raw markdown content | |
| markdown_content = result.get_markdown() | |
| update_status(f"Retrieved markdown content: {len(markdown_content)} characters") | |
| # Process markdown content with preserved structure | |
| update_status("Creating text splitter") | |
| text_splitter = RecursiveCharacterTextSplitter( | |
| chunk_size=1000, | |
| chunk_overlap=200, | |
| ) | |
| # Split the content into chunks | |
| update_status("Splitting content into chunks") | |
| chunks = text_splitter.split_text(markdown_content) | |
| update_status(f"Created {len(chunks)} chunks") | |
| # Create Document objects with metadata | |
| update_status("Creating Document objects") | |
| documents = [] | |
| for i, chunk in enumerate(chunks): | |
| doc = Document( | |
| page_content=chunk, | |
| metadata={ | |
| "chunk": i + 1, | |
| "source": file_name, | |
| "total_chunks": len(chunks) | |
| } | |
| ) | |
| documents.append(doc) | |
| if i % 20 == 0 and i > 0: | |
| update_status(f"Created {i}/{len(chunks)} Document objects") | |
| # Store documents in vector database | |
| update_status("Generating embeddings and storing in vector database...") | |
| db_start_time = time.time() | |
| vector_store = PGVector.from_documents( | |
| documents=documents, | |
| embedding=GeminiEmbeddings(status_callback=status_callback), | |
| collection_name="pdf_embeddings", | |
| connection_string=connection_string, | |
| pre_delete_collection=True | |
| ) | |
| db_time = time.time() - db_start_time | |
| update_status(f"Vector database storage completed in {db_time:.2f} seconds") | |
| total_time = time.time() - start_time | |
| update_status(f"Total document processing completed in {total_time:.2f} seconds") | |
| return vector_store | |
| except Exception as e: | |
| error_msg = f"Failed to create vector store: {str(e)}" | |
| logger.error(error_msg, exc_info=True) | |
| if status_callback: | |
| status_callback(f"Error: {error_msg}") | |
| raise Exception(error_msg) | |
| def query_document(vector_store: VectorStore, query: str, k: int = 5): | |
| logger.info(f"Querying document with: '{query}'") | |
| start_time = time.time() | |
| try: | |
| # Perform similarity search with metadata filter options | |
| logger.info(f"Performing similarity search with k={k}, fetch_k={2*k}") | |
| search_start_time = time.time() | |
| docs = vector_store.similarity_search( | |
| query, | |
| k=k, | |
| fetch_k=2*k # Fetch more candidates for better results | |
| ) | |
| search_time = time.time() - search_start_time | |
| logger.info(f"Similarity search completed in {search_time:.2f} seconds, found {len(docs)} documents") | |
| # Sort results by page number for coherent context | |
| logger.info("Sorting results by page/chunk number") | |
| docs = sorted(docs, key=lambda x: (x.metadata.get('page', 0), x.metadata.get('chunk', 0))) | |
| # Log the chunks retrieved | |
| chunk_ids = [doc.metadata.get('chunk', 'Unknown') for doc in docs] | |
| logger.info(f"Retrieved chunks: {chunk_ids}") | |
| total_time = time.time() - start_time | |
| logger.info(f"Total query processing completed in {total_time:.2f} seconds") | |
| return docs | |
| except Exception as e: | |
| logger.error(f"Error during similarity search: {str(e)}", exc_info=True) | |
| st.error(f"Error during similarity search: {str(e)}") | |
| raise e | |
| def generate_response(docs, query: str) -> str: | |
| logger.info("Generating response") | |
| start_time = time.time() | |
| try: | |
| logger.info("Initializing Gemini model") | |
| model = genai.GenerativeModel("gemini-2.5-pro") | |
| # Format context with chunk numbers for better traceability | |
| logger.info("Formatting context from documents") | |
| formatted_contexts = [] | |
| for doc in docs: | |
| chunk_num = doc.metadata.get('chunk', 'Unknown') | |
| formatted_contexts.append(f"[Chunk {chunk_num}]: {doc.page_content}") | |
| context = "\n\n".join(formatted_contexts) | |
| logger.info(f"Combined context length: {len(context)} characters") | |
| # Build the prompt | |
| logger.info("Building prompt") | |
| prompt = f""" | |
| Today's Date: {datetime.datetime.now().strftime("%Y-%m-%d")} | |
| You are an AI assistant designed to analyze and extract information directly from uploaded PDF documents. | |
| Your primary goal is to provide accurate, concise, and contextually relevant answers strictly based on the content of the PDF. | |
| If a question cannot be answered using the provided document, clearly state that the information is not available instead of making assumptions or fabricating answers. | |
| The context below contains markdown content from a PDF with preserved tables, lists, and formatting. Use this structure when relevant in your answers. | |
| If Uncertain, Respond: "The provided PDF does not contain enough information to answer that question." | |
| Context: | |
| {context} | |
| Question: {query} | |
| Answer:""" | |
| # Generate response | |
| logger.info("Sending request to Gemini API") | |
| api_start_time = time.time() | |
| response = model.generate_content(prompt) | |
| api_time = time.time() - api_start_time | |
| logger.info(f"Gemini API response received in {api_time:.2f} seconds") | |
| total_time = time.time() - start_time | |
| logger.info(f"Total response generation completed in {total_time:.2f} seconds") | |
| return response.text | |
| except Exception as e: | |
| logger.error(f"Error generating response: {str(e)}", exc_info=True) | |
| st.error(f"Error generating response: {str(e)}") | |
| raise e | |
| def main(): | |
| # Set page config | |
| st.set_page_config( | |
| page_title="Prompt PDF : Chat with your Doc", | |
| page_icon="📄", | |
| layout="centered" | |
| ) | |
| logger.info("Starting application") | |
| # Initialize session state | |
| if 'vector_store' not in st.session_state: | |
| st.session_state.vector_store = None | |
| logger.info("Initialized vector_store in session state") | |
| if 'processing_query' not in st.session_state: | |
| st.session_state.processing_query = False | |
| logger.info("Initialized processing_query in session state") | |
| if 'session_id' not in st.session_state: | |
| st.session_state.session_id = str(uuid.uuid4()) | |
| logger.info(f"New session started with ID: {st.session_state.session_id}") | |
| if 'messages' not in st.session_state: | |
| st.session_state.messages = [] | |
| logger.info("Initialized messages in session state") | |
| # Main title | |
| st.header("Prompt PDF: Chat with your Doc 💬") | |
| # Sidebar for document upload and processing | |
| with st.sidebar: | |
| st.subheader("Document Settings") | |
| try: | |
| ensure_pgvector() # Initial checks | |
| logger.info("PGVector extension check completed") | |
| except Exception as e: | |
| logger.error(f"Failed to initialize pgvector: {str(e)}") | |
| st.error("Failed to initialize application requirements: pgvector()") | |
| return | |
| # File uploader | |
| pdf = st.file_uploader("Upload your Doc", type='pdf') | |
| if pdf is not None: | |
| logger.info(f"PDF uploaded: {pdf.name if hasattr(pdf, 'name') else 'unnamed'}") | |
| try: | |
| if st.button("Process Document"): | |
| logger.info("Process Document button clicked") | |
| # Create placeholder for dynamic progress updates | |
| progress_placeholder = st.empty() | |
| progress_placeholder.info("Starting document processing...") | |
| # Initialize processing state in session state | |
| if 'processing_status' not in st.session_state: | |
| st.session_state.processing_status = "" | |
| # Define a callback function for logging that updates the UI | |
| def update_processing_status(message): | |
| st.session_state.processing_status = message | |
| progress_placeholder.info(f"Processing: {message}") | |
| logger.info(message) | |
| try: | |
| start_time = time.time() | |
| # Process document with status updates | |
| st.session_state.vector_store = process_document( | |
| pdf, | |
| status_callback=update_processing_status | |
| ) | |
| processing_time = time.time() - start_time | |
| logger.info(f"Document processed successfully in {processing_time:.2f} seconds") | |
| # Add system message | |
| doc_name = pdf.name if hasattr(pdf, 'name') else "your document" | |
| system_msg = f"Document '{doc_name}' has been processed. You can now ask questions about it." | |
| st.session_state.messages.append({"role": "assistant", "content": system_msg}) | |
| logger.info(f"Added system message about document processing: {doc_name}") | |
| # Clear progress placeholder and show success | |
| progress_placeholder.empty() | |
| st.success("Document processed successfully!") | |
| except Exception as e: | |
| logger.error(f"Error processing document: {str(e)}", exc_info=True) | |
| st.error(f"Error processing document: {str(e)}") | |
| st.error(f"Error details: {type(e).__name__}") | |
| except Exception as e: | |
| logger.error(f"Error reading PDF: {str(e)}", exc_info=True) | |
| st.error(f"Error reading PDF: {str(e)}") | |
| # Display chat messages | |
| for message in st.session_state.messages: | |
| with st.chat_message(message["role"]): | |
| st.markdown(message["content"]) | |
| # Chat input | |
| if prompt := st.chat_input("What is up?"): | |
| logger.info(f"New query received: {prompt}") | |
| # Add user message to chat | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| with st.chat_message("user"): | |
| st.markdown(prompt) | |
| # Only process if we have a vector store and not already processing | |
| if st.session_state.vector_store and not st.session_state.processing_query: | |
| # Set processing flag to prevent infinite loops | |
| st.session_state.processing_query = True | |
| # Process query and generate response | |
| with st.chat_message("assistant"): | |
| with st.spinner("Thinking..."): | |
| try: | |
| logger.info("Starting query processing") | |
| start_time = time.time() | |
| # Get relevant documents | |
| docs = query_document(st.session_state.vector_store, prompt) | |
| logger.info(f"Retrieved {len(docs)} documents from vector store") | |
| # Generate response | |
| response = generate_response(docs, prompt) | |
| processing_time = time.time() - start_time | |
| logger.info(f"Generated response in {processing_time:.2f} seconds") | |
| # Display the response | |
| st.markdown(response) | |
| # Add to message history | |
| st.session_state.messages.append({"role": "assistant", "content": response}) | |
| # Create an expander for source information | |
| with st.expander("View source chunks", expanded=False): | |
| st.write(f"Source: {docs[0].metadata.get('source', 'Unknown') if docs else 'Unknown'}") | |
| # Show the actual content of each chunk used | |
| for i, doc in enumerate(docs): | |
| chunk_num = doc.metadata.get('chunk', 'Unknown') | |
| st.markdown(f"**Chunk {chunk_num}:**") | |
| st.markdown(doc.page_content) | |
| if i < len(docs) - 1: | |
| st.markdown("---") | |
| logger.info("Query processing completed successfully") | |
| except Exception as e: | |
| logger.error(f"Error processing query: {str(e)}", exc_info=True) | |
| st.error(f"Error processing query: {str(e)}") | |
| finally: | |
| # Reset the processing flag | |
| st.session_state.processing_query = False | |
| elif not st.session_state.vector_store: | |
| # If no document is processed yet | |
| with st.chat_message("assistant"): | |
| st.markdown("Please upload and process a document first before asking questions.") | |
| st.session_state.messages.append({"role": "assistant", "content": "Please upload and process a document first before asking questions."}) | |
| st.session_state.processing_query = False | |
| if __name__ == "__main__": | |
| main() |