Ahmed12322 commited on
Commit
196966d
Β·
verified Β·
1 Parent(s): e8d21ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -65
app.py CHANGED
@@ -1,71 +1,100 @@
1
  import streamlit as st
2
- import fitz # PyMuPDF
3
- from langchain.text_splitter import RecursiveCharacterTextSplitter
4
- from langchain.embeddings import HuggingFaceEmbeddings
5
- from langchain.vectorstores import FAISS
6
- import pickle
7
  from groq import Groq
8
  import os
 
 
9
 
10
- # Streamlit App
11
- st.title("RAG-based PDF Query App")
12
- st.write("Upload a PDF, extract its content, and query it using Groq API.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  # Upload PDF
15
- uploaded_file = st.file_uploader("Upload a PDF", type=["pdf"])
16
-
17
- if uploaded_file is not None:
18
- # Extract text from PDF
19
- def extract_text_from_pdf(uploaded_file):
20
- doc = fitz.open(stream=uploaded_file.read(), filetype="pdf")
21
- text = ""
22
- for page in doc:
23
- text += page.get_text()
24
- return text
25
-
26
- pdf_text = extract_text_from_pdf(uploaded_file)
27
- st.success("PDF uploaded and extracted successfully!")
28
-
29
- # Chunk & Tokenize Text
30
- def chunk_text(text, chunk_size=500, overlap=50):
31
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=overlap)
32
- return text_splitter.split_text(text)
33
-
34
- chunks = chunk_text(pdf_text)
35
-
36
- # Create Embeddings & Store in FAISS
37
- embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
38
- vector_store = FAISS.from_texts(chunks, embedding_model)
39
-
40
- # Save FAISS index
41
- with open("faiss_index.pkl", "wb") as f:
42
- pickle.dump(vector_store, f)
43
-
44
- st.success("Document processed and stored in vector database!")
45
-
46
- # Query Section
47
- query = st.text_input("Enter your query:")
48
-
49
- if st.button("Search"):
50
- if query:
51
- # Load FAISS index
52
- with open("faiss_index.pkl", "rb") as f:
53
- vector_store = pickle.load(f)
54
-
55
- docs = vector_store.similarity_search(query, k=3)
56
- context = "\n".join([doc.page_content for doc in docs])
57
-
58
-
59
- GROQ_API_KEY = os.environ["GROQ_API_KEY"] # Ensure you have stored it properly
60
- client = Groq(api_key=GROQ_API_KEY)
61
-
62
- response = client.chat.completions.create(
63
- messages=[{"role": "user", "content": context + "\n\n" + query}],
64
- model="llama-3.3-70b-versatile",
65
- )
66
-
67
- st.subheader("Response:")
68
- st.write(response.choices[0].message.content)
69
- else:
70
- st.warning("Please enter a query to search.")
71
-
 
1
  import streamlit as st
2
+ import faiss
3
+ import numpy as np
4
+ from sentence_transformers import SentenceTransformer
 
 
5
  from groq import Groq
6
  import os
7
+ import pypdf
8
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
9
 
10
+ # Set Groq API key
11
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY", "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")
12
+
13
+ # Load embedding model
14
+ embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
15
+
16
+ # Set up Groq client
17
+ client = Groq(api_key=GROQ_API_KEY)
18
+
19
+ # Function to extract text from PDF
20
+ def extract_text_from_pdf(uploaded_file):
21
+ reader = pypdf.PdfReader(uploaded_file)
22
+ text = "\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
23
+ return text
24
+
25
+ # Function to create text chunks
26
+ def create_chunks(text, chunk_size=500, chunk_overlap=100):
27
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
28
+ return text_splitter.split_text(text)
29
+
30
+ # Function to create and save FAISS index
31
+ def create_faiss_index(chunks):
32
+ embeddings = embedding_model.encode(chunks, convert_to_numpy=True)
33
+
34
+ # Create FAISS index
35
+ dimension = embeddings.shape[1]
36
+ index = faiss.IndexFlatL2(dimension)
37
+ index.add(embeddings)
38
+
39
+ # Save FAISS index and chunks
40
+ faiss.write_index(index, "faiss_index.bin")
41
+ np.save("chunks.npy", chunks)
42
+
43
+ return index, chunks
44
+
45
+ # Function to search FAISS
46
+ def search_faiss(query, index, chunks, top_k=2):
47
+ if index is None:
48
+ return ["No database found. Please upload a PDF first."]
49
+
50
+ query_embedding = embedding_model.encode([query], convert_to_numpy=True)
51
+ distances, indices = index.search(query_embedding, top_k)
52
+ return [chunks[i] for i in indices[0]]
53
+
54
+ # Function to query Groq
55
+ def query_groq(query):
56
+ chat_completion = client.chat.completions.create(
57
+ messages=[{"role": "user", "content": query}],
58
+ model="llama-3.3-70b-versatile",
59
+ )
60
+ return chat_completion.choices[0].message.content
61
+
62
+ # Streamlit UI
63
+ st.set_page_config(page_title="RAG Chatbot", page_icon="πŸ€–")
64
+ st.title("πŸ“„ RAG-Based Chatbot with FAISS & Groq")
65
 
66
  # Upload PDF
67
+ uploaded_file = st.file_uploader("πŸ“€ Upload a PDF file", type="pdf")
68
+
69
+ if uploaded_file:
70
+ with st.spinner("πŸ”„ Processing PDF..."):
71
+ text = extract_text_from_pdf(uploaded_file)
72
+ chunks = create_chunks(text)
73
+
74
+ # Create FAISS index
75
+ index, chunks = create_faiss_index(chunks)
76
+
77
+ # Store in session state
78
+ st.session_state["faiss_index"] = index
79
+ st.session_state["chunks"] = chunks
80
+
81
+ st.success("βœ… PDF processed successfully!")
82
+
83
+ # Load FAISS index if available
84
+ if "faiss_index" in st.session_state and "chunks" in st.session_state:
85
+ index = st.session_state["faiss_index"]
86
+ chunks = st.session_state["chunks"]
87
+ else:
88
+ index = None
89
+ chunks = []
90
+
91
+ # User query input
92
+ user_query = st.text_input("πŸ’¬ Ask me something about the document:")
93
+
94
+ if st.button("Search") and user_query:
95
+ with st.spinner("πŸ”Ž Retrieving response..."):
96
+ retrieved_text = search_faiss(user_query, index, chunks)
97
+ response = query_groq("\n".join(retrieved_text))
98
+
99
+ st.write("### πŸ€– AI Response:")
100
+ st.write(response)