Spaces:
Build error
Build error
SHAMIL SHAHBAZ AWAN commited on
Update app.py
Browse files17 unmodified lines18192021222324252627282930316 unmodified lines38394041424344454647483 unmodified lines52535455565758596061626364656667686970717273747576777879808182838485868788899091922 unmodified lines95969798991001 unmodified line10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516617 unmodified linesbackground-repeat: no-repeat;}}h1 {{color: black !important;}}h2, h3, h4, h5, h6, p {{color: black;}}.footer {{position: fixed;bottom: 0;6 unmodified linesfont-size: 14px;}}.stButton button {{background-color: green;color: white;}}.stTextInput input {{background-color: white;color: black;3 unmodified linesunsafe_allow_html=True)# Load 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.")# Initialize Groq clientgroq_client = Groq(api_key=os.getenv("GROQ_API_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"# 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")# Load or create FAISS indexif os.path.exists(vectorstore_path):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:index = faiss.IndexFlatL2(embedder.get_sentence_embedding_dimension())# Variable to hold chunks globallychunks = []def load_pdf_text(file_path):"""Extract text from the given PDF file."""text = ""2 unmodified linestext += page.extract_text()return textdef chunk_text(text, chunk_size=500, overlap=100):"""Chunk the text into overlapping chunks."""chunks = []1 unmodified linechunks.append(text[i:i + chunk_size])return chunksdef process_and_store_document(file_path):"""Process the PDF document, chunk text, generate embeddings, and store them in FAISS."""global chunksst.info("Processing PDF document...")text = load_pdf_text(file_path)chunks = chunk_text(text)embeddings = embedder.encode(chunks, show_progress_bar=True)index.add(np.array(embeddings))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}")st.title("The Rise of Agentic AI RAG Application")if st.button("Process PDF"):process_and_store_document(file_path)user_query = st.text_input("Enter your query:")if user_query:if not chunks:st.error("Please process the document first by clicking 'Process PDF'.")else:query_embedding = embedder.encode([user_query])distances, indices = index.search(np.array(query_embedding), k=5)if indices.size == 0 or np.any(indices[0] == -1):st.error("No relevant results found in the index.")else: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:retrieved_chunks = [chunks[idx] for idx in valid_indices]st.subheader("Retrieved Chunks")for chunk in retrieved_chunks:st.write(chunk)combined_input = " ".join(retrieved_chunks) + user_querytry:# Using the Groq client for generating a responsechat_completion = groq_client.chat.completions.create(messages=[{"role": "user", "content": combined_input}],model="llama3-8b-8192")response = chat_completion.choices[0].message.contentst.subheader("Generated Response")st.write(response)except Exception as e:st.error(f"Error generating response: {e}")st.markdown("<div class='footer'>Created by Shamil Shahbaz</div>", unsafe_allow_html=True)17 unmodified lines18192021222324252627282930313233346 unmodified lines4142434445464748495051523 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991002 unmodified lines1031041051061071081091 unmodified line11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819917 unmodified linesbackground-repeat: no-repeat;}}/* Ensure title is black */h1 {{color: black !important; /* Force title color to black */}}/* Set footer text color to white */h2, h3, h4, h5, h6, p {{color: black; /* Set text color to black */}}/* Set footer styling */.footer {{position: fixed;bottom: 0;6 unmodified linesfont-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 linesunsafe_allow_html=True)# Use your Groq API key from Hugging Face SecretsHUGGINGFACE_KEY = os.getenv("HUGGINGFACE_KEY")if not HUGGINGFACE_KEY:st.error("Groq API key not found. Please set it in Hugging Face Secrets.")# 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" # 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") # Correct path to the index file# Load or create FAISS indexif os.path.exists(vectorstore_path):# If the index file exists, read ittry: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 oneindex = 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 linestext += 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 linechunks.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 # Make chunks global to access in the query partst.info("Processing PDF document...")# Extract text from the PDF filetext = load_pdf_text(file_path)# Chunk the text into smaller pieceschunks = chunk_text(text)# Generate embeddings for each chunkembeddings = embedder.encode(chunks, show_progress_bar=True)# Add the embeddings to the FAISS indexindex.add(np.array(embeddings))# Save the updated FAISS indextry: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")# Query input for the useruser_query = st.text_input("Enter your query:")if user_query:# Check if there are any chunks in the indexif not chunks:st.error("Please process the document first by clicking 'Process PDF'.")else:# Generate embedding for the user queryquery_embedding = embedder.encode([user_query])# Perform the search on the FAISS indexdistances, indices = index.search(np.array(query_embedding), k=5)# Check if the indices returned are validif 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 listvalid_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 indicesretrieved_chunks = [chunks[idx] for idx in valid_indices]# Display the retrieved chunksst.subheader("Retrieved Chunks")for chunk in retrieved_chunks:st.write(chunk)# Combine the retrieved chunks with the query and generate a response using Groqcombined_input = " ".join(retrieved_chunks) + user_query# Generate a response with Groqtry:chat_completion = groq_client.chat.completions.create(messages=[{"role": "user","content": combined_input,}],model="llama3-8b-8192", # Specify the model you want to use)# Display the generated responsest.subheader("Generated 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