Spaces:
Build error
Build error
SHAMIL SHAHBAZ AWAN commited on
Update app.py
Browse files17 unmodified lines181920212222232425262726282930313233346 unmodified lines414243444546474845495051523 unmodified lines5657585559606162586364606165666768697071676872737475767778797580818283848586878889909192939495969798991002 unmodified lines1031041051061071081091 unmodified line11111211311411511610711711811912012112212312412512612712812913013113213313413513613713813914014114212512612714314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817915418015615718118218318418518615916018718818916219019119219319419519619719819917 unmodified lines background-repeat: no-repeat; }} /* Ensure title is black */ h1 {{ color: black !important; color: black !important; /* Force title color to black */ }} /* Set footer text color to white */ h2, h3, h4, h5, h6, p {{ color: black; color: black; /* Set text color to black */ }} /* Set footer styling */ .footer {{ position: fixed; bottom: 0;6 unmodified lines font-size: 14px; }} /* Set processing button color to green */ .stButton button {{ background-color: green; color: white; }} /* Set query input block background color to white */ .stTextInput input {{ background-color: white; color: black;3 unmodified lines unsafe_allow_html=True)
# Load Hugging Face Secrets# Use your Groq API key from Hugging Face SecretsHUGGINGFACE_KEY = os.getenv("HUGGINGFACE_KEY")
if not HUGGINGFACE_KEY: st.error("Hugging Face API token not found. Please set it in the Hugging Face Secrets.") st.error("Groq API key not found. Please set it in Hugging Face Secrets.")
# Initialize Groq clientgroq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))# Initialize Groq client with the correct API keygroq_client = Groq(api_key=HUGGINGFACE_KEY)
# Load the SentenceTransformer model for embedding generationembedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
# Define file path and vector store folderfile_path = "The Rise of Agentic AI.pdf" VECTORSTORE_FOLDER = "vectorstore" file_path = "The Rise of Agentic AI.pdf" # File directly in the root directory of the appVECTORSTORE_FOLDER = "vectorstore" # Folder where the FAISS index will be stored
# Ensure the vector store folder existsif not os.path.exists(VECTORSTORE_FOLDER): os.makedirs(VECTORSTORE_FOLDER)
# Define the vector store pathvectorstore_path = os.path.join(VECTORSTORE_FOLDER, "index.faiss") vectorstore_path = os.path.join(VECTORSTORE_FOLDER, "index.faiss") # Correct path to the index file
# Load or create FAISS indexif os.path.exists(vectorstore_path): # If the index file exists, read it try: index = faiss.read_index(vectorstore_path) except Exception as e: st.error(f"Error reading the FAISS index: {e}") index = faiss.IndexFlatL2(embedder.get_sentence_embedding_dimension())else: # If the index file doesn't exist, create a new one index = faiss.IndexFlatL2(embedder.get_sentence_embedding_dimension())
# Variable to hold chunks globallychunks = []
# Function to load text from PDFdef load_pdf_text(file_path): """Extract text from the given PDF file.""" text = ""2 unmodified lines text += page.extract_text() return text
# Function to chunk text into smaller piecesdef chunk_text(text, chunk_size=500, overlap=100): """Chunk the text into overlapping chunks.""" chunks = []1 unmodified line chunks.append(text[i:i + chunk_size]) return chunks
# Process the document and update vector storedef process_and_store_document(file_path): """Process the PDF document, chunk text, generate embeddings, and store them in FAISS.""" global chunks global chunks # Make chunks global to access in the query part st.info("Processing PDF document...") # Extract text from the PDF file text = load_pdf_text(file_path) # Chunk the text into smaller pieces chunks = chunk_text(text) # Generate embeddings for each chunk embeddings = embedder.encode(chunks, show_progress_bar=True) # Add the embeddings to the FAISS index index.add(np.array(embeddings)) # Save the updated FAISS index try: faiss.write_index(index, vectorstore_path) st.success("Document processed and vector store updated!") except Exception as e: st.error(f"Error saving the FAISS index: {e}")
# User interface for Streamlitst.title("The Rise of Agentic AI RAG Application")
if st.button("Process PDF"): process_and_store_document(file_path)
# Query input for the useruser_query = st.text_input("Enter your query:")
if user_query: # Check if there are any chunks in the index if not chunks: st.error("Please process the document first by clicking 'Process PDF'.") else: # Generate embedding for the user query query_embedding = embedder.encode([user_query]) # Perform the search on the FAISS index distances, indices = index.search(np.array(query_embedding), k=5) # Check if the indices returned are valid if indices.size == 0 or np.any(indices[0] == -1): st.error("No relevant results found in the index.") else: # Ensure indices are within the bounds of the chunks list valid_indices = [idx for idx in indices[0] if idx < len(chunks)] if not valid_indices: st.error("No valid indices found for the retrieved chunks.") else: # Retrieve the most relevant chunks based on the valid indices retrieved_chunks = [chunks[idx] for idx in valid_indices] # Display the retrieved chunks st.subheader("Retrieved Chunks") for chunk in retrieved_chunks: st.write(chunk) # Combine the retrieved chunks with the query and generate a response using Groq combined_input = " ".join(retrieved_chunks) + user_query # Generate a response with Groq try: # Using the Groq client for generating a response chat_completion = groq_client.chat.completions.create( messages=[{"role": "user", "content": combined_input}], model="llama3-8b-8192" messages=[{ "role": "user", "content": combined_input, }], model="llama3-8b-8192", # Specify the model you want to use ) response = chat_completion.choices[0].message.content
# Display the generated response st.subheader("Generated Response") st.write(response) st.write(chat_completion.choices[0].message.content) except Exception as e: st.error(f"Error generating response: {e}")
# Button to trigger document processingif st.button("Process PDF"): process_and_store_document(file_path)
# Footerst.markdown("<div class='footer'>Created by Shamil Shahbaz</div>", unsafe_allow_html=True)app.py+53-20