Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,21 @@
|
|
| 1 |
import os
|
| 2 |
from PyPDF2 import PdfReader
|
| 3 |
-
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 4 |
-
from langchain.embeddings import HuggingFaceEmbeddings # Corrected import
|
| 5 |
import streamlit as st
|
|
|
|
| 6 |
from langchain.vectorstores import FAISS
|
| 7 |
-
from langchain.chains.question_answering import load_qa_chain
|
| 8 |
from langchain.prompts import PromptTemplate
|
| 9 |
-
from
|
| 10 |
-
from
|
| 11 |
import torch
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
|
|
|
| 17 |
def get_pdf_text(pdf_docs):
|
| 18 |
text = ""
|
| 19 |
for pdf in pdf_docs:
|
|
@@ -22,13 +24,11 @@ def get_pdf_text(pdf_docs):
|
|
| 22 |
text += page.extract_text()
|
| 23 |
return text
|
| 24 |
|
| 25 |
-
# Function to split text into chunks
|
| 26 |
def get_text_chunks(text):
|
| 27 |
splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
|
| 28 |
-
|
| 29 |
-
return chunks
|
| 30 |
|
| 31 |
-
#
|
| 32 |
def get_vector_store(chunks):
|
| 33 |
try:
|
| 34 |
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
|
@@ -37,124 +37,101 @@ def get_vector_store(chunks):
|
|
| 37 |
except Exception as e:
|
| 38 |
raise RuntimeError(f"Error processing embeddings: {e}")
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
response = model(input_text, max_length=200, num_return_sequences=1)
|
| 57 |
-
return response[0]['generated_text']
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
#
|
| 64 |
def clear_chat_history():
|
| 65 |
st.session_state.messages = [{"role": "assistant", "content": "در خدمتیم"}]
|
| 66 |
|
| 67 |
-
# Function to handle user input
|
| 68 |
-
def user_input(user_question):
|
| 69 |
-
try:
|
| 70 |
-
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2") # Corrected here
|
| 71 |
-
new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
|
| 72 |
-
docs = new_db.similarity_search(user_question, k=4)
|
| 73 |
-
chain = get_conversational_chain()
|
| 74 |
-
response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True)
|
| 75 |
-
return response
|
| 76 |
-
except Exception as e:
|
| 77 |
-
raise RuntimeError(f"Error generating response: {e}")
|
| 78 |
-
|
| 79 |
-
# Main function to run the Streamlit app
|
| 80 |
def main():
|
| 81 |
-
st.set_page_config(
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
#
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
<style>
|
| 91 |
-
body {
|
| 92 |
-
background-color: #000000;
|
| 93 |
-
color: #ffffff;
|
| 94 |
-
}
|
| 95 |
-
.main {
|
| 96 |
-
background-color: #333333;
|
| 97 |
-
padding: 20px;
|
| 98 |
-
border-radius: 10px;
|
| 99 |
-
}
|
| 100 |
-
</style>
|
| 101 |
-
""",
|
| 102 |
-
unsafe_allow_html=True
|
| 103 |
-
)
|
| 104 |
|
| 105 |
if "uploaded" not in st.session_state:
|
| 106 |
st.session_state.uploaded = False
|
| 107 |
|
| 108 |
if not st.session_state.uploaded:
|
| 109 |
st.title("A Personal Assistant for your Standards ...")
|
| 110 |
-
pdf_docs = st.file_uploader("فایل مورد نظر راآپلود کنید
|
| 111 |
if st.button("تایید"):
|
| 112 |
if pdf_docs:
|
| 113 |
-
|
| 114 |
-
st.info("در حال پردازش")
|
| 115 |
raw_text = get_pdf_text(pdf_docs)
|
| 116 |
text_chunks = get_text_chunks(raw_text)
|
| 117 |
get_vector_store(text_chunks)
|
| 118 |
st.session_state.uploaded = True
|
| 119 |
st.success("پردازش موفق")
|
| 120 |
-
st.query_params["uploaded"] = "true"
|
| 121 |
-
except RuntimeError as e:
|
| 122 |
-
st.error(str(e))
|
| 123 |
else:
|
| 124 |
st.error("لطفا حداقل یک فایل را آپلود کنید")
|
| 125 |
else:
|
| 126 |
-
# Main content area for displaying chat messages
|
| 127 |
st.title("Assistant ready ...")
|
| 128 |
st.write("میتونین سوالتونو بپرسین")
|
| 129 |
st.button('حذف مکالمه', on_click=clear_chat_history)
|
| 130 |
|
| 131 |
-
# Initialize chat history
|
| 132 |
if "messages" not in st.session_state:
|
| 133 |
st.session_state.messages = [{"role": "assistant", "content": "در خدمتیم"}]
|
| 134 |
|
| 135 |
-
# Display chat messages
|
| 136 |
for message in st.session_state.messages:
|
| 137 |
with st.chat_message(message["role"]):
|
| 138 |
st.write(message["content"])
|
| 139 |
|
| 140 |
-
# Chat input
|
| 141 |
if prompt := st.chat_input():
|
| 142 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 143 |
with st.chat_message("user"):
|
| 144 |
st.write(prompt)
|
| 145 |
|
| 146 |
-
# Generate bot response
|
| 147 |
if st.session_state.messages[-1]["role"] != "assistant":
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
if __name__ == "__main__":
|
| 160 |
main()
|
|
|
|
| 1 |
import os
|
| 2 |
from PyPDF2 import PdfReader
|
|
|
|
|
|
|
| 3 |
import streamlit as st
|
| 4 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 5 |
from langchain.vectorstores import FAISS
|
|
|
|
| 6 |
from langchain.prompts import PromptTemplate
|
| 7 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
import torch
|
| 10 |
|
| 11 |
+
# ========== Configuration ==========
|
| 12 |
+
EMBEDDING_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2" # Replace with actual model name
|
| 13 |
+
LLM_MODEL_NAME = "deepseek-ai/Janus-Pro-7B" # Replace with actual model name
|
| 14 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 15 |
+
|
| 16 |
|
| 17 |
+
|
| 18 |
+
# ========== Text Splitting ==========
|
| 19 |
def get_pdf_text(pdf_docs):
|
| 20 |
text = ""
|
| 21 |
for pdf in pdf_docs:
|
|
|
|
| 24 |
text += page.extract_text()
|
| 25 |
return text
|
| 26 |
|
|
|
|
| 27 |
def get_text_chunks(text):
|
| 28 |
splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
|
| 29 |
+
return splitter.split_text(text)
|
|
|
|
| 30 |
|
| 31 |
+
# ========== Vector Store ==========
|
| 32 |
def get_vector_store(chunks):
|
| 33 |
try:
|
| 34 |
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
|
|
|
| 37 |
except Exception as e:
|
| 38 |
raise RuntimeError(f"Error processing embeddings: {e}")
|
| 39 |
|
| 40 |
+
# ========== Response Generation ==========
|
| 41 |
+
class DeepSeekChat:
|
| 42 |
+
def __init__(self):
|
| 43 |
+
self.tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_NAME)
|
| 44 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 45 |
+
LLM_MODEL_NAME,
|
| 46 |
+
torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
|
| 47 |
+
low_cpu_mem_usage=True
|
| 48 |
+
).to(DEVICE)
|
| 49 |
+
|
| 50 |
+
def generate(self, context, question):
|
| 51 |
+
prompt_template = """Answer based on context:
|
| 52 |
+
Context: {context}
|
| 53 |
+
Question: {question}
|
| 54 |
+
Answer:"""
|
| 55 |
|
| 56 |
+
prompt = prompt_template.format(context=context, question=question)
|
| 57 |
+
inputs = self.tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
outputs = self.model.generate(
|
| 60 |
+
inputs.input_ids,
|
| 61 |
+
max_new_tokens=200,
|
| 62 |
+
temperature=0.3,
|
| 63 |
+
do_sample=True
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 67 |
|
| 68 |
+
# ========== Streamlit App ==========
|
| 69 |
def clear_chat_history():
|
| 70 |
st.session_state.messages = [{"role": "assistant", "content": "در خدمتیم"}]
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
def main():
|
| 73 |
+
st.set_page_config(page_title="Chatbot", layout="wide", initial_sidebar_state="expanded")
|
| 74 |
+
|
| 75 |
+
# Custom CSS
|
| 76 |
+
st.markdown("""
|
| 77 |
+
<style>
|
| 78 |
+
body { background-color: #000000; color: #ffffff; }
|
| 79 |
+
.main { background-color: #333333; padding: 20px; border-radius: 10px; }
|
| 80 |
+
</style>
|
| 81 |
+
""", unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
if "uploaded" not in st.session_state:
|
| 84 |
st.session_state.uploaded = False
|
| 85 |
|
| 86 |
if not st.session_state.uploaded:
|
| 87 |
st.title("A Personal Assistant for your Standards ...")
|
| 88 |
+
pdf_docs = st.file_uploader("فایل مورد نظر راآپلود کنید", accept_multiple_files=True)
|
| 89 |
if st.button("تایید"):
|
| 90 |
if pdf_docs:
|
| 91 |
+
with st.spinner("در حال پردازش..."):
|
|
|
|
| 92 |
raw_text = get_pdf_text(pdf_docs)
|
| 93 |
text_chunks = get_text_chunks(raw_text)
|
| 94 |
get_vector_store(text_chunks)
|
| 95 |
st.session_state.uploaded = True
|
| 96 |
st.success("پردازش موفق")
|
|
|
|
|
|
|
|
|
|
| 97 |
else:
|
| 98 |
st.error("لطفا حداقل یک فایل را آپلود کنید")
|
| 99 |
else:
|
|
|
|
| 100 |
st.title("Assistant ready ...")
|
| 101 |
st.write("میتونین سوالتونو بپرسین")
|
| 102 |
st.button('حذف مکالمه', on_click=clear_chat_history)
|
| 103 |
|
|
|
|
| 104 |
if "messages" not in st.session_state:
|
| 105 |
st.session_state.messages = [{"role": "assistant", "content": "در خدمتیم"}]
|
| 106 |
|
|
|
|
| 107 |
for message in st.session_state.messages:
|
| 108 |
with st.chat_message(message["role"]):
|
| 109 |
st.write(message["content"])
|
| 110 |
|
|
|
|
| 111 |
if prompt := st.chat_input():
|
| 112 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 113 |
with st.chat_message("user"):
|
| 114 |
st.write(prompt)
|
| 115 |
|
|
|
|
| 116 |
if st.session_state.messages[-1]["role"] != "assistant":
|
| 117 |
+
with st.spinner("در حال پاسخگویی..."):
|
| 118 |
+
try:
|
| 119 |
+
# Load embeddings and vector store
|
| 120 |
+
embeddings = DeepSeekEmbeddings()
|
| 121 |
+
db = FAISS.load_local("faiss_index", embeddings)
|
| 122 |
+
docs = db.similarity_search(prompt, k=4)
|
| 123 |
+
context = "\n".join([d.page_content for d in docs])
|
| 124 |
+
|
| 125 |
+
# Generate response
|
| 126 |
+
chat_model = DeepSeekChat()
|
| 127 |
+
response = chat_model.generate(context, prompt)
|
| 128 |
+
|
| 129 |
+
# Display response
|
| 130 |
+
with st.chat_message("assistant"):
|
| 131 |
+
st.write(response)
|
| 132 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 133 |
+
except Exception as e:
|
| 134 |
+
st.error(f"خطا: {str(e)}")
|
| 135 |
|
| 136 |
if __name__ == "__main__":
|
| 137 |
main()
|