Terence9's picture
Update app.py
d3b87a5 verified
import os
import json
import base64
from datetime import datetime
from flask import Flask, render_template, request, jsonify
from werkzeug.utils import secure_filename
from predict import predict_waste
app = Flask(__name__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'uploads')
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
app.config['HISTORY_FILE'] = os.path.join(BASE_DIR, 'prediction_history.json')
# Ensure upload directory exists
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def load_history():
if os.path.exists(app.config['HISTORY_FILE']):
try:
with open(app.config['HISTORY_FILE'], 'r') as f:
return json.load(f)
except json.JSONDecodeError:
return []
return []
def save_history(history):
with open(app.config['HISTORY_FILE'], 'w') as f:
json.dump(history, f)
@app.route('/')
def home():
history = load_history()
return render_template('index.html', history=history)
@app.route('/predict', methods=['POST'])
def predict():
if 'file' not in request.files:
return jsonify({'error': 'No file uploaded'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected'}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
try:
# Read the file for history before prediction
with open(filepath, 'rb') as img_file:
img_data = base64.b64encode(img_file.read()).decode('utf-8')
prediction = predict_waste(filepath)
# Save to history
history = load_history()
history.append({
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'prediction': prediction,
'image': img_data
})
# Keep only last 10 predictions
history = history[-10:]
save_history(history)
# Clean up the uploaded file
os.remove(filepath)
return jsonify({'prediction': prediction})
except Exception as e:
return jsonify({'error': str(e)}), 500
return jsonify({'error': 'Invalid file type'}), 400
@app.route('/clear-history', methods=['POST'])
def clear_history():
save_history([])
return jsonify({'success': True})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True)