Spaces:
Build error
Build error
Update app.py
Browse files12345678910111213146 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192# app.pyfrom fastapi import FastAPI, File, UploadFilefrom fastapi.middleware.cors import CORSMiddlewareimport numpy as npimport tensorflow as tffrom tensorflow.lite.python.interpreter import Interpreterimport osimport google.generativeai as genaiimport uvicornfrom typing import Optionalfrom pydantic import BaseModelapp = FastAPI()6 unmodified linesallow_headers=["*"],)# Load the TensorFlow Lite modelinterpreter = Interpreter(model_path="model.tflite")interpreter.allocate_tensors()# Get input and output detailsinput_details = interpreter.get_input_details()output_details = interpreter.get_output_details()# Define categoriesdata_cat = ['disposable cups', 'paper', 'plastic bottle']img_height, img_width = 224, 224# Configure Gemini APIGEMINI_API_KEY = os.getenv('GEMINI_API_KEY', 'AIzaSyBx0A7BA-nKVZOiVn39JXzdGKgeGQqwAFg')genai.configure(api_key=GEMINI_API_KEY)# Initialize Gemini modelgemini_model = genai.GenerativeModel('gemini-pro')@app.post("/predict")async def predict(file: UploadFile = File(...)):try:contents = await file.read()# Preprocess the imageimg = tf.image.decode_image(contents, channels=3)img = tf.image.resize(img, [img_height, img_width])img_bat = np.expand_dims(img, 0).astype(np.float32)# Set input tensorinterpreter.set_tensor(input_details[0]['index'], img_bat)# Run inferenceinterpreter.invoke()# Get the resultoutput_data = interpreter.get_tensor(output_details[0]['index'])predicted_class = data_cat[np.argmax(output_data)]confidence = float(np.max(output_data) * 100)# Generate sustainability insights with Gemini APIprompt = 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 explanationFormat 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)}"return {"class": predicted_class,"confidence": confidence,"insights": insights}except Exception as e:return {"error": str(e)}if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)123456789106 unmodified lines1718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384from fastapi import FastAPI, File, UploadFilefrom fastapi.middleware.cors import CORSMiddlewareimport tensorflow as tfimport numpy as npfrom tensorflow import kerasimport google.generativeai as genaiimport osapp = FastAPI()6 unmodified linesallow_headers=["*"],)# Configure Gemini APIGEMINI_API_KEY = os.getenv('GEMINI_API_KEY', 'AIzaSyBx0A7BA-nKVZOiVn39JXzdGKgeGQqwAFg')genai.configure(api_key=GEMINI_API_KEY)gemini_model = genai.GenerativeModel('gemini-pro')# Load the modelmodel = keras.models.load_model('Image_classify.keras')# Define categories and image dimensionsdata_cat = ['disposable cups', 'paper', 'plastic bottle']img_height, img_width = 224, 224def generate_recycling_insight(detected_object):"""Generate sustainability insights for detected objects"""try:prompt = f"""You are a sustainability-focused AI. Analyze the {detected_object} (which is a solid dry waste)and generate the top three innovative, eco-friendly recommendations for repurposing it. Ensure each recommendation is:- Give the Title of the recommendation- Practical and easy to implement- Environmentally beneficial- Clearly explained in one or two concise sentences"""response = gemini_model.generate_content(prompt)return response.text.strip()except Exception as e:return f"Error generating insight: {str(e)}"@app.post("/predict")async def predict(file: UploadFile = File(...)):try:# Read and preprocess the imagecontents = await file.read()image_load = tf.image.decode_image(contents, channels=3)image_load = tf.image.resize(image_load, [img_height, img_width])img_bat = tf.expand_dims(image_load, 0)# Perform predictionpredictions = model.predict(img_bat, verbose=0)score = tf.nn.softmax(predictions[0])confidence = float(np.max(score) * 100)if confidence < 45:return {"error": "Confidence too low to make a prediction","confidence": confidence}# Get prediction and insightspredicted_class = data_cat[np.argmax(score)]sustainability_insight = generate_recycling_insight(predicted_class)return {"class": predicted_class,"confidence": confidence,"insights": sustainability_insight}except Exception as e:return {"error": str(e)}if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)
app.py+46-54