Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566671 unmodified line697071727374757677787980818283848586878889909192935 unmodified lines991001011021031041052 unmodified linesimport numpy as npfrom tensorflow.keras.applications.efficientnet import preprocess_inputfrom PIL import Imagefrom tensorflow.keras.layers import InputLayer# Import các lớp Augmentation mà mô hình có thể đã lưufrom tensorflow.keras.layers import RandomFlip, RandomRotation, RandomZoom, RandomContrast# 1. Định nghĩa hằng sốMODEL_PATH = "best_model.h5" # Tên file mô hình đã upload (ĐÃ SỬA: Đồng bộ với tên file trên GitHub)IMG_SIZE = (224, 224)CLASS_NAMES = ['bad', 'good', 'very_good']# =================================================================# KHẮC PHỤC LỖI DESERIALIZATION CHO CÁC LỚP AUGMENTATION VÀ INPUT LAYER# Mục đích: Bỏ qua tham số 'batch_shape' và 'data_format' không tương thích.class FixedInputLayer(InputLayer):"""Xử lý lỗi batch_shape."""def __init__(self, **kwargs):if 'batch_shape' in kwargs:kwargs['input_shape'] = kwargs['batch_shape'][1:]del kwargs['batch_shape']super().__init__(**kwargs)def fix_augmentation_layer(LayerClass):"""Tạo lớp cố định để loại bỏ tham số 'data_format'."""class FixedLayer(LayerClass):def __init__(self, **kwargs):if 'data_format' in kwargs:del kwargs['data_format']super().__init__(**kwargs)return FixedLayer# Tạo các lớp cố định cho AugmentationFixedRandomFlip = fix_augmentation_layer(RandomFlip)FixedRandomRotation = fix_augmentation_layer(RandomRotation)FixedRandomZoom = fix_augmentation_layer(RandomZoom)FixedRandomContrast = fix_augmentation_layer(RandomContrast)# =================================================================# 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, # Fix InputLayer'RandomFlip': FixedRandomFlip, # Fix RandomFlip'RandomRotation': FixedRandomRotation, # Fix RandomRotation'RandomZoom': FixedRandomZoom, # Fix RandomZoom'RandomContrast': FixedRandomContrast # Fix RandomContrast# Bổ sung các lớp Augmentation khác nếu cần})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 = None1 unmodified lineif model is None:return "❌ Lỗi: Không thể tải mô hình.", 0.0# Chuyển đổi từ numpy array của Gradio sang PIL Image và resizeimg_pil = Image.fromarray(img_input).convert("RGB")img_resized = img_pil.resize(IMG_SIZE)# Preprocessarr = np.array(img_resized).astype("float32")arr = preprocess_input(arr)arr = np.expand_dims(arr, 0) # Thêm dimension batch size# Dự đoánpreds = model.predict(arr)[0]idx = np.argmax(preds)confidence = preds[idx]label = CLASS_NAMES[idx]# Trả về kết quảreturn f"✅ Kết quả: {label}", float(confidence)# 3. Định nghĩa giao diện Gradiodemo = gr.Interface(fn=predict_guava_quality,inputs=gr.Image(type="numpy", label="Tải ảnh Quả Ổi"),5 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)2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990911 unmodified line939495969798991001011021031041051061071081091101111121131141151161171181191201211225 unmodified lines1281291301311321332 unmodified linesimport numpy as npfrom tensorflow.keras.applications.efficientnet import preprocess_inputfrom PIL import Imagefrom tensorflow.keras.layers import InputLayer, RandomFlip, RandomRotation, RandomZoom, RandomContrastfrom tensorflow.keras.layers import RandomWidth, RandomHeight# 1. Định nghĩa hằng sốMODEL_PATH = "best_model.h5"IMG_SIZE = (224, 224)CLASS_NAMES = ['bad', 'good', 'very_good']# =================================================================# KHẮC PHỤC LỖI TƯƠNG THÍCH PHIÊN BẢN (KERAS 3 -> KERAS 2)# =================================================================# 1. Mock DTypePolicy (Xử lý lỗi: Unknown dtype policy: 'DTypePolicy')class MockDTypePolicy:"""Lớp giả lập để thay thế DTypePolicy của Keras 3.Giúp tránh lỗi deserialization khi chạy trên môi trường cũ."""def __init__(self, **kwargs):pass # Không làm gì cả, chỉ cần tồn tại để không báo lỗi@classmethoddef from_config(cls, config):return cls(**config)def get_config(self):return {}# 2. Xử lý InputLayer (Xử lý lỗi: batch_shape)class FixedInputLayer(InputLayer):def __init__(self, **kwargs):if 'batch_shape' in kwargs:kwargs['input_shape'] = kwargs['batch_shape'][1:]del kwargs['batch_shape']# Xóa dtype nếu nó là dạng dictionary (config của Keras 3)if 'dtype' in kwargs and isinstance(kwargs['dtype'], dict):del kwargs['dtype']super().__init__(**kwargs)# 3. Xử lý Augmentation Layers (Xử lý lỗi: data_format & dtype policy)def fix_augmentation_layer(LayerClass):class FixedLayer(LayerClass):def __init__(self, **kwargs):# Xóa tham số data_format gây lỗiif 'data_format' in kwargs:del kwargs['data_format']# Xóa tham số dtype gây lỗi (DTypePolicy)if 'dtype' in kwargs:del kwargs['dtype']super().__init__(**kwargs)return FixedLayer# 4. Đăng ký tất cả Custom ObjectsCUSTOM_OBJECTS = {'InputLayer': FixedInputLayer,# Đăng ký lớp giả lập DTypePolicy'DTypePolicy': MockDTypePolicy,# Augmentation Layers đã được vá lỗi'RandomFlip': fix_augmentation_layer(RandomFlip),'RandomRotation': fix_augmentation_layer(RandomRotation),'RandomZoom': fix_augmentation_layer(RandomZoom),'RandomContrast': fix_augmentation_layer(RandomContrast),'RandomWidth': fix_augmentation_layer(RandomWidth),'RandomHeight': fix_augmentation_layer(RandomHeight)}# =================================================================# 2. Tải mô hìnhmodel = Nonetry:# Tắt log TensorFlowtf.get_logger().setLevel('ERROR')# Tải mô hình với danh sách custom objects đầy đủmodel = tf.keras.models.load_model(MODEL_PATH,custom_objects=CUSTOM_OBJECTS)print("✅ Mô hình đã được tải thành công.")except Exception as e:print(f"❌ Lỗi tải mô hình: {e}")model = None1 unmodified lineif model is None:return "❌ Lỗi: Không thể tải mô hình.", 0.0if img_input is None:return "❌ Vui lòng tải ảnh lên.", 0.0try:# Chuyển đổi ảnhimg_pil = Image.fromarray(img_input).convert("RGB")img_resized = img_pil.resize(IMG_SIZE)# Preprocessarr = np.array(img_resized).astype("float32")arr = preprocess_input(arr)arr = np.expand_dims(arr, 0)# Dự đoánpreds = model.predict(arr)[0]idx = np.argmax(preds)confidence = preds[idx]label = CLASS_NAMES[idx]return f"✅ Kết quả: {label}", float(confidence)except Exception as e:return f"❌ Lỗi xử lý ảnh: {str(e)}", 0.0# 3. Giao diện Gradiodemo = gr.Interface(fn=predict_guava_quality,inputs=gr.Image(type="numpy", label="Tải ảnh Quả Ổi"),5 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 Appif __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)
app.py+70-42