Files
Smartwave/cloud/app.py
T
Ninluc 81de985580
Build, push image, and notify Watchtower / build-image (push) Successful in 3m59s
Build, push image, and notify Watchtower / notify (push) Successful in 7s
Answer with cooking plan and save edamam API tokens
2026-07-27 14:37:05 +02:00

119 lines
3.8 KiB
Python

import os
import base64
import uuid
from flask import Flask, request, jsonify
from pymongo import MongoClient
from APIs import generate, EdamamAPI
import sys
from microwaveCookPlanner import MicrowaveCookPlanner
sys.path.insert(0, '..')
try:
from shared import config
except ImportError:
from ..shared import config
app = Flask(__name__)
# ---------------------------------------------------------
# Configuration & Setup
# ---------------------------------------------------------
# Configure MongoDB connection (adjust the URI as needed for your environment)
MONGO_URI = os.getenv("MONGO_URI", "mongodb://localhost:27017/")
client = MongoClient(MONGO_URI)
db = client["microwave_network_db"]
cooking_collection = db["cooking_parameters"]
device_network_collection = db["device_network"]
# Ensure the camera image storage directory exists when the app starts
CAMERA_IMAGE_DIR = "storage/dishCameraImages"
os.makedirs(CAMERA_IMAGE_DIR, exist_ok=True)
# ---------------------------------------------------------
# Classes
# ---------------------------------------------------------
microwave_cook_planner = MicrowaveCookPlanner()
# ---------------------------------------------------------
# Routes
# ---------------------------------------------------------
@app.route("/")
def hello_world():
gen = generate(prompt="Say Hello, to the user !")
print(gen)
return f"<p>{gen}</p>"
@app.route("/cooking-params", methods=["POST"])
def cooking_params():
data = request.get_json()
if not data:
return jsonify({"error": "Invalid or missing JSON payload"}), 400
# 1. Handle the Camera Image
camera_image_b64 = data.get("camera_image")
if camera_image_b64:
# Generate a unique filename using UUID to avoid overwriting
filename = f"dish_{uuid.uuid4().hex}.jpg"
filepath = os.path.join(CAMERA_IMAGE_DIR, filename)
try:
# Decode the base64 string and save it as a binary file
with open(filepath, "wb") as f:
f.write(base64.b64decode(camera_image_b64))
# Replace the giant base64 string in the dictionary with the local file path
# so we don't bloat the MongoDB document
data["camera_image"] = filepath
except Exception as e:
return jsonify({"error": f"Failed to save camera image: {str(e)}"}), 500
# 2. Save to MongoDB
try:
# Insert the dictionary directly into Mongo (it will retain your exact JSON keys)
cooking_collection.insert_one(data)
# Remove the Mongo-injected '_id' object before returning the response
data.pop("_id", None)
except Exception as e:
return jsonify({"error": f"Database error: {str(e)}"}), 500
# 3. Returns with the cooking parameters
cooking_plan = microwave_cook_planner.generate_plan(
image_path=data.get("camera_image"),
height_cm=data.get("height_cm", 4.0),
initial_temp_c=data.get("initial_temp_c", 20.0),
microwave_wattage=data.get("microwave_wattage", 900)
)
return jsonify(cooking_plan), 201
@app.route("/device-network", methods=["POST"])
def device_network():
data = request.get_json()
if not data:
return jsonify({"error": "Invalid or missing JSON payload"}), 400
# 2. Save to MongoDB
try:
# Insert the dictionary directly into Mongo (it will retain your exact JSON keys)
device_network_collection.insert_one(data)
return "", 200
except Exception as e:
return jsonify({"error": f"Database error: {str(e)}"}), 500
@app.route("/debug", methods=["GET"])
def debug():
image_path = "microwaveDish.jpg"
edamam = EdamamAPI()
return edamam.analyze_dish_image(image_path)
if __name__ == "__main__":
app.run(debug=config.DEBUG)