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