Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,91 +1,37 @@
|
|
| 1 |
import openai
|
| 2 |
import gradio as gr
|
| 3 |
import os
|
|
|
|
| 4 |
|
| 5 |
-
# Google docs access
|
| 6 |
-
import googleapiclient.discovery as discovery
|
| 7 |
-
from httplib2 import Http
|
| 8 |
-
from oauth2client import client
|
| 9 |
-
from oauth2client import file
|
| 10 |
-
from oauth2client import tools
|
| 11 |
-
|
| 12 |
-
SCOPES = 'https://www.googleapis.com/auth/documents.readonly'
|
| 13 |
-
DISCOVERY_DOC = 'https://docs.googleapis.com/$discovery/rest?version=v1'
|
| 14 |
-
DOCUMENT_ID = '16hjgy8pqI_2KI1vZfHdPk_VVuQUHLnZu-fdSQAVi45Q'
|
| 15 |
|
| 16 |
# env
|
| 17 |
openai.api_key = os.environ.get('openai-api')
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# Blocks
|
| 20 |
with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
if not credentials or credentials.invalid:
|
| 35 |
-
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
|
| 36 |
-
credentials = tools.run_flow(flow, store)
|
| 37 |
-
return credentials
|
| 38 |
-
|
| 39 |
-
def main():
|
| 40 |
-
credentials = get_credentials()
|
| 41 |
-
http = credentials.authorize(Http())
|
| 42 |
-
docs_service = discovery.build(
|
| 43 |
-
'docs', 'v1', http=http, discoveryServiceUrl=DISCOVERY_DOC)
|
| 44 |
-
doc = docs_service.documents().get(documentId=DOCUMENT_ID).execute()
|
| 45 |
-
doc_content = doc.get('body').get('content')
|
| 46 |
-
docsread = read_structural_elements(doc_content)
|
| 47 |
-
|
| 48 |
-
if __name__ == '__main__':
|
| 49 |
-
main()
|
| 50 |
-
|
| 51 |
-
def read_paragraph_element(element):
|
| 52 |
-
"""Returns the text in the given ParagraphElement.
|
| 53 |
-
|
| 54 |
-
Args:
|
| 55 |
-
element: a ParagraphElement from a Google Doc.
|
| 56 |
-
"""
|
| 57 |
-
text_run = element.get('textRun')
|
| 58 |
-
if not text_run:
|
| 59 |
-
return ''
|
| 60 |
-
return text_run.get('content')
|
| 61 |
-
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
in nested elements.
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
if 'paragraph' in value:
|
| 73 |
-
elements = value.get('paragraph').get('elements')
|
| 74 |
-
for elem in elements:
|
| 75 |
-
text += read_paragraph_element(elem)
|
| 76 |
-
elif 'table' in value:
|
| 77 |
-
# The text in table cells are in nested Structural Elements and tables may be
|
| 78 |
-
# nested.
|
| 79 |
-
table = value.get('table')
|
| 80 |
-
for row in table.get('tableRows'):
|
| 81 |
-
cells = row.get('tableCells')
|
| 82 |
-
for cell in cells:
|
| 83 |
-
text += read_structural_elements(cell.get('content'))
|
| 84 |
-
elif 'tableOfContents' in value:
|
| 85 |
-
# The text in the TOC is also in a Structural Element.
|
| 86 |
-
toc = value.get('tableOfContents')
|
| 87 |
-
text += read_structural_elements(toc.get('content'))
|
| 88 |
-
return text
|
| 89 |
|
| 90 |
def showall(code:str):
|
| 91 |
visibility = gr.update(visible = True)
|
|
@@ -134,7 +80,16 @@ with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
|
| 134 |
messages_history3 += {"role": "system", "content": themehelp}
|
| 135 |
messages_history3 += {"role": "assistant", "content": languagedict[language]['helpfirst']}
|
| 136 |
return messages_history1, messages_history2, messages_history3
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
def user(msg, chatbot, state, language: str, mode: str):
|
| 139 |
#Bot context
|
| 140 |
if mode == "mode1":
|
|
@@ -149,7 +104,15 @@ with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
|
| 149 |
elif len(state) > 10:
|
| 150 |
state.append({'role':'system','content':f"Remember your mission as briefed earlier:\n\n{context}"})
|
| 151 |
chatbot.append([msg, None])
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
state.append({'role':'user','content':msg})
|
| 154 |
print(f'state is\n{state}')
|
| 155 |
print(f'chatbot is\n{chatbot}')
|
|
@@ -171,8 +134,7 @@ with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
|
| 171 |
chatbot2up = [[None,languagedict[language]['interviewquestionsfirst']]]
|
| 172 |
state2up = [{"role": "system", "content": themeinterviewquestions},{"role": "assistant", "content": languagedict[language]['interviewquestionsfirst']}]
|
| 173 |
chatbot3up = [[None,languagedict[language]['whatcanidofirst']]]
|
| 174 |
-
|
| 175 |
-
state3up = [{"role": "system", "content": themehelp + f"\n{complement}"},{"role": "assistant", "content": languagedict[language]['helpfirst']}]
|
| 176 |
return titleup, input1up, input2up, input3up, chatbot1up, chatbot2up, chatbot3up, state1up, state2up, state3up
|
| 177 |
|
| 178 |
languageoptions = ["English", "廣東話"]
|
|
@@ -237,7 +199,7 @@ with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
|
| 237 |
- Breakdown the potential challenges for them to anticipate
|
| 238 |
- Provide advice on how to overcome these challenges
|
| 239 |
|
| 240 |
-
IMPORTANT: write in {language}, in the style of a native
|
| 241 |
"""
|
| 242 |
|
| 243 |
themeinterviewquestions = f"""
|
|
@@ -248,7 +210,7 @@ with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
|
| 248 |
|
| 249 |
Then ask another question.
|
| 250 |
|
| 251 |
-
IMPORTANT: write in {language}, in the style of a native
|
| 252 |
"""
|
| 253 |
|
| 254 |
themehelp = f"""
|
|
@@ -261,7 +223,7 @@ with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
|
| 261 |
- leisure
|
| 262 |
If the question is not related to any of these topics, answer 'This is beyond my domain of competence, please ask a social worker.'
|
| 263 |
|
| 264 |
-
IMPORTANT: write in {language}, in the style of a native
|
| 265 |
"""
|
| 266 |
|
| 267 |
#INTERFACE
|
|
@@ -276,9 +238,7 @@ with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
|
| 276 |
with gr.Tab(f"{languagedict['English']['help']} / {languagedict['廣東話']['help']}"):
|
| 277 |
chatbot3 = gr.Chatbot([[None,languagedict['English']['helpfirst']]])
|
| 278 |
input3 = gr.Textbox(label = languagedict['English']['helplabel'], placeholder = languagedict['English']['helpph'], visible = False)
|
| 279 |
-
|
| 280 |
-
complement = f"To answer, use primarily the information indicated here:\n{instructions}"
|
| 281 |
-
state3 = gr.State([{"role": "system", "content": themehelp + f"\n{complement}"},{"role": "assistant", "content": languagedict['English']['helpfirst']}])
|
| 282 |
clear = gr.Button('Clear')
|
| 283 |
|
| 284 |
# Launcher
|
|
|
|
| 1 |
import openai
|
| 2 |
import gradio as gr
|
| 3 |
import os
|
| 4 |
+
import pandas as pd
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# env
|
| 8 |
openai.api_key = os.environ.get('openai-api')
|
| 9 |
+
SHEET_ID = '119qz8UpCdwCu_gyPtayi7JmhSM0nUddolOyJcqsMnmA'
|
| 10 |
+
SHEET_NAME = 'MIW_Sources'
|
| 11 |
|
| 12 |
# Blocks
|
| 13 |
with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
| 14 |
|
| 15 |
+
#Initiatlize data
|
| 16 |
+
url = f'https://docs.google.com/spreadsheets/d/{SHEET_ID}/gviz/tq?tqx=out:csv&sheet={SHEET_NAME}'
|
| 17 |
+
df = pd.read_csv(url)
|
| 18 |
+
|
| 19 |
+
def filter_and_concatenate(df, input_string):
|
| 20 |
+
# If input string is empty, return concatenation of all values
|
| 21 |
+
if input_string == "":
|
| 22 |
+
concatenated_string = ""
|
| 23 |
+
for _, row in df.iterrows():
|
| 24 |
+
concatenated_string += '|'.join(str(value) for value in row.values) + '\n'
|
| 25 |
+
return concatenated_string
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
# Filter the dataframe based on the input string
|
| 28 |
+
filtered_df = df[df['category'] == input_string]
|
|
|
|
| 29 |
|
| 30 |
+
# Concatenate the values from other columns
|
| 31 |
+
concatenated_string = ''
|
| 32 |
+
for _, row in filtered_df.iterrows():
|
| 33 |
+
concatenated_string += '|'.join(str(value) for value in row.values[1:]) + '\n'
|
| 34 |
+
return concatenated_string
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
def showall(code:str):
|
| 37 |
visibility = gr.update(visible = True)
|
|
|
|
| 80 |
messages_history3 += {"role": "system", "content": themehelp}
|
| 81 |
messages_history3 += {"role": "assistant", "content": languagedict[language]['helpfirst']}
|
| 82 |
return messages_history1, messages_history2, messages_history3
|
| 83 |
+
|
| 84 |
+
def getlist(df):
|
| 85 |
+
# Extract distinct values from the first column
|
| 86 |
+
distinct_values = df.iloc[:, 0].unique()
|
| 87 |
+
|
| 88 |
+
# Join the distinct values into a string separated by ", "
|
| 89 |
+
distinct_values_string = ",".join(str(value) for value in distinct_values)
|
| 90 |
+
|
| 91 |
+
return distinct_values_string
|
| 92 |
+
|
| 93 |
def user(msg, chatbot, state, language: str, mode: str):
|
| 94 |
#Bot context
|
| 95 |
if mode == "mode1":
|
|
|
|
| 104 |
elif len(state) > 10:
|
| 105 |
state.append({'role':'system','content':f"Remember your mission as briefed earlier:\n\n{context}"})
|
| 106 |
chatbot.append([msg, None])
|
| 107 |
+
|
| 108 |
+
if mode == 'mode3'
|
| 109 |
+
#Append instructions to msg
|
| 110 |
+
listvalues = getlist(df)
|
| 111 |
+
queryforcategory = [{'role':'user','content':f"Out of this list of words/expressions separated by a comma:\n{listvalues}\n, which one corresponds the best to the theme in this message:\n{msg}\n\nThe result should be one of the elements from the list only."}]
|
| 112 |
+
matchcat = answer(queryforcategory)
|
| 113 |
+
instructions = filter_and_concatenate(df, matchcat)
|
| 114 |
+
msg = msg +f"\n\nUse the following elements to document your answer:\n{instructions}"
|
| 115 |
+
msg = msg + f"\n\nAnswer in {language}, keep it casual but respectful"
|
| 116 |
state.append({'role':'user','content':msg})
|
| 117 |
print(f'state is\n{state}')
|
| 118 |
print(f'chatbot is\n{chatbot}')
|
|
|
|
| 134 |
chatbot2up = [[None,languagedict[language]['interviewquestionsfirst']]]
|
| 135 |
state2up = [{"role": "system", "content": themeinterviewquestions},{"role": "assistant", "content": languagedict[language]['interviewquestionsfirst']}]
|
| 136 |
chatbot3up = [[None,languagedict[language]['whatcanidofirst']]]
|
| 137 |
+
state3up = [{"role": "system", "content": themehelp},{"role": "assistant", "content": languagedict[language]['helpfirst']}]
|
|
|
|
| 138 |
return titleup, input1up, input2up, input3up, chatbot1up, chatbot2up, chatbot3up, state1up, state2up, state3up
|
| 139 |
|
| 140 |
languageoptions = ["English", "廣東話"]
|
|
|
|
| 199 |
- Breakdown the potential challenges for them to anticipate
|
| 200 |
- Provide advice on how to overcome these challenges
|
| 201 |
|
| 202 |
+
IMPORTANT: write in {language}, in the style of a native. Keep it casual but respectful.
|
| 203 |
"""
|
| 204 |
|
| 205 |
themeinterviewquestions = f"""
|
|
|
|
| 210 |
|
| 211 |
Then ask another question.
|
| 212 |
|
| 213 |
+
IMPORTANT: write in {language}, in the style of a native. Keep it casual but respectful.
|
| 214 |
"""
|
| 215 |
|
| 216 |
themehelp = f"""
|
|
|
|
| 223 |
- leisure
|
| 224 |
If the question is not related to any of these topics, answer 'This is beyond my domain of competence, please ask a social worker.'
|
| 225 |
|
| 226 |
+
IMPORTANT: write in {language}, in the style of a native. Keep it casual but respectful.
|
| 227 |
"""
|
| 228 |
|
| 229 |
#INTERFACE
|
|
|
|
| 238 |
with gr.Tab(f"{languagedict['English']['help']} / {languagedict['廣東話']['help']}"):
|
| 239 |
chatbot3 = gr.Chatbot([[None,languagedict['English']['helpfirst']]])
|
| 240 |
input3 = gr.Textbox(label = languagedict['English']['helplabel'], placeholder = languagedict['English']['helpph'], visible = False)
|
| 241 |
+
state3 = gr.State([{"role": "system", "content": themehelp},{"role": "assistant", "content": languagedict['English']['helpfirst']}])
|
|
|
|
|
|
|
| 242 |
clear = gr.Button('Clear')
|
| 243 |
|
| 244 |
# Launcher
|