搭建Web UI实现Python脚本触发与机器学习实时可视化展示
Got it, let's walk through exactly how to set this up. We'll use Flask as our lightweight backend (perfect for this use case) to handle the button click, run your existing ML script, generate the plot, and serve it to a simple HTML frontend.
Step 1: Set Up Dependencies
First, make sure you have Flask installed alongside your existing libraries. Run this in your terminal:
pip install flask matplotlib numpy scikit-learn
Step 2: Backend Flask App (app.py)
Create a file named app.py in your project root. This will handle the request from the frontend, execute your ML code, generate the plot, and send it back.
Note: We'll configure matplotlib to use a non-interactive backend (since we're running it on a server, no display needed) and save the plot to Flask's static folder so the frontend can access it.
from flask import Flask, render_template, request, jsonify import matplotlib.pyplot as plt import numpy as np from sklearn import datasets # Example import, replace with your actual ML imports import uuid # To generate unique filenames for plots app = Flask(__name__) # Switch matplotlib to non-interactive backend plt.switch_backend('Agg') def run_ml_script(): # Replace this with your existing ML script logic # Example: Generate a sample plot using scikit-learn's iris dataset iris = datasets.load_iris() X = iris.data[:, :2] # Take first two features y = iris.target plt.figure(figsize=(8, 6)) plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis') plt.xlabel('Sepal Length') plt.ylabel('Sepal Width') plt.title('Iris Dataset Scatter Plot') # Generate unique filename to avoid conflicts plot_filename = f"plot_{uuid.uuid4().hex}.png" plot_path = f"static/{plot_filename}" plt.savefig(plot_path) plt.close() # Close the plot to free up memory return plot_filename @app.route('/') def index(): return render_template('index.html') @app.route('/generate-plot', methods=['POST']) def generate_plot(): try: plot_filename = run_ml_script() return jsonify({'success': True, 'plot_url': f'/static/{plot_filename}'}) except Exception as e: return jsonify({'success': False, 'error': str(e)}) if __name__ == '__main__': app.run(debug=True)
Step 3: Frontend HTML (templates/index.html)
Create a templates folder in your project root, then add index.html inside it. This will have a button to trigger the script and an area to display the generated plot.
<!DOCTYPE html> <html> <head> <title>ML Plot Generator</title> <style> body { font-family: Arial, sans-serif; max-width: 800px; margin: 2rem auto; padding: 0 1rem; } .button-container { margin: 2rem 0; } #generate-btn { padding: 0.8rem 1.5rem; font-size: 1rem; cursor: pointer; background: #007bff; color: white; border: none; border-radius: 4px; } #generate-btn:disabled { background: #6c757d; cursor: not-allowed; } #plot-container { margin-top: 2rem; } #plot-img { max-width: 100%; } #error-message { color: #dc3545; margin-top: 1rem; } </style> </head> <body> <h1>ML Model Output Visualizer</h1> <div class="button-container"> <button id="generate-btn">Run ML Script & Show Plot</button> </div> <div id="plot-container"> <img id="plot-img" style="display: none;" alt="Generated ML Plot"> </div> <div id="error-message"></div> <script> const generateBtn = document.getElementById('generate-btn'); const plotImg = document.getElementById('plot-img'); const errorMsg = document.getElementById('error-message'); generateBtn.addEventListener('click', async () => { generateBtn.disabled = true; generateBtn.textContent = 'Running...'; errorMsg.textContent = ''; plotImg.style.display = 'none'; try { const response = await fetch('/generate-plot', { method: 'POST' }); const data = await response.json(); if (data.success) { plotImg.src = data.plot_url; plotImg.style.display = 'block'; } else { errorMsg.textContent = `Error: ${data.error}`; } } catch (err) { errorMsg.textContent = 'Failed to connect to server. Please try again.'; } finally { generateBtn.disabled = false; generateBtn.textContent = 'Run ML Script & Show Plot'; } }); </script> </body> </html>
Step 4: Project Structure
Your project should look like this:
your-project/ ├── app.py ├── templates/ │ └── index.html └── static/ # Flask will create this automatically if needed
Step 5: Run the App
Run the Flask app with:
python app.py
Then open your browser and go to http://localhost:5000. Click the button, and you should see your ML plot load after the script runs!
Key Notes
- Replace the
run_ml_script()function's content with your actual Python ML code. Just make sure you generate a matplotlib plot and save it to thestaticfolder as shown. - Using
uuidfor plot filenames ensures that multiple users (or repeated clicks) won't overwrite each other's plots. - The
debug=Trueflag inapp.run()is great for development, but remember to turn it off in production.
内容的提问来源于stack exchange,提问作者johnny68

