import os
from flask import Flask, request, render_template, jsonify
from werkzeug.utils import secure_filename
from classifier import ImageClassifier

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads'
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

classifier = ImageClassifier()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
    if 'image' not in request.files:
        return jsonify({'error': 'No image uploaded'}), 400

    file = request.files['image']
    filename = secure_filename(file.filename)
    save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    file.save(save_path)

    predictions = classifier.predict(save_path)
    return jsonify({
        'predictions': predictions,
        'image_url': '/' + save_path.replace('\\', '/')
    })

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