please redesign this GUI ensuring all the logic is practical and everything functions as intended. It's supposed to have the user interact with an LLM requesting code, then generate a response and parsing the code from the response. Then executing and debugging the code in a loop (max 5 time) trying to fix whatever might be wrong. you'll get the idea if you look at the code just make sure it's not doing stupid shit like permanently flashing "Processing" in red with a progress bar running and cutting code in half sending it back to the llm... import pygame
import pygame_gui
import re
import io
import contextlib
from gradio_client import Client

# Constants
WINDOW_WIDTH = 900
WINDOW_HEIGHT = 700

# Worker function to handle prediction and execution of code
def extract_code(text):
    pattern = r'```python(.*?)```'
    matches = re.findall(pattern, text, re.DOTALL)
    return "\n".join(match.strip() for match in matches) if matches else "No valid code found."

def is_valid_code(code):
    return bool(code.strip()) and len(code.splitlines()) >= 2

def execute_code(code):
    output = io.StringIO()
    with contextlib.redirect_stdout(output):
        try:
            if is_valid_code(code):
                exec(code, globals())
                return output.getvalue() if output.getvalue() else "Code executed without output."
            else:
                return "No valid code to execute."
        except Exception as e:
            return f"Execution error: {str(e)}"

# Pygame Application Class
class ChatGPTApp:
    def __init__(self):
        pygame.init()
        self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
        pygame.display.set_caption("ChatGPT API Interface")
        self.ui_manager = pygame_gui.UIManager((WINDOW_WIDTH, WINDOW_HEIGHT))

        # Input Fields
        self.input_field = pygame_gui.elements.UITextEntryLine(relative_rect=pygame.Rect(50, 50, 800, 30), manager=self.ui_manager)
        self.input_field.set_text("Type your message here...")

        # Top P Slider
        self.top_p_slider = pygame_gui.elements.UIHorizontalSlider(relative_rect=pygame.Rect(50, 100, 800, 30),
                                                                   manager=self.ui_manager,
                                                                   value_range=(0, 100),
                                                                   start_value=100)

        # Temperature Slider
        self.temp_slider = pygame_gui.elements.UIHorizontalSlider(relative_rect=pygame.Rect(50, 150, 800, 30),
                                                                   manager=self.ui_manager,
                                                                   value_range=(0, 100),
                                                                   start_value=100)

        # Filename Input
        self.filename_field = pygame_gui.elements.UITextEntryLine(relative_rect=pygame.Rect(50, 200, 800, 30), manager=self.ui_manager)
        self.filename_field.set_text("Enter filename to save code (e.g., output.py)")

        # Buttons
        self.predict_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(50, 250, 200, 50),
                                                            text='Predict',
                                                            manager=self.ui_manager)
        
        self.save_execute_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect(300, 250, 200, 50),
                                                                text='Save and Execute Code',
                                                                manager=self.ui_manager)

        # Text Areas for response and output
        self.response_area = pygame_gui.elements.UITextBox(relative_rect=pygame.Rect(50, 320, 800, 100), manager=self.ui_manager)
        self.code_area = pygame_gui.elements.UITextBox(relative_rect=pygame.Rect(50, 450, 800, 100), manager=self.ui_manager)
        self.execution_area = pygame_gui.elements.UITextBox(relative_rect=pygame.Rect(50, 580, 800, 100), manager=self.ui_manager)

        # Initialize Gradio Client
        self.client = Client("yuntian-deng/ChatGPT")
        
        self.running = True

    def run(self):
        while self.running:
            time_delta = self.ui_manager.get_time_delta()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                
                self.ui_manager.process_events(event)

                if event.type == pygame.USEREVENT:   
                    if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                        if event.ui_element == self.predict_button:
                            self.start_prediction_thread()
                        elif event.ui_element == self.save_execute_button:
                            self.save_and_execute_code()

            self.window.fill((255, 255, 255))
            self.ui_manager.update(time_delta)
            self.ui_manager.draw_ui(self.window)
            pygame.display.flip()

    def start_prediction_thread(self):
        inputs = self.input_field.get_text()
        if not inputs.strip():
            print("Please enter a message before predicting.")
            return

        top_p = self.top_p_slider.get_current_value() / 100.0
        temperature = self.temp_slider.get_current_value() / 100.0
        # Call to the API must be handled here, simulate it for now
        result = self.client.predict(inputs=inputs, top_p=top_p, temperature=temperature, chat_counter=1)
        response_text = result[0][0][1]
        code = extract_code(response_text)

        self.response_area.set_text(response_text)
        self.code_area.set_text(code)
        execution_result = execute_code(code)
        self.execution_area.set_text(execution_result)

    def save_and_execute_code(self):
        code = self.code_area.get_text()
        filename = self.filename_field.get_text()

        if not filename:
            print("Please enter a filename to save the code.")
            return

        try:
            with open(filename, 'w') as f:
                f.write(code)
            print("Code saved successfully!")
        except Exception as e:
            print(f"Failed to save code: {str(e)}")

# Main Application Entry
if __name__ == "__main__":
    app = ChatGPTApp()
    app.run()
    pygame.quit()