Ahmed12322 commited on
Commit
b86c29a
Β·
verified Β·
1 Parent(s): c22b282

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -39
app.py CHANGED
@@ -7,8 +7,8 @@ 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")
@@ -16,86 +16,65 @@ embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
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)
101
-
 
7
  import pypdf
8
  from langchain.text_splitter import RecursiveCharacterTextSplitter
9
 
10
+ # Set Groq API key (replace with your actual key or use HF secrets)
11
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY") # Use HF secrets tab in Space settings
12
 
13
  # Load embedding model
14
  embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
 
16
  # Set up Groq client
17
  client = Groq(api_key=GROQ_API_KEY)
18
 
19
+ # 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
+ # Split text into 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
+ # Create FAISS index
31
  def create_faiss_index(chunks):
32
  embeddings = embedding_model.encode(chunks, convert_to_numpy=True)
 
 
33
  dimension = embeddings.shape[1]
34
  index = faiss.IndexFlatL2(dimension)
35
  index.add(embeddings)
 
 
 
 
 
36
  return index, chunks
37
 
38
+ # Search FAISS index
39
  def search_faiss(query, index, chunks, top_k=2):
40
  if index is None:
41
  return ["No database found. Please upload a PDF first."]
 
42
  query_embedding = embedding_model.encode([query], convert_to_numpy=True)
43
  distances, indices = index.search(query_embedding, top_k)
44
  return [chunks[i] for i in indices[0]]
45
 
46
+ # Query Groq
47
  def query_groq(query):
48
  chat_completion = client.chat.completions.create(
49
  messages=[{"role": "user", "content": query}],
50
+ model="llama-3-70b-8192", # or llama-3-8b-8192, depending on your access
51
  )
52
  return chat_completion.choices[0].message.content
53
 
54
  # Streamlit UI
55
  st.set_page_config(page_title="RAG Chatbot", page_icon="πŸ€–")
56
+ st.title("πŸ“„ RAG Chatbot with FAISS & Groq")
57
 
58
+ uploaded_file = st.file_uploader("πŸ“€ Upload a PDF", type="pdf")
 
59
 
60
  if uploaded_file:
61
  with st.spinner("πŸ”„ Processing PDF..."):
62
  text = extract_text_from_pdf(uploaded_file)
63
  chunks = create_chunks(text)
 
 
64
  index, chunks = create_faiss_index(chunks)
 
 
65
  st.session_state["faiss_index"] = index
66
  st.session_state["chunks"] = chunks
67
+ st.success("βœ… PDF processed!")
68
 
69
+ index = st.session_state.get("faiss_index", None)
70
+ chunks = st.session_state.get("chunks", [])
71
 
72
+ user_query = st.text_input("πŸ’¬ Ask something about the document:")
 
 
 
 
 
 
 
 
 
73
 
74
  if st.button("Search") and user_query:
75
+ with st.spinner("πŸ”Ž Generating response..."):
76
+ retrieved = search_faiss(user_query, index, chunks)
77
+ context = "\n".join(retrieved)
78
+ response = query_groq(context + "\n\nAnswer the question: " + user_query)
79
  st.write("### πŸ€– AI Response:")
80
  st.write(response)