meraj12 commited on
Commit
ed873c2
·
verified ·
1 Parent(s): 77b1c2d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -59
app.py CHANGED
@@ -1,77 +1,58 @@
1
- # Save as app.py
2
  import streamlit as st
3
- import fitz # PyMuPDF
4
- import faiss
5
- import os
6
  import numpy as np
 
7
  from sentence_transformers import SentenceTransformer
8
  import requests
9
 
10
- # Load SentenceTransformer model
11
- embedder = SentenceTransformer("all-MiniLM-L6-v2")
12
 
13
- # Load and split PDF
14
- def load_and_split_pdf(pdf_path):
15
- doc = fitz.open(pdf_path)
16
- chunks = []
17
- for page in doc:
18
- text = page.get_text()
19
- chunks.extend([chunk.strip() for chunk in text.split("\n") if chunk.strip()])
20
- return chunks
21
 
22
- # Embed chunks and save in FAISS
23
- def create_faiss_index(text_chunks):
24
- embeddings = embedder.encode(text_chunks)
25
- index = faiss.IndexFlatL2(embeddings.shape[1])
26
- index.add(np.array(embeddings))
27
- return index, text_chunks, embeddings
28
 
29
- # Search in FAISS
30
- def search_faiss(query, index, text_chunks, k=3):
31
- query_vec = embedder.encode([query])
32
- D, I = index.search(query_vec, k)
33
- results = [text_chunks[i] for i in I[0]]
34
  return "\n".join(results)
35
 
36
- # Call Groq API with context
37
- def ask_groq(query, context, groq_api_key):
 
38
  headers = {
39
- "Authorization": f"Bearer {groq_api_key}",
40
  "Content-Type": "application/json"
41
  }
42
-
43
  data = {
44
  "model": "llama3-8b-8192",
45
  "messages": [
46
- {"role": "system", "content": "Answer the user's question using the provided context."},
47
- {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {query}"}
48
  ]
49
  }
50
-
51
- response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=data)
52
- return response.json()['choices'][0]['message']['content'] if response.status_code == 200 else response.text
53
-
54
- # Streamlit UI
55
- st.set_page_config(page_title="Meraj Graphics RAG Bot")
56
- st.title("📄 Meraj Graphics Assistant")
57
-
58
- uploaded_pdf = st.file_uploader("Upload your PDF with business info", type="pdf")
59
-
60
- if uploaded_pdf:
61
- with open("temp.pdf", "wb") as f:
62
- f.write(uploaded_pdf.read())
63
-
64
- st.success("PDF uploaded successfully!")
65
- chunks = load_and_split_pdf("temp.pdf")
66
- index, chunk_texts, embeddings = create_faiss_index(chunks)
67
-
68
- query = st.text_input("Ask a question about our services:")
69
- groq_key = st.text_input("Enter your Groq API key", type="password")
70
-
71
- if st.button("Get Answer"):
72
- if query and groq_key:
73
- context = search_faiss(query, index, chunk_texts)
74
- answer = ask_groq(query, context, groq_key)
75
- st.markdown(f"**Answer:** {answer}")
76
- else:
77
- st.warning("Please enter both a query and API key.")
 
1
+ # app.py
2
  import streamlit as st
 
 
 
3
  import numpy as np
4
+ import faiss
5
  from sentence_transformers import SentenceTransformer
6
  import requests
7
 
8
+ st.set_page_config(page_title="Meraj Graphics Assistant")
 
9
 
10
+ # Load model and index
11
+ @st.cache_resource
12
+ def load_data():
13
+ embedder = SentenceTransformer("all-MiniLM-L6-v2")
14
+ index = faiss.read_index("index.faiss")
15
+ chunks = np.load("chunks.npy", allow_pickle=True)
16
+ return embedder, index, chunks
 
17
 
18
+ embedder, index, chunks = load_data()
 
 
 
 
 
19
 
20
+ # Search FAISS
21
+ def search(query, top_k=3):
22
+ q_embed = embedder.encode([query])
23
+ D, I = index.search(np.array(q_embed), top_k)
24
+ results = [chunks[i] for i in I[0]]
25
  return "\n".join(results)
26
 
27
+ # Call Groq API
28
+ def query_groq(context, question, api_key):
29
+ url = "https://api.groq.com/openai/v1/chat/completions"
30
  headers = {
31
+ "Authorization": f"Bearer {api_key}",
32
  "Content-Type": "application/json"
33
  }
 
34
  data = {
35
  "model": "llama3-8b-8192",
36
  "messages": [
37
+ {"role": "system", "content": "Answer based on the context."},
38
+ {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"}
39
  ]
40
  }
41
+ response = requests.post(url, headers=headers, json=data)
42
+ return response.json()["choices"][0]["message"]["content"]
43
+
44
+ # UI
45
+ st.title("📋 Meraj Graphics Chat Assistant")
46
+
47
+ question = st.text_input("Ask something about our services:")
48
+ groq_key = st.text_input("Groq API Key", type="password")
49
+
50
+ if st.button("Get Answer"):
51
+ if not question or not groq_key:
52
+ st.warning("Please provide both question and API key.")
53
+ else:
54
+ with st.spinner("Searching..."):
55
+ context = search(question)
56
+ answer = query_groq(context, question, groq_key)
57
+ st.success("Answer:")
58
+ st.write(answer)