this is my app.py code along with the index.html code...i dont know whats wrong with…
- 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 loadeddocument.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">×</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(); } });
- Assistant
It looks like there are a few issues with your code that are preventing it from working properly. Additionally, enhancing the UI can greatly improve the user experience. Below, I've fixed the issues in your
app.pyandindex.htmlcode and updated the UI to be more modern and interactive with cool animations and effects.
Issues and Fixes
-
Mismatch Between Server Response and Client Expectation
- Issue: The JavaScript code expects a JSON response from the
/analyzeendpoint, but the Flask route is rendering an HTML template. - Fix: Modify the
/analyzeroute to return a JSON response usingjsonify, and update the data structure accordingly.
- Issue: The JavaScript code expects a JSON response from the
-
Inconsistent Element IDs and Selectors
- Issue: The JavaScript code references element IDs and classes that don't exist or don't match those in the HTML.
- Fix: Update the HTML to include the correct IDs and classes, and adjust the JavaScript selectors accordingly.
-
Missing Elements and Libraries
- Issue: The code references elements like
loadingOverlayand libraries liketippy.jsthat aren't included in the HTML. - Fix: Add these elements and include the necessary external libraries via CDN.
- Issue: The code references elements like
-
UI/UX Improvements
- Enhancements:
- Implement a modern design using Tailwind CSS.
- Add animations, transitions, and interactive elements.
- Use a beautiful background and ensure the UI is responsive and user-friendly.
- Enhancements:
Updated
app.pyHere's the fixed and updated
app.py:from flask import Flask, render_template, request, jsonify import pandas as pd import joblib from sklearn.metrics import accuracy_score, classification_report 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(): 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" # Confidence Score if hasattr(model, 'predict_proba'): confidence = max(model.predict_proba(text_vec)[0]) * 100 else: confidence = 50.0 # Default confidence if predict_proba is not available # Performance Metrics performance_data = None if show_performance: report = classification_report(y_test, model.predict(X_test_vec), output_dict=True) performance_data = { 'accuracy': report['accuracy'] * 100, 'precision': report['weighted avg']['precision'] * 100, 'recall': report['weighted avg']['recall'] * 100, 'f1_score': report['weighted avg']['f1-score'] * 100 } # 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', '#A78BFA']) plt.tight_layout() img = io.BytesIO() plt.savefig(img, format='png', transparent=True) img.seek(0) plot_url = base64.b64encode(img.getvalue()).decode() elif viz_choice == 'Box Plot': plt.figure(figsize=(6, 6)) df.boxplot(column=['generated']) plt.tight_layout() img = io.BytesIO() plt.savefig(img, format='png', transparent=True) img.seek(0) plot_url = base64.b64encode(img.getvalue()).decode() # Data Preview head_data = df.head().to_html(classes='table table-striped') if show_head else None tail_data = df.tail().to_html(classes='table table-striped') if show_tail else None # Prepare JSON response data = { 'prediction': prediction, 'confidence': confidence, 'plot_url': plot_url, 'head_data': head_data, 'tail_data': tail_data, 'performance_data': performance_data } return jsonify(data) if __name__ == '__main__': app.run(debug=True)Key Changes:
- Imported
jsonifyto return JSON responses. - Modified the
/analyzeroute to return a JSON object with all necessary data. - Added confidence score calculation with a default value if
predict_probais not available. - Prepared
performance_dataas a dictionary with detailed metrics. - Adjusted the plots to have transparent backgrounds and consistent styling.
Updated
index.htmlwith Enhanced UIBelow is the updated
index.htmlwith UI enhancements:<!DOCTYPE html> <html lang="en"> <head> <!-- ... Head content remains the same up to styles ... --> <!-- Import TailwindCSS via CDN for modern styling --> <script src="https://cdn.tailwindcss.com"></script> <!-- Include Tippy.js for tooltips --> <script src="https://unpkg.com/@popperjs/core@2"></script> <script src="https://unpkg.com/tippy.js@6"></script> <link rel="stylesheet" href="https://unpkg.com/tippy.js@6/animations/scale.css" /> <!-- Include Animate.css for animations --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/> <style> /* Custom styles to override Tailwind defaults if needed */ /* ... Custom CSS here ... */ </style> </head> <body class="bg-gray-50"> <!-- Navbar --> <nav class="bg-white shadow-md fixed w-full z-10"> <div class="container mx-auto px-6 py-3 flex justify-between items-center"> <a href="#" class="text-xl font-bold text-gray-800 hover:text-gray-700"> AI Text Classifier </a> <div> <button id="theme-toggle" class="focus:outline-none"> <!-- The theme toggle icon will be injected here --> </button> </div> </div> </nav> <div class="container mx-auto mt-24 px-6"> <!-- Header --> <header class="text-center mb-12"> <h1 class="text-4xl font-extrabold text-gray-800 animate__animated animate__fadeInDown"> AI Text Classifier </h1> <p class="mt-4 text-lg text-gray-600 animate__animated animate__fadeInUp"> Advanced text analysis tool powered by machine learning to detect AI-generated content with high accuracy. </p> </header> <!-- Main Card --> <main class="bg-white rounded-lg shadow-lg p-8 mb-10 animate__animated animate__zoomIn"> <div id="error-message" class="bg-red-100 text-red-800 px-4 py-2 rounded-md mb-6 hidden"></div> <form id="classifier-form" class="space-y-6"> <div class="grid grid-cols-1 md:grid-cols-2 gap-8"> <!-- Text Input --> <div> <label for="text" class="block text-lg font-medium text-gray-700">Text to Analyze</label> <textarea id="text" name="text" required placeholder="Enter the text you want to analyze..." class="mt-2 w-full rounded-md border-gray-300 focus:ring-indigo-500 focus:border-indigo-500"></textarea> <p id="word-counter" class="text-sm text-gray-500 mt-1">0 words</p> </div> <!-- Options --> <div> <!-- Model Selection --> <div> <label for="model" class="block text-lg font-medium text-gray-700">Model Selection</label> <select id="model" name="model" required class="mt-2 w-full rounded-md border-gray-300 focus:ring-indigo-500 focus:border-indigo-500"> <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> <!-- Visualization Type --> <div class="mt-6"> <label for="visualization" class="block text-lg font-medium text-gray-700">Visualization Type</label> <select id="visualization" name="visualization" class="mt-2 w-full rounded-md border-gray-300 focus:ring-indigo-500 focus:border-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> <!-- Additional Options --> <div class="mt-6"> <label class="block text-lg font-medium text-gray-700">Additional Options</label> <div class="mt-2 space-y-4"> <label class="inline-flex items-center"> <input type="checkbox" name="head" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"> <span class="ml-2">Show Dataset Head</span> </label> <label class="inline-flex items-center"> <input type="checkbox" name="tail" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"> <span class="ml-2">Show Dataset Tail</span> </label> <label class="inline-flex items-center"> <input type="checkbox" name="performance" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"> <span class="ml-2">Show Model Performance</span> </label> </div> </div> </div> </div> <div class="text-center"> <button type="submit" id="submit-btn" class="w-full md:w-auto bg-indigo-600 text-white px-6 py-3 rounded-md font-semibold hover:bg-indigo-700 transition duration-300 ease-in-out inline-flex items-center justify-center"> <span>Analyze Text</span> <svg id="loading-spinner" class="animate-spin -mr-1 ml-3 h-5 w-5 text-white hidden" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"> <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle> <path class="opacity-75" fill="currentColor" d="M12 2a10 10 0 00-7.071 17.071l1.414-1.414A8 8 0 1112 4v2z"></path> </svg> </button> </div> </form> </main> <!-- Results Section --> <section id="results" class="space-y-8"> <!-- Results will be dynamically inserted here --> </section> </div> <!-- Footer --> <footer class="bg-white mt-16 py-6"> <div class="container mx-auto text-center text-gray-500"> © 2023 AI Text Classifier. All rights reserved. </div> </footer> <!-- Scripts --> <script> // JavaScript code remains the same, with selectors adjusted to match the updated HTML document.addEventListener('DOMContentLoaded', function() { // Get DOM elements const form = document.getElementById('classifier-form'); const submitBtn = document.getElementById('submit-btn'); const resultSection = document.getElementById('results'); const textInput = document.getElementById('text'); const wordCounter = document.getElementById('word-counter'); const themeToggle = document.getElementById('theme-toggle'); const errorMessage = document.getElementById('error-message'); const loadingSpinner = document.getElementById('loading-spinner'); // 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 d="M12 3a9 9 0 000 18 9 9 0 000-18z"></path></svg>' : '<svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20"><path d="M10 15a1 1 0 011-1h3.586l-.293-.293a1 1 0 011.414-1.414l2 2A1 1 0 0117 16a1.003 1.003 0 01-.707-.293l-2-2A1 1 0 0113 14.586V18a1 1 0 11-2 0v-3zM3.293 6.293a1 1 0 00-1.414 0l-2 2A1 1 0 000 8a1 1 0 01.293.707L2.586 10H6a1 1 0 000-2H4.414l-.293-.293a1 1 0 000-1.414zM17 8a1 1 0 01.707-.293l2-2A1.001 1.001 0 0118 5a1 1 0 00-.707.293l-2 2A1 1 0 0115 8h3a1 1 0 110 2h-3a1 1 0 010-2zM3 12a1 1 0 100 2h1.586l.293.293a1 1 0 101.414-1.414l-2-2A1 1 0 003 12zM12 1a1 1 0 011 1v3a1 1 0 11-2 0V2a1 1 0 011-1z"/></svg>'; } // Form submission handling form.addEventListener('submit', async function(e) { e.preventDefault(); // Clear previous error message errorMessage.textContent = ''; errorMessage.classList.add('hidden'); // Validate input const text = textInput.value.trim(); if (!text) { showError('Please enter some text to analyze'); return; } // Disable submit button and show loader submitBtn.disabled = true; loadingSpinner.classList.remove('hidden'); 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(); // Update UI with results updateResults(data); // Smooth scroll to results resultSection.scrollIntoView({ behavior: 'smooth' }); } catch (error) { showError(error.message || 'An error occurred during analysis'); console.error('Error:', error); } finally { // Enable submit button and hide loader submitBtn.disabled = false; loadingSpinner.classList.add('hidden'); } }); function showError(message) { errorMessage.textContent = message; errorMessage.classList.remove('hidden'); } function updateResults(data) { // Clear previous results resultSection.innerHTML = ''; // Prediction Result if (data.prediction) { const predictionCard = createResultCard('Prediction Result', ` <div class="flex items-center justify-between"> <div> <h3 class="text-2xl font-bold ${data.prediction === 'AI-generated' ? 'text-indigo-600' : 'text-green-600'}"> ${data.prediction} </h3> <p class="text-gray-600">Confidence: ${data.confidence.toFixed(1)}%</p> </div> <div class="ml-4"> ${createConfidenceMeter(data.confidence)} </div> </div> `); resultSection.appendChild(predictionCard); } // Performance Metrics if (data.performance_data) { const performanceCard = createResultCard('Model Performance', ` <div class="grid grid-cols-2 gap-4"> ${createPerformanceMetrics(data.performance_data)} </div> `); resultSection.appendChild(performanceCard); } // Visualization 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-md shadow-lg"> `); resultSection.appendChild(visualizationCard); } // Data Preview 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); } } function createResultCard(title, content) { const card = document.createElement('div'); card.className = 'bg-white p-6 rounded-lg shadow-md animate__animated animate__fadeInUp'; card.innerHTML = ` <h2 class="text-xl font-semibold mb-4 text-gray-800">${title}</h2> ${content} `; return card; } function createConfidenceMeter(confidence) { const degree = (confidence / 100) * 180; return ` <div class="w-24 h-12"> <div class="relative"> <svg viewBox="0 0 180 90" class="transform -rotate-90"> <path d="M90,0 A90,90 0 0,1 0,90 L90,90 Z" fill="#f0f0f0"></path> <path d="M90,0 A90,90 0 ${confidence > 50 ? 1 : 0},1 ${90 - 90 * Math.cos(Math.PI * confidence / 100)},${90 + 90 * Math.sin(Math.PI * confidence / 100)} L90,90 Z" fill="${confidence > 70 ? '#4F46E5' : confidence > 40 ? '#F59E0B' : '#DC2626'}"></path> </svg> <div class="absolute inset-0 flex items-center justify-center"> <span class="text-lg font-bold">${confidence.toFixed(0)}%</span> </div> </div> </div> `; } function createPerformanceMetrics(performance) { return ` <div class="text-center"> <h4 class="text-gray-600">Accuracy</h4> <p class="text-xl font-bold text-indigo-600">${performance.accuracy.toFixed(2)}%</p> </div> <div class="text-center"> <h4 class="text-gray-600">Precision</h4> <p class="text-xl font-bold text-blue-600">${performance.precision.toFixed(2)}%</p> </div> <div class="text-center"> <h4 class="text-gray-600">Recall</h4> <p class="text-xl font-bold text-green-600">${performance.recall.toFixed(2)}%</p> </div> <div class="text-center"> <h4 class="text-gray-600">F1 Score</h4> <p class="text-xl font-bold text-yellow-600">${performance.f1_score.toFixed(2)}%</p> </div> `; } }); </script> </body> </html>Key Enhancements:
- Modern Styling: Utilized Tailwind CSS to create a modern and responsive design.
- Animations: Added animations using Animate.css for elements like headers, cards, and buttons.
- Interactive Elements: Implemented interactive buttons and theme toggle.
- Enhanced Visuals:
- Updated colors to be more vibrant and consistent.
- Styled the confidence meter and performance metrics.
- Tooltips: Included Tippy.js for potential tooltips (though not explicitly used in the code).
- Responsive Design: Ensured the layout adjusts gracefully on different screen sizes.
Additional Notes
- External Libraries:
- Tailwind CSS: Provides utility classes for rapid UI development.
- Animate.css: Adds CSS animations for elements.
- Tippy.js: Optional, for tooltips (you can remove it if not needed).
- Assets:
- Ensure that any images or fonts used are properly loaded or included.
- Testing:
- Test the application thoroughly to ensure all features work as expected.
- Check for any console errors in the browser's developer tools.
- Performance:
- Optimize images and assets to improve loading times.
- Consider minifying and bundling CSS and JS for production.
By addressing the issues and enhancing the UI, your application should now work correctly and provide an engaging user experience. Feel free to customize the styles and animations further to match your preferences.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.