Spaces:
Runtime error
Runtime error
Download sequential-algo/predict.py from NexNoor/PoultryShieldAI: direct link, hf CLI and curl.
- Browser
- Download file 1.76 kB
-
https://huggingface.co/spaces/NexNoor/PoultryShieldAI/resolve/main/sequential-algo/predict.py
- Command line
-
hf download hf://spaces/NexNoor/PoultryShieldAI/sequential-algo/predict.py
-
curl -L -o predict.py https://huggingface.co/spaces/NexNoor/PoultryShieldAI/resolve/main/sequential-algo/predict.py
1.76 kB
| import os | |
| import numpy as np | |
| import tensorflow as tf | |
| class_names= ['cocci', 'healthy', 'ncd', 'salmo'] | |
| def predict(): | |
| prediction = [] | |
| image_files = load_test_data() | |
| # Iterate over the image files | |
| for i, image_file in enumerate(image_files): | |
| # Load and preprocess the image | |
| image_path = os.path.join(get_upload_dir(), image_file) | |
| img = tf.keras.preprocessing.image.load_img(image_path, target_size=(256, 256)) | |
| img_array = tf.keras.preprocessing.image.img_to_array(img) | |
| img_array = tf.expand_dims(img_array, 0) # Create a batch axis | |
| # Make predictions | |
| saved_model=load_model(get_model_path()) | |
| predictions = saved_model.predict(img_array) | |
| predicted_label = class_names[np.argmax(predictions[0])] | |
| accuracy = round(np.max(predictions[0]) * 100, 2) | |
| prediction.append({"label": predicted_label, "accuracy": accuracy}) | |
| return prediction | |
| def load_test_data(): | |
| upload_dir = os.path.abspath(get_upload_dir()) | |
| image_files = [f for f in os.listdir(upload_dir) if f.endswith(('.jpg', '.png', '.jpeg'))] | |
| return image_files or [] | |
| def load_model(model_path): | |
| try: | |
| return tf.keras.models.load_model(model_path) | |
| except Exception as e: | |
| raise ValueError(f"Failed to load model from '{model_path}': {str(e)}") | |
| def get_pwd(): | |
| # Define the path relative to the script's directory | |
| return os.path.dirname(os.path.abspath(__file__)) | |
| def get_upload_dir(): | |
| upload_dir = os.path.join(get_pwd(), '..', 'uploads') | |
| # Get the absolute path to the uploads directory | |
| return os.path.abspath(upload_dir) | |
| def get_model_path(): | |
| current_dir = get_pwd() | |
| return os.path.join(current_dir, 'model', 'sequential-model.keras') | |