Upload usage_example.py with huggingface_hub
Browse files- usage_example.py +40 -0
usage_example.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from huggingface_hub import hf_hub_download
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
# Download model and class names from Hugging Face
|
| 9 |
+
model_path = hf_hub_download(repo_id="abdo1176/brain-model-test", filename="model.keras")
|
| 10 |
+
class_names_path = hf_hub_download(repo_id="abdo1176/brain-model-test", filename="class_names.json")
|
| 11 |
+
|
| 12 |
+
# Load model and class names
|
| 13 |
+
model = tf.keras.models.load_model(model_path)
|
| 14 |
+
with open(class_names_path, 'r') as f:
|
| 15 |
+
class_names = json.load(f)
|
| 16 |
+
|
| 17 |
+
def preprocess_image(image_path):
|
| 18 |
+
"""Preprocess image for model prediction"""
|
| 19 |
+
image = Image.open(image_path).convert('RGB')
|
| 20 |
+
image = image.resize((224, 224))
|
| 21 |
+
image = np.array(image) / 255.0
|
| 22 |
+
image = np.expand_dims(image, axis=0)
|
| 23 |
+
return image
|
| 24 |
+
|
| 25 |
+
def predict_brain_tumor(image_path):
|
| 26 |
+
"""Predict brain tumor from MRI image"""
|
| 27 |
+
image = preprocess_image(image_path)
|
| 28 |
+
predictions = model.predict(image)
|
| 29 |
+
predicted_idx = np.argmax(predictions[0])
|
| 30 |
+
confidence = float(predictions[0][predicted_idx])
|
| 31 |
+
|
| 32 |
+
return {
|
| 33 |
+
"predicted_class": class_names[predicted_idx],
|
| 34 |
+
"confidence": confidence,
|
| 35 |
+
"all_predictions": {class_names[i]: float(predictions[0][i]) for i in range(len(class_names))}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
# Example usage:
|
| 39 |
+
# result = predict_brain_tumor("path/to/your/mri_image.jpg")
|
| 40 |
+
# print(f"Prediction: {result['predicted_class']} (Confidence: {result['confidence']:.2%})")
|