import os from flask import Blueprint, Flask, render_template, jsonify, send_file, request default_image_path = "./static/photo.jpg" image_path = "" state = "put" trash_type = "" api = Blueprint('api', __name__) # 放下垃圾 @api.route("/putdown") def putdown(): global state state = "camera" return "ok" # 拍好照 @api.route("/pic") def pic(): global state, image_path path = request.args.get("path") if not path or not os.path.isfile(path): return "sad", 400 image_path = path state = "identify" return "ok" # 辨識好 @api.route("/result") def result(): global state, trash_type trash = request.args.get("type") if not trash: return "sad", 400 trash_type = trash state = "identified" return "ok" # 準備好下一個 @api.route("/ready") def ready(): global state state = "put" return "ok" app = Flask(__name__) app.register_blueprint(api, url_prefix="/api") @app.route("/") def index(): return send_file("index.html") @app.route("/poll") def poll(): data = { "state": state } if state == "identified": data |= {"type": trash_type} return jsonify(data) @app.route("/photo") def photo(): if not image_path: return send_file(default_image_path) return send_file(image_path) if __name__ == "__main__": app.run(debug=True)