File size: 7,006 Bytes
c48801f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
from pathlib import Path
import requests
import time
from random import randrange
from PIL import Image
import cv2
import numpy as np
from io import BytesIO

import streamlit as st
from streamlit_option_menu import option_menu

from src.styles.menu_styles import FOOTER_STYLES, HEADER_STYLES
from src.utils.lang import en, vi
from src.utils.ui import message_func
from src.utils.footer import show_info
from src.utils.helpers import get_random_img, get_files_in_dir


# --- PATH SETTINGS ---
current_dir: Path = Path(__file__).parent if "__file__" in locals() else Path.cwd()
css_file: Path = current_dir / "src/styles/.css"
assets_dir: Path = current_dir / "src/assets"
img_dir: Path = assets_dir / "img"

# --- GENERAL SETTINGS ---
PAGE_TITLE: str = "VNPT Chatbot"
PAGE_ICON: str = "🤖"
LANG_EN: str = "En"
LANG_VI: str = "Vi"
AI_MODEL_OPTIONS: list[str] = [
    "v.0.0.1",
]
API_ADDRESS: str = ""

st.set_page_config(page_title=PAGE_TITLE, page_icon=PAGE_ICON, layout="wide")

# --- LOAD CSS ---
with open(css_file) as f:
    st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
    
selected_lang = option_menu(
    menu_title=None,
    options=[LANG_EN, LANG_VI, ],
    icons=["globe2", "translate"],
    menu_icon="cast",
    default_index=0,
    orientation="horizontal",
    styles=HEADER_STYLES
)
    
# Storing The Context
if "locale" not in st.session_state:
    st.session_state.locale = en
if "seed" not in st.session_state:
    st.session_state.seed = randrange(10**3)
if "user_text" not in st.session_state:
    st.session_state.user_text = ""

def main(api_address, 
         conversation_path_param,
         new_chat_path_param,
         chat_append_path_param,
         process_path_param,
         guide_path_param):
    st.sidebar.selectbox(label=st.session_state.locale.select_placeholder1, key="model", options=AI_MODEL_OPTIONS)
            
    if st.sidebar.button(st.session_state.locale.reset_conversation):
        response = requests.post(api_address + new_chat_path_param)
        # Check if request was successful (status code 200)
        assert response.status_code == 200, response.status_code
    
    # Add guide
    st.sidebar.write("------------------------------------")
    response = requests.post(api_address + guide_path_param,
                             json={"language": st.session_state.locale.lang_code})
    assert response.status_code == 200, response.status_code
    guide_dict = response.json()["options_dict"]
    guide_options = {}
    option_is_selected = False
    option_prompt = ""
    for k, v in guide_dict.items():
        guide_options[k] = st.sidebar.button(k, use_container_width=True)
        if guide_options[k]:
            option_is_selected = True
            option_prompt = v
        
    prompt = st.chat_input()
    print(prompt)
    if option_is_selected:
        print("Appending ...")
        response = requests.post(api_address + chat_append_path_param, 
                                 json={"role": "user", "content": option_prompt})
        assert response.status_code == 200, response.status_code
    if prompt:
        print("Appending ...")
        response = requests.post(api_address + chat_append_path_param, 
                                 json={"role": "user", "content": prompt})
        assert response.status_code == 200, response.status_code
    
    # Visual conversation
    response = requests.get(api_address + conversation_path_param,
                            json={"language": st.session_state.locale.lang_code})
    assert response.status_code == 200, response.status_code
    messages = response.json()["conversation"]
    for message in messages:
        message_func(
            message["content"],
            role = message["role"],
        )
        urls = message.get("urls", [])
        titles = message.get("titles", [])
        
        if len(urls) and not isinstance(urls[0], list):
            urls = [[url] for url in urls]
        if len(titles) and not isinstance(titles[0], list):
            titles = [[title] for title in titles]
        
        for sub_urls, sub_titles in zip(urls, titles):
            display_images(sub_urls, sub_titles)
        
        # for url, title in zip(urls, titles):
        #     display_image_with_title_and_url(title, url)
        
    # Process the conversation if prompt
    if prompt or option_is_selected:
        print("Processing ...")
        start = time.time()
        response = requests.post(api_address + process_path_param,
                                 json={"language": st.session_state.locale.lang_code})
        assert response.status_code == 200, response.status_code
        logs = response.json()["logs"]
        for data in logs:
            urls = data["urls"]
            titles = data["titles"]
            end = time.time()
            print("done")
            print(data)
            print(end - start)
            message_func(
                data["content"],
                role=data["role"]
            )
            for url, title in zip(urls, titles):
                display_image_with_title_and_url(title, url)
    message_func(
        "",
        role="assistant"
    )

    # if st.session_state.user_text:
    #     show_conversation()
    #     st.session_state.user_text = ""
    # get_user_input()
    # show_chat_buttons()
             
def run_agi():
    global API_ADDRESS
    print(API_ADDRESS)
    st.sidebar.text_input("API address", key="api_address")
    api_address = st.session_state.api_address
    ##TODO: Dynamic this
    conversation_path_param = "/chatbot/"
    new_chat_path_param = "/chatbot/new_chat"
    chat_append_path_param = "/chatbot/append_text_from_user"
    process_path_param = "/chatbot/process"
    guide_path_param = "/chatbot/guide_options"
    
    match selected_lang:
        case "En":
            st.session_state.locale = en
        case "Vi":
            st.session_state.locale = vi
        case _:
            st.session_state.locale = en
    st.markdown(f"<h1 style='text-align: center;'>{st.session_state.locale.title}</h1>", unsafe_allow_html=True)
    selected_footer = option_menu(
        menu_title=None,
        options=[
            st.session_state.locale.footer_option1,
            st.session_state.locale.footer_option0,
        ],
        icons=["info-circle", "chat-square-text"],  # https://icons.getbootstrap.com/
        menu_icon="cast",
        default_index=0,
        orientation="horizontal",
        styles=FOOTER_STYLES
    )
    
    match selected_footer:
        case st.session_state.locale.footer_option0:
            main(api_address, 
                conversation_path_param,
                new_chat_path_param,
                chat_append_path_param,
                process_path_param,
                guide_path_param)
        case st.session_state.locale.footer_option1:
            show_info()
        case _:
            show_info()
            
                
if __name__ == "__main__":
    run_agi()