Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import numpy as np
|
| 4 |
+
from tensorflow.keras.applications.efficientnet import preprocess_input
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
# 1. Định nghĩa hằng số
|
| 8 |
+
MODEL_PATH = "best_model.h5" # Tên file mô hình đã upload
|
| 9 |
+
IMG_SIZE = (224, 224)
|
| 10 |
+
CLASS_NAMES = ['bad', 'good', 'very_good'] # Dùng list cứng nếu không muốn dùng pickle
|
| 11 |
+
|
| 12 |
+
# 2. Tải mô hình
|
| 13 |
+
# Sử dụng try/except để xử lý lỗi nếu model.h5 quá lớn
|
| 14 |
+
try:
|
| 15 |
+
model = tf.keras.models.load_model(MODEL_PATH)
|
| 16 |
+
except Exception as e:
|
| 17 |
+
# Nếu mô hình không tải được (ví dụ: lỗi cấu trúc), in ra lỗi
|
| 18 |
+
print(f"Lỗi tải mô hình: {e}")
|
| 19 |
+
model = None
|
| 20 |
+
|
| 21 |
+
def predict_guava_quality(img_input):
|
| 22 |
+
if model is None:
|
| 23 |
+
return "❌ Lỗi: Không thể tải mô hình.", 0.0
|
| 24 |
+
|
| 25 |
+
# Chuyển đổi từ numpy array của Gradio sang PIL Image và resize
|
| 26 |
+
img_pil = Image.fromarray(img_input).convert("RGB")
|
| 27 |
+
img_resized = img_pil.resize(IMG_SIZE)
|
| 28 |
+
|
| 29 |
+
# Preprocess
|
| 30 |
+
arr = np.array(img_resized).astype("float32")
|
| 31 |
+
arr = preprocess_input(arr)
|
| 32 |
+
arr = np.expand_dims(arr, 0) # Thêm dimension batch size
|
| 33 |
+
|
| 34 |
+
# Dự đoán
|
| 35 |
+
preds = model.predict(arr)[0]
|
| 36 |
+
idx = np.argmax(preds)
|
| 37 |
+
confidence = preds[idx]
|
| 38 |
+
label = CLASS_NAMES[idx]
|
| 39 |
+
|
| 40 |
+
# Trả về kết quả
|
| 41 |
+
return f"✅ Kết quả: {label}", float(confidence)
|
| 42 |
+
|
| 43 |
+
# 3. Định nghĩa giao diện Gradio
|
| 44 |
+
demo = gr.Interface(
|
| 45 |
+
fn=predict_guava_quality,
|
| 46 |
+
inputs=gr.Image(type="numpy", label="Tải ảnh Quả Ổi"),
|
| 47 |
+
outputs=[
|
| 48 |
+
gr.Textbox(label="Dự đoán"),
|
| 49 |
+
gr.Number(label="Độ tin cậy (%)", precision=2)
|
| 50 |
+
],
|
| 51 |
+
title="Phân loại Chất lượng Quả Ổi (EfficientNetB0)",
|
| 52 |
+
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)."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# 4. Chạy Gradio App (Hugging Face Spaces sẽ tự gọi file này)
|
| 56 |
+
# demo.launch()
|