Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

this is my app.py code along with the index.html code...i dont know whats wrong with…

  1. User

    this is my app.py code along with the index.html code...i dont know whats wrong with this code...but its not working well and i was having issues ...please fix it and also make the ui a lot more amazing , cool ,modern and awesome with cool animations, transitons and effects with beautiful background and interactive elements " from flask import Flask, render_template, request import pandas as pd import joblib from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt import io import base64 from sklearn.model_selection import train_test_split app = Flask(name)

    Load the CSV file

    df = pd.read_csv('data.csv')

    Load models and vectorizer

    vectorizer = joblib.load('vectorizer.pkl') models = { 'Logistic Regression': joblib.load('Logistic Regression.pkl'), 'Random Forest': joblib.load('Random Forest.pkl'), 'SVM': joblib.load('SVM.pkl'), 'Naive Bayes': joblib.load('Naive Bayes.pkl') }

    Preprocess data for accuracy calculation

    X = df['text'] y = df['generated'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) X_test_vec = vectorizer.transform(X_test)

    @app.route('/') def index(): return render_template('index.html', prediction=None, plot_url=None, head_data=None, tail_data=None, performance_data=None)

    @app.route('/analyze', methods=['POST']) def analyze(): text = request.form['text'] model_choice = request.form['model'] viz_choice = request.form['visualization'] show_head = request.form.get('head') show_tail = request.form.get('tail') show_performance = request.form.get('performance')

    # Model Selection
    model = models.get(model_choice, models['Logistic Regression'])
    
    # Prediction
    text_vec = vectorizer.transform([text])
    prediction_num = model.predict(text_vec)[0]
    prediction = "Human-generated" if prediction_num == 0 else "AI-generated"
    accuracy = accuracy_score(y_test, model.predict(X_test_vec))
    
    # Visualization
    plot_url = None
    if viz_choice == 'Pie Chart':
        plt.figure(figsize=(6, 6))
        df['generated'].value_counts().plot.pie(autopct='%1.1f%%')
        img = io.BytesIO()
        plt.savefig(img, format='png')
        img.seek(0)
        plot_url = base64.b64encode(img.getvalue()).decode()
    
    elif viz_choice == 'Box Plot':
        plt.figure(figsize=(6, 6))
        df.boxplot(column=['generated'])
        img = io.BytesIO()
        plt.savefig(img, format='png')
        img.seek(0)
        plot_url = base64.b64encode(img.getvalue()).decode()
    
    # Prepare Data for Display
    head_data = df.head().to_html() if show_head else None
    tail_data = df.tail().to_html() if show_tail else None
    performance_data = f"Accuracy: {accuracy:.2f}" if show_performance else None
    
    return render_template('index.html', prediction=prediction, plot_url=plot_url,
                           head_data=head_data, tail_data=tail_data, 
                           performance_data=performance_data)
    

    if name == 'main': app.run(debug=True) " "

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    
        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--background);
            color: var(--text);
            line-height: 1.6;
            min-height: 100vh;
        }
    
        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 1rem;
        }
    
        .header {
            text-align: center;
            margin-bottom: 3rem;
            animation: fadeInDown 0.8s ease-out;
        }
    
        .header h1 {
            font-size: 2.5rem;
            color: var(--primary);
            margin-bottom: 1rem;
            font-weight: 700;
        }
    
        .header p {
            color: var(--text-light);
            font-size: 1.1rem;
            max-width: 600px;
            margin: 0 auto;
        }
    
        .main-card {
            background: var(--card);
            border-radius: 1rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            padding: 2rem;
            margin-bottom: 2rem;
            animation: fadeInUp 0.8s ease-out;
        }
    
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 2rem;
            margin-bottom: 2rem;
        }
    
        .form-group {
            margin-bottom: 1.5rem;
        }
    
        label {
            display: block;
            font-weight: 500;
            margin-bottom: 0.5rem;
            color: var(--text);
        }
    
        textarea {
            width: 100%;
            min-height: 150px;
            padding: 1rem;
            border: 2px solid var(--border);
            border-radius: 0.5rem;
            font-size: 1rem;
            font-family: inherit;
            resize: vertical;
            transition: all 0.3s ease;
        }
    
        textarea:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px var(--focus-ring);
            outline: none;
        }
    
        select {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 2px solid var(--border);
            border-radius: 0.5rem;
            font-size: 1rem;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%236B7280'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 1rem center;
            background-size: 1.5em;
            transition: all 0.3s ease;
        }
    
        select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px var(--focus-ring);
            outline: none;
        }
    
        .checkbox-group {
            display: flex;
            gap: 1.5rem;
            flex-wrap: wrap;
            margin-top: 1rem;
        }
    
        .checkbox-wrapper {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
    
        .checkbox-wrapper input[type="checkbox"] {
            width: 1.2rem;
            height: 1.2rem;
            border: 2px solid var(--border);
            border-radius: 0.25rem;
            cursor: pointer;
        }
    
        .submit-btn {
            background-color: var(--primary);
            color: white;
            padding: 1rem 2rem;
            border: none;
            border-radius: 0.5rem;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }
    
        .submit-btn:hover {
            background-color: var(--primary-dark);
            transform: translateY(-1px);
        }
    
        .submit-btn:disabled {
            background-color: var(--text-light);
            cursor: not-allowed;
        }
    
        .results {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 2rem;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.5s ease;
        }
    
        .results.show {
            opacity: 1;
            transform: translateY(0);
        }
    
        .result-card {
            background: var(--card);
            border-radius: 1rem;
            padding: 1.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
    
        .result-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }
    
        .result-header {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1rem;
        }
    
        .result-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }
    
        .result-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--text);
        }
    
        .confidence-bar {
            width: 100%;
            height: 8px;
            background-color: var(--border);
            border-radius: 4px;
            margin: 1rem 0;
            overflow: hidden;
        }
    
        .confidence-fill {
            height: 100%;
            background-color: var(--primary);
            border-radius: 4px;
            transition: width 1s ease-out;
        }
    
        .performance-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            margin-top: 1rem;
        }
    
        .performance-item {
            text-align: center;
            padding: 1rem;
            background-color: var(--background);
            border-radius: 0.5rem;
        }
    
        .performance-value {
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--primary);
        }
    
        .performance-label {
            font-size: 0.875rem;
            color: var(--text-light);
        }
    
        .visualization-card img {
            width: 100%;
            height: auto;
            border-radius: 0.5rem;
            margin-top: 1rem;
        }
    
        .table-wrapper {
            overflow-x: auto;
            margin-top: 1rem;
        }
    
        .table {
            width: 100%;
            border-collapse: collapse;
        }
    
        .table th,
        .table td {
            padding: 0.75rem 1rem;
            border-bottom: 1px solid var(--border);
            text-align: left;
        }
    
        .table th {
            background-color: var(--background);
            font-weight: 600;
        }
    
        .loading-spinner {
            display: inline-block;
            width: 1.5rem;
            height: 1.5rem;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s linear infinite;
        }
    
        .error-message {
            color: var(--danger);
            background-color: rgba(220, 38, 38, 0.1);
            padding: 1rem;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
            display: none;
        }
    
        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
    
        @keyframes fadeInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    
        @media (max-width: 768px) {
            .container {
                margin: 1rem auto;
            }
    
            .header h1 {
                font-size: 2rem;
            }
    
            .form-grid {
                grid-template-columns: 1fr;
            }
    
            .checkbox-group {
                flex-direction: column;
                gap: 1rem;
            }
        }
    </style>
    
        <main class="main-card">
            <div class="error-message" id="error-message"></div>
            
            <form id="classifier-form">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="text">Text to Analyze</label>
                        <textarea id="text" name="text" required placeholder="Enter the text you want to analyze..."></textarea>
                    </div>
    
                    <div>
                        <div class="form-group">
                            <label for="model">Model Selection</label>
                            <select id="model" name="model" required>
                                <option value="Logistic Regression">Logistic Regression</option>
                                <option value="Random Forest">Random Forest</option>
                                <option value="SVM">Support Vector Machine</option>
                                <option value="Naive Bayes">Naive Bayes</option>
                            </select>
                        </div>
    
                        <div class="form-group">
                            <label for="visualization">Visualization Type</label>
                            <select id="visualization" name="visualization">
                                <option value="None">None</option>
                                <option value="Pie Chart">Distribution Pie Chart</option>
                                <option value="Box Plot">Length Distribution Box Plot</option>
                            </select>
                        </div>
    
                        <div class="form-group">
                            <label>Additional Options</label>
                            <div class="checkbox-group">
                                <label class="checkbox-wrapper">
                                    <input type="checkbox" name="head">
                                    Show Dataset Head
                                </label>
                                <label class="checkbox-wrapper">
                                    <input type="checkbox" name="tail">
                                    Show Dataset Tail
                                </label>
                                <label class="checkbox-wrapper">
                                    <input type="checkbox" name="performance">
                                    Show Model Performance
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
    
                <button type="submit" class="submit-btn" id="submit-btn">
                    <span>Analyze Text</span>
                    <div class="loading-spinner" style="display: none;"></div>
                </button>
            </form>
        </main>
    
        <section class="results" id="results">
            <!-- Results will be dynamically inserted here -->
        </section>
    </div>
    
    <script>
      // Wait for the DOM to be fully loaded
    

    document.addEventListener('DOMContentLoaded', function() { // Get DOM elements const form = document.getElementById('classifier-form'); const submitBtn = document.querySelector('input[type="submit"]'); const resultSection = document.getElementById('result-section'); const loadingOverlay = document.getElementById('loading-overlay'); const confidenceChart = document.getElementById('confidence-chart'); const textInput = document.getElementById('text'); const wordCounter = document.getElementById('word-counter'); const themeToggle = document.getElementById('theme-toggle');

    // Initialize tooltips
    const tooltips = document.querySelectorAll('[data-tooltip]');
    tooltips.forEach(tooltip => {
        tippy(tooltip, {
            content: tooltip.getAttribute('data-tooltip'),
            placement: 'top',
            animation: 'scale',
            theme: 'modern'
        });
    });
    
    // Word counter functionality
    textInput.addEventListener('input', function() {
        const words = this.value.trim().split(/\s+/).filter(word => word.length > 0);
        wordCounter.textContent = `${words.length} words`;
        
        // Validate input length
        if (words.length > 1000) {
            wordCounter.classList.add('text-red-500');
        } else {
            wordCounter.classList.remove('text-red-500');
        }
    });
    
    // Theme toggling functionality
    let isDark = localStorage.getItem('dark-mode') === 'true';
    updateTheme();
    
    themeToggle.addEventListener('click', () => {
        isDark = !isDark;
        localStorage.setItem('dark-mode', isDark);
        updateTheme();
    });
    
    function updateTheme() {
        document.documentElement.classList.toggle('dark', isDark);
        themeToggle.innerHTML = isDark ? 
            '<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path></svg>' :
            '<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path></svg>';
    }
    
    // Form submission handling
    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        // Validate input
        const text = textInput.value.trim();
        if (!text) {
            showNotification('Please enter some text to analyze', 'error');
            return;
        }
    
        // Show loading state
        showLoading(true);
        
        try {
            const formData = new FormData(form);
            const response = await fetch('/analyze', {
                method: 'POST',
                body: formData
            });
    
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
    
            const data = await response.json();
            
            if (data.error) {
                throw new Error(data.error);
            }
    
            // Update UI with results
            updateResults(data);
            
            // Smooth scroll to results
            resultSection.scrollIntoView({ behavior: 'smooth' });
    
        } catch (error) {
            showNotification(error.message || 'An error occurred during analysis', 'error');
            console.error('Error:', error);
        } finally {
            showLoading(false);
        }
    });
    
    function updateResults(data) {
        // Clear previous results
        resultSection.innerHTML = '';
        
        // Add prediction result card
        if (data.prediction) {
            const predictionCard = createResultCard('Prediction Result', `
                <div class="flex items-center justify-between">
                    <div>
                        <h3 class="text-xl font-semibold ${data.prediction === 'AI-generated' ? 'text-purple-600' : 'text-green-600'}">
                            ${data.prediction}
                        </h3>
                        <p class="text-gray-600 dark:text-gray-300">Confidence: ${data.confidence.toFixed(1)}%</p>
                    </div>
                    <div class="confidence-meter">
                        ${createConfidenceMeter(data.confidence)}
                    </div>
                </div>
            `);
            resultSection.appendChild(predictionCard);
        }
    
        // Add performance metrics if available
        if (data.performance_data) {
            const performanceCard = createResultCard('Model Performance', `
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                    ${createPerformanceMetrics(data.performance_data)}
                </div>
            `);
            resultSection.appendChild(performanceCard);
        }
    
        // Add visualization if available
        if (data.plot_url) {
            const visualizationCard = createResultCard('Visualization', `
                <img src="data:image/png;base64,${data.plot_url}" 
                     alt="Data Visualization" 
                     class="w-full h-auto rounded-lg shadow-lg"
                     loading="lazy">
            `);
            resultSection.appendChild(visualizationCard);
        }
    
        // Add data preview if available
        if (data.head_data || data.tail_data) {
            const dataPreviewCard = createResultCard('Data Preview', `
                ${data.head_data ? '<div class="mb-4"><h3 class="font-semibold mb-2">Head of Data</h3>' + data.head_data + '</div>' : ''}
                ${data.tail_data ? '<div><h3 class="font-semibold mb-2">Tail of Data</h3>' + data.tail_data + '</div>' : ''}
            `);
            resultSection.appendChild(dataPreviewCard);
        }
    
        // Show results section with animation
        resultSection.classList.add('show');
    }
    
    function createResultCard(title, content) {
        const card = document.createElement('div');
        card.className = 'result-card fade-in';
        card.innerHTML = `
            <h2 class="text-xl font-semibold mb-4 text-gray-800 dark:text-gray-200">
                ${title}
            </h2>
            ${content}
        `;
        return card;
    }
    
    function createConfidenceMeter(confidence) {
        const degree = (confidence / 100) * 180;
        return `
            <div class="relative w-24 h-24">
                <svg class="transform -rotate-90 w-24 h-24">
                    <circle
                        cx="48"
                        cy="48"
                        r="36"
                        stroke-width="8"
                        stroke="#e2e8f0"
                        fill="none"
                    />
                    <circle
                        cx="48"
                        cy="48"
                        r="36"
                        stroke-width="8"
                        stroke="${confidence > 75 ? '#8b5cf6' : confidence > 50 ? '#60a5fa' : '#f87171'}"
                        fill="none"
                        stroke-dasharray="${2 * Math.PI * 36}"
                        stroke-dashoffset="${2 * Math.PI * 36 * (1 - confidence / 100)}"
                        class="transition-all duration-1000 ease-out"
                    />
                </svg>
                <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-center">
                    <span class="text-xl font-bold">${confidence.toFixed(0)}%</span>
                </div>
            </div>
        `;
    }
    
    function createPerformanceMetrics(performance) {
        return `
            <div class="metric-card">
                <h4>Accuracy</h4>
                <p class="text-2xl font-bold text-purple-600">${performance.accuracy}%</p>
            </div>
            <div class="metric-card">
                <h4>Precision</h4>
                <p class="text-2xl font-bold text-blue-600">${performance.precision}%</p>
            </div>
            <div class="metric-card">
                <h4>Recall</h4>
                <p class="text-2xl font-bold text-green-600">${performance.recall}%</p>
            </div>
            <div class="metric-card">
                <h4>F1 Score</h4>
                <p class="text-2xl font-bold text-yellow-600">${performance.f1}%</p>
            </div>
        `;
    }
    
    function showLoading(show) {
        loadingOverlay.classList.toggle('hidden', !show);
        submitBtn.disabled = show;
        submitBtn.value = show ? 'Analyzing...' : 'Analyze';
    }
    
    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification ${type} animate-slide-in`;
        notification.innerHTML = `
            <div class="notification-content">
                <span class="notification-message">${message}</span>
                <button class="notification-close">&times;</button>
            </div>
        `;
    
        document.body.appendChild(notification);
    
        // Auto-remove after 5 seconds
        setTimeout(() => {
            notification.classList.add('animate-slide-out');
            setTimeout(() => notification.remove(), 300);
        }, 5000);
    
        // Close button functionality
        notification.querySelector('.notification-close').addEventListener('click', () => {
            notification.classList.add('animate-slide-out');
            setTimeout(() => notification.remove(), 300);
        });
    }
    
    // Handle keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + Enter to submit
        if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
            if (!submitBtn.disabled) {
                form.dispatchEvent(new Event('submit'));
            }
        }
    });
    
    // Initialize custom select styling
    const selects = document.querySelectorAll('select');
    selects.forEach(select => {
        const wrapper = document.createElement('div');
        wrapper.className = 'custom-select-wrapper';
        select.parentNode.insertBefore(wrapper, select);
        wrapper.appendChild(select);
    });
    

    });

    // Prevent form submission on Enter key document.addEventListener('keypress', function(e) { if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') { e.preventDefault(); } });

  2. Assistant

    Certainly! Let's address the issues in your Flask application and enhance the UI to make it more modern, interactive, and visually appealing.

    1. Fixing the Backend (app.py)

    Issues Identified:

    • Response Format Mismatch: Your frontend JavaScript expects a JSON response from the /analyze endpoint, but the backend is rendering an HTML template instead.
    • Incomplete Performance Metrics: The backend only calculates accuracy but the frontend expects additional metrics like precision, recall, and F1 score.
    • Confidence Score Calculation: The frontend expects a confidence score (data.confidence), but it's not being calculated in the backend.

    Solutions:

    • Modify the /analyze route to return a JSON response instead of rendering a template.
    • Calculate additional performance metrics: precision, recall, and F1 score.
    • Calculate the confidence score for the prediction.
    • Ensure all required data is included in the JSON response.

    2. Enhancing the Frontend (index.html)

    Issues Identified:

    • CSS Class Mismatch: The frontend uses classes like text-red-500 which are Tailwind CSS classes, but Tailwind isn't included. This results in styles not being applied.
    • Element ID Mismatch: The JavaScript refers to an element with the ID result-section, but the HTML has id="results".
    • Improving UI/UX: Adding modern animations, transitions, a beautiful background, and interactive elements to make the UI more engaging.

    Solutions:

    • Include Tailwind CSS: To utilize Tailwind CSS classes, include Tailwind via CDN.
    • Fix Element IDs: Ensure consistency between HTML and JavaScript.
    • Enhance UI/UX: Utilize Tailwind's utility classes and add CSS animations/transitions for a more dynamic and modern look.

    Below are the corrected and enhanced versions of app.py and index.html.


    Corrected app.py

    from flask import Flask, render_template, request, jsonify
    import pandas as pd
    import joblib
    from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
    import matplotlib.pyplot as plt
    import io
    import base64
    from sklearn.model_selection import train_test_split
    
    app = Flask(__name__)
    
    # Load the CSV file
    df = pd.read_csv('data.csv')
    
    # Load models and vectorizer
    vectorizer = joblib.load('vectorizer.pkl')
    models = {
        'Logistic Regression': joblib.load('Logistic Regression.pkl'),
        'Random Forest': joblib.load('Random Forest.pkl'),
        'SVM': joblib.load('SVM.pkl'),
        'Naive Bayes': joblib.load('Naive Bayes.pkl')
    }
    
    # Preprocess data for accuracy calculation
    X = df['text']
    y = df['generated']
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    X_test_vec = vectorizer.transform(X_test)
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/analyze', methods=['POST'])
    def analyze():
        try:
            text = request.form['text']
            model_choice = request.form['model']
            viz_choice = request.form.get('visualization', 'None')
            show_head = request.form.get('head')
            show_tail = request.form.get('tail')
            show_performance = request.form.get('performance')
    
            # Model Selection
            model = models.get(model_choice, models['Logistic Regression'])
    
            # Prediction
            text_vec = vectorizer.transform([text])
            prediction_num = model.predict(text_vec)[0]
            prediction = "Human-generated" if prediction_num == 0 else "AI-generated"
    
            # Confidence Score
            if hasattr(model, "predict_proba"):
                proba = model.predict_proba(text_vec)[0]
                confidence = max(proba) * 100
            else:
                confidence = None  # Some models like SVM might not have predict_proba
    
            # Performance Metrics
            y_pred = model.predict(X_test_vec)
            accuracy = accuracy_score(y_test, y_pred) * 100
            precision = precision_score(y_test, y_pred, zero_division=0) * 100
            recall = recall_score(y_test, y_pred, zero_division=0) * 100
            f1 = f1_score(y_test, y_pred, zero_division=0) * 100
    
            performance_data = None
            if show_performance:
                performance_data = {
                    'accuracy': round(accuracy, 2),
                    'precision': round(precision, 2),
                    'recall': round(recall, 2),
                    'f1': round(f1, 2)
                }
    
            # Visualization
            plot_url = None
            if viz_choice == 'Pie Chart':
                plt.figure(figsize=(6, 6))
                df['generated'].value_counts().plot.pie(autopct='%1.1f%%', colors=['#4F46E5', '#10B981'])
                plt.title('Distribution of Generated Content')
                img = io.BytesIO()
                plt.savefig(img, format='png', bbox_inches='tight')
                plt.close()
                img.seek(0)
                plot_url = base64.b64encode(img.getvalue()).decode()
    
            elif viz_choice == 'Box Plot':
                plt.figure(figsize=(6, 6))
                df['text_length'] = df['text'].apply(len)
                df.boxplot(column=['text_length', 'generated'], by='generated', grid=False)
                plt.title('Text Length Distribution by Category')
                plt.suptitle('')
                plt.xlabel('Generated Category')
                plt.ylabel('Text Length')
                img = io.BytesIO()
                plt.savefig(img, format='png', bbox_inches='tight')
                plt.close()
                img.seek(0)
                plot_url = base64.b64encode(img.getvalue()).decode()
    
            # Prepare Data for Display
            head_data_html = df.head().to_html(classes='table-auto w-full text-left hidden', index=False) if show_head else None
            tail_data_html = df.tail().to_html(classes='table-auto w-full text-left hidden', index=False) if show_tail else None
    
            response = {
                'prediction': prediction,
                'confidence': round(confidence, 2) if confidence is not None else "N/A",
                'performance_data': performance_data,
                'plot_url': plot_url,
                'head_data': head_data_html,
                'tail_data': tail_data_html
            }
    
            return jsonify(response)
        except Exception as e:
            return jsonify({'error': str(e)}), 500
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    Key Changes:

    1. JSON Response: The /analyze route now returns a JSON response using jsonify instead of rendering an HTML template.
    2. Performance Metrics: Added calculation for precision, recall, and F1 score.
    3. Confidence Score: Calculated the confidence score using predict_proba if the model supports it.
    4. Error Handling: Wrapped the analysis logic in a try-except block to catch and return errors gracefully.
    5. Visualization Enhancements: Improved the plots with titles and proper labeling.
    6. Data Previews: Added classes to the tables for styling and initially set them to hidden. They will be displayed via JavaScript if the user selects to view them.

    Enhanced index.html

    To make the frontend more modern and interactive, we'll utilize Tailwind CSS for utility-first styling, include smooth animations, and ensure all JavaScript interacts correctly with the backend.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>AI Text Classifier | Professional Analysis Tool</title>
        <!-- Tailwind CSS CDN -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/3.3.2/tailwind.min.css" rel="stylesheet">
        <!-- Font Awesome for Icons -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
        <style>
            /* Custom Animations */
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(20px); }
                to { opacity: 1; transform: translateY(0); }
            }
            .fade-in {
                animation: fadeIn 0.8s ease-out forwards;
            }
            /* Loading Spinner */
            .loading-spinner {
                border: 4px solid rgba(0, 0, 0, 0.1);
                border-left-color: #4F46E5;
                border-radius: 50%;
                width: 20px;
                height: 20px;
                animation: spin 1s linear infinite;
            }
            @keyframes spin {
                to { transform: rotate(360deg); }
            }
            /* Notification Styles */
            .notification {
                position: fixed;
                top: 20px;
                right: 20px;
                background-color: #F87171;
                color: white;
                padding: 1rem 1.5rem;
                border-radius: 0.5rem;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                display: flex;
                align-items: center;
                justify-content: space-between;
                min-width: 250px;
                z-index: 1000;
                opacity: 0;
                transform: translateX(100%);
                transition: all 0.5s ease;
            }
            .notification.show {
                opacity: 1;
                transform: translateX(0);
            }
            .notification.info {
                background-color: #3B82F6;
            }
            .notification.success {
                background-color: #10B981;
            }
            .notification.error {
                background-color: #F87171;
            }
            .notification button {
                background: none;
                border: none;
                color: white;
                font-size: 1.2rem;
                cursor: pointer;
            }
        </style>
    </head>
    <body class="bg-gray-100 min-h-screen flex items-center justify-center">
        <div class="container mx-auto p-6">
            <header class="text-center mb-8">
                <h1 class="text-4xl font-bold text-indigo-600 mb-4 animate-pulse">AI Text Classifier</h1>
                <p class="text-gray-600">Detect AI-generated content with high accuracy using our advanced machine learning tool.</p>
            </header>
    
            <main class="bg-white shadow-lg rounded-lg p-8 animate-fade-in">
                <form id="classifier-form" class="space-y-6">
                    <div>
                        <label for="text" class="block text-gray-700 font-semibold mb-2">Text to Analyze</label>
                        <textarea id="text" name="text" rows="5" class="w-full p-4 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" placeholder="Enter the text you want to analyze..." required></textarea>
                    </div>
    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="model" class="block text-gray-700 font-semibold mb-2">Model Selection</label>
                            <select id="model" name="model" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" required>
                                <option value="Logistic Regression">Logistic Regression</option>
                                <option value="Random Forest">Random Forest</option>
                                <option value="SVM">Support Vector Machine</option>
                                <option value="Naive Bayes">Naive Bayes</option>
                            </select>
                        </div>
    
                        <div>
                            <label for="visualization" class="block text-gray-700 font-semibold mb-2">Visualization Type</label>
                            <select id="visualization" name="visualization" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                <option value="None">None</option>
                                <option value="Pie Chart">Distribution Pie Chart</option>
                                <option value="Box Plot">Length Distribution Box Plot</option>
                            </select>
                        </div>
                    </div>
    
                    <div>
                        <span class="block text-gray-700 font-semibold mb-2">Additional Options</span>
                        <div class="flex items-center space-x-6">
                            <label class="inline-flex items-center">
                                <input type="checkbox" name="head" class="form-checkbox h-5 w-5 text-indigo-600">
                                <span class="ml-2 text-gray-700">Show Dataset Head</span>
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" name="tail" class="form-checkbox h-5 w-5 text-indigo-600">
                                <span class="ml-2 text-gray-700">Show Dataset Tail</span>
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" name="performance" class="form-checkbox h-5 w-5 text-indigo-600">
                                <span class="ml-2 text-gray-700">Show Model Performance</span>
                            </label>
                        </div>
                    </div>
    
                    <button type="submit" class="w-full bg-indigo-600 text-white font-semibold py-3 rounded-lg hover:bg-indigo-700 transition duration-300 flex items-center justify-center space-x-2">
                        <span>Analyze Text</span>
                        <div class="loading-spinner hidden" id="loading-spinner"></div>
                    </button>
                </form>
            </main>
    
            <section class="mt-10 space-y-6" id="results">
                <!-- Results will be dynamically inserted here -->
            </section>
        </div>
    
        <!-- Notification Container -->
        <div id="notification-container"></div>
    
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const form = document.getElementById('classifier-form');
                const loadingSpinner = document.getElementById('loading-spinner');
                const submitBtn = form.querySelector('button[type="submit"]');
                const resultsSection = document.getElementById('results');
                const notificationContainer = document.getElementById('notification-container');
    
                form.addEventListener('submit', async function(e) {
                    e.preventDefault();
    
                    // Clear previous results
                    resultsSection.innerHTML = '';
    
                    // Show loading spinner
                    loadingSpinner.classList.remove('hidden');
                    submitBtn.disabled = true;
    
                    try {
                        const formData = new FormData(form);
                        const response = await fetch('/analyze', {
                            method: 'POST',
                            body: formData
                        });
    
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || 'An error occurred during analysis.');
                        }
    
                        const data = await response.json();
    
                        // Display Prediction
                        const predictionCard = document.createElement('div');
                        predictionCard.className = 'bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded';
                        predictionCard.innerHTML = `
                            <p class="font-bold">Prediction: <span class="font-semibold">${data.prediction}</span></p>
                            <p>Confidence: <span class="font-semibold">${data.confidence}%</span></p>
                        `;
                        resultsSection.appendChild(predictionCard);
    
                        // Display Performance Metrics if available
                        if (data.performance_data) {
                            const performanceCard = document.createElement('div');
                            performanceCard.className = 'bg-blue-100 border-l-4 border-blue-500 text-blue-700 p-4 rounded';
                            performanceCard.innerHTML = `
                                <p class="font-bold">Model Performance:</p>
                                <ul class="list-disc list-inside">
                                    <li>Accuracy: ${data.performance_data.accuracy}%</li>
                                    <li>Precision: ${data.performance_data.precision}%</li>
                                    <li>Recall: ${data.performance_data.recall}%</li>
                                    <li>F1 Score: ${data.performance_data.f1}%</li>
                                </ul>
                            `;
                            resultsSection.appendChild(performanceCard);
                        }
    
                        // Display Visualization if available
                        if (data.plot_url) {
                            const vizCard = document.createElement('div');
                            vizCard.className = 'bg-purple-100 border-l-4 border-purple-500 text-purple-700 p-4 rounded';
                            vizCard.innerHTML = `
                                <p class="font-bold mb-2">Visualization:</p>
                                <img src="data:image/png;base64,${data.plot_url}" alt="Visualization" class="rounded-lg shadow-md">
                            `;
                            resultsSection.appendChild(vizCard);
                        }
    
                        // Display Data Preview if available
                        if (data.head_data || data.tail_data) {
                            const dataPreviewCard = document.createElement('div');
                            dataPreviewCard.className = 'bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4 rounded';
                            dataPreviewCard.innerHTML = `<p class="font-bold mb-2">Data Preview:</p>`;
    
                            if (data.head_data) {
                                dataPreviewCard.innerHTML += `
                                    <h3 class="font-semibold mb-1">Head of Data:</h3>
                                    ${data.head_data}
                                `;
                            }
    
                            if (data.tail_data) {
                                dataPreviewCard.innerHTML += `
                                    <h3 class="font-semibold mt-4 mb-1">Tail of Data:</h3>
                                    ${data.tail_data}
                                `;
                            }
    
                            resultsSection.appendChild(dataPreviewCard);
                        }
    
                    } catch (error) {
                        showNotification(error.message, 'error');
                    } finally {
                        // Hide loading spinner
                        loadingSpinner.classList.add('hidden');
                        submitBtn.disabled = false;
                    }
                });
    
                function showNotification(message, type = 'info') {
                    const notification = document.createElement('div');
                    notification.className = `notification ${type === 'error' ? 'error' : 'info'}`;
                    notification.innerHTML = `
                        <span>${message}</span>
                        <button>&times;</button>
                    `;
                    notificationContainer.appendChild(notification);
    
                    // Show the notification
                    setTimeout(() => {
                        notification.classList.add('show');
                    }, 100);
    
                    // Remove after 5 seconds
                    setTimeout(() => {
                        notification.classList.remove('show');
                        setTimeout(() => {
                            notification.remove();
                        }, 500);
                    }, 5000);
    
                    // Close on button click
                    notification.querySelector('button').addEventListener('click', () => {
                        notification.classList.remove('show');
                        setTimeout(() => {
                            notification.remove();
                        }, 500);
                    });
                }
            });
        </script>
    </body>
    </html>
    

    Key Enhancements:

    1. Tailwind CSS Integration:

      • Included Tailwind CSS via CDN for utility-first styling.
      • Utilized Tailwind classes to style elements, ensuring responsiveness and a modern look.
    2. Responsive Design:

      • The form adapts to different screen sizes using Tailwind's grid system.
      • Ensured the layout looks good on both mobile and desktop devices.
    3. Animations and Transitions:

      • Added a fadeIn animation for the main form.
      • Implemented smooth transitions for the submit button and notifications.
    4. Improved Visual Feedback:

      • Loading spinner is displayed within the submit button during the analysis.
      • Success and error notifications appear dynamically at the top-right corner.
    5. Consistency in Element IDs:

      • Ensured that JavaScript correctly references elements by matching IDs (results instead of result-section).
    6. Enhanced Accessibility:

      • Added focus states and clear labels to form elements for better accessibility.
    7. Interactive Elements:

      • Hover effects on buttons to indicate interactivity.
      • Rounded borders and shadows for cards to create depth.
    8. Notifications:

      • Implemented a notification system to inform users of errors or important information dynamically.

    3. Additional Recommendations

    • Data Security: Ensure that the data.csv, vectorizer.pkl, and model .pkl files are securely stored and accessed. Consider handling edge cases where these files might be missing or corrupted.

    • Model Compatibility: Verify that all models support predict_proba. If not, handle cases where confidence cannot be calculated to avoid errors.

    • Validation: Implement more robust input validation on both frontend and backend to ensure the application handles unexpected inputs gracefully.

    • Styling Consistency: While Tailwind CSS provides extensive styling options, ensure that any custom CSS does not conflict with Tailwind classes. Alternatively, rely more on Tailwind's utilities for a consistent design system.

    • Performance Optimization: For large datasets or complex models, consider implementing asynchronous processing or background tasks to prevent the frontend from freezing during analysis.


    By implementing these changes, your Flask application should function correctly, and the user interface will be modern, responsive, and engaging with smooth animations and transitions. Feel free to further customize the UI elements to match your specific design preferences!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.