-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamlit.py
75 lines (56 loc) · 2.29 KB
/
streamlit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import streamlit as st
import requests
from Helpers.configs import get_settings
import time
import mimetypes
app_setting = get_settings()
def get_message(user_input):
response = requests.post(app_setting.FASTAPI_URL+'/chat', params={"query": user_input})
bot_message = response.json().get("query")
return bot_message
def response_generator(bot_message):
for word in bot_message.split("\n"):
yield word + " \n"
time.sleep(0.080)
def upload_file(file):
mime_type, _ = mimetypes.guess_type(file.name)
files = {
"file": (file.name, file.getvalue(), mime_type)
}
response = requests.post(app_setting.FASTAPI_URL+'/upload', files=files)
output = response.json().get("query")
return output , response.status_code
st.title("Chat With Your Documents")
response = requests.get(app_setting.FASTAPI_URL)
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = [
{"role": "assistant", "content": response.json().get('query')}
]
# Display chat messages from history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if user_input := st.chat_input("Type your message"):
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(user_input)
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": user_input})
with st.spinner("The assistant is thinking..."):
bot_message = get_message(user_input)
# Display assistant response in chat message container
with st.chat_message("assistant"):
output = st.write_stream(response_generator(bot_message))
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": output})
with st.sidebar:
uploaded_file = st.sidebar.file_uploader("Upload a file", type=["txt", "pdf"])
if uploaded_file is not None:
with st.spinner("Uploading... Please wait"):
file_response, status_code = upload_file(uploaded_file)
if status_code == 200:
st.sidebar.success(f"{file_response}")
else :
st.sidebar.error(f"{file_response}")
uploaded_file=None