Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,10 @@
|
|
| 1 |
-
# app.py
|
| 2 |
from fastapi import FastAPI, File, UploadFile
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
-
import numpy as np
|
| 5 |
import tensorflow as tf
|
| 6 |
-
|
| 7 |
-
import
|
| 8 |
import google.generativeai as genai
|
| 9 |
-
import
|
| 10 |
-
from typing import Optional
|
| 11 |
-
from pydantic import BaseModel
|
| 12 |
|
| 13 |
app = FastAPI()
|
| 14 |
|
|
@@ -21,72 +17,68 @@ app.add_middleware(
|
|
| 21 |
allow_headers=["*"],
|
| 22 |
)
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
-
|
|
|
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
| 30 |
-
output_details = interpreter.get_output_details()
|
| 31 |
|
| 32 |
-
# Define categories
|
| 33 |
data_cat = ['disposable cups', 'paper', 'plastic bottle']
|
| 34 |
img_height, img_width = 224, 224
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
@app.post("/predict")
|
| 44 |
async def predict(file: UploadFile = File(...)):
|
| 45 |
try:
|
|
|
|
| 46 |
contents = await file.read()
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
img = tf.image.resize(img, [img_height, img_width])
|
| 51 |
-
img_bat = np.expand_dims(img, 0).astype(np.float32)
|
| 52 |
-
|
| 53 |
-
# Set input tensor
|
| 54 |
-
interpreter.set_tensor(input_details[0]['index'], img_bat)
|
| 55 |
-
|
| 56 |
-
# Run inference
|
| 57 |
-
interpreter.invoke()
|
| 58 |
|
| 59 |
-
#
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
confidence = float(np.max(
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
Format each recommendation with a clear title followed by the explanation on a new line.
|
| 74 |
-
"""
|
| 75 |
|
| 76 |
-
try:
|
| 77 |
-
response = gemini_model.generate_content(prompt)
|
| 78 |
-
insights = response.text.strip()
|
| 79 |
-
except Exception as e:
|
| 80 |
-
insights = f"Error generating insights: {str(e)}"
|
| 81 |
-
|
| 82 |
return {
|
| 83 |
"class": predicted_class,
|
| 84 |
"confidence": confidence,
|
| 85 |
-
"insights":
|
| 86 |
}
|
| 87 |
|
| 88 |
except Exception as e:
|
| 89 |
return {"error": str(e)}
|
| 90 |
|
| 91 |
if __name__ == "__main__":
|
|
|
|
| 92 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, File, UploadFile
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 3 |
import tensorflow as tf
|
| 4 |
+
import numpy as np
|
| 5 |
+
from tensorflow import keras
|
| 6 |
import google.generativeai as genai
|
| 7 |
+
import os
|
|
|
|
|
|
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
|
|
|
| 17 |
allow_headers=["*"],
|
| 18 |
)
|
| 19 |
|
| 20 |
+
# Configure Gemini API
|
| 21 |
+
GEMINI_API_KEY = os.getenv('GEMINI_API_KEY', 'AIzaSyBx0A7BA-nKVZOiVn39JXzdGKgeGQqwAFg')
|
| 22 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 23 |
+
gemini_model = genai.GenerativeModel('gemini-pro')
|
| 24 |
|
| 25 |
+
# Load the model
|
| 26 |
+
model = keras.models.load_model('Image_classify.keras')
|
|
|
|
| 27 |
|
| 28 |
+
# Define categories and image dimensions
|
| 29 |
data_cat = ['disposable cups', 'paper', 'plastic bottle']
|
| 30 |
img_height, img_width = 224, 224
|
| 31 |
|
| 32 |
+
def generate_recycling_insight(detected_object):
|
| 33 |
+
"""Generate sustainability insights for detected objects"""
|
| 34 |
+
try:
|
| 35 |
+
prompt = f"""
|
| 36 |
+
You are a sustainability-focused AI. Analyze the {detected_object} (which is a solid dry waste)
|
| 37 |
+
and generate the top three innovative, eco-friendly recommendations for repurposing it. Ensure each recommendation is:
|
| 38 |
+
- Give the Title of the recommendation
|
| 39 |
+
- Practical and easy to implement
|
| 40 |
+
- Environmentally beneficial
|
| 41 |
+
- Clearly explained in one or two concise sentences
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
response = gemini_model.generate_content(prompt)
|
| 45 |
+
return response.text.strip()
|
| 46 |
+
except Exception as e:
|
| 47 |
+
return f"Error generating insight: {str(e)}"
|
| 48 |
|
| 49 |
@app.post("/predict")
|
| 50 |
async def predict(file: UploadFile = File(...)):
|
| 51 |
try:
|
| 52 |
+
# Read and preprocess the image
|
| 53 |
contents = await file.read()
|
| 54 |
+
image_load = tf.image.decode_image(contents, channels=3)
|
| 55 |
+
image_load = tf.image.resize(image_load, [img_height, img_width])
|
| 56 |
+
img_bat = tf.expand_dims(image_load, 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
# Perform prediction
|
| 59 |
+
predictions = model.predict(img_bat, verbose=0)
|
| 60 |
+
score = tf.nn.softmax(predictions[0])
|
| 61 |
+
confidence = float(np.max(score) * 100)
|
| 62 |
+
|
| 63 |
+
if confidence < 45:
|
| 64 |
+
return {
|
| 65 |
+
"error": "Confidence too low to make a prediction",
|
| 66 |
+
"confidence": confidence
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
# Get prediction and insights
|
| 70 |
+
predicted_class = data_cat[np.argmax(score)]
|
| 71 |
+
sustainability_insight = generate_recycling_insight(predicted_class)
|
|
|
|
|
|
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
return {
|
| 74 |
"class": predicted_class,
|
| 75 |
"confidence": confidence,
|
| 76 |
+
"insights": sustainability_insight
|
| 77 |
}
|
| 78 |
|
| 79 |
except Exception as e:
|
| 80 |
return {"error": str(e)}
|
| 81 |
|
| 82 |
if __name__ == "__main__":
|
| 83 |
+
import uvicorn
|
| 84 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|