khangey commited on
Commit
68dfc67
·
1 Parent(s): 1fa184f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -0
app.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ from pathlib import Path
4
+ from typing import Dict, List, Tuple
5
+
6
+ import gradio as gr
7
+ import requests
8
+
9
+ from chat import ChatGpt
10
+ from store import store_message_pair
11
+
12
+ # Environment Variables
13
+ DEBUG = bool(os.getenv("DEBUG", False))
14
+ VERBOSE = bool(os.getenv("V", False))
15
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
16
+ BING_TRANSLATE_API_KEY = os.getenv("BING_TRANSLATE_API_KEY")
17
+
18
+ # Type Definitions
19
+ ROLE_USER = "user"
20
+ ROLE_ASSISTANT = "assistant"
21
+ CHATGPT_MSG = Dict[str, str] # {"role": "user|assistant", "content": "text"}
22
+ CHATGPT_HISTROY = List[CHATGPT_MSG]
23
+ CHATBOT_MSG = Tuple[str, str] # (user_message, bot_response)
24
+ CHATBOT_HISTORY = List[CHATBOT_MSG]
25
+
26
+ # Constants
27
+ LANG_BO = "bo"
28
+ LANG_MEDIUM = "en"
29
+
30
+ chatbot = ChatGpt(OPENAI_API_KEY)
31
+
32
+
33
+ def bing_translate(text: str, from_lang: str, to_lang: str):
34
+ if DEBUG:
35
+ if from_lang != "bo":
36
+ return "ཀཀཀཀཀཀ"
37
+ return "aaaaa"
38
+ headers = {
39
+ "Ocp-Apim-Subscription-Key": BING_TRANSLATE_API_KEY,
40
+ "Content-Type": "application/json",
41
+ "Ocp-Apim-Subscription-Region": "eastus",
42
+ "X-ClientTraceId": str(uuid.uuid4()),
43
+ }
44
+ resp = requests.post(
45
+ url="https://api.cognitive.microsofttranslator.com/translate",
46
+ params={"api-version": "3.0", "from": from_lang, "to": to_lang},
47
+ json=[{"text": text}],
48
+ headers=headers,
49
+ )
50
+ result = resp.json()
51
+ if resp.status_code == 200:
52
+ return result[0]["translations"][0]["text"]
53
+ else:
54
+ raise Exception("Error in translation API: ", result)
55
+
56
+
57
+ def user(input_bo: str, history_bo: list):
58
+ history_bo.append([input_bo, None])
59
+ return "", history_bo
60
+
61
+
62
+ def store_chat(
63
+ chat_id: str,
64
+ msg_pair_bo: Tuple[str, str],
65
+ msg_pair_medium: Tuple[str, str],
66
+ medium_lang: str,
67
+ ):
68
+ msg_pair = {
69
+ "bo": msg_pair_bo,
70
+ medium_lang: msg_pair_medium,
71
+ }
72
+ store_message_pair(chat_id, msg_pair)
73
+
74
+
75
+ def bot(history_bo: list, chat_id: str):
76
+ """Translate user input to English, send to OpenAI, translate response to Tibetan, and return to user.
77
+
78
+ Args:
79
+ input_bo (str): Tibetan input from user
80
+ history_bo (CHATBOT_HISTORY): Tibetan history of gradio chatbot
81
+ history_en (CHATGPT_HISTORY): English history of OpenAI ChatGPT
82
+
83
+ Returns:
84
+ history_bo (CHATBOT_HISTORY): Tibetan history of gradio chatbot
85
+ history_en (CHATGPT_HISTORY): English history of OpenAI ChatGPT
86
+ """
87
+ input_bo = history_bo[-1][0]
88
+ input_ = bing_translate(input_bo, LANG_BO, LANG_MEDIUM)
89
+ response = chatbot.generate_response(input_)
90
+ resopnse_bo = bing_translate(response, LANG_MEDIUM, LANG_BO)
91
+ history_bo[-1][1] = resopnse_bo
92
+ if VERBOSE:
93
+ print("------------------------")
94
+ print(history_bo)
95
+ print(history_en)
96
+ print("------------------------")
97
+
98
+ store_chat(
99
+ chat_id=chat_id,
100
+ msg_pair_bo=(input_bo, resopnse_bo),
101
+ msg_pair_medium=(input_, response),
102
+ medium_lang=LANG_MEDIUM,
103
+ )
104
+ return history_bo
105
+
106
+
107
+ def get_chat_id():
108
+ chatbot.clear_history()
109
+ return str(uuid.uuid4())
110
+
111
+
112
+ css_fn = Path(__file__).resolve().parent / "static" / "app.css"
113
+ assert css_fn.exists() and css_fn.is_file(), f"CSS file not found: {css_fn}"
114
+
115
+ with gr.Blocks(css=str(css_fn), theme=gr.themes.Soft()) as demo:
116
+ chat_id = gr.State(value=get_chat_id)
117
+ history_en = gr.State(value=[])
118
+ history_bo = gr.Chatbot(label="Tibetan Chatbot", elem_id="maiChatHistory").style(
119
+ height=650
120
+ )
121
+ input_bo = gr.Textbox(
122
+ show_label=False,
123
+ placeholder="Type here...",
124
+ elem_id="maiChatInput",
125
+ )
126
+ input_submit_btn = gr.Button("Submit")
127
+ input_bo.submit(
128
+ fn=user,
129
+ inputs=[input_bo, history_bo],
130
+ outputs=[input_bo, history_bo],
131
+ queue=False,
132
+ ).then(
133
+ fn=bot,
134
+ inputs=[history_bo, chat_id],
135
+ outputs=[history_bo],
136
+ )
137
+ input_submit_btn.click(
138
+ fn=user,
139
+ inputs=[input_bo, history_bo],
140
+ outputs=[input_bo, history_bo],
141
+ queue=False,
142
+ ).then(
143
+ fn=bot,
144
+ inputs=[history_bo, chat_id],
145
+ outputs=[history_bo],
146
+ )
147
+
148
+ clear = gr.Button("Clear")
149
+ clear.click(lambda: [], None, history_bo, queue=False)
150
+
151
+ demo.launch()