Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines345678910101112131415161718192021222324252627282930311332333435363715383940414243444546184748495030 unmodified lines8182835556848586872 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'] # Dùng list cứng nếu không muốn dùng pickleCLASS_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_shape kwargs['input_shape'] = kwargs['batch_shape'][1:] del kwargs['batch_shape'] super().__init__(**kwargs)
# =================================================================
# 2. Tải mô hình# Sử dụng try/except để xử lý lỗi nếu model.h5 quá lớnmodel = Nonetry: # Tắt log TensorFlow khi chạy trên nền tảng tf.get_logger().setLevel('ERROR') # SỬ DỤNG custom_objects KHI TẢI MÔ HÌNH model = tf.keras.models.load_model(MODEL_PATH) model = 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ỗi print(f"Lỗi tải mô hình: {e}") print(f"❌ Lỗi tải mô hình: {e}") model = None
def predict_guava_quality(img_input):30 unmodified lines description="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()# 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 container demo.launch(server_name="0.0.0.0", server_port=7860)app.py+37-6