Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +134 -0
- requirements.txt +16 -0
app.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from streamlit_chat import message
|
3 |
+
from langchain.chains import ConversationalRetrievalChain
|
4 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
5 |
+
from langchain.llms import Replicate
|
6 |
+
from langchain.text_splitter import CharacterTextSplitter
|
7 |
+
from langchain.vectorstores import FAISS
|
8 |
+
from langchain.memory import ConversationBufferMemory
|
9 |
+
from langchain.document_loaders import PyPDFLoader, TextLoader, Docx2txtLoader
|
10 |
+
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
|
11 |
+
from deep_translator import GoogleTranslator
|
12 |
+
import os
|
13 |
+
import tempfile
|
14 |
+
|
15 |
+
# Initialize session state
|
16 |
+
def initialize_session_state():
|
17 |
+
if 'history' not in st.session_state:
|
18 |
+
st.session_state['history'] = []
|
19 |
+
|
20 |
+
if 'generated' not in st.session_state:
|
21 |
+
st.session_state['generated'] = ["Hello! Ask me about your file π€"]
|
22 |
+
|
23 |
+
if 'past' not in st.session_state:
|
24 |
+
st.session_state['past'] = ["Hey! π"]
|
25 |
+
|
26 |
+
if 'selected_languages' not in st.session_state:
|
27 |
+
st.session_state['selected_languages'] = []
|
28 |
+
|
29 |
+
# Conversation chat function with translation
|
30 |
+
def conversation_chat(query, chain, history, selected_languages):
|
31 |
+
translated_queries = [GoogleTranslator(source='auto', target=lang).translate(query) for lang in selected_languages]
|
32 |
+
result = chain({"question": query, "chat_history": history})
|
33 |
+
translated_answers = [GoogleTranslator(source='auto', target=lang).translate(result["answer"]) for lang in selected_languages]
|
34 |
+
history.append((query, result["answer"]))
|
35 |
+
return translated_answers
|
36 |
+
|
37 |
+
# Display chat history
|
38 |
+
def display_chat_history(chain, selected_languages):
|
39 |
+
reply_container = st.container()
|
40 |
+
container = st.container()
|
41 |
+
|
42 |
+
with container:
|
43 |
+
with st.form(key='my_form', clear_on_submit=True):
|
44 |
+
user_input = st.text_input("Question:", placeholder="Ask about your Documents", key='input')
|
45 |
+
submit_button = st.form_submit_button(label='Send')
|
46 |
+
|
47 |
+
if submit_button and user_input:
|
48 |
+
with st.spinner('Generating response...'):
|
49 |
+
output = conversation_chat(user_input, chain, st.session_state['history'], selected_languages)
|
50 |
+
|
51 |
+
st.session_state['past'].append(user_input)
|
52 |
+
st.session_state['generated'].extend(output)
|
53 |
+
|
54 |
+
if st.session_state['generated']:
|
55 |
+
with reply_container:
|
56 |
+
for i in range(len(st.session_state['generated'])):
|
57 |
+
message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="thumbs")
|
58 |
+
message(st.session_state["generated"][i], key=str(i), avatar_style="bottts")
|
59 |
+
|
60 |
+
# Create conversational chain
|
61 |
+
def create_conversational_chain(vector_store):
|
62 |
+
replicate_api_token = "r8_47kvoIaHBIPYgBBoiGSrmoTN3cgazu71MyjHh"
|
63 |
+
os.environ["REPLICATE_API_TOKEN"] = replicate_api_token
|
64 |
+
|
65 |
+
llm = Replicate(
|
66 |
+
streaming=True,
|
67 |
+
model="replicate/llama-2-70b-chat:58d078176e02c219e11eb4da5a02a7830a283b14cf8f94537af893ccff5ee781",
|
68 |
+
callbacks=[StreamingStdOutCallbackHandler()],
|
69 |
+
input={"temperature": 0.01, "max_length": 500, "top_p": 1},
|
70 |
+
replicate_api_token=replicate_api_token
|
71 |
+
)
|
72 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
73 |
+
|
74 |
+
chain = ConversationalRetrievalChain.from_llm(llm=llm, chain_type='stuff',
|
75 |
+
retriever=vector_store.as_retriever(search_kwargs={"k": 2}),
|
76 |
+
memory=memory)
|
77 |
+
return chain
|
78 |
+
|
79 |
+
# Main function
|
80 |
+
def main():
|
81 |
+
initialize_session_state()
|
82 |
+
|
83 |
+
# Header and Tagline
|
84 |
+
st.title("LANGSMITH BOT")
|
85 |
+
st.subheader("Your Professional Assistant for Document Insights")
|
86 |
+
|
87 |
+
# Main interface
|
88 |
+
st.sidebar.title("Document Processing π")
|
89 |
+
uploaded_files = st.sidebar.file_uploader("Upload files", accept_multiple_files=True)
|
90 |
+
|
91 |
+
languages = ["en", "es", "fr", "de", "it", "pt", "zh", "ja", "ko", "hi", "sa"]
|
92 |
+
language_labels = {
|
93 |
+
"en": "English", "es": "Spanish", "fr": "French", "de": "German",
|
94 |
+
"it": "Italian", "pt": "Portuguese", "zh": "Chinese", "ja": "Japanese",
|
95 |
+
"ko": "Korean", "hi": "Hindi", "sa": "Sanskrit"
|
96 |
+
}
|
97 |
+
selected_languages = st.sidebar.multiselect("Select languages for conversation", languages, format_func=lambda x: language_labels[x])
|
98 |
+
st.session_state['selected_languages'] = selected_languages
|
99 |
+
|
100 |
+
if uploaded_files:
|
101 |
+
text = []
|
102 |
+
for file in uploaded_files:
|
103 |
+
file_extension = os.path.splitext(file.name)[1]
|
104 |
+
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
105 |
+
temp_file.write(file.read())
|
106 |
+
temp_file_path = temp_file.name
|
107 |
+
|
108 |
+
loader = None
|
109 |
+
if file_extension == ".pdf":
|
110 |
+
loader = PyPDFLoader(temp_file_path)
|
111 |
+
elif file_extension == ".docx" or file_extension == ".doc":
|
112 |
+
loader = Docx2txtLoader(temp_file_path)
|
113 |
+
elif file_extension == ".txt":
|
114 |
+
loader = TextLoader(temp_file_path)
|
115 |
+
|
116 |
+
if loader:
|
117 |
+
text.extend(loader.load())
|
118 |
+
os.remove(temp_file_path)
|
119 |
+
|
120 |
+
text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=100, length_function=len)
|
121 |
+
text_chunks = text_splitter.split_documents(text)
|
122 |
+
|
123 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",
|
124 |
+
model_kwargs={'device': 'cpu'})
|
125 |
+
vector_store = FAISS.from_documents(text_chunks, embedding=embeddings)
|
126 |
+
chain = create_conversational_chain(vector_store)
|
127 |
+
display_chat_history(chain, st.session_state['selected_languages'])
|
128 |
+
|
129 |
+
# Add a footer
|
130 |
+
st.markdown("---")
|
131 |
+
st.markdown("Team Chandrama: Shine with Glory!!!! β¨π")
|
132 |
+
|
133 |
+
if __name__ == "__main__":
|
134 |
+
main()
|
requirements.txt
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
langchain
|
2 |
+
torch
|
3 |
+
accelerate
|
4 |
+
sentence_transformers
|
5 |
+
streamlit_chat
|
6 |
+
streamlit
|
7 |
+
faiss-cpu
|
8 |
+
tiktoken
|
9 |
+
ctransformers
|
10 |
+
huggingface-hub
|
11 |
+
pypdf
|
12 |
+
python-dotenv
|
13 |
+
replicate
|
14 |
+
docx2txt
|
15 |
+
langchain-community
|
16 |
+
deep-translator
|