viugialai's picture
update
629c088
Raw History Blame Contribute Delete
8.22 kB
import os
# Ẩn các cảnh báo TensorFlow
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.efficientnet import preprocess_input
import numpy as np
import gradio as gr
import cv2
# --- CẤU HÌNH HỆ THỐNG ---
MODEL_PATH = 'EfficientNetB0_flower_recognition_dl_model_fine_tuned.h5'
IMG_SIZE = (224, 224)
# Tải mô hình
try:
model = tf.keras.models.load_model(MODEL_PATH)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
print(f"✅ Botanical AI Engine Ready!")
except Exception as e:
print(f"❌ Error: {e}")
exit()
# Danh sách lớp hoa
DATA_DIR = 'flower_classification/flowers'
if os.path.exists(DATA_DIR):
class_names = sorted([d for d in os.listdir(DATA_DIR) if os.path.isdir(os.path.join(DATA_DIR, d))])
else:
class_names = ['daisy', 'dandelion', 'rose', 'sunflower', 'tulip']
# Lấy tên lớp Conv cuối cho Grad-CAM
try:
with open('last_conv_layer_name.txt', 'r') as f:
LAST_CONV_LAYER_NAME = f.read().strip()
except:
LAST_CONV_LAYER_NAME = 'top_activation'
# --- HÀM XỬ LÝ GRAD-CAM ---
def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
grad_model = tf.keras.models.Model([model.inputs], [model.get_layer(last_conv_layer_name).output, model.output])
with tf.GradientTape() as tape:
last_conv_layer_output, preds = grad_model(img_array)
if pred_index is None: pred_index = tf.argmax(preds[0])
class_channel = preds[:, pred_index]
grads = tape.gradient(class_channel, last_conv_layer_output)
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
last_conv_layer_output = last_conv_layer_output[0]
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
heatmap = tf.squeeze(heatmap)
heatmap = tf.maximum(heatmap, 0) / (tf.math.reduce_max(heatmap) + 1e-10)
return heatmap.numpy()
def display_gradcam(img, heatmap, alpha=0.5):
img_np = np.array(img)
img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
img_np = cv2.resize(img_np, IMG_SIZE)
heatmap = np.uint8(255 * heatmap)
heatmap = cv2.resize(heatmap, (img_np.shape[1], img_np.shape[0]))
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
superimposed_img = heatmap * alpha + img_np
return cv2.cvtColor(np.uint8(superimposed_img), cv2.COLOR_BGR2RGB)
# --- HÀM DỰ ĐOÁN CHÍNH ---
def predict_flower(img):
if img is None: return "### 🍃 Đang chờ bạn tải ảnh hoa lên...", None, None
img_resized = img.resize(IMG_SIZE)
img_array = image.img_to_array(img_resized)
img_array = np.expand_dims(img_array, axis=0)
processed_img = preprocess_input(img_array)
predictions = model.predict(processed_img, verbose=0)[0]
results = {class_names[i]: float(predictions[i]) for i in range(len(class_names))}
top_idx = np.argmax(predictions)
top_conf = predictions[top_idx] * 100
heatmap = make_gradcam_heatmap(processed_img, model, LAST_CONV_LAYER_NAME, top_idx)
gradcam_img = display_gradcam(img, heatmap)
if top_conf < 60.0:
msg = f"## ⚠️ Lưu ý nhẹ nhàng\n\nHệ thống thấy ảnh này có vẻ không giống các loại hoa đã học lắm.\n\nPhân loại gần nhất: **{class_names[top_idx].upper()}** ({top_conf:.2f}%)"
else:
msg = f"## 🌺 Kết quả: Hoa {class_names[top_idx].upper()}\n\nĐộ tin cậy: **{top_conf:.2f}%**"
return msg, results, gradcam_img
# --- TẠO DANH SÁCH EXAMPLES TỰ ĐỘNG ---
example_list = []
if os.path.exists(DATA_DIR):
for flower_type in class_names:
folder_path = os.path.join(DATA_DIR, flower_type)
if os.path.exists(folder_path):
files = [f for f in os.listdir(folder_path) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
if files:
# Lấy ảnh đầu tiên của mỗi loại làm ví dụ
example_list.append([os.path.join(folder_path, files[0])])
# --- GIAO DIỆN GRADIO (BOTANICAL SOFT STYLE) ---
custom_css = """
body { background-color: #fdfcf0 !important; }
.main-container { background: white; border-radius: 30px; padding: 35px; box-shadow: 0 10px 30px rgba(45, 90, 39, 0.08); border: 1px solid #e8f5e9; }
.header-area { text-align: center; margin-bottom: 35px; }
.header-area h1 { color: #2d5a27; font-weight: 700; font-size: 2.8rem; font-family: 'Georgia', serif; margin-bottom: 5px; }
.header-area p { color: #6b8e23; font-size: 1.1rem; font-style: italic; }
.predict-btn { background: #81c784 !important; color: white !important; border: none !important; font-weight: 600 !important; border-radius: 50px !important; font-size: 1.1rem !important; transition: all 0.3s ease !important; }
.predict-btn:hover { background: #66bb6a !important; transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102, 187, 106, 0.3); }
.result-card { background: #f1f8e9; border-radius: 20px; padding: 20px; border: 1px solid #dcedc8; margin-bottom: 20px; color: #33691e; }
label span { color: #2d5a27 !important; font-weight: 600 !important; }
footer { display: none !important; }
"""
with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="green", font=["Quicksand", "sans-serif"])) as demo:
with gr.Column(elem_classes="header-area"):
gr.Markdown("# 🌸 Khu Vườn Nhận Diện Hoa")
gr.Markdown("Khám phá vẻ đẹp của thiên nhiên qua lăng kính AI nhẹ nhàng")
with gr.Row(elem_classes="main-container"):
# Cột trái: Tải ảnh
with gr.Column(scale=1):
gr.Markdown("### 📸 Tải ảnh hoa lên đây")
input_img = gr.Image(type="pil", label="Chọn một tấm ảnh thật đẹp nhé", height=400)
# PHẦN EXAMPLES (ẢNH MẪU)
if example_list:
gr.Examples(
examples=example_list,
inputs=input_img,
label="Hoặc chọn một ảnh mẫu từ khu vườn:"
)
with gr.Row():
clear_btn = gr.Button("LÀM MỚI", variant="secondary")
btn = gr.Button("NHẬN DIỆN NGAY", variant="primary", elem_classes="predict-btn")
gr.Markdown("---")
gr.Markdown("### 🌿 Thông tin hệ thống")
gr.Markdown("✨ **Mô hình:** EfficientNet-B0 (Chính xác & Nhẹ nhàng)\n"
"✨ **Công nghệ:** Grad-CAM (Giải thích vùng tập trung)\n"
"✨ **Đối tượng:** 5 loại hoa phổ biến")
# Cột phải: Kết quả
with gr.Column(scale=1):
gr.Markdown("### 🏁 Kết quả từ khu vườn")
with gr.Column(elem_classes="result-card"):
output_text = gr.Markdown("### 🍃 Đang chờ bạn...")
output_label = gr.Label(num_top_classes=3, label="Độ tin cậy chi tiết")
gr.Markdown("### 👁️ Vùng AI đang ngắm nhìn")
with gr.Column(elem_classes="result-card"):
gradcam_output = gr.Image(label="Bản đồ nhiệt tập trung", height=300)
gr.Markdown("💡 *Vùng màu đỏ là nơi AI đang 'ngắm nhìn' kỹ nhất để nhận ra bông hoa của bạn.*")
gr.Markdown("### 💡 Giải thích kỹ thuật:")
gr.Markdown("- **Độ tin cậy > 60%:** Hệ thống tự tin đây là hoa đã học.\n"
"- **Độ tin cậy < 60%:** Hệ thống cảnh báo ảnh lạ hoặc mờ.\n"
"- **Grad-CAM:** Trực quan hóa vùng quan trọng nhất AI dùng để dự đoán.")
# Xử lý sự kiện
btn.click(fn=predict_flower, inputs=input_img, outputs=[output_text, output_label, gradcam_output])
input_img.upload(fn=predict_flower, inputs=input_img, outputs=[output_text, output_label, gradcam_output])
clear_btn.click(lambda: (None, None, None), None, [input_img, output_label, gradcam_output])
if __name__ == "__main__":
demo.launch(share=True)