File size: 4,280 Bytes
806b298
c18eb4a
fb64db4
 
806b298
d9002a2
4ecc916
d9002a2
4a18c89
2cefdc2
 
74c4ff7
560eb12
793072f
4ecc916
c18eb4a
806b298
74c4ff7
806b298
 
560eb12
 
 
 
 
de2139a
 
4a18c89
 
ec5af7e
de2139a
560eb12
 
 
2cefdc2
560eb12
 
 
c18eb4a
560eb12
c18eb4a
 
560eb12
 
c18eb4a
 
560eb12
 
 
 
 
 
 
 
806b298
 
f847d40
 
 
d9002a2
 
4a18c89
 
 
 
 
 
48b9027
 
 
 
 
2cefdc2
 
48b9027
74c4ff7
 
 
 
 
 
 
 
 
 
 
1ff37d9
4a18c89
 
 
f847d40
793072f
2cefdc2
 
 
 
 
de2139a
48b9027
4a18c89
 
 
de2139a
4a18c89
d9002a2
 
48b9027
ec5af7e
48b9027
 
 
fb64db4
 
 
9df676c
48b9027
560eb12
fb64db4
 
 
f847d40
48b9027
fb64db4
 
d9002a2
fb64db4
f847d40
 
 
 
560eb12
f847d40
 
48b9027
4a18c89
806b298
fb64db4
 
 
 
 
 
 
 
 
 
806b298
fb64db4
48b9027
d9002a2
806b298
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import os
import uuid
from pathlib import Path
from typing import Dict, List, Tuple

import gradio as gr
import requests

from chat import ChatGpt
from store import store_message_pair

# 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": "eastus",
        "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 store_chat(
    chat_id: str,
    msg_pair_bo: Tuple[str, str],
    msg_pair_medium: Tuple[str, str],
    medium_lang: str,
):
    msg_pair = {
        "bo": msg_pair_bo,
        medium_lang: msg_pair_medium,
    }
    store_message_pair(chat_id, msg_pair)


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("------------------------")

    store_chat(
        chat_id=chat_id,
        msg_pair_bo=(input_bo, resopnse_bo),
        msg_pair_medium=(input_, response),
        medium_lang=LANG_MEDIUM,
    )
    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").style(
        height=650
    )
    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()