CoolFace
Apppublic

sasuke3215/ai-model

sourceHugging Faceapache-2.0updated 3y agoView on Hugging Face
0likes
app.py64 linesDownload Raw Back to root
1from flask import Flask, request, jsonify2from flask_cors import CORS3import tensorflow as tf4from PIL import Image5import numpy as np6import io7import base648 9app = Flask(__name__)10CORS(app)11model = tf.saved_model.load("./converted_savedmodel/model.savedmodel")12 13# Define the target size for images (adjust based on your model's input size)14TARGET_SIZE = (224, 224)15 16def preprocess_image(image_data):17    # Load and preprocess the image18    image = Image.open(io.BytesIO(image_data)).convert("RGB")19    image = image.resize((224, 224))  # Resize to match the model's input shape20    image_array = np.array(image) / 255.0  # Normalize pixel values to [0, 1]21    image_array = np.expand_dims(image_array, axis=0)  # Add batch dimension22    return image_array23 24def predict_mask(image_data):25    image_array = preprocess_image(image_data)26 27    # Make predictions using the loaded TensorFlow model with the specified signature28    predictions = model.signatures['serving_default'](tf.constant(image_array, dtype=tf.float32))29 30    # Assuming your model outputs a probability for mask presence (adjust based on your model)31    probability_mask = predictions['sequential_3'].numpy()[0][0]32 33    # You can define your own threshold for mask detection34    mask_detected = probability_mask > 0.535 36    return {37        'Freshness': int(mask_detected),  # Convert boolean to integer38        'Freshness_probability': float(probability_mask)39    }40 41@app.route('/predict_freshness', methods=['POST'])42def predict_mask_route():43    print("Request received")44 45    try:46        data = request.get_json()47        if 'image' not in data:48            return jsonify({'error': 'No image provided in the request'}), 40049 50        base64_image = data['image']51        image_data = base64.b64decode(base64_image)52        53        print(f"Received image data size in predict_freshness: {len(image_data)} bytes")54        result = predict_mask(image_data)55        print(f"Prediction result: {result}")56        return jsonify(result)57    except Exception as e:58        print(f"Error processing request: {e}")59        return jsonify({'error': 'Internal server error'}), 50060 61if __name__ == '__main__':62    app.run(debug=True)63else:64    gunicorn_app = app.run(debug=False)