Spaces:
Sleeping
Sleeping
Create app,py
Browse files
app,py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import streamlit as st
|
| 4 |
+
from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader, UnstructuredMarkdownLoader, WebBaseLoader
|
| 5 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 6 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 7 |
+
from langchain_community.vectorstores import FAISS
|
| 8 |
+
from langchain.chains import RetrievalQA
|
| 9 |
+
from langchain_community.chat_models import ChatOpenAI
|
| 10 |
+
|
| 11 |
+
# Streamlit App Title
|
| 12 |
+
st.title("📄 DeepSeek-Powered RAG Chatbot")
|
| 13 |
+
|
| 14 |
+
# Step 1: Input API Key
|
| 15 |
+
api_key = st.text_input("🔑 Enter your DeepSeek API Key:", type="password")
|
| 16 |
+
|
| 17 |
+
if api_key:
|
| 18 |
+
# Set the API key as an environment variable (optional)
|
| 19 |
+
os.environ["DEEPSEEK_API_KEY"] = api_key
|
| 20 |
+
|
| 21 |
+
# Step 2: Upload Document or Enter Web Link
|
| 22 |
+
input_option = st.radio("Choose input type:", ("Upload Document", "Web Link"))
|
| 23 |
+
|
| 24 |
+
if input_option == "Upload Document":
|
| 25 |
+
uploaded_file = st.file_uploader("📂 Upload a document", type=["pdf", "docx", "md"])
|
| 26 |
+
else:
|
| 27 |
+
web_link = st.text_input("🌐 Enter the web link:")
|
| 28 |
+
|
| 29 |
+
# Use session state to persist the vector_store
|
| 30 |
+
if "vector_store" not in st.session_state:
|
| 31 |
+
st.session_state.vector_store = None
|
| 32 |
+
|
| 33 |
+
if (input_option == "Upload Document" and uploaded_file and st.session_state.vector_store is None) or \
|
| 34 |
+
(input_option == "Web Link" and web_link and st.session_state.vector_store is None):
|
| 35 |
+
try:
|
| 36 |
+
with st.spinner("Processing document..."):
|
| 37 |
+
if input_option == "Upload Document":
|
| 38 |
+
# Save the uploaded file temporarily
|
| 39 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{uploaded_file.name.split('.')[-1]}") as tmp_file:
|
| 40 |
+
tmp_file.write(uploaded_file.getvalue())
|
| 41 |
+
tmp_file_path = tmp_file.name
|
| 42 |
+
|
| 43 |
+
# Load the document based on file type
|
| 44 |
+
if uploaded_file.name.endswith(".pdf"):
|
| 45 |
+
loader = PyPDFLoader(tmp_file_path)
|
| 46 |
+
elif uploaded_file.name.endswith(".docx"):
|
| 47 |
+
loader = Docx2txtLoader(tmp_file_path)
|
| 48 |
+
elif uploaded_file.name.endswith(".md"):
|
| 49 |
+
loader = UnstructuredMarkdownLoader(tmp_file_path)
|
| 50 |
+
else:
|
| 51 |
+
st.error("Unsupported file type!")
|
| 52 |
+
st.stop()
|
| 53 |
+
|
| 54 |
+
documents = loader.load()
|
| 55 |
+
|
| 56 |
+
# Remove the temporary file
|
| 57 |
+
os.unlink(tmp_file_path)
|
| 58 |
+
else:
|
| 59 |
+
# Load the web page content
|
| 60 |
+
loader = WebBaseLoader(web_link)
|
| 61 |
+
documents = loader.load()
|
| 62 |
+
|
| 63 |
+
# Split the document into chunks
|
| 64 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 65 |
+
chunks = text_splitter.split_documents(documents)
|
| 66 |
+
|
| 67 |
+
# Generate embeddings and store them in a vector database
|
| 68 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 69 |
+
st.session_state.vector_store = FAISS.from_documents(chunks, embeddings)
|
| 70 |
+
|
| 71 |
+
st.success("Document processed successfully!")
|
| 72 |
+
except Exception as e:
|
| 73 |
+
st.error(f"Error processing document: {e}")
|
| 74 |
+
st.stop()
|
| 75 |
+
|
| 76 |
+
# Step 3: Ask Questions About the Document
|
| 77 |
+
if st.session_state.vector_store:
|
| 78 |
+
st.subheader("💬 Chat with Your Document")
|
| 79 |
+
user_query = st.text_input("Ask a question:")
|
| 80 |
+
|
| 81 |
+
if user_query:
|
| 82 |
+
try:
|
| 83 |
+
# Set up the RAG pipeline with DeepSeek LLM
|
| 84 |
+
retriever = st.session_state.vector_store.as_retriever()
|
| 85 |
+
llm = ChatOpenAI(
|
| 86 |
+
model="deepseek-chat",
|
| 87 |
+
openai_api_key=api_key,
|
| 88 |
+
openai_api_base="https://api.deepseek.com/v1",
|
| 89 |
+
temperature=0.85,
|
| 90 |
+
max_tokens=1000 # Adjust token limit for safety
|
| 91 |
+
)
|
| 92 |
+
qa_chain = RetrievalQA.from_chain_type(llm=llm, retriever=retriever)
|
| 93 |
+
|
| 94 |
+
# Generate response
|
| 95 |
+
with st.spinner("Generating response..."):
|
| 96 |
+
response = qa_chain.run(user_query)
|
| 97 |
+
|
| 98 |
+
# Check if the response is relevant or not
|
| 99 |
+
if "I don't know" in response or "not in the document" in response.lower():
|
| 100 |
+
response = "I'm here to assist you with questions about uploaded documents or related web links."
|
| 101 |
+
|
| 102 |
+
st.write(f"**Answer:** {response}")
|
| 103 |
+
except Exception as e:
|
| 104 |
+
st.error(f"Error generating response: {e}")
|
| 105 |
+
else:
|
| 106 |
+
st.warning("Please enter your DeepSeek API key to proceed.")
|