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