can you fix this code and make sure its a single file instead of saparating the html:
# app.py

import os
import json
from flask import Flask, request, jsonify, make_response
from datetime import datetime, timezone
from flask_cors import CORS

from _GenUI_v5 import generate_ui, llm_logs, append_log

app = Flask(__name__)
CORS(app)  # Enable CORS if needed

# Directory to save UI states
SAVE_DIR = 'saved_ui_states'
os.makedirs(SAVE_DIR, exist_ok=True)

@app.route('/')
def index():
    return '''
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <!-- Your existing head content -->
        <meta charset="UTF-8">
        <title>AI App Generator</title>
        <style>
            /* Base styles */
            body {
                font-family: Arial, sans-serif;
                background-color: #282c34;
                margin: 0;
                padding: 0;
                color: #ffffff;
                display: flex;
                flex-direction: column;
                align-items: center;
                min-height: 100vh;
            }
            .container {
                width: 90%;
                max-width: 1000px;
                margin-top: 30px;
                position: relative;
            }
            /* Loading spinner styles */
            .loader {
                border: 16px solid #f3f3f3;
                border-top: 16px solid #61dafb;
                border-radius: 50%;
                width: 80px;
                height: 80px;
                animation: spin 2s linear infinite;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                display: none;
                z-index: 9999;
            }
            @keyframes spin {
                0% { transform: translate(-50%, -50%) rotate(0deg); }
                100% { transform: translate(-50%, -50%) rotate(360deg); }
            }
            .buttonsection {
                display: flex;
                justify-content: center;
                margin-bottom: 20px;
                gap: 10px;
            }
            .buttonsection button {
                padding: 10px;
                font-size: 18px;
                border: none;
                background-color: transparent;
                color: #61dafb;
                cursor: pointer;
                border-radius: 50%;
            }
            .buttonsection button:hover {
                background-color: #20232a;
            }
            .buttonsection button:focus {
                outline: none;
            }
            .buttonsection button img {
                width: 30px;
                height: 30px;
            }
            .inputsection {
                display: flex;
                margin-bottom: 20px;
                gap: 10px;
                align-items: center;
            }
            .inputsection input[type="text"],
            .inputsection input[type="number"] {
                flex: 1;
                padding: 12px;
                font-size: 16px;
                border: 1px solid #ccc;
                border-radius: 4px;
                outline: none;
            }
            .inputsection button {
                padding: 12px 24px;
                font-size: 16px;
                border: none;
                background-color: #61dafb;
                color: #282c34;
                cursor: pointer;
                border-radius: 4px;
            }
            .inputsection button:hover {
                background-color: #21a1f1;
            }
            .generatedui {
                background-color: #20232a;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                margin-bottom: 20px;
                color: #61dafb;
                width: 100%;
            }
            .logsection {
                background-color: #20232a;
                padding: 15px;
                border-radius: 8px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                height: 300px;
                overflow-y: scroll;
                width: 100%;
                color: #ffffff;
            }
            .logentry {
                font-family: monospace;
                font-size: 12px;
                margin-bottom: 5px;
            }
            h1, h2 {
                text-align: center;
                color: #61dafb;
            }
            /* Speed button styles */
            .speed-button {
                padding: 10px;
                border: none;
                background-color: transparent;
                cursor: pointer;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: background-color 0.2s;
                outline: none;
            }
            .speed-button:hover {
                background-color: #61dafb;
            }
            .speed-button img {
                width: 24px;
                height: 24px;
            }
        </style>
    </head>
    <body>
    <div class="container">
        <div id="loader" class="loader"></div>
        <h1>AI App Generator</h1>
        <div class="buttonsection">
            <button onclick="refreshUI()" class="speed-button" tabindex="-1" onmousedown="return false;">
                <img src="https://img.icons8.com/ios-filled/50/ffffff/refresh.png" alt="Refresh">
            </button>
            <button onclick="clearUI()" class="speed-button" tabindex="-1" onmousedown="return false;">
                <img src="https://img.icons8.com/ios-filled/50/ffffff/erase.png" alt="Clear">
            </button>
            <button onclick="saveUI()" class="speed-button" tabindex="-1" onmousedown="return false;">
                <img src="https://img.icons8.com/ios-filled/50/ffffff/save.png" alt="Save">
            </button>
        </div>
        <div class="inputsection">
            <input type="text" id="appInput" placeholder="Enter application name (e.g., Notepad, Music Player)">
            <input type="number" id="maxTokensInput" placeholder="Max Tokens (e.g., 1000)" min="500" max="4000" step="100">
            <button onclick="generateApp()">Send</button>
        </div>
        <div id="generatedUI" class="generatedui">
            <!-- Generated UI will appear here -->
        </div>
        <h2>LLM Interaction Logs</h2>
        <div id="logs" class="logsection">
            <!-- Logs will appear here -->
        </div>
    </div>
    <script type="text/javascript">
        let currentUI = null;

        // Show loader
        function showLoader() {
            document.getElementById('loader').style.display = 'block';
        }

        // Hide loader
        function hideLoader() {
            document.getElementById('loader').style.display = 'none';
        }

        // Function to generate the application
        async function generateApp() {
            const appName = document.getElementById('appInput').value.trim();
            const maxTokens = parseInt(document.getElementById('maxTokensInput').value.trim()) || 1000;
            if (!appName) {
                alert('Please enter an application name.');
                return;
            }

            appendLog(`Sending request to generate UI for "${appName}".`);
            showLoader();

            // Send request to generate UI
            try {
                const response = await fetch('/generate', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({application_name: appName, max_tokens: maxTokens})
                });

                if (response.ok) {
                    const uiJson = await response.json();
                    if (uiJson.error) {
                        throw new Error(uiJson.error);
                    }
                    currentUI = uiJson;
                    renderUI(uiJson);
                    appendLog(`Generated UI for "${appName}".`);
                } else {
                    const error = await response.json();
                    throw new Error(error.error || 'Unknown error occurred.');
                }
            } catch (error) {
                alert('Error: ' + error.message);
                appendLog(`Error generating UI for "${appName}": ${error.message}`);
            } finally {
                hideLoader();
            }
        }

        function renderUI(uiJson) {
            const generatedUI = document.getElementById('generatedUI');
            generatedUI.innerHTML = ''; // Clear previous UI

            // Remove existing generated styles to prevent duplication
            const existingStyles = document.querySelectorAll('style.generated-style');
            existingStyles.forEach(style => style.remove());

            // Create style element
            const style = document.createElement('style');
            style.className = 'generated-style';
            style.innerHTML = uiJson.css;
            document.head.appendChild(style);

            // Create a container for the generated HTML
            const container = document.createElement('div');
            container.innerHTML = uiJson.html;

            // Append container to generatedUI div
            generatedUI.appendChild(container);

            // Remove existing generated scripts to prevent duplication
            const existingScripts = document.querySelectorAll('script.generated-script');
            existingScripts.forEach(script => script.remove());

            // Execute the generated JS
            try {
                // Create a new script element
                const script = document.createElement('script');
                script.type = 'text/javascript';
                script.className = 'generated-script';
                // Wrap the JS code in an IIFE to prevent polluting global scope
                script.text = `(function() {\n${uiJson.js}\n})();`;
                document.body.appendChild(script);
                appendLog('Executed generated JavaScript.');
            } catch (e) {
                console.error('Error executing generated JS:', e);
                appendLog('Error executing generated JavaScript.');
            }
        }

        function appendLog(message) {
            const logs = document.getElementById('logs');
            const logEntry = document.createElement('div');
            logEntry.className = 'logentry';
            const timestamp = new Date().toLocaleString();
            logEntry.textContent = `[${timestamp}] ${message}`;
            logs.prepend(logEntry);

            // Send the log to the server
            fetch('/log', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({message: message})
            }).catch(error => {
                console.error('Error sending log to server:', error);
            });
        }

        // Override the global triggerEvent function
        window.triggerEvent = function(eventType, eventData) {
            handleEvent(eventType, eventData);
        }

        async function handleEvent(eventType, eventData) {
            // Handle client-side events without calling the backend
            if (eventType === 'openFile') {
                // Handle opening file dialog
                const input = document.createElement('input');
                input.type = 'file';
                input.onchange = async (e) => {
                    const file = e.target.files[0];
                    if (file) {
                        const text = await file.text();
                        // Do something with the file content, e.g., display in UI
                        console.log('File content:', text);
                        // Update UI as needed
                    }
                };
                input.click();
                appendLog('Handled openFile event on client side.');
                return;
            } else if (eventType === 'saveFile') {
                // Handle saving file dialog
                const blob = new Blob([eventData.content || ''], { type: 'text/plain' });
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = eventData.filename || 'untitled.txt';
                link.click();
                appendLog('Handled saveFile event on client side.');
                return;
            }
            // For other events that require backend processing
            try {
                showLoader();
                const response = await fetch('/event', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        event_type: eventType,
                        event_data: eventData
                    })
                });

                if (response.ok) {
                    const updatedUiJson = await response.json();
                    if (updatedUiJson.error) {
                        throw new Error(updatedUiJson.error);
                    }
                    currentUI = updatedUiJson;
                    renderUI(updatedUiJson);
                    appendLog(`Handled event

this is how it was before, but i keep getting responses with err: no json format found...

# app.py

import os
import json
from flask import Flask, request, jsonify
from datetime import datetime, timezone
from flask_cors import CORS

from _GenUI_v5 import generate_ui, llm_logs, append_log

app = Flask(__name__)
CORS(app)  # Enable CORS if needed

# Directory to save UI states
SAVE_DIR = 'saved_ui_states'
os.makedirs(SAVE_DIR, exist_ok=True)

@app.route('/')
def index():
    return '''
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <!-- Your existing head content -->
        <meta charset="UTF-8">
        <title>AI App Generator</title>
        <style>
            /* Your existing CSS styles */
            /* ... (Include your styles here) ... */
        </style>
    </head>
    <body>
    <div class="container">
        <!-- Your existing body content -->
        <!-- ... (Include your HTML content here) ... -->
    </div>
    <script type="text/javascript">
        let currentUI = null;

        // Show loader
        function showLoader() {
            document.getElementById('loader').style.display = 'block';
        }

        // Hide loader
        function hideLoader() {
            document.getElementById('loader').style.display = 'none';
        }

        // Function to generate the application
        async function generateApp() {
            // ... existing code ...
        }

        function renderUI(uiJson) {
            const generatedUI = document.getElementById('generatedUI');
            generatedUI.innerHTML = ''; // Clear previous UI

            // Remove existing generated styles to prevent duplication
            const existingStyles = document.querySelectorAll('style.generated-style');
            existingStyles.forEach(style => style.remove());

            // Create style element
            const style = document.createElement('style');
            style.className = 'generated-style';
            style.innerHTML = uiJson.css;
            document.head.appendChild(style);

            // Create a container for the generated HTML
            const container = document.createElement('div');
            container.innerHTML = uiJson.html;

            // Append container to generatedUI div
            generatedUI.appendChild(container);

            // Remove existing generated scripts to prevent duplication
            const existingScripts = document.querySelectorAll('script.generated-script');
            existingScripts.forEach(script => script.remove());

            // Execute the generated JS
            try {
                // Create a new script element
                const script = document.createElement('script');
                script.type = 'text/javascript';
                script.className = 'generated-script';
                // Wrap the JS code in an IIFE to prevent polluting global scope
                script.text = `(function() {\n${uiJson.js}\n})();`;
                document.body.appendChild(script);
                appendLog('Executed generated JavaScript.');
            } catch (e) {
                console.error('Error executing generated JS:', e);
                appendLog('Error executing generated JavaScript.');
            }
        }

        function appendLog(message) {
            const logs = document.getElementById('logs');
            const logEntry = document.createElement('div');
            logEntry.className = 'logentry';
            const timestamp = new Date().toLocaleString();
            logEntry.textContent = `[${timestamp}] ${message}`;
            logs.prepend(logEntry);

            // Send the log to the server
            fetch('/log', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({message: message})
            }).catch(error => {
                console.error('Error sending log to server:', error);
            });
        }

        // Override the global triggerEvent function
        window.triggerEvent = function(eventType, eventData) {
            handleEvent(eventType, eventData);
        }

        async function handleEvent(eventType, eventData) {
            // Handle client-side events without calling the backend
            if (eventType === 'openFile') {
                // Handle opening file dialog
                const input = document.createElement('input');
                input.type = 'file';
                input.onchange = async (e) => {
                    const file = e.target.files[0];
                    if (file) {
                        const text = await file.text();
                        // Do something with the file content, e.g., display in UI
                        console.log('File content:', text);
                        // Update UI as needed
                    }
                };
                input.click();
                appendLog('Handled openFile event on client side.');
                return;
            } else if (eventType === 'saveFile') {
                // Handle saving file dialog
                const blob = new Blob([eventData.content || ''], { type: 'text/plain' });
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = eventData.filename || 'untitled.txt';
                link.click();
                appendLog('Handled saveFile event on client side.');
                return;
            }
            // For other events that require backend processing
            try {
                showLoader();
                const response = await fetch('/event', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        event_type: eventType,
                        event_data: eventData
                    })
                });

                if (response.ok) {
                    const updatedUiJson = await response.json();
                    if (updatedUiJson.error) {
                        throw new Error(updatedUiJson.error);
                    }
                    currentUI = updatedUiJson;
                    renderUI(updatedUiJson);
                    appendLog(`Handled event '${eventType}' with data: ${JSON.stringify(eventData)}`);
                } else {
                    const error = await response.json();
                    appendLog(`Error handling event '${eventType}': ${error.error}`);
                }
            } catch (error) {
                console.error('Error handling event:', error);
                appendLog(`Error handling event '${eventType}': ${error.message}`);
            } finally {
                hideLoader();
            }
        }

        // Function to refresh the current UI by requesting an improved version from the LLM
        async function refreshUI() {
            if (!currentUI) {
                alert('No UI to refresh. Please generate an application first.');
                return;
            }

            const appName = document.getElementById('appInput').value.trim() || 'DynamicApp';
            const maxTokens = parseInt(document.getElementById('maxTokensInput').value.trim()) || 1500;

            appendLog(`Sending request to refresh UI for "${appName}".`);
            showLoader();

            try {
                const response = await fetch('/refresh', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        application_name: appName,
                        current_ui: currentUI,
                        max_tokens: maxTokens
                    })
                });

                if (response.ok) {
                    const updatedUiJson = await response.json();
                    if (updatedUiJson.error) {
                        throw new Error(updatedUiJson.error);
                    }
                    currentUI = updatedUiJson;
                    renderUI(updatedUiJson);
                    appendLog(`Refreshed UI for "${appName}".`);
                } else {
                    const error = await response.json();
                    alert('Error: ' + error.error);
                    appendLog(`Error refreshing UI for "${appName}": ${error.error}`);
                }
            } catch (error) {
                console.error('Error refreshing UI:', error);
                appendLog(`Error refreshing UI for "${appName}": ${error.message}`);
            } finally {
                hideLoader();
            }
        }

        // Function to clear the current UI
        function clearUI() {
            const generatedUI = document.getElementById('generatedUI');
            generatedUI.innerHTML = ''; // Clear UI
            currentUI = null;
            appendLog('Cleared the generated UI.');
        }

        // Function to save the current UI state to a JSON file
        async function saveUI() {
            if (!currentUI) {
                alert('No UI to save.');
                return;
            }

            const filename = prompt('Enter filename to save the UI (e.g., my_app.json):', `saved_ui_${Date.now()}.json`);
            if (!filename) {
                alert('Save cancelled.');
                return;
            }

            appendLog(`Sending request to save UI as "${filename}".`);

            try {
                const response = await fetch('/save', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        ui_json: currentUI,
                        filename: filename
                    })
                });

                if (response.ok) {
                    const res = await response.json();
                    appendLog(`Saved UI to ${res.filepath}`);
                    alert(`UI saved successfully to ${res.filepath}`);
                } else {
                    const error = await response.json();
                    alert('Error: ' + error.error);
                    appendLog(`Error saving UI: ${error.error}`);
                }
            } catch (error) {
                console.error('Error saving UI:', error);
                appendLog(`Error saving UI: ${error.message}`);
            }
        }
    </script>
    </body>
    </html>
    '''

@app.route('/generate', methods=['POST'])
def generate():
    data = request.get_json()
    application_name = data.get('application_name')
    current_ui = data.get('current_ui')
    user_event = data.get('user_event')
    max_tokens = data.get('max_tokens', 1000)  # Default to 1000

    if not application_name:
        error_msg = 'No application name provided.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 400

    try:
        ui_json = generate_ui(application_name, current_ui, user_event, max_tokens=max_tokens)
        return jsonify(ui_json)
    except Exception as e:
        error_message = f"Error generating UI: {e}"
        append_log(error_message)
        return jsonify({'error': error_message}), 500

@app.route('/event', methods=['POST'])
def handle_event():
    data = request.get_json()
    event_type = data.get('event_type')
    event_data = data.get('event_data')
    max_tokens = data.get('max_tokens', 1000)

    if not event_type:
        error_msg = 'No event type provided.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 400

    # Log the received event
    append_log(f"Received event '{event_type}' with data: {event_data}")

    # Retrieve the latest UI JSON from logs
    last_ui = None
    for log in reversed(llm_logs):
        if 'Valid UI Generated' in log.get('message', ''):
            last_ui = log.get('response')
            break

    user_event = {
        'event_type': event_type,
        'event_data': event_data
    }

    try:
        # Generate updated UI based on the event
        updated_ui = generate_ui("DynamicApp", current_ui=last_ui, user_event=user_event, max_tokens=max_tokens)

        success_msg = f"Event '{event_type}' handled with data: {event_data}"
        append_log(success_msg)
        return jsonify(updated_ui)
    except Exception as e:
        error_message = f"Error handling event: {e}"
        append_log(error_message)
        return jsonify({'error': error_message}), 500

@app.route('/refresh', methods=['POST'])
def refresh():
    data = request.get_json()
    application_name = data.get('application_name', 'DynamicApp')
    current_ui = data.get('current_ui')
    max_tokens = data.get('max_tokens', 1000)

    if not current_ui:
        error_msg = 'No current UI provided for refresh.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 400

    try:
        ui_json = generate_ui(application_name, current_ui=current_ui, max_tokens=max_tokens)
        return jsonify(ui_json)
    except Exception as e:
        error_message = f"Error refreshing UI: {e}"
        append_log(error_message)
        return jsonify({'error': error_message}), 500

@app.route('/save', methods=['POST'])
def save_ui():
    data = request.get_json()
    ui_json = data.get('ui_json')
    filename = data.get('filename')

    if not ui_json:
        error_msg = 'No UI JSON provided to save.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 400

    if not filename:
        filename = f'saved_ui_{datetime.now(timezone.utc).isoformat().replace(":", "-")}.json'

    try:
        filepath = os.path.join(SAVE_DIR, filename)
        with open(filepath, 'w') as f:
            json.dump(ui_json, f, indent=4)
        success_msg = f"UI saved to {filepath}"
        append_log(success_msg)
        return jsonify({'status': 'UI saved successfully.', 'filepath': filepath}), 200
    except Exception as e:
        error_message = f"Error saving UI: {e}"
        append_log(error_message)
        return jsonify({'error': error_message}), 500

@app.route('/log', methods=['POST'])
def receive_log():
    data = request.get_json()
    message = data.get('message')
    if not message:
        return jsonify({'error': 'No log message provided.'}), 400

    append_log(message)
    return jsonify({'status': 'Log received.'}), 200

@app.errorhandler(Exception)
def handle_exception(e):
    # For debugging purposes, we can return the exception details
    error_message = f"Unhandled exception: {str(e)}"
    append_log(error_message)
    # Log the exception with traceback
    import traceback
    traceback.print_exc()
    response = make_response(jsonify({'error': error_message}), 500)
    return response

@app.errorhandler(404)
def page_not_found(e):
    # Return JSON response for 404 errors
    append_log(f"404 Error: {e}")
    return jsonify({'error': 'Not found'}), 404

if __name__ == '__main__':
    app.run(debug=True)

i have 2 more files for genUI and openAI call API which are saparated