|
|
|
"""101234444_aml_assignment_1.ipynb |
|
|
|
Automatically generated by Colaboratory. |
|
|
|
Original file is located at |
|
https://colab.research.google.com/drive/1GBU5kKqfnliMP-lElZZ4VgVgcsyqy1wQ |
|
""" |
|
|
|
import requests |
|
import tensorflow as tf |
|
import PIL.Image |
|
import numpy as np |
|
import json |
|
import gradio as gr |
|
|
|
|
|
url_model = "https://huggingface.co/ImanAmran/ml_assignment_1/resolve/main/final_model.h5" |
|
response_model = requests.get(url_model) |
|
with open("final_model.h5", "wb") as f_model: |
|
f_model.write(response_model.content) |
|
|
|
|
|
url_indices = "https://huggingface.co/ImanAmran/ml_assignment_1/resolve/main/class_indices.json" |
|
response_indices = requests.get(url_indices) |
|
class_indices = response_indices.json() |
|
|
|
|
|
model = tf.keras.models.load_model("final_model.h5") |
|
|
|
|
|
index_to_class = {v: k for k, v in class_indices.items()} |
|
|
|
def classify_image(image: PIL.Image.Image): |
|
try: |
|
|
|
if not isinstance(image, PIL.Image.Image): |
|
image = PIL.Image.fromarray(image) |
|
image_resized = image.resize((375, 375)) |
|
image_array = np.array(image_resized) |
|
image_array = np.expand_dims(image_array, axis=0) |
|
|
|
|
|
img_preprocessed = tf.keras.applications.resnet50.preprocess_input(image_array) |
|
|
|
|
|
predictions = model.predict(img_preprocessed) |
|
predicted_class_idx = np.argmax(predictions) |
|
|
|
|
|
predicted_class_label = index_to_class[predicted_class_idx] |
|
return predicted_class_label |
|
|
|
except Exception as e: |
|
return str(e) |
|
|
|
|
|
iface = gr.Interface( |
|
fn=classify_image, |
|
inputs=gr.components.Image(), |
|
outputs=gr.components.Textbox(), |
|
live=True, |
|
share=True |
|
) |
|
|