ankitv42 commited on
Commit
58be8bd
·
verified ·
1 Parent(s): ac285b6

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +68 -0
  2. requirements (1).txt +7 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import tempfile
4
+ from langchain_community.vectorstores import FAISS
5
+ from langchain_groq import ChatGroq
6
+ from langchain_community.embeddings import HuggingFaceBgeEmbeddings
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain_core.runnables import RunnablePassthrough
9
+ from langchain.document_loaders import PyPDFLoader
10
+ from langchain import hub
11
+
12
+ # Set API key (replace with your actual key)
13
+ os.environ["GROQ_API_KEY"] = "your_groq_api_key"
14
+
15
+ # Streamlit UI
16
+ st.title("📄 PDF Chatbot with RAG")
17
+ st.write("Upload a PDF and ask questions!")
18
+
19
+ # File uploader
20
+ uploaded_file = st.file_uploader("Upload a PDF", type="pdf")
21
+
22
+ if uploaded_file:
23
+ # Save uploaded PDF temporarily
24
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
25
+ temp_file.write(uploaded_file.read())
26
+ temp_file_path = temp_file.name
27
+
28
+ # Load and process PDF
29
+ loader = PyPDFLoader(temp_file_path)
30
+ docs = loader.load()
31
+
32
+ # Initialize LLM and Embeddings
33
+ llm = ChatGroq(model="llama3-8b-8192")
34
+ model_name = "BAAI/bge-small-en"
35
+ hf_embeddings = HuggingFaceBgeEmbeddings(
36
+ model_name=model_name,
37
+ model_kwargs={'device': 'cpu'},
38
+ encode_kwargs={'normalize_embeddings': True}
39
+ )
40
+
41
+ # Split text
42
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
43
+ splits = text_splitter.split_documents(docs)
44
+
45
+ # Create FAISS vector store
46
+ vectorstore = FAISS.from_documents(documents=splits, embedding=hf_embeddings)
47
+ retriever = vectorstore.as_retriever()
48
+
49
+ # Load RAG prompt
50
+ prompt = hub.pull("rlm/rag-prompt")
51
+
52
+ def format_docs(docs):
53
+ return "\n\n".join(doc.page_content for doc in docs)
54
+
55
+ # RAG Chain
56
+ rag_chain = (
57
+ {"context": retriever | format_docs, "question": RunnablePassthrough()}
58
+ | prompt
59
+ | llm
60
+ )
61
+
62
+ # User Query
63
+ user_query = st.text_input("Ask a question from the PDF:")
64
+
65
+ if user_query:
66
+ response = rag_chain.invoke(user_query)
67
+ st.write("### 🤖 AI Response:")
68
+ st.write(response)
requirements (1).txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ pypdf
3
+ langchain_core
4
+ langchain_community
5
+ langchain_groq
6
+ faiss-cpu
7
+ sentence-transformers