-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
187 lines (162 loc) · 8.11 KB
/
app.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# from openai import OpenAI
import openai
import streamlit as st
import datetime
import email_validate as ev
# Set page title and favicon
st.set_page_config(page_title="SEERAH BOT", page_icon="📜")
st.title("SEERAH BOT")
client = openai.OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
from typing_extensions import override
from openai import AssistantEventHandler
def insertTodb(query,response):
import pymongo
client = pymongo.MongoClient(st.secrets["MONGO_URI"])
db = client.books
db.seerahbooks.insert_one({"user":st.session_state.name,"email":st.session_state.email, "query":query,"response":response,"datetime":str(datetime.datetime.now()),"date":str(datetime.date.today()),"time":str(datetime.datetime.now().time())})
class EventHandler(AssistantEventHandler):
@override
def on_text_created(self, text) -> None:
print(f"", end="", flush=True)
@override
def on_tool_call_created(self, tool_call):
print(f"{tool_call.type}\n", flush=True)
@override
def on_message_done(self, message) -> None:
# Extract the message content
message_content = message.content[0].text
annotations = message_content.annotations
citations = []
# Iterate over the annotations and add footnotes
for index, annotation in enumerate(annotations):
# Replace the text with a footnote
message_content.value = message_content.value.replace(annotation.text, f' [{index}]')
# Gather citations based on annotation attributes
if (file_citation := getattr(annotation, 'file_citation', None)):
cited_file = client.files.retrieve(file_citation.file_id)
qt=file_citation.quote
if qt:
citations.append(f'[{index}] {qt} from {cited_file.filename}')
else:
citations.append(f'[{index}] from {cited_file.filename}')
elif (file_path := getattr(annotation, 'file_path', None)):
cited_file = client.files.retrieve(file_path.file_id)
citations.append(f'[{index}] Click <here> to download {cited_file.filename}')
# Note: File download functionality not implemented above for brevity
# Add footnotes to the end of the message before displaying to user
message_content.value += '\n' + '\n'.join(citations)
st.session_state.messages.append({"role": "assistant", "content": message_content.value})
response = st.write(message_content.value)# +"\nCitations: ".join(citations) )
insertTodb(st.session_state.messages[-2]["content"],message_content.value)
# print(response)
# print("Citations\n".join(citations))
def label_email(email):
if not ev.is_valid_email(email):
return "Invalid"
if not ev.has_valid_mx_record(email.split('@')[1]):
return "Invalid"
if not ev.verify_email(email):
return "Unknown"
if ev.is_disposable(email.split('@')[1]):
return "Risky"
return "Valid"
with st.sidebar:
with st.form("my_form"):
st.link_button("Check out Video about over Project", "https://www.youtube.com/watch?v=MgWLN9kC254")
if "name" in st.session_state:
st.write("Assalamoalikum ", st.session_state.name, " Welcome to Seerah Bot, How can I help you today?")
else:
user = st.text_input("Your Good name", "")
st.write("Assalamoalikum ", user, " Welcome to Seerah Bot, How can I help you today?")
email = st.text_input("Your Email", "" )
checkbox_val = st.checkbox("I here by share my query to Seerah Bot, and it can be used for training purposes.")
# Every form must have a submit button.
submitted = st.form_submit_button("Submit")
if submitted:
if label_email(email)=="Valid":
st.session_state.name=user
st.session_state.email=email
if checkbox_val:
st.session_state.checked=True
st.write("May Allah give barakah in your knowledge and help you in your journey to learn more about Seerah.")
else:
st.write("Please enter a valid email address.")
# if "name" in st.session_state and "checked" in st.session_state :
# if prompt := st.chat_input("What is up?"):
# st.session_state.messages.append({"role": "user", "content": st.session_state.name+" asks "+prompt})
# with st.chat_message("user"):
# st.markdown(prompt)
# with st.chat_message("assistant"):
# thread = client.beta.threads.create(
# messages=[
# {"role": "user", "content": prompt}
# # for m in st.session_state.messages
# ],
# # ,
# # tool_resources={
# # "file_search": {
# # "vector_store_ids": ["vs_gPspfa4idD83ozY9M28BsHox"]
# # }
# # }
# # event_handler=EventHandler()
# )
# # report=[]
# # for event in streams:
# # if event.data.object=="thread.message.delta":
# # for content in event.data.delta.content:
# # if content.type=="text":
# # report.append(content.value)
# # st.session_state.messages.append({"role": "assistant", "content": content.value})
# # resul=
# with client.beta.threads.runs.stream(
# thread_id=thread.id,
# assistant_id=st.secrets["assistant_id"] ,
# instructions="Please address the user as Seerah Bot. The user has a premium account.",
# event_handler=EventHandler(),
# ) as stream:
# stream.until_done()
# # response = st.write_stream(streams)
# # st.session_state.messages.append({"role": "assistant", "content": response})
if "name" in st.session_state and "email" in st.session_state:
if "messages" not in st.session_state:
st.session_state.messages = []
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if prompt := st.chat_input("What is up?"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
thread = client.beta.threads.create(
messages=[
{"role": "user", "content": prompt}
# for m in st.session_state.messages
],
# ,
# tool_resources={
# "file_search": {
# "vector_store_ids": ["vs_gPspfa4idD83ozY9M28BsHox"]
# }
# }
# event_handler=EventHandler()
)
# report=[]
# for event in streams:
# if event.data.object=="thread.message.delta":
# for content in event.data.delta.content:
# if content.type=="text":
# report.append(content.value)
# st.session_state.messages.append({"role": "assistant", "content": content.value})
# resul=
with client.beta.threads.runs.stream(
thread_id=thread.id,
assistant_id=st.secrets["assistant_id"] ,
instructions="Please address the user as Seerah Bot. The user has a premium account.",
event_handler=EventHandler(),
) as stream:
stream.until_done()
# response = st.write_stream(streams)
# st.session_state.messages.append({"role": "assistant", "content": response})
else:
st.write("Please enter your name and email in the sidebar to start the conversation.")