i get this msg, i dont wat to fix show me the code below the input in a text output box: Generated code is invalid even after fixing

fix this code it should requst a html and show the request and response below in text, if we got both the display the result by turning it into html from the json fields and values you requested from the llm:


from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import os
import json
import datetime
import requests
from dotenv import load_dotenv
import textwrap

load_dotenv()

app = Flask(__name__, static_folder='static', static_url_path='/static')
CORS(app)

# Configuration
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
LLM_MODEL = 'gpt-4o-mini'
OPENAI_API_URL = os.getenv('OPENAI_API_URL', 'https://api.openai.com/v1/chat/completions')
OLLAMA_API_BASE = os.getenv('OLLAMA_API_BASE', 'http://localhost:11434')

GENERATED_GUIS_DIR = os.path.join(os.getcwd(), 'generated_guis')
USER_DATA_DIR = os.path.join(os.getcwd(), 'user_data')

os.makedirs(GENERATED_GUIS_DIR, exist_ok=True)
os.makedirs(USER_DATA_DIR, exist_ok=True)

# Sample JSON to guide LLM
SAMPLE_JSON = {
    "fields": [
        {"label": "First Name", "type": "text", "name": "first_name"},
        {"label": "Last Name", "type": "text", "name": "last_name"},
        {"label": "Email", "type": "email", "name": "email"},
        {"label": "Password", "type": "password", "name": "password"},
        {"label": "Age", "type": "number", "name": "age"},
        {"label": "Gender", "type": "select", "name": "gender", "options": ["Male", "Female", "Other"]},
        {"label": "Subscribe to Newsletter", "type": "checkbox", "name": "subscribe"},
        {"label": "Country", "type": "select", "name": "country", "options": ["USA", "Canada", "UK", "Australia"]},
        {"label": "Bio", "type": "textarea", "name": "bio"},
        {"label": "Profile Picture", "type": "file", "name": "profile_pic"}
    ]
}

# Helper Functions
def generate_gui_with_llm(prompt):
    headers = {
        'Authorization': f'Bearer {OPENAI_API_KEY}',
        'Content-Type': 'application/json',
    }
    data = {
        "model": LLM_MODEL,
        "messages": [
            {"role": "system", "content": "You are a helpful assistant that generates React components based on user specifications."},
            {"role": "user", "content": prompt}
        ],
        "max_tokens": 3000,
        "temperature": 0.5,
    }
    response = requests.post(OPENAI_API_URL, headers=headers, json=data)
    response.raise_for_status()
    return response.json()

def validate_code(code):
    try:
        exec(code)
        return True
    except Exception:
        return False

def fix_code_with_llm(code):
    prompt = f"""
The following React component code has syntax errors. Please fix the errors without changing the functionality.

{code}

Fixed Code:
"""
    response = generate_gui_with_llm(prompt)
    fixed_code = response['choices'][0]['message']['content']
    return fixed_code

# API Endpoints
@app.route('/generate-gui', methods=['POST'])
def generate_gui():
    try:
        data = request.json
        user_request = data.get('request')
        if not user_request:
            return jsonify({"error": "No request provided"}), 400
        app_name = user_request.replace("Create a ", "").strip().replace(" ", "")

        prompt = f"""
Create a React component for a {app_name} with a clean UI like Google search on a black shiny background. The component should be highly reactive and lightweight, optimized for fast rendering.
Ensure the following functionalities are implemented:
- {user_request}
- Data persistence through JSON files
- Responsive design
- Error handling

Use the following sample JSON as a reference for form fields:
{json.dumps(SAMPLE_JSON)}

Output the React component code in strict format.
"""
        llm_response = generate_gui_with_llm(prompt)
        code = llm_response['choices'][0]['message']['content']

        if not validate_code(code):
            code = fix_code_with_llm(code)
            if not validate_code(code):
                return jsonify({"error": "Generated code is invalid even after fixing"}), 400

        gui_config = {
            "app_name": app_name,
            "code": code,
            "created_at": datetime.datetime.now().isoformat()
        }

        gui_file_path = os.path.join(GENERATED_GUIS_DIR, f"{app_name}_GUI.json")
        with open(gui_file_path, 'w') as f:
            json.dump(gui_config, f, indent=4)

        return jsonify(gui_config), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/save-data', methods=['POST'])
def save_data():
    try:
        data = request.json
        app_name = data.get('app_name')
        user_data = data.get('data')

        if not app_name or not user_data:
            return jsonify({"error": "Missing app_name or data"}), 400

        timestamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
        data_file_path = os.path.join(USER_DATA_DIR, f"{app_name}_data_{timestamp}.json")

        with open(data_file_path, 'w') as f:
            json.dump(user_data, f, indent=4)

        return jsonify({"message": "Data saved successfully"}), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/load-gui', methods=['POST'])
def load_gui():
    try:
        if 'file' not in request.files:
            return jsonify({"error": "No file part"}), 400

        file = request.files['file']
        if file.filename == '':
            return jsonify({"error": "No selected file"}), 400

        if not file.filename.endswith('.json'):
            return jsonify({"error": "Invalid file type"}), 400

        gui_config = json.load(file)
        return jsonify(gui_config), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/status', methods=['GET'])
def status():
    return jsonify({"status": "Server is running"}), 200

# Serve the frontend
@app.route('/')
def index():
    return textwrap.dedent("""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Dynamic GUI Generator</title>
        <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
        <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <style>
            body { 
                font-family: Arial, sans-serif; 
                background: linear-gradient(135deg, #1c1c1c, #2c2c2c); 
                color: #ffffff; 
                display: flex; 
                justify-content: center; 
                align-items: center; 
                height: 100vh; 
                margin: 0;
            }
            .container { 
                background: rgba(255, 255, 255, 0.1); 
                padding: 20px 30px; 
                border-radius: 10px; 
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3); 
                width: 400px; 
            }
            .input-group { 
                display: flex; 
                align-items: center; 
            }
            input[type="text"] { 
                flex: 1; 
                padding: 10px; 
                border: none; 
                border-radius: 4px; 
                margin-right: 10px; 
            }
            button { 
                background-color: #4285F4; 
                color: white; 
                border: none; 
                padding: 10px 15px; 
                border-radius: 4px; 
                cursor: pointer; 
                display: flex; 
                align-items: center; 
                justify-content: center;
            }
            button:hover { 
                background-color: #3367D6; 
            }
            .paperclip { 
                margin-left: 10px; 
                cursor: pointer; 
            }
            .error { 
                color: #ff4d4d; 
                margin-top: 10px; 
                height: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h2 style="text-align:center; margin-bottom:20px;">Dynamic GUI Generator</h2>
            <div class="input-group">
                <input
                    type="text"
                    id="request"
                    placeholder="e.g., Create a Todo List"
                />
                <button onclick="handleGenerate()">
                    ►
                </button>
                <label class="paperclip">
                    📎
                    <input type="file" id="fileInput" style="display:none;" onchange="handleFileLoad()" accept=".json"/>
                </label>
            </div>
            <div class="error" id="errorOutput"></div>
            <div id="componentContainer" style="margin-top:20px;"></div>
        </div>
        <script type="text/javascript">
            function handleGenerate() {
                const request = document.getElementById('request').value;
                const errorOutput = document.getElementById('errorOutput');
                const componentContainer = document.getElementById('componentContainer');
                errorOutput.textContent = '';
                componentContainer.innerHTML = '';

                if (!request) {
                    errorOutput.textContent = 'Please enter a request.';
                    return;
                }

                axios.post('/generate-gui', { request, llm: 'gpt-4o-mini' })
                    .then(response => {
                        const guiConfig = response.data;
                        generateComponent(guiConfig.code, guiConfig.app_name);
                    })
                    .catch(err => {
                        errorOutput.textContent = err.response?.data?.error || 'Generation failed';
                    });
            }

            function handleFileLoad() {
                const fileInput = document.getElementById('fileInput');
                const file = fileInput.files[0];
                const errorOutput = document.getElementById('errorOutput');
                const componentContainer = document.getElementById('componentContainer');
                errorOutput.textContent = '';
                componentContainer.innerHTML = '';

                if (!file) {
                    errorOutput.textContent = 'No file selected.';
                    return;
                }

                const formData = new FormData();
                formData.append('file', file);

                axios.post('/load-gui', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                })
                .then(response => {
                    const guiConfig = response.data;
                    generateComponent(guiConfig.code, guiConfig.app_name);
                })
                .catch(err => {
                    errorOutput.textContent = err.response?.data?.error || 'Loading failed';
                });
            }

            function generateComponent(code, appName) {
                const errorOutput = document.getElementById('errorOutput');
                const componentContainer = document.getElementById('componentContainer');

                try {
                    const Comp = eval(code);
                    ReactDOM.render(React.createElement(Comp, { setUserData: setUserData }), componentContainer);
                } catch (e) {
                    errorOutput.textContent = 'Failed to render the component.';
                }

                function setUserData(data) {
                    axios.post('/save-data', {
                        app_name: appName,
                        data: data,
                    })
                    .then(response => {
                        console.log('Data saved successfully');
                    })
                    .catch(err => {
                        errorOutput.textContent = err.response?.data?.error || 'Save failed';
                    });
                };
            }
        </script>
    </body>
    </html>
    """)

if __name__ == '__main__':
    os.makedirs('generated_guis', exist_ok=True)
    os.makedirs('user_data', exist_ok=True)
    app.run(host='0.0.0.0', port=5000, debug=True)