Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines345678910111213141516171819202130 unmodified lines52535455562 unmodified linesimport numpy as npfrom tensorflow.keras.applications.efficientnet import preprocess_inputfrom PIL import Image# 1. Định nghĩa hằng sốMODEL_PATH = "best_model.h5" # Tên file mô hình đã uploadIMG_SIZE = (224, 224)CLASS_NAMES = ['bad', 'good', 'very_good'] # Dùng list cứng nếu không muốn dùng pickle# 2. Tải mô hình# Sử dụng try/except để xử lý lỗi nếu model.h5 quá lớntry:model = tf.keras.models.load_model(MODEL_PATH)except Exception as e:# Nếu mô hình không tải được (ví dụ: lỗi cấu trúc), in ra lỗiprint(f"Lỗi tải mô hình: {e}")model = Nonedef predict_guava_quality(img_input):30 unmodified linesdescription="Tải lên ảnh quả ổi để phân loại thành: Hàng xuất khẩu (very_good), Hàng nội địa (good), hoặc Loại bỏ (bad).")# 4. Chạy Gradio App (Hugging Face Spaces sẽ tự gọi file này)# demo.launch()2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495030 unmodified lines818283848586872 unmodified linesimport numpy as npfrom tensorflow.keras.applications.efficientnet import preprocess_inputfrom PIL import Imagefrom tensorflow.keras.layers import InputLayer# 1. Định nghĩa hằng sốMODEL_PATH = "best_model.h5" # Tên file mô hình đã uploadIMG_SIZE = (224, 224)CLASS_NAMES = ['bad', 'good', 'very_good']# =================================================================# KHẮC PHỤC LỖI DESERIALIZATION (batch_shape)# Nếu mô hình được lưu bằng Keras cũ, ta cần định nghĩa lại InputLayer# để chấp nhận tham số batch_shape khi tải.class FixedInputLayer(InputLayer):"""Tạo InputLayer cố định để xử lý lỗi "Unrecognized keyword arguments: ['batch_shape']"khi tải mô hình đã lưu bằng TF/Keras cũ hơn."""def __init__(self, **kwargs):if 'batch_shape' in kwargs:# Chuyển batch_shape thành input_shapekwargs['input_shape'] = kwargs['batch_shape'][1:]del kwargs['batch_shape']super().__init__(**kwargs)# =================================================================# 2. Tải mô hìnhmodel = Nonetry:# Tắt log TensorFlow khi chạy trên nền tảngtf.get_logger().setLevel('ERROR')# SỬ DỤNG custom_objects KHI TẢI MÔ HÌNHmodel = tf.keras.models.load_model(MODEL_PATH,custom_objects={'InputLayer': FixedInputLayer # Sử dụng lớp FixedInputLayer để thay thế})print("✅ Mô hình đã được tải thành công.")except Exception as e:# Nếu mô hình không tải được (ví dụ: lỗi cấu trúc), in ra lỗiprint(f"❌ Lỗi tải mô hình: {e}")model = Nonedef predict_guava_quality(img_input):30 unmodified linesdescription="Tải lên ảnh quả ổi để phân loại thành: Hàng xuất khẩu (very_good), Hàng nội địa (good), hoặc Loại bỏ (bad).")# 4. Chạy Gradio App (Hugging Face Spaces sẽ tự chạy file này)if __name__ == "__main__":# Server port và name cần thiết để Gradio chạy trong môi trường containerdemo.launch(server_name="0.0.0.0", server_port=7860)
app.py+37-6