| import os
|
| from flask import Flask, request, jsonify, render_template
|
| import torch
|
| import torch.nn as nn
|
| from torchvision import models, transforms
|
| from PIL import Image
|
| from openai import OpenAI
|
| from flask_cors import CORS
|
| from fridgeItemDetector import fridge_item_detector, black_list_classes
|
|
|
| app = Flask(__name__, static_url_path='/static')
|
| CORS(app)
|
|
|
|
|
|
|
| app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| open_ai_api_key = os.getenv("OPEN_AI_KEY")
|
|
|
|
|
| client = OpenAI(api_key=open_ai_api_key)
|
| def generate_recipe(ingredients_text):
|
| prompt = f"Ingredients: {ingredients_text}. List 3 possible recipes with these ingredients and provide the essential cooking steps only."
|
| message = [{"role": "system", "content": prompt}]
|
|
|
| try:
|
| completion = client.chat.completions.create(
|
| model="gpt-4o-mini",
|
| messages=message,
|
| temperature=0.38,
|
| max_tokens=500
|
| )
|
|
|
| return completion.choices[0].message.content
|
| except Exception as e:
|
| return f"Error generating recipe: {str(e)}"
|
|
|
|
|
|
|
| @app.route('/')
|
| def home():
|
| return render_template('index.html')
|
|
|
|
|
| @app.route('/upload', methods=['POST'])
|
| def upload_image():
|
| try:
|
|
|
| if 'fridge-image' not in request.files:
|
| return jsonify({"error": "No file part"})
|
|
|
| file = request.files['fridge-image']
|
| if file.filename == '':
|
| return jsonify({"error": "No selected file"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| try:
|
|
|
| result = fridge_item_detector.detect_objects(
|
| file,
|
| prob_cutoff=0.9,
|
| black_list_classes=black_list_classes,
|
| annotate_image=False,
|
| return_unique_label=True
|
| )
|
| detected_ingredient = ", ".join(result)
|
| except Exception as e:
|
| return jsonify({"error": f"Error during model inference: {str(e)}"})
|
|
|
|
|
| try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| recipe = generate_recipe(detected_ingredient)
|
| except Exception as e:
|
| return jsonify({"error": f"Error generating recipe: {str(e)}"})
|
|
|
| return jsonify({"ingredient": detected_ingredient, "recipe": recipe})
|
|
|
| except Exception as e:
|
| return jsonify({"error": f"Unexpected error: {str(e)}"})
|
|
|
| if __name__ == '__main__':
|
| app.run(debug=True)
|
|
|