Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines3456786789111011121314161715161718192021222324252627282930313233343520363738394041424344454628474849505152535455565758593637383940606162636465666768697071727374757677784779808150828384535455565758596085868788648990911 unmodified line93949596979899727374757677787910010110210310410510610710881828384851091101111121131148788115116117118901191201211225 unmodified lines1281291301021311321041332 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, RandomContrastfrom 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" # Tên file mô hình đã upload (ĐÃ SỬA: Đồng bộ với tên file trên GitHub)MODEL_PATH = "best_model.h5"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.# 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 @classmethod def 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): """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'] # 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): """Tạo lớp cố định để loại bỏ tham số 'data_format'.""" class FixedLayer(LayerClass): def __init__(self, **kwargs): # Xóa tham số data_format gây lỗi if '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
# 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)# 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 TensorFlow khi chạy trên nền tảng # Tắt log TensorFlow tf.get_logger().setLevel('ERROR') # SỬ DỤNG custom_objects KHI TẢI MÔ HÌNH # Tải mô hình với danh sách custom objects đầy đủ model = 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 } custom_objects=CUSTOM_OBJECTS ) 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}") model = None
1 unmodified line if model is None: return "❌ Lỗi: Không thể tải mô hình.", 0.0
if img_input is None: return "❌ Vui lòng tải ảnh lên.", 0.0
try: # Chuyển đổi từ numpy array của Gradio sang PIL Image và resize img_pil = Image.fromarray(img_input).convert("RGB") img_resized = img_pil.resize(IMG_SIZE) # Preprocess arr = np.array(img_resized).astype("float32") arr = preprocess_input(arr) arr = np.expand_dims(arr, 0) # Thêm dimension batch size # Chuyển đổi ảnh img_pil = Image.fromarray(img_input).convert("RGB") img_resized = img_pil.resize(IMG_SIZE) # Preprocess arr = np.array(img_resized).astype("float32") arr = preprocess_input(arr) arr = np.expand_dims(arr, 0)
# Dự đoán preds = model.predict(arr)[0] idx = np.argmax(preds) confidence = preds[idx] label = CLASS_NAMES[idx] # Dự đoán preds = 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) return f"✅ Kết quả: {label}", float(confidence) except Exception as e: return f"❌ Lỗi xử lý ảnh: {str(e)}", 0.0
# 3. Định nghĩa giao diện Gradio# 3. Giao diện Gradiodemo = gr.Interface( fn=predict_guava_quality, inputs=gr.Image(type="numpy", label="Tải ảnh Quả Ổi"),5 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ự chạy file này)# 4. Chạy Appif __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+70-42