Ahmed235 commited on
Commit
0b188bd
1 Parent(s): 95236c7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from PIL import Image
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ from transformers import TFAutoModelForSequenceClassification, AutoTokenizer
6
+ from tensorflow.keras.models import load_model
7
+ import ipywidgets as widgets
8
+ from IPython.display import display
9
+
10
+ model_path = 'final_teath_classifier.h5'
11
+
12
+ model = tf.keras.models.load_model(model_path)
13
+
14
+ # Load the model from Hugging Face model hub
15
+
16
+ def preprocess_image(image: Image.Image) -> np.ndarray:
17
+ # Resize the image to match input size
18
+ image = image.resize((256, 256))
19
+ # Convert image to array and preprocess input
20
+ img_array = np.array(image) / 255.0
21
+ # Add batch dimension
22
+ img_array = np.expand_dims(img_array, axis=0)
23
+ return img_array
24
+
25
+ def predict_image(image_path):
26
+ img = Image.open(image_path)
27
+ # Preprocess the image
28
+ img_array = preprocess_image(img)
29
+ # Convert image array to string using base64 encoding (for text-based models)
30
+ #inputs = tokenizer.encode(img_array, return_tensors="tf")
31
+ # Make prediction
32
+ outputs = model(img_array)
33
+ predictions = tf.nn.softmax(outputs.logits, axis=-1)
34
+ predicted_class = np.argmax(predictions)
35
+ if predicted_class == 0:
36
+ predict_label = "Clean"
37
+ else:
38
+ predict_label = "Carries"
39
+
40
+ return predict_label, predictions.numpy().flatten()
41
+
42
+ # Create a file uploader widget
43
+ uploader = widgets.FileUpload(accept="image/*", multiple=False)
44
+
45
+ # Display the file uploader widget
46
+ display(uploader)
47
+
48
+ # Define a callback function to handle the uploaded image
49
+ def on_upload(change):
50
+ # Get the uploaded image file
51
+ image_file = list(uploader.value.values())[0]["content"]
52
+ # Save the image to a temporary file
53
+ with open("temp_image.jpg", "wb") as f:
54
+ f.write(image_file)
55
+ # Get predictions for the uploaded image
56
+ predict_label, logits = predict_image("temp_image.jpg")
57
+ # Create a JSON object with the predictions
58
+ predictions_json = {
59
+ "predicted_class": predict_label,
60
+ "evaluations": [f"{logit*100:.4f}%" for logit in logits]
61
+ }
62
+ # Print the JSON object
63
+ print(json.dumps(predictions_json, indent=4))
64
+
65
+ # Set the callback function for when a file is uploaded
66
+ uploader.observe(on_upload, names="value")