File size: 3,732 Bytes
507b005
 
 
 
 
 
 
 
9620306
507b005
 
406e574
507b005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cfbb4a
 
 
 
 
 
f0de542
406e574
507b005
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
import os
import time
from typing import List, Tuple, Optional, Dict, Union

import requests
import gradio as gr

TITLE = """<h1 align="center">Insight LLM 💬</h1>"""
SUBTITLE = """<h2 align="center">Effortlessly analyze and compare Thai stocks from 56-1 One Report with advanced LLM insights.</h2>"""
DUPLICATE = """
<div style="text-align: center; display: flex; justify-content: center; align-items: center;">
    <span>Duplicate the Space and run securely with your API KEY.</span>
</div>
"""

AVATAR_IMAGES = (
    None,
    "https://media.roboflow.com/spaces/gemini-icon.png"
)

CHAT_HISTORY = List[Tuple[Optional[Union[Tuple[str], str]], Optional[str]]]

def preprocess_chat_history(
    history: CHAT_HISTORY
) -> List[Dict[str, Union[str, List[str]]]]:
    messages = []
    for user_message, model_message in history:
        if isinstance(user_message, tuple):
            pass
        elif user_message is not None:
            messages.append({'role': 'user', 'parts': [user_message]})
        if model_message is not None:
            messages.append({'role': 'model', 'parts': [model_message]})
    return messages

def user(text_prompt: str, chatbot: CHAT_HISTORY):
    if text_prompt:
        chatbot.append((text_prompt, None))
    return "", chatbot

def bot(
    chatbot: CHAT_HISTORY
):
    if len(chatbot) == 0:
        return chatbot

    if chatbot[-1][0] and isinstance(chatbot[-1][0], str):
        text_prompt = chatbot[-1][0]
        try:
            response = requests.get(
                "https://api-obon.conf.in.th/team15/query",
                params={"text": text_prompt}
            )
            response.raise_for_status()  # Raise an error for bad status codes

            try:
                response_json = response.json()
                chatbot[-1][1] = response_json.get("text", "")
            except ValueError:
                chatbot[-1][1] = f"{response.text}"
        except requests.exceptions.RequestException as e:
            chatbot[-1][1] = f"Error: {e}"
    else:
        chatbot[-1][1] = "Invalid input"

    return chatbot

chatbot_component = gr.Chatbot(
    label='API Chatbot',
    bubble_full_width=False,
    avatar_images=AVATAR_IMAGES,
    scale=2,
    height=400
)
text_prompt_component = gr.Textbox(
    placeholder="Hi there! [press Enter]", show_label=False, autofocus=True, scale=8
)
run_button_component = gr.Button(value="Run", variant="primary", scale=1)

user_inputs = [
    text_prompt_component,
    chatbot_component
]

bot_inputs = [
    chatbot_component
]

with gr.Blocks() as demo:
    gr.HTML(TITLE)
    gr.HTML(SUBTITLE)
    gr.HTML(DUPLICATE)
    with gr.Column():
        chatbot_component.render()
        with gr.Row():
            text_prompt_component.render()
            run_button_component.render()

    run_button_component.click(
        fn=user,
        inputs=user_inputs,
        outputs=[text_prompt_component, chatbot_component],
        queue=False
    ).then(
        fn=bot, inputs=bot_inputs, outputs=[chatbot_component],
    )

    text_prompt_component.submit(
        fn=user,
        inputs=user_inputs,
        outputs=[text_prompt_component, chatbot_component],
        queue=False
    ).then(
        fn=bot, inputs=bot_inputs, outputs=[chatbot_component],
    )

    # Adding the detail about currently available stock data within the Blocks context
    stock_detail = """
    <div style="text-align: center; display: flex; justify-content: center; align-items: center; margin-top: 20px;">
        <span>Currently, we have data for the following stocks: KBANK, SCB, TTB, AIS, TRUE, SANSIRI, ORIGIN.</span>
    </div>
    """
    gr.HTML(stock_detail)

demo.queue(max_size=99).launch(debug=False, show_error=True)