File size: 4,216 Bytes
a5a8279
 
127b728
73432f0
127b728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ab43b4
 
 
 
127b728
 
 
 
 
 
 
 
 
 
 
4ab43b4
 
 
 
 
127b728
 
 
4ab43b4
127b728
 
4ab43b4
127b728
 
 
 
 
 
 
 
 
4ab43b4
 
127b728
 
29d3cbb
4ab43b4
 
 
 
127b728
 
 
4ab43b4
 
 
 
127b728
 
 
4ab43b4
66abc84
127b728
1d5da2c
 
 
 
 
 
76dff7b
1d5da2c
ecd8dfd
 
 
 
127b728
ecd8dfd
 
 
 
9394a1f
127b728
 
 
3531378
73432f0
127b728
4ab43b4
127b728
 
4ab43b4
 
 
127b728
 
4ab43b4
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
import os
import json
import logging
import gradio as gr
from utils.chatbot_logic import conversation  # Import the chatbot logic

# Configure logging to both file and console
log_file_path = "logs/chatbot_interface.log"  
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[
        logging.FileHandler(log_file_path, mode='a', encoding='utf-8'),  # Save logs to a file
        logging.StreamHandler()  # Print logs to the console
    ]
)

class ChatbotInterface:
    def __init__(self, config_path: str = 'config/gradio_config.json'):
        """
        Initialize the ChatbotInterface with configuration.
        :param config_path: Path to the configuration JSON file.
        """
        self.config = self.load_config(config_path)
        self.title = self.config["chatbot_title"]
        self.description = self.config["chatbot_description"]
        self.input_label = self.config["chatbot_input_label"]
        self.input_placeholder = self.config["chatbot_input_placeholder"]
        self.output_label = self.config["chatbot_output_label"]
        self.reset_button = self.config["chatbot_reset_button"]
        self.submit_button = self.config["chatbot_submit_button"]

    @staticmethod
    def load_config(config_path: str) -> dict:
        """
        Load the configuration for Gradio GUI interface from the JSON file.
        :param config_path: Path to the configuration JSON file.
        :return: Configuration dictionary.
        """
        if not os.path.exists(config_path):
            logging.error(f"Configuration file not found: {config_path}")
            raise FileNotFoundError(f"Configuration file not found: {config_path}")

        with open(config_path, 'r') as config_file:
            config = json.load(config_file)

        required_keys = [
            "chatbot_title", "chatbot_description", "chatbot_input_label",
            "chatbot_input_placeholder", "chatbot_output_label",
            "chatbot_reset_button", "chatbot_submit_button"
        ]
        for key in required_keys:
            if key not in config:
                logging.error(f"Missing required configuration key: {key}")
                raise ValueError(f"Missing required configuration key: {key}")

        logging.info("Configuration loaded successfully.")
        return config

    def reset_output(self) -> list:
        """
        Reset the chatbot output.
        :return: An empty list to reset the output.
        """
        return []

    def create_interface(self) -> gr.Blocks:
        """
        Create the Gradio Blocks interface.
        :return: A Gradio Blocks interface object.
        """
        with gr.Blocks() as demo:
            gr.Markdown(f"## {self.title}\n{self.description}")

            # Chatbot history component
            chatbot_output = gr.Chatbot(label=self.output_label)

            # User input
            user_input = gr.Textbox(
                lines=2,
                label=self.input_label,
                placeholder=self.input_placeholder
            )
            
            user_input.submit(fn=conversation, inputs=[user_input, chatbot_output], outputs=chatbot_output)
            # Buttons
            with gr.Row():
                reset = gr.Button(self.reset_button, variant="secondary")
                submit = gr.Button(self.submit_button, variant="primary")

            # Button actions
            submit.click(fn=conversation, inputs=[user_input, chatbot_output], outputs=chatbot_output)
            user_input.submit(fn=conversation, inputs=[user_input, chatbot_output], outputs=chatbot_output)
            reset.click(fn=self.reset_output, inputs=None, outputs=chatbot_output)

        logging.info("Gradio interface created successfully.")
        return demo


if __name__ == "__main__":
    try:
        # Instantiate the ChatbotInterface class and create the interface
        chatbot_interface = ChatbotInterface()
        demo = chatbot_interface.create_interface()

        # Launch the Gradio interface
        logging.info("Launching the Gradio interface...")
        demo.launch()
    except Exception as e:
        logging.error(f"An error occurred: {e}")