OmarEllethy's picture
Update app.py
4bbe7c5 verified
import subprocess
import tensorflow as tf
import numpy as np
from PIL import Image
import io
from flask import Flask, request, jsonify
# Function to install a package using pip
def install_package(package):
try:
subprocess.check_call(['pip', 'install', package])
except subprocess.CalledProcessError as e:
print(f"Error installing {package}: {e}")
# List of libraries to install
libraries = [
'gradio',
'tensorflow',
'numpy',
'Pillow',
'opencv-python-headless',
'Flask',
'joblib'
]
# Install each library using pip
for library in libraries:
install_package(library)
# Attempt to import required libraries after installation
try:
import joblib
except ImportError:
print("Error: joblib failed to install or import.")
exit(1)
# Load the pre-trained TensorFlow model
model = tf.keras.models.load_model("imageclassifier.h5")
# Save the model as .pkl file
joblib.dump(model, "imageclassifier.pkl")
# Initialize Flask application
app = Flask(__name__)
# Load the model from .pkl file
model = joblib.load("imageclassifier.pkl")
# Define the function to predict the teeth health
def predict_teeth_health(image):
# Convert the PIL image object to a numpy array
image = np.array(image)
# Perform any necessary preprocessing (resizing, normalization, etc.) here if needed
# Make a prediction
prediction = model.predict(image.reshape(1, -1))
# Assuming binary classification, adjust as per your model's output
probability_good = prediction[0] # Assuming it's a binary classification
# Define the prediction result
result = {
"prediction": "Your Teeth are Good & You Don't Need To Visit Doctor" if probability_good > 0.5 else "Your Teeth are Bad & You Need To Visit Doctor"
}
return result
# Define route to accept image and return prediction
@app.route('/predict', methods=['POST'])
def predict():
# Ensure an image was properly uploaded to our endpoint
if request.method == 'POST':
file = request.files['image']
if file:
# Read the image using PIL
img = Image.open(file.stream)
# Perform prediction
prediction = predict_teeth_health(img)
return jsonify(prediction)
if __name__ == '__main__':
app.run(debug=True)