Jason St George commited on
Commit
d637df6
Β·
1 Parent(s): 290c3b8
Files changed (2) hide show
  1. app.py +4 -4
  2. app_model.py +882 -0
app.py CHANGED
@@ -241,10 +241,6 @@ with block:
241
  gr.Markdown("<h3><center>TerenceGPT</center></h3>")
242
  # gr.Image(type='filepath', value='McKenna3.jpg', shape=(200,100))
243
 
244
- gr.HTML("Please initialize the chain by clicking 'Start Chain!' before submitting a question.")
245
- with gr.Row():
246
- init_chain_button = gr.Button(value="Start Chain!", variant="primary").style(full_width=False)
247
-
248
  chatbot = gr.Chatbot()
249
 
250
  with gr.Row():
@@ -255,6 +251,10 @@ with block:
255
  )
256
  submit = gr.Button(value="Send", variant="secondary").style(full_width=False)
257
 
 
 
 
 
258
  gr.HTML(
259
  "<center>Powered by <a href='https://github.com/hwchase17/langchain'>LangChain πŸ¦œοΈπŸ”— and Unicorn Farts πŸ¦„πŸ’¨</a></center>"
260
  )
 
241
  gr.Markdown("<h3><center>TerenceGPT</center></h3>")
242
  # gr.Image(type='filepath', value='McKenna3.jpg', shape=(200,100))
243
 
 
 
 
 
244
  chatbot = gr.Chatbot()
245
 
246
  with gr.Row():
 
251
  )
252
  submit = gr.Button(value="Send", variant="secondary").style(full_width=False)
253
 
254
+ gr.HTML("Please initialize the chain by clicking 'Start Chain!' before submitting a question.")
255
+ with gr.Row():
256
+ init_chain_button = gr.Button(value="Start Chain!", variant="primary").style(full_width=False)
257
+
258
  gr.HTML(
259
  "<center>Powered by <a href='https://github.com/hwchase17/langchain'>LangChain πŸ¦œοΈπŸ”— and Unicorn Farts πŸ¦„πŸ’¨</a></center>"
260
  )
app_model.py ADDED
@@ -0,0 +1,882 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import ssl
4
+ from contextlib import closing
5
+ from typing import Optional, Tuple
6
+ import datetime
7
+
8
+ import boto3
9
+ import gradio as gr
10
+ import requests
11
+
12
+ # UNCOMMENT TO USE WHISPER
13
+ import warnings
14
+ import whisper
15
+
16
+ from langchain import ConversationChain, LLMChain
17
+
18
+ from langchain.agents import load_tools, initialize_agent
19
+ from langchain.chains.conversation.memory import ConversationBufferMemory
20
+ from langchain.llms import OpenAI
21
+ from threading import Lock
22
+
23
+ # Console to variable
24
+ from io import StringIO
25
+ import sys
26
+ import re
27
+
28
+ from openai.error import AuthenticationError, InvalidRequestError, RateLimitError
29
+
30
+ # Pertains to Express-inator functionality
31
+ from langchain.prompts import PromptTemplate
32
+
33
+ from polly_utils import PollyVoiceData, NEURAL_ENGINE
34
+ from azure_utils import AzureVoiceData
35
+
36
+ # Pertains to question answering functionality
37
+ from langchain.embeddings.openai import OpenAIEmbeddings
38
+ from langchain.text_splitter import CharacterTextSplitter
39
+ from langchain.vectorstores.faiss import FAISS
40
+ from langchain.docstore.document import Document
41
+ from langchain.chains.question_answering import load_qa_chain
42
+
43
+ news_api_key = os.environ["NEWS_API_KEY"]
44
+ tmdb_bearer_token = os.environ["TMDB_BEARER_TOKEN"]
45
+
46
+ TOOLS_LIST = ['serpapi', 'wolfram-alpha', 'pal-math', 'pal-colored-objects'] #'google-search','news-api','tmdb-api','open-meteo-api'
47
+ TOOLS_DEFAULT_LIST = ['serpapi', 'pal-math']
48
+ BUG_FOUND_MSG = "Congratulations, you've found a bug in this application!"
49
+ # AUTH_ERR_MSG = "Please paste your OpenAI key from openai.com to use this application. It is not necessary to hit a button or key after pasting it."
50
+ AUTH_ERR_MSG = "Please paste your OpenAI key from openai.com to use this application. "
51
+ MAX_TOKENS = 512
52
+
53
+ LOOPING_TALKING_HEAD = "videos/Masahiro.mp4"
54
+ TALKING_HEAD_WIDTH = "192"
55
+ MAX_TALKING_HEAD_TEXT_LENGTH = 155
56
+
57
+ # Pertains to Express-inator functionality
58
+ NUM_WORDS_DEFAULT = 0
59
+ MAX_WORDS = 400
60
+ FORMALITY_DEFAULT = "N/A"
61
+ TEMPERATURE_DEFAULT = 0.5
62
+ EMOTION_DEFAULT = "N/A"
63
+ LANG_LEVEL_DEFAULT = "N/A"
64
+ TRANSLATE_TO_DEFAULT = "N/A"
65
+ LITERARY_STYLE_DEFAULT = "N/A"
66
+ PROMPT_TEMPLATE = PromptTemplate(
67
+ input_variables=["original_words", "num_words", "formality", "emotions", "lang_level", "translate_to",
68
+ "literary_style"],
69
+ template="Restate {num_words}{formality}{emotions}{lang_level}{translate_to}{literary_style}the following: \n{original_words}\n",
70
+ )
71
+
72
+ POLLY_VOICE_DATA = PollyVoiceData()
73
+ AZURE_VOICE_DATA = AzureVoiceData()
74
+
75
+ # Pertains to WHISPER functionality
76
+ WHISPER_DETECT_LANG = "Detect language"
77
+
78
+
79
+ # UNCOMMENT TO USE WHISPER
80
+ warnings.filterwarnings("ignore")
81
+ WHISPER_MODEL = whisper.load_model("tiny")
82
+ print("WHISPER_MODEL", WHISPER_MODEL)
83
+
84
+
85
+ # UNCOMMENT TO USE WHISPER
86
+ def transcribe(aud_inp, whisper_lang):
87
+ if aud_inp is None:
88
+ return ""
89
+ aud = whisper.load_audio(aud_inp)
90
+ aud = whisper.pad_or_trim(aud)
91
+ mel = whisper.log_mel_spectrogram(aud).to(WHISPER_MODEL.device)
92
+ _, probs = WHISPER_MODEL.detect_language(mel)
93
+ options = whisper.DecodingOptions()
94
+ if whisper_lang != WHISPER_DETECT_LANG:
95
+ whisper_lang_code = POLLY_VOICE_DATA.get_whisper_lang_code(whisper_lang)
96
+ options = whisper.DecodingOptions(language=whisper_lang_code)
97
+ result = whisper.decode(WHISPER_MODEL, mel, options)
98
+ print("result.text", result.text)
99
+ result_text = ""
100
+ if result and result.text:
101
+ result_text = result.text
102
+ return result_text
103
+
104
+
105
+ # Temporarily address Wolfram Alpha SSL certificate issue
106
+ ssl._create_default_https_context = ssl._create_unverified_context
107
+
108
+
109
+ # TEMPORARY FOR TESTING
110
+ def transcribe_dummy(aud_inp_tb, whisper_lang):
111
+ if aud_inp_tb is None:
112
+ return ""
113
+ # aud = whisper.load_audio(aud_inp)
114
+ # aud = whisper.pad_or_trim(aud)
115
+ # mel = whisper.log_mel_spectrogram(aud).to(WHISPER_MODEL.device)
116
+ # _, probs = WHISPER_MODEL.detect_language(mel)
117
+ # options = whisper.DecodingOptions()
118
+ # options = whisper.DecodingOptions(language="ja")
119
+ # result = whisper.decode(WHISPER_MODEL, mel, options)
120
+ result_text = "Whisper will detect language"
121
+ if whisper_lang != WHISPER_DETECT_LANG:
122
+ whisper_lang_code = POLLY_VOICE_DATA.get_whisper_lang_code(whisper_lang)
123
+ result_text = f"Whisper will use lang code: {whisper_lang_code}"
124
+ print("result_text", result_text)
125
+ return aud_inp_tb
126
+
127
+
128
+ # Pertains to Express-inator functionality
129
+ def transform_text(desc, express_chain, num_words, formality,
130
+ anticipation_level, joy_level, trust_level,
131
+ fear_level, surprise_level, sadness_level, disgust_level, anger_level,
132
+ lang_level, translate_to, literary_style):
133
+ num_words_prompt = ""
134
+ if num_words and int(num_words) != 0:
135
+ num_words_prompt = "using up to " + str(num_words) + " words, "
136
+
137
+ # Change some arguments to lower case
138
+ formality = formality.lower()
139
+ anticipation_level = anticipation_level.lower()
140
+ joy_level = joy_level.lower()
141
+ trust_level = trust_level.lower()
142
+ fear_level = fear_level.lower()
143
+ surprise_level = surprise_level.lower()
144
+ sadness_level = sadness_level.lower()
145
+ disgust_level = disgust_level.lower()
146
+ anger_level = anger_level.lower()
147
+
148
+ formality_str = ""
149
+ if formality != "n/a":
150
+ formality_str = "in a " + formality + " manner, "
151
+
152
+ # put all emotions into a list
153
+ emotions = []
154
+ if anticipation_level != "n/a":
155
+ emotions.append(anticipation_level)
156
+ if joy_level != "n/a":
157
+ emotions.append(joy_level)
158
+ if trust_level != "n/a":
159
+ emotions.append(trust_level)
160
+ if fear_level != "n/a":
161
+ emotions.append(fear_level)
162
+ if surprise_level != "n/a":
163
+ emotions.append(surprise_level)
164
+ if sadness_level != "n/a":
165
+ emotions.append(sadness_level)
166
+ if disgust_level != "n/a":
167
+ emotions.append(disgust_level)
168
+ if anger_level != "n/a":
169
+ emotions.append(anger_level)
170
+
171
+ emotions_str = ""
172
+ if len(emotions) > 0:
173
+ if len(emotions) == 1:
174
+ emotions_str = "with emotion of " + emotions[0] + ", "
175
+ else:
176
+ emotions_str = "with emotions of " + ", ".join(emotions[:-1]) + " and " + emotions[-1] + ", "
177
+
178
+ lang_level_str = ""
179
+ if lang_level != LANG_LEVEL_DEFAULT:
180
+ lang_level_str = "at a level that a person in " + lang_level + " can easily comprehend, " if translate_to == TRANSLATE_TO_DEFAULT else ""
181
+
182
+ translate_to_str = ""
183
+ if translate_to != TRANSLATE_TO_DEFAULT:
184
+ translate_to_str = "translated to " + translate_to + (
185
+ "" if lang_level == TRANSLATE_TO_DEFAULT else " at a level that a person in " + lang_level + " can easily comprehend") + ", "
186
+
187
+ literary_style_str = ""
188
+ if literary_style != LITERARY_STYLE_DEFAULT:
189
+ if literary_style == "Prose":
190
+ literary_style_str = "as prose, "
191
+ if literary_style == "Story":
192
+ literary_style_str = "as a story, "
193
+ elif literary_style == "Summary":
194
+ literary_style_str = "as a summary, "
195
+ elif literary_style == "Outline":
196
+ literary_style_str = "as an outline numbers and lower case letters, "
197
+ elif literary_style == "Bullets":
198
+ literary_style_str = "as bullet points using bullets, "
199
+ elif literary_style == "Poetry":
200
+ literary_style_str = "as a poem, "
201
+ elif literary_style == "Haiku":
202
+ literary_style_str = "as a haiku, "
203
+ elif literary_style == "Limerick":
204
+ literary_style_str = "as a limerick, "
205
+ elif literary_style == "Rap":
206
+ literary_style_str = "as a rap, "
207
+ elif literary_style == "Joke":
208
+ literary_style_str = "as a very funny joke with a setup and punchline, "
209
+ elif literary_style == "Knock-knock":
210
+ literary_style_str = "as a very funny knock-knock joke, "
211
+ elif literary_style == "FAQ":
212
+ literary_style_str = "as a FAQ with several questions and answers, "
213
+
214
+ formatted_prompt = PROMPT_TEMPLATE.format(
215
+ original_words=desc,
216
+ num_words=num_words_prompt,
217
+ formality=formality_str,
218
+ emotions=emotions_str,
219
+ lang_level=lang_level_str,
220
+ translate_to=translate_to_str,
221
+ literary_style=literary_style_str
222
+ )
223
+
224
+ trans_instr = num_words_prompt + formality_str + emotions_str + lang_level_str + translate_to_str + literary_style_str
225
+ if express_chain and len(trans_instr.strip()) > 0:
226
+ generated_text = express_chain.run(
227
+ {'original_words': desc, 'num_words': num_words_prompt, 'formality': formality_str,
228
+ 'emotions': emotions_str, 'lang_level': lang_level_str, 'translate_to': translate_to_str,
229
+ 'literary_style': literary_style_str}).strip()
230
+ else:
231
+ print("Not transforming text")
232
+ generated_text = desc
233
+
234
+ # replace all newlines with <br> in generated_text
235
+ generated_text = generated_text.replace("\n", "\n\n")
236
+
237
+ prompt_plus_generated = "GPT prompt: " + formatted_prompt + "\n\n" + generated_text
238
+
239
+ print("\n==== date/time: " + str(datetime.datetime.now() - datetime.timedelta(hours=5)) + " ====")
240
+ print("prompt_plus_generated: " + prompt_plus_generated)
241
+
242
+ return generated_text
243
+
244
+
245
+ def load_chain(tools_list, llm):
246
+ chain = None
247
+ express_chain = None
248
+ memory = None
249
+ if llm:
250
+ print("\ntools_list", tools_list)
251
+ tool_names = tools_list
252
+ tools = load_tools(tool_names, llm=llm, news_api_key=news_api_key, tmdb_bearer_token=tmdb_bearer_token)
253
+
254
+ memory = ConversationBufferMemory(memory_key="chat_history")
255
+
256
+ chain = initialize_agent(tools, llm, agent="conversational-react-description", verbose=True, memory=memory)
257
+ express_chain = LLMChain(llm=llm, prompt=PROMPT_TEMPLATE, verbose=True)
258
+ return chain, express_chain, memory
259
+
260
+
261
+ def set_openai_api_key(api_key):
262
+ """Set the api key and return chain.
263
+ If no api_key, then None is returned.
264
+ """
265
+ if api_key and api_key.startswith("sk-") and len(api_key) > 50:
266
+ os.environ["OPENAI_API_KEY"] = api_key
267
+ print("\n\n ++++++++++++++ Setting OpenAI API key ++++++++++++++ \n\n")
268
+ print(str(datetime.datetime.now()) + ": Before OpenAI, OPENAI_API_KEY length: " + str(
269
+ len(os.environ["OPENAI_API_KEY"])))
270
+ llm = OpenAI(temperature=0, max_tokens=MAX_TOKENS)
271
+ print(str(datetime.datetime.now()) + ": After OpenAI, OPENAI_API_KEY length: " + str(
272
+ len(os.environ["OPENAI_API_KEY"])))
273
+ chain, express_chain, memory = load_chain(TOOLS_DEFAULT_LIST, llm)
274
+
275
+ # Pertains to question answering functionality
276
+ embeddings = OpenAIEmbeddings()
277
+ qa_chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff")
278
+
279
+ print(str(datetime.datetime.now()) + ": After load_chain, OPENAI_API_KEY length: " + str(
280
+ len(os.environ["OPENAI_API_KEY"])))
281
+ os.environ["OPENAI_API_KEY"] = ""
282
+ return chain, express_chain, llm, embeddings, qa_chain, memory
283
+ return None, None, None, None, None, None
284
+
285
+
286
+ def run_chain(chain, inp, capture_hidden_text):
287
+ output = ""
288
+ hidden_text = None
289
+ if capture_hidden_text:
290
+ error_msg = None
291
+ tmp = sys.stdout
292
+ hidden_text_io = StringIO()
293
+ sys.stdout = hidden_text_io
294
+
295
+ try:
296
+ output = chain.run(input=inp)
297
+ except AuthenticationError as ae:
298
+ error_msg = AUTH_ERR_MSG + str(datetime.datetime.now()) + ". " + str(ae)
299
+ print("error_msg", error_msg)
300
+ except RateLimitError as rle:
301
+ error_msg = "\n\nRateLimitError: " + str(rle)
302
+ except ValueError as ve:
303
+ error_msg = "\n\nValueError: " + str(ve)
304
+ except InvalidRequestError as ire:
305
+ error_msg = "\n\nInvalidRequestError: " + str(ire)
306
+ except Exception as e:
307
+ error_msg = "\n\n" + BUG_FOUND_MSG + ":\n\n" + str(e)
308
+
309
+ sys.stdout = tmp
310
+ hidden_text = hidden_text_io.getvalue()
311
+
312
+ # remove escape characters from hidden_text
313
+ hidden_text = re.sub(r'\x1b[^m]*m', '', hidden_text)
314
+
315
+ # remove "Entering new AgentExecutor chain..." from hidden_text
316
+ hidden_text = re.sub(r"Entering new AgentExecutor chain...\n", "", hidden_text)
317
+
318
+ # remove "Finished chain." from hidden_text
319
+ hidden_text = re.sub(r"Finished chain.", "", hidden_text)
320
+
321
+ # Add newline after "Thought:" "Action:" "Observation:" "Input:" and "AI:"
322
+ hidden_text = re.sub(r"Thought:", "\n\nThought:", hidden_text)
323
+ hidden_text = re.sub(r"Action:", "\n\nAction:", hidden_text)
324
+ hidden_text = re.sub(r"Observation:", "\n\nObservation:", hidden_text)
325
+ hidden_text = re.sub(r"Input:", "\n\nInput:", hidden_text)
326
+ hidden_text = re.sub(r"AI:", "\n\nAI:", hidden_text)
327
+
328
+ if error_msg:
329
+ hidden_text += error_msg
330
+
331
+ print("hidden_text: ", hidden_text)
332
+ else:
333
+ try:
334
+ output = chain.run(input=inp)
335
+ except AuthenticationError as ae:
336
+ output = AUTH_ERR_MSG + str(datetime.datetime.now()) + ". " + str(ae)
337
+ print("output", output)
338
+ except RateLimitError as rle:
339
+ output = "\n\nRateLimitError: " + str(rle)
340
+ except ValueError as ve:
341
+ output = "\n\nValueError: " + str(ve)
342
+ except InvalidRequestError as ire:
343
+ output = "\n\nInvalidRequestError: " + str(ire)
344
+ except Exception as e:
345
+ output = "\n\n" + BUG_FOUND_MSG + ":\n\n" + str(e)
346
+
347
+ return output, hidden_text
348
+
349
+
350
+ def reset_memory(history, memory):
351
+ memory.clear()
352
+ history = []
353
+ return history, history, memory
354
+
355
+
356
+ class ChatWrapper:
357
+
358
+ def __init__(self):
359
+ self.lock = Lock()
360
+
361
+ def __call__(
362
+ self, api_key: str, inp: str, history: Optional[Tuple[str, str]], chain: Optional[ConversationChain],
363
+ trace_chain: bool, speak_text: bool, talking_head: bool, monologue: bool, express_chain: Optional[LLMChain],
364
+ num_words, formality, anticipation_level, joy_level, trust_level,
365
+ fear_level, surprise_level, sadness_level, disgust_level, anger_level,
366
+ lang_level, translate_to, literary_style, qa_chain, docsearch, use_embeddings
367
+ ):
368
+ """Execute the chat functionality."""
369
+ self.lock.acquire()
370
+ try:
371
+ print("\n==== date/time: " + str(datetime.datetime.now()) + " ====")
372
+ print("inp: " + inp)
373
+ print("trace_chain: ", trace_chain)
374
+ print("speak_text: ", speak_text)
375
+ print("talking_head: ", talking_head)
376
+ print("monologue: ", monologue)
377
+ history = history or []
378
+ # If chain is None, that is because no API key was provided.
379
+ output = "Please paste your OpenAI key from openai.com to use this app. " + str(datetime.datetime.now())
380
+ hidden_text = output
381
+
382
+ if chain:
383
+ # Set OpenAI key
384
+ import openai
385
+ openai.api_key = api_key
386
+ if not monologue:
387
+ if use_embeddings:
388
+ if inp and inp.strip() != "":
389
+ if docsearch:
390
+ docs = docsearch.similarity_search(inp)
391
+ output = str(qa_chain.run(input_documents=docs, question=inp))
392
+ else:
393
+ output, hidden_text = "Please supply some text in the the Embeddings tab.", None
394
+ else:
395
+ output, hidden_text = "What's on your mind?", None
396
+ else:
397
+ output, hidden_text = run_chain(chain, inp, capture_hidden_text=trace_chain)
398
+ else:
399
+ output, hidden_text = inp, None
400
+
401
+ output = transform_text(output, express_chain, num_words, formality, anticipation_level, joy_level,
402
+ trust_level,
403
+ fear_level, surprise_level, sadness_level, disgust_level, anger_level,
404
+ lang_level, translate_to, literary_style)
405
+
406
+ text_to_display = output
407
+ if trace_chain:
408
+ text_to_display = hidden_text + "\n\n" + output
409
+ history.append((inp, text_to_display))
410
+
411
+ html_video, temp_file, html_audio, temp_aud_file = None, None, None, None
412
+ if speak_text:
413
+ if talking_head:
414
+ if len(output) <= MAX_TALKING_HEAD_TEXT_LENGTH:
415
+ html_video, temp_file = do_html_video_speak(output, translate_to)
416
+ else:
417
+ temp_file = LOOPING_TALKING_HEAD
418
+ html_video = create_html_video(temp_file, TALKING_HEAD_WIDTH)
419
+ html_audio, temp_aud_file = do_html_audio_speak(output, translate_to)
420
+ else:
421
+ html_audio, temp_aud_file = do_html_audio_speak(output, translate_to)
422
+ else:
423
+ if talking_head:
424
+ temp_file = LOOPING_TALKING_HEAD
425
+ html_video = create_html_video(temp_file, TALKING_HEAD_WIDTH)
426
+ else:
427
+ # html_audio, temp_aud_file = do_html_audio_speak(output, translate_to)
428
+ # html_video = create_html_video(temp_file, "128")
429
+ pass
430
+
431
+ except Exception as e:
432
+ raise e
433
+ finally:
434
+ self.lock.release()
435
+ return history, history, html_video, temp_file, html_audio, temp_aud_file, ""
436
+ # return history, history, html_audio, temp_aud_file, ""
437
+
438
+
439
+ chat = ChatWrapper()
440
+
441
+
442
+ def do_html_audio_speak(words_to_speak, polly_language):
443
+ polly_client = boto3.Session(
444
+ aws_access_key_id=os.environ["AWS_ACCESS_KEY_ID"],
445
+ aws_secret_access_key=os.environ["AWS_SECRET_ACCESS_KEY"],
446
+ region_name=os.environ["AWS_DEFAULT_REGION"]
447
+ ).client('polly')
448
+
449
+ # voice_id, language_code, engine = POLLY_VOICE_DATA.get_voice(polly_language, "Female")
450
+ voice_id, language_code, engine = POLLY_VOICE_DATA.get_voice(polly_language, "Male")
451
+ if not voice_id:
452
+ # voice_id = "Joanna"
453
+ voice_id = "Matthew"
454
+ language_code = "en-US"
455
+ engine = NEURAL_ENGINE
456
+ response = polly_client.synthesize_speech(
457
+ Text=words_to_speak,
458
+ OutputFormat='mp3',
459
+ VoiceId=voice_id,
460
+ LanguageCode=language_code,
461
+ Engine=engine
462
+ )
463
+
464
+ html_audio = '<pre>no audio</pre>'
465
+
466
+ # Save the audio stream returned by Amazon Polly on Lambda's temp directory
467
+ if "AudioStream" in response:
468
+ with closing(response["AudioStream"]) as stream:
469
+ # output = os.path.join("/tmp/", "speech.mp3")
470
+
471
+ try:
472
+ with open('audios/tempfile.mp3', 'wb') as f:
473
+ f.write(stream.read())
474
+ temp_aud_file = gr.File("audios/tempfile.mp3")
475
+ temp_aud_file_url = "/file=" + temp_aud_file.value['name']
476
+ html_audio = f'<audio autoplay><source src={temp_aud_file_url} type="audio/mp3"></audio>'
477
+ except IOError as error:
478
+ # Could not write to file, exit gracefully
479
+ print(error)
480
+ return None, None
481
+ else:
482
+ # The response didn't contain audio data, exit gracefully
483
+ print("Could not stream audio")
484
+ return None, None
485
+
486
+ return html_audio, "audios/tempfile.mp3"
487
+
488
+
489
+ def create_html_video(file_name, width):
490
+ temp_file_url = "/file=" + tmp_file.value['name']
491
+ html_video = f'<video width={width} height={width} autoplay muted loop><source src={temp_file_url} type="video/mp4" poster="Masahiro.png"></video>'
492
+ return html_video
493
+
494
+
495
+ def do_html_video_speak(words_to_speak, azure_language):
496
+ azure_voice = AZURE_VOICE_DATA.get_voice(azure_language, "Male")
497
+ if not azure_voice:
498
+ azure_voice = "en-US-ChristopherNeural"
499
+
500
+ headers = {"Authorization": f"Bearer {os.environ['EXHUMAN_API_KEY']}"}
501
+ body = {
502
+ 'bot_name': 'Masahiro',
503
+ 'bot_response': words_to_speak,
504
+ 'azure_voice': azure_voice,
505
+ 'azure_style': 'friendly',
506
+ 'animation_pipeline': 'high_speed',
507
+ }
508
+ api_endpoint = "https://api.exh.ai/animations/v1/generate_lipsync"
509
+ res = requests.post(api_endpoint, json=body, headers=headers)
510
+ print("res.status_code: ", res.status_code)
511
+
512
+ html_video = '<pre>no video</pre>'
513
+ if isinstance(res.content, bytes):
514
+ response_stream = io.BytesIO(res.content)
515
+ print("len(res.content)): ", len(res.content))
516
+
517
+ with open('videos/tempfile.mp4', 'wb') as f:
518
+ f.write(response_stream.read())
519
+ temp_file = gr.File("videos/tempfile.mp4")
520
+ temp_file_url = "/file=" + temp_file.value['name']
521
+ html_video = f'<video width={TALKING_HEAD_WIDTH} height={TALKING_HEAD_WIDTH} autoplay><source src={temp_file_url} type="video/mp4" poster="Masahiro.png"></video>'
522
+ else:
523
+ print('video url unknown')
524
+ return html_video, "videos/tempfile.mp4"
525
+
526
+
527
+ def update_selected_tools(widget, state, llm):
528
+ if widget:
529
+ state = widget
530
+ chain, express_chain, memory = load_chain(state, llm)
531
+ return state, llm, chain, express_chain
532
+
533
+
534
+ def update_talking_head(widget, state):
535
+ if widget:
536
+ state = widget
537
+
538
+ video_html_talking_head = create_html_video(LOOPING_TALKING_HEAD, TALKING_HEAD_WIDTH)
539
+ return state, video_html_talking_head
540
+ else:
541
+ # return state, create_html_video(LOOPING_TALKING_HEAD, "32")
542
+ return None, "<pre></pre>"
543
+
544
+
545
+ def update_foo(widget, state):
546
+ if widget:
547
+ state = widget
548
+ return state
549
+
550
+
551
+ # Pertains to question answering functionality
552
+ def update_embeddings(embeddings_text, embeddings, qa_chain):
553
+ if embeddings_text:
554
+ text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
555
+ texts = text_splitter.split_text(embeddings_text)
556
+
557
+ docsearch = FAISS.from_texts(texts, embeddings)
558
+ print("Embeddings updated")
559
+ return docsearch
560
+
561
+
562
+ # Pertains to question answering functionality
563
+ def update_use_embeddings(widget, state):
564
+ if widget:
565
+ state = widget
566
+ return state
567
+
568
+
569
+ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
570
+ llm_state = gr.State()
571
+ history_state = gr.State()
572
+ chain_state = gr.State()
573
+ express_chain_state = gr.State()
574
+ tools_list_state = gr.State(TOOLS_DEFAULT_LIST)
575
+ trace_chain_state = gr.State(False)
576
+ speak_text_state = gr.State(False)
577
+ talking_head_state = gr.State(True)
578
+ monologue_state = gr.State(False) # Takes the input and repeats it back to the user, optionally transforming it.
579
+ memory_state = gr.State()
580
+
581
+ # Pertains to Express-inator functionality
582
+ num_words_state = gr.State(NUM_WORDS_DEFAULT)
583
+ formality_state = gr.State(FORMALITY_DEFAULT)
584
+ anticipation_level_state = gr.State(EMOTION_DEFAULT)
585
+ joy_level_state = gr.State(EMOTION_DEFAULT)
586
+ trust_level_state = gr.State(EMOTION_DEFAULT)
587
+ fear_level_state = gr.State(EMOTION_DEFAULT)
588
+ surprise_level_state = gr.State(EMOTION_DEFAULT)
589
+ sadness_level_state = gr.State(EMOTION_DEFAULT)
590
+ disgust_level_state = gr.State(EMOTION_DEFAULT)
591
+ anger_level_state = gr.State(EMOTION_DEFAULT)
592
+ lang_level_state = gr.State(LANG_LEVEL_DEFAULT)
593
+ translate_to_state = gr.State(TRANSLATE_TO_DEFAULT)
594
+ literary_style_state = gr.State(LITERARY_STYLE_DEFAULT)
595
+
596
+ # Pertains to WHISPER functionality
597
+ whisper_lang_state = gr.State(WHISPER_DETECT_LANG)
598
+
599
+ # Pertains to question answering functionality
600
+ embeddings_state = gr.State()
601
+ qa_chain_state = gr.State()
602
+ docsearch_state = gr.State()
603
+ use_embeddings_state = gr.State(False)
604
+
605
+ with gr.Tab("Chat"):
606
+ with gr.Row():
607
+ with gr.Column():
608
+ gr.HTML(
609
+ """<b><center>GPT + WolframAlpha + Whisper</center></b>
610
+ <p><center>Hit Enter after pasting your OpenAI API key</center></p>""")
611
+
612
+ openai_api_key_textbox = gr.Textbox(placeholder="Paste your OpenAI API key (sk-...) and hit Enter",
613
+ show_label=False, lines=1, type='password')
614
+
615
+ with gr.Row():
616
+ with gr.Column(scale=1, min_width=TALKING_HEAD_WIDTH, visible=True):
617
+ speak_text_cb = gr.Checkbox(label="Enable speech", value=False)
618
+ speak_text_cb.change(update_foo, inputs=[speak_text_cb, speak_text_state],
619
+ outputs=[speak_text_state])
620
+
621
+ my_file = gr.File(label="Upload a file", type="file", visible=False)
622
+ tmp_file = gr.File(LOOPING_TALKING_HEAD, visible=False)
623
+ # tmp_file_url = "/file=" + tmp_file.value['name']
624
+ htm_video = create_html_video(LOOPING_TALKING_HEAD, TALKING_HEAD_WIDTH)
625
+ video_html = gr.HTML(htm_video)
626
+
627
+ # my_aud_file = gr.File(label="Audio file", type="file", visible=True)
628
+ tmp_aud_file = gr.File("audios/tempfile.mp3", visible=False)
629
+ tmp_aud_file_url = "/file=" + tmp_aud_file.value['name']
630
+ htm_audio = f'<audio><source src={tmp_aud_file_url} type="audio/mp3"></audio>'
631
+ audio_html = gr.HTML(htm_audio)
632
+
633
+ with gr.Column(scale=7):
634
+ chatbot = gr.Chatbot()
635
+
636
+ with gr.Row():
637
+ message = gr.Textbox(label="What's on your mind??",
638
+ placeholder="What's the answer to life, the universe, and everything?",
639
+ lines=1)
640
+ submit = gr.Button(value="Send", variant="secondary").style(full_width=False)
641
+
642
+ # UNCOMMENT TO USE WHISPER
643
+ with gr.Row():
644
+ audio_comp = gr.Microphone(source="microphone", type="filepath", label="Just say it!",
645
+ interactive=True, streaming=False)
646
+ audio_comp.change(transcribe, inputs=[audio_comp, whisper_lang_state], outputs=[message])
647
+
648
+ # TEMPORARY FOR TESTING
649
+ # with gr.Row():
650
+ # audio_comp_tb = gr.Textbox(label="Just say it!", lines=1)
651
+ # audio_comp_tb.submit(transcribe_dummy, inputs=[audio_comp_tb, whisper_lang_state], outputs=[message])
652
+
653
+ gr.Examples(
654
+ examples=["How many people live in Canada?",
655
+ "What is 2 to the 30th power?",
656
+ "If x+y=10 and x-y=4, what are x and y?",
657
+ "How much did it rain in SF today?",
658
+ "Get me information about the movie 'Avatar'",
659
+ "What are the top tech headlines in the US?",
660
+ "On the desk, you see two blue booklets, two purple booklets, and two yellow pairs of sunglasses - "
661
+ "if I remove all the pairs of sunglasses from the desk, how many purple items remain on it?"],
662
+ inputs=message
663
+ )
664
+
665
+ with gr.Tab("Settings"):
666
+ tools_cb_group = gr.CheckboxGroup(label="Tools:", choices=TOOLS_LIST,
667
+ value=TOOLS_DEFAULT_LIST)
668
+ tools_cb_group.change(update_selected_tools,
669
+ inputs=[tools_cb_group, tools_list_state, llm_state],
670
+ outputs=[tools_list_state, llm_state, chain_state, express_chain_state])
671
+
672
+ trace_chain_cb = gr.Checkbox(label="Show reasoning chain in chat bubble", value=False)
673
+ trace_chain_cb.change(update_foo, inputs=[trace_chain_cb, trace_chain_state],
674
+ outputs=[trace_chain_state])
675
+
676
+ # speak_text_cb = gr.Checkbox(label="Speak text from agent", value=False)
677
+ # speak_text_cb.change(update_foo, inputs=[speak_text_cb, speak_text_state],
678
+ # outputs=[speak_text_state])
679
+
680
+ talking_head_cb = gr.Checkbox(label="Show talking head", value=True)
681
+ talking_head_cb.change(update_talking_head, inputs=[talking_head_cb, talking_head_state],
682
+ outputs=[talking_head_state, video_html])
683
+
684
+ monologue_cb = gr.Checkbox(label="Babel fish mode (translate/restate what you enter, no conversational agent)",
685
+ value=False)
686
+ monologue_cb.change(update_foo, inputs=[monologue_cb, monologue_state],
687
+ outputs=[monologue_state])
688
+
689
+ reset_btn = gr.Button(value="Reset chat", variant="secondary").style(full_width=False)
690
+ reset_btn.click(reset_memory, inputs=[history_state, memory_state], outputs=[chatbot, history_state, memory_state])
691
+
692
+ with gr.Tab("Whisper STT"):
693
+ whisper_lang_radio = gr.Radio(label="Whisper speech-to-text language:", choices=[
694
+ WHISPER_DETECT_LANG, "Arabic", "Arabic (Gulf)", "Catalan", "Chinese (Cantonese)", "Chinese (Mandarin)",
695
+ "Danish", "Dutch", "English (Australian)", "English (British)", "English (Indian)", "English (New Zealand)",
696
+ "English (South African)", "English (US)", "English (Welsh)", "Finnish", "French", "French (Canadian)",
697
+ "German", "German (Austrian)", "Georgian", "Hindi", "Icelandic", "Indonesian", "Italian", "Japanese",
698
+ "Korean", "Norwegian", "Polish",
699
+ "Portuguese (Brazilian)", "Portuguese (European)", "Romanian", "Russian", "Spanish (European)",
700
+ "Spanish (Mexican)", "Spanish (US)", "Swedish", "Turkish", "Ukrainian", "Welsh"],
701
+ value=WHISPER_DETECT_LANG)
702
+
703
+ whisper_lang_radio.change(update_foo,
704
+ inputs=[whisper_lang_radio, whisper_lang_state],
705
+ outputs=[whisper_lang_state])
706
+
707
+ with gr.Tab("Translate to"):
708
+ lang_level_radio = gr.Radio(label="Language level:", choices=[
709
+ LANG_LEVEL_DEFAULT, "1st grade", "2nd grade", "3rd grade", "4th grade", "5th grade", "6th grade",
710
+ "7th grade", "8th grade", "9th grade", "10th grade", "11th grade", "12th grade", "University"],
711
+ value=LANG_LEVEL_DEFAULT)
712
+ lang_level_radio.change(update_foo, inputs=[lang_level_radio, lang_level_state],
713
+ outputs=[lang_level_state])
714
+
715
+ translate_to_radio = gr.Radio(label="Language:", choices=[
716
+ TRANSLATE_TO_DEFAULT, "Arabic", "Arabic (Gulf)", "Catalan", "Chinese (Cantonese)", "Chinese (Mandarin)",
717
+ "Danish", "Dutch", "English (Australian)", "English (British)", "English (Indian)", "English (New Zealand)",
718
+ "English (South African)", "English (US)", "English (Welsh)", "Finnish", "French", "French (Canadian)",
719
+ "German", "German (Austrian)", "Georgian", "Hindi", "Icelandic", "Indonesian", "Italian", "Japanese",
720
+ "Korean", "Norwegian", "Polish",
721
+ "Portuguese (Brazilian)", "Portuguese (European)", "Romanian", "Russian", "Spanish (European)",
722
+ "Spanish (Mexican)", "Spanish (US)", "Swedish", "Turkish", "Ukrainian", "Welsh",
723
+ "emojis", "Gen Z slang", "how the stereotypical Karen would say it", "Klingon", "Neanderthal",
724
+ "Pirate", "Strange Planet expospeak technical talk", "Yoda"],
725
+ value=TRANSLATE_TO_DEFAULT)
726
+
727
+ translate_to_radio.change(update_foo,
728
+ inputs=[translate_to_radio, translate_to_state],
729
+ outputs=[translate_to_state])
730
+
731
+ with gr.Tab("Formality"):
732
+ formality_radio = gr.Radio(label="Formality:",
733
+ choices=[FORMALITY_DEFAULT, "Casual", "Polite", "Honorific"],
734
+ value=FORMALITY_DEFAULT)
735
+ formality_radio.change(update_foo,
736
+ inputs=[formality_radio, formality_state],
737
+ outputs=[formality_state])
738
+
739
+ with gr.Tab("Lit style"):
740
+ literary_style_radio = gr.Radio(label="Literary style:", choices=[
741
+ LITERARY_STYLE_DEFAULT, "Prose", "Story", "Summary", "Outline", "Bullets", "Poetry", "Haiku", "Limerick", "Rap",
742
+ "Joke", "Knock-knock", "FAQ"],
743
+ value=LITERARY_STYLE_DEFAULT)
744
+
745
+ literary_style_radio.change(update_foo,
746
+ inputs=[literary_style_radio, literary_style_state],
747
+ outputs=[literary_style_state])
748
+
749
+ with gr.Tab("Emotions"):
750
+ anticipation_level_radio = gr.Radio(label="Anticipation level:",
751
+ choices=[EMOTION_DEFAULT, "Interest", "Anticipation", "Vigilance"],
752
+ value=EMOTION_DEFAULT)
753
+ anticipation_level_radio.change(update_foo,
754
+ inputs=[anticipation_level_radio, anticipation_level_state],
755
+ outputs=[anticipation_level_state])
756
+
757
+ joy_level_radio = gr.Radio(label="Joy level:",
758
+ choices=[EMOTION_DEFAULT, "Serenity", "Joy", "Ecstasy"],
759
+ value=EMOTION_DEFAULT)
760
+ joy_level_radio.change(update_foo,
761
+ inputs=[joy_level_radio, joy_level_state],
762
+ outputs=[joy_level_state])
763
+
764
+ trust_level_radio = gr.Radio(label="Trust level:",
765
+ choices=[EMOTION_DEFAULT, "Acceptance", "Trust", "Admiration"],
766
+ value=EMOTION_DEFAULT)
767
+ trust_level_radio.change(update_foo,
768
+ inputs=[trust_level_radio, trust_level_state],
769
+ outputs=[trust_level_state])
770
+
771
+ fear_level_radio = gr.Radio(label="Fear level:",
772
+ choices=[EMOTION_DEFAULT, "Apprehension", "Fear", "Terror"],
773
+ value=EMOTION_DEFAULT)
774
+ fear_level_radio.change(update_foo,
775
+ inputs=[fear_level_radio, fear_level_state],
776
+ outputs=[fear_level_state])
777
+
778
+ surprise_level_radio = gr.Radio(label="Surprise level:",
779
+ choices=[EMOTION_DEFAULT, "Distraction", "Surprise", "Amazement"],
780
+ value=EMOTION_DEFAULT)
781
+ surprise_level_radio.change(update_foo,
782
+ inputs=[surprise_level_radio, surprise_level_state],
783
+ outputs=[surprise_level_state])
784
+
785
+ sadness_level_radio = gr.Radio(label="Sadness level:",
786
+ choices=[EMOTION_DEFAULT, "Pensiveness", "Sadness", "Grief"],
787
+ value=EMOTION_DEFAULT)
788
+ sadness_level_radio.change(update_foo,
789
+ inputs=[sadness_level_radio, sadness_level_state],
790
+ outputs=[sadness_level_state])
791
+
792
+ disgust_level_radio = gr.Radio(label="Disgust level:",
793
+ choices=[EMOTION_DEFAULT, "Boredom", "Disgust", "Loathing"],
794
+ value=EMOTION_DEFAULT)
795
+ disgust_level_radio.change(update_foo,
796
+ inputs=[disgust_level_radio, disgust_level_state],
797
+ outputs=[disgust_level_state])
798
+
799
+ anger_level_radio = gr.Radio(label="Anger level:",
800
+ choices=[EMOTION_DEFAULT, "Annoyance", "Anger", "Rage"],
801
+ value=EMOTION_DEFAULT)
802
+ anger_level_radio.change(update_foo,
803
+ inputs=[anger_level_radio, anger_level_state],
804
+ outputs=[anger_level_state])
805
+
806
+ with gr.Tab("Max words"):
807
+ num_words_slider = gr.Slider(label="Max number of words to generate (0 for don't care)",
808
+ value=NUM_WORDS_DEFAULT, minimum=0, maximum=MAX_WORDS, step=10)
809
+ num_words_slider.change(update_foo,
810
+ inputs=[num_words_slider, num_words_state],
811
+ outputs=[num_words_state])
812
+
813
+ with gr.Tab("Embeddings"):
814
+ embeddings_text_box = gr.Textbox(label="Enter text for embeddings and hit Create:",
815
+ lines=20)
816
+
817
+ with gr.Row():
818
+ use_embeddings_cb = gr.Checkbox(label="Use embeddings", value=False)
819
+ use_embeddings_cb.change(update_use_embeddings, inputs=[use_embeddings_cb, use_embeddings_state],
820
+ outputs=[use_embeddings_state])
821
+
822
+ embeddings_text_submit = gr.Button(value="Create", variant="secondary").style(full_width=False)
823
+ embeddings_text_submit.click(update_embeddings,
824
+ inputs=[embeddings_text_box, embeddings_state, qa_chain_state],
825
+ outputs=[docsearch_state])
826
+
827
+ gr.HTML("""
828
+ <p>This application, developed by <a href='https://www.linkedin.com/in/javafxpert/'>James L. Weaver</a>,
829
+ demonstrates a conversational agent implemented with OpenAI GPT-3.5 and LangChain.
830
+ When necessary, it leverages tools for complex math, searching the internet, and accessing news and weather.
831
+ Uses talking heads from <a href='https://exh.ai/'>Ex-Human</a>.
832
+ For faster inference without waiting in queue, you may duplicate the space.
833
+ </p>""")
834
+
835
+ gr.HTML("""
836
+ <form action="https://www.paypal.com/donate" method="post" target="_blank">
837
+ <input type="hidden" name="business" value="AK8BVNALBXSPQ" />
838
+ <input type="hidden" name="no_recurring" value="0" />
839
+ <input type="hidden" name="item_name" value="Please consider helping to defray the cost of APIs such as SerpAPI and WolframAlpha that this app uses." />
840
+ <input type="hidden" name="currency_code" value="USD" />
841
+ <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" title="PayPal - The safer, easier way to pay online!" alt="Donate with PayPal button" />
842
+ <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" />
843
+ </form>
844
+ """)
845
+
846
+ gr.HTML("""<center>
847
+ <a href="https://huggingface.co/spaces/JavaFXpert/Chat-GPT-LangChain?duplicate=true">
848
+ <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
849
+ Powered by <a href='https://github.com/hwchase17/langchain'>LangChain πŸ¦œοΈπŸ”—</a>
850
+ </center>""")
851
+
852
+ message.submit(chat, inputs=[openai_api_key_textbox, message, history_state, chain_state, trace_chain_state,
853
+ speak_text_state, talking_head_state, monologue_state,
854
+ express_chain_state, num_words_state, formality_state,
855
+ anticipation_level_state, joy_level_state, trust_level_state, fear_level_state,
856
+ surprise_level_state, sadness_level_state, disgust_level_state, anger_level_state,
857
+ lang_level_state, translate_to_state, literary_style_state,
858
+ qa_chain_state, docsearch_state, use_embeddings_state],
859
+ outputs=[chatbot, history_state, video_html, my_file, audio_html, tmp_aud_file, message])
860
+ # outputs=[chatbot, history_state, audio_html, tmp_aud_file, message])
861
+
862
+ submit.click(chat, inputs=[openai_api_key_textbox, message, history_state, chain_state, trace_chain_state,
863
+ speak_text_state, talking_head_state, monologue_state,
864
+ express_chain_state, num_words_state, formality_state,
865
+ anticipation_level_state, joy_level_state, trust_level_state, fear_level_state,
866
+ surprise_level_state, sadness_level_state, disgust_level_state, anger_level_state,
867
+ lang_level_state, translate_to_state, literary_style_state,
868
+ qa_chain_state, docsearch_state, use_embeddings_state],
869
+ outputs=[chatbot, history_state, video_html, my_file, audio_html, tmp_aud_file, message])
870
+ # outputs=[chatbot, history_state, audio_html, tmp_aud_file, message])
871
+
872
+ openai_api_key_textbox.change(set_openai_api_key,
873
+ inputs=[openai_api_key_textbox],
874
+ outputs=[chain_state, express_chain_state, llm_state, embeddings_state,
875
+ qa_chain_state, memory_state])
876
+ openai_api_key_textbox.submit(set_openai_api_key,
877
+ inputs=[openai_api_key_textbox],
878
+ outputs=[chain_state, express_chain_state, llm_state, embeddings_state,
879
+ qa_chain_state, memory_state])
880
+
881
+ block.launch(debug=True)
882
+