|
from flask import Flask, request, jsonify
|
|
import numpy as np
|
|
import tensorflow as tf
|
|
from tensorflow.lite.python.interpreter import Interpreter
|
|
import os
|
|
import google.generativeai as genai
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
interpreter = Interpreter(model_path="model.tflite")
|
|
interpreter.allocate_tensors()
|
|
|
|
|
|
input_details = interpreter.get_input_details()
|
|
output_details = interpreter.get_output_details()
|
|
|
|
|
|
data_cat = ['disposable cups', 'paper', 'plastic bottle']
|
|
img_height, img_width = 224, 224
|
|
|
|
|
|
GEMINI_API_KEY = os.getenv('GEMINI_API_KEY', 'AIzaSyBx0A7BA-nKVZOiVn39JXzdGKgeGQqwAFg')
|
|
genai.configure(api_key=GEMINI_API_KEY)
|
|
|
|
|
|
gemini_model = genai.GenerativeModel('gemini-pro')
|
|
|
|
@app.route('/predict', methods=['POST'])
|
|
def predict():
|
|
if 'image' not in request.files:
|
|
return jsonify({"error": "No image uploaded"}), 400
|
|
|
|
file = request.files['image']
|
|
try:
|
|
|
|
img = tf.image.decode_image(file.read(), channels=3)
|
|
img = tf.image.resize(img, [img_height, img_width])
|
|
img_bat = np.expand_dims(img, 0).astype(np.float32)
|
|
|
|
|
|
interpreter.set_tensor(input_details[0]['index'], img_bat)
|
|
|
|
|
|
interpreter.invoke()
|
|
|
|
|
|
output_data = interpreter.get_tensor(output_details[0]['index'])
|
|
predicted_class = data_cat[np.argmax(output_data)]
|
|
confidence = np.max(output_data) * 100
|
|
|
|
|
|
prompt = f"""
|
|
You are a sustainability-focused AI. Analyze the {predicted_class} (solid dry waste)
|
|
and generate the top three innovative, eco-friendly recommendations for repurposing it.
|
|
Each recommendation should:
|
|
- Provide a title
|
|
- Be practical and easy to implement
|
|
- Be environmentally beneficial
|
|
- Include a one or two-sentence explanation
|
|
Format each recommendation with a clear title followed by the explanation on a new line.
|
|
"""
|
|
|
|
try:
|
|
|
|
response = gemini_model.generate_content(prompt)
|
|
insights = response.text.strip()
|
|
|
|
except Exception as e:
|
|
insights = f"Error generating insights: {str(e)}"
|
|
print(f"Gemini API error: {str(e)}")
|
|
|
|
|
|
return jsonify({
|
|
"class": predicted_class,
|
|
"confidence": confidence,
|
|
"insights": insights
|
|
})
|
|
|
|
except Exception as e:
|
|
return jsonify({"error": str(e)}), 500
|
|
|
|
if __name__ == "__main__":
|
|
app.run(debug=True)
|
|
|