Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,35 +1,76 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
import torch
|
| 3 |
-
|
|
|
|
| 4 |
from PIL import Image, ImageDraw, ImageFont
|
| 5 |
import numpy as np
|
| 6 |
-
from
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
# Tải model YOLO (detection)
|
| 10 |
-
yolo_model_path = "best.pt"
|
| 11 |
-
yolo_model = YOLO(yolo_model_path)
|
| 12 |
-
|
| 13 |
-
# Tải model classification (.h5)
|
| 14 |
-
classification_model_path = "classification.h5"
|
| 15 |
-
class_model = load_model(classification_model_path)
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
# Ánh xạ tiếng Anh -> tiếng Việt
|
| 21 |
class_mapping = {
|
| 22 |
-
'
|
| 23 |
-
'
|
| 24 |
-
'
|
| 25 |
-
'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
}
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
pil_image = Image.open(image).convert("RGB")
|
| 31 |
|
| 32 |
-
#
|
| 33 |
results = yolo_model.predict(pil_image, conf=conf_threshold, iou=iou_threshold, imgsz=image_size)
|
| 34 |
boxes = results[0].boxes
|
| 35 |
num_boxes = len(boxes)
|
|
@@ -37,51 +78,59 @@ def detect_and_classify(image, image_size, conf_threshold=0.4, iou_threshold=0.5
|
|
| 37 |
if num_boxes == 0:
|
| 38 |
severity = "Tốt"
|
| 39 |
recommendation = "Làn da bạn khá ổn! Tiếp tục duy trì thói quen chăm sóc da."
|
| 40 |
-
return
|
| 41 |
|
| 42 |
-
# Lấy
|
| 43 |
-
xyxy = boxes.xyxy.detach().cpu().numpy().astype(int)
|
| 44 |
confidences = boxes.conf.detach().cpu().numpy()
|
|
|
|
| 45 |
|
| 46 |
# Chuẩn bị vẽ
|
| 47 |
draw = ImageDraw.Draw(pil_image)
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
#
|
| 51 |
classified_results = []
|
| 52 |
-
for i, box in enumerate(xyxy, start=1):
|
| 53 |
-
x1, y1, x2, y2 = box
|
| 54 |
-
crop = pil_image.crop((x1, y1, x2, y2))
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
# Dự đoán loại mụn
|
| 62 |
-
pred = class_model.predict(img_arr)
|
| 63 |
-
class_idx = np.argmax(pred)
|
| 64 |
-
class_name_en = class_labels[class_idx]
|
| 65 |
-
class_name_vn = class_mapping.get(class_name_en, class_name_en) # Lấy tên tiếng Việt
|
| 66 |
-
conf = confidences[i-1]
|
| 67 |
-
|
| 68 |
-
# Vẽ box và label
|
| 69 |
-
text = f"#{i}: {class_name_en} ({class_name_vn}) ({conf:.2f})"
|
| 70 |
-
bbox = draw.textbbox((0,0), text, font=font)
|
| 71 |
-
text_w = bbox[2]-bbox[0]
|
| 72 |
-
text_h = bbox[3]-bbox[1]
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
draw.rectangle([x1, y1, x2, y2], outline="red", width=2)
|
| 75 |
draw.rectangle([x1, y1 - text_h, x1 + text_w, y1], fill="red")
|
| 76 |
-
draw.text((x1, y1 - text_h),
|
| 77 |
|
|
|
|
| 78 |
classified_results.append((i, class_name_en, class_name_vn))
|
| 79 |
|
| 80 |
-
# Đánh giá tình trạng dựa trên số lượng mụn
|
| 81 |
-
if num_boxes >
|
| 82 |
severity = "Nặng"
|
| 83 |
recommendation = "Bạn nên đến gặp bác sĩ da liễu và sử dụng liệu trình trị mụn chuyên sâu."
|
| 84 |
-
elif
|
| 85 |
severity = "Trung bình"
|
| 86 |
recommendation = "Duy trì skincare đều đặn với sữa rửa mặt dịu nhẹ và dưỡng ẩm."
|
| 87 |
else:
|
|
@@ -93,19 +142,19 @@ def detect_and_classify(image, image_size, conf_threshold=0.4, iou_threshold=0.5
|
|
| 93 |
for idx, cname_en, cname_vn in classified_results:
|
| 94 |
acne_types_str += f"Mụn #{idx}: {cname_en} ({cname_vn})\n"
|
| 95 |
|
| 96 |
-
|
| 97 |
-
predicted_image_save_path = "predicted_image.jpg"
|
| 98 |
-
pil_image.save(predicted_image_save_path)
|
| 99 |
-
|
| 100 |
-
return predicted_image_save_path, f"Tình trạng mụn: {severity}", recommendation, acne_types_str
|
| 101 |
|
|
|
|
| 102 |
description_md = """
|
| 103 |
-
## Ứng
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
| 107 |
"""
|
| 108 |
|
|
|
|
| 109 |
inputs = [
|
| 110 |
gr.Image(type="filepath", label="Ảnh Khuôn Mặt"),
|
| 111 |
gr.Slider(minimum=320, maximum=1280, step=32, value=640, label="Kích thước ảnh (Image Size)"),
|
|
@@ -114,18 +163,20 @@ inputs = [
|
|
| 114 |
]
|
| 115 |
|
| 116 |
outputs = [
|
| 117 |
-
gr.Image(type="
|
| 118 |
-
gr.Textbox(label="Tình Trạng Mụn"
|
| 119 |
-
gr.Textbox(label="Khuyến Nghị"
|
| 120 |
-
gr.Textbox(label="Loại Mụn Phát Hiện"
|
| 121 |
]
|
| 122 |
|
|
|
|
| 123 |
app = gr.Interface(
|
| 124 |
fn=detect_and_classify,
|
| 125 |
inputs=inputs,
|
| 126 |
outputs=outputs,
|
| 127 |
-
title="YOLO +
|
| 128 |
description=description_md
|
| 129 |
)
|
| 130 |
|
|
|
|
| 131 |
app.launch(share=True)
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from torchvision import models, transforms
|
| 4 |
from PIL import Image, ImageDraw, ImageFont
|
| 5 |
import numpy as np
|
| 6 |
+
from ultralytics import YOLO
|
| 7 |
+
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# Kiểm tra thiết bị
|
| 10 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 11 |
+
print(f'Sử dụng thiết bị: {device}')
|
| 12 |
+
|
| 13 |
+
# Định nghĩa kiến trúc mô hình phân loại
|
| 14 |
+
class ClassificationModel(nn.Module):
|
| 15 |
+
def __init__(self, num_classes=12):
|
| 16 |
+
super(ClassificationModel, self).__init__()
|
| 17 |
+
self.model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT) # Sử dụng pretrained weights
|
| 18 |
+
num_ftrs = self.model.fc.in_features
|
| 19 |
+
self.model.fc = nn.Linear(num_ftrs, num_classes) # Thay đổi lớp cuối cùng
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
return self.model(x)
|
| 23 |
+
|
| 24 |
+
# Khởi tạo và tải mô hình phân loại
|
| 25 |
+
classification_model = ClassificationModel(num_classes=12)
|
| 26 |
+
classification_model.load_state_dict(torch.load('classification_state_dict.pt', map_location=device))
|
| 27 |
+
classification_model.to(device)
|
| 28 |
+
classification_model.eval()
|
| 29 |
+
|
| 30 |
+
# Tải mô hình YOLO
|
| 31 |
+
yolo_model = YOLO('best.pt') # Đảm bảo rằng 'best.pt' nằm trong thư mục hiện tại
|
| 32 |
+
|
| 33 |
+
# Định nghĩa các lớp mụn
|
| 34 |
+
class_labels = [
|
| 35 |
+
'acne_scars', 'blackhead', 'cystic', 'flat_wart', 'folliculitis',
|
| 36 |
+
'keloid', 'milium', 'papular', 'purulent', 'sebo-crystan-conglo',
|
| 37 |
+
'syringoma', 'whitehead'
|
| 38 |
+
]
|
| 39 |
|
| 40 |
# Ánh xạ tiếng Anh -> tiếng Việt
|
| 41 |
class_mapping = {
|
| 42 |
+
'acne_scars': 'Sẹo mụn',
|
| 43 |
+
'blackhead': 'Mụn đầu đen',
|
| 44 |
+
'cystic': 'Mụn nang',
|
| 45 |
+
'flat_wart': 'Mụn sần phẳng',
|
| 46 |
+
'folliculitis': 'Viêm nang lông',
|
| 47 |
+
'keloid': 'Mụn sẹo uốn',
|
| 48 |
+
'milium': 'Mụn mili',
|
| 49 |
+
'papular': 'Mụn nhỏ',
|
| 50 |
+
'purulent': 'Mụn mủ',
|
| 51 |
+
'sebo-crystan-conglo': 'Mụn bã đen kết tủa',
|
| 52 |
+
'syringoma': 'Mụn nang mồ hôi',
|
| 53 |
+
'whitehead': 'Mụn đầu trắng'
|
| 54 |
}
|
| 55 |
|
| 56 |
+
# Định nghĩa các biến đổi dữ liệu cho mô hình phân loại
|
| 57 |
+
transform = transforms.Compose([
|
| 58 |
+
transforms.Resize((224, 224)),
|
| 59 |
+
transforms.ToTensor(),
|
| 60 |
+
transforms.Normalize([0.485, 0.456, 0.406],
|
| 61 |
+
[0.229, 0.224, 0.225])
|
| 62 |
+
])
|
| 63 |
+
|
| 64 |
+
def detect_and_classify(image, image_size=640, conf_threshold=0.4, iou_threshold=0.5):
|
| 65 |
+
"""
|
| 66 |
+
Hàm này nhận vào một ảnh, phát hiện các vùng mụn bằng YOLO,
|
| 67 |
+
phân loại từng vùng mụn bằng mô hình ResNet18, và trả về ảnh đã được
|
| 68 |
+
annotate cùng với các thông tin liên quan.
|
| 69 |
+
"""
|
| 70 |
+
# Mở ảnh và chuyển đổi sang RGB
|
| 71 |
pil_image = Image.open(image).convert("RGB")
|
| 72 |
|
| 73 |
+
# Dự đoán bằng YOLO
|
| 74 |
results = yolo_model.predict(pil_image, conf=conf_threshold, iou=iou_threshold, imgsz=image_size)
|
| 75 |
boxes = results[0].boxes
|
| 76 |
num_boxes = len(boxes)
|
|
|
|
| 78 |
if num_boxes == 0:
|
| 79 |
severity = "Tốt"
|
| 80 |
recommendation = "Làn da bạn khá ổn! Tiếp tục duy trì thói quen chăm sóc da."
|
| 81 |
+
return pil_image, f"Tình trạng mụn: {severity}", recommendation, "Không phát hiện mụn."
|
| 82 |
|
| 83 |
+
# Lấy thông tin bounding boxes
|
| 84 |
+
xyxy = boxes.xyxy.detach().cpu().numpy().astype(int) # Toạ độ bounding box
|
| 85 |
confidences = boxes.conf.detach().cpu().numpy()
|
| 86 |
+
class_ids = boxes.cls.detach().cpu().numpy().astype(int)
|
| 87 |
|
| 88 |
# Chuẩn bị vẽ
|
| 89 |
draw = ImageDraw.Draw(pil_image)
|
| 90 |
+
try:
|
| 91 |
+
font = ImageFont.truetype("arial.ttf", 15)
|
| 92 |
+
except IOError:
|
| 93 |
+
font = ImageFont.load_default()
|
| 94 |
|
| 95 |
+
# Danh sách để lưu kết quả phân loại
|
| 96 |
classified_results = []
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
for i, (box, cls_id, conf) in enumerate(zip(xyxy, class_ids, confidences), start=1):
|
| 99 |
+
x1, y1, x2, y2 = box
|
| 100 |
+
class_name_en = class_labels[cls_id]
|
| 101 |
+
class_name_vn = class_mapping.get(class_name_en, class_name_en)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
+
# Cắt crop vùng mụn
|
| 104 |
+
crop = pil_image.crop((x1, y1, x2, y2))
|
| 105 |
+
img_transformed = transform(crop).unsqueeze(0).to(device)
|
| 106 |
+
|
| 107 |
+
with torch.no_grad():
|
| 108 |
+
output = classification_model(img_transformed)
|
| 109 |
+
probabilities = torch.softmax(output, dim=1)
|
| 110 |
+
top_prob, top_class = probabilities.topk(1, dim=1)
|
| 111 |
+
top_prob = top_prob.item()
|
| 112 |
+
top_class = top_class.item()
|
| 113 |
+
class_name_en = class_labels[top_class]
|
| 114 |
+
class_name_vn = class_mapping.get(class_name_en, class_name_en)
|
| 115 |
+
|
| 116 |
+
# Vẽ bounding box và nhãn
|
| 117 |
+
label = f"#{i}: {class_name_en} ({class_name_vn}) ({top_prob:.2f})"
|
| 118 |
+
# Sử dụng textbbox thay vì textsize
|
| 119 |
+
text_bbox = draw.textbbox((0, 0), label, font=font)
|
| 120 |
+
text_w = text_bbox[2] - text_bbox[0]
|
| 121 |
+
text_h = text_bbox[3] - text_bbox[1]
|
| 122 |
draw.rectangle([x1, y1, x2, y2], outline="red", width=2)
|
| 123 |
draw.rectangle([x1, y1 - text_h, x1 + text_w, y1], fill="red")
|
| 124 |
+
draw.text((x1, y1 - text_h), label, fill="white", font=font)
|
| 125 |
|
| 126 |
+
# Thêm kết quả phân loại vào danh sách
|
| 127 |
classified_results.append((i, class_name_en, class_name_vn))
|
| 128 |
|
| 129 |
+
# Đánh giá tình trạng da dựa trên số lượng mụn
|
| 130 |
+
if num_boxes > 20:
|
| 131 |
severity = "Nặng"
|
| 132 |
recommendation = "Bạn nên đến gặp bác sĩ da liễu và sử dụng liệu trình trị mụn chuyên sâu."
|
| 133 |
+
elif 10 <= num_boxes <= 20:
|
| 134 |
severity = "Trung bình"
|
| 135 |
recommendation = "Duy trì skincare đều đặn với sữa rửa mặt dịu nhẹ và dưỡng ẩm."
|
| 136 |
else:
|
|
|
|
| 142 |
for idx, cname_en, cname_vn in classified_results:
|
| 143 |
acne_types_str += f"Mụn #{idx}: {cname_en} ({cname_vn})\n"
|
| 144 |
|
| 145 |
+
return pil_image, f"Tình trạng mụn: {severity}", recommendation, acne_types_str
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
# Mô tả ứng dụng
|
| 148 |
description_md = """
|
| 149 |
+
## Ứng Dụng Nhận Diện và Phân Loại Mụn Bằng YOLO và ResNet18
|
| 150 |
+
|
| 151 |
+
1. **Phát hiện mụn:** Sử dụng mô hình YOLO để phát hiện các vùng mụn trên khuôn mặt.
|
| 152 |
+
2. **Phân loại mụn:** Sử dụng mô hình ResNet18 đã được huấn luyện để phân loại từng vùng mụn thành 12 loại khác nhau.
|
| 153 |
+
3. **Hiển thị kết quả:** Ảnh sau khi xử lý sẽ hiển thị các bounding boxes, nhãn tiếng Anh và tiếng Việt của loại mụn, cùng với độ chính xác của mỗi phân loại.
|
| 154 |
+
4. **Đánh giá tình trạng da:** Cung cấp đánh giá tổng quát về tình trạng da và khuyến nghị tương ứng dựa trên số lượng mụn được phát hiện.
|
| 155 |
"""
|
| 156 |
|
| 157 |
+
# Định nghĩa giao diện Gradio
|
| 158 |
inputs = [
|
| 159 |
gr.Image(type="filepath", label="Ảnh Khuôn Mặt"),
|
| 160 |
gr.Slider(minimum=320, maximum=1280, step=32, value=640, label="Kích thước ảnh (Image Size)"),
|
|
|
|
| 163 |
]
|
| 164 |
|
| 165 |
outputs = [
|
| 166 |
+
gr.Image(type="pil", label="Ảnh Sau Khi Xử Lý"),
|
| 167 |
+
gr.Textbox(label="Tình Trạng Mụn"),
|
| 168 |
+
gr.Textbox(label="Khuyến Nghị"),
|
| 169 |
+
gr.Textbox(label="Loại Mụn Phát Hiện")
|
| 170 |
]
|
| 171 |
|
| 172 |
+
# Tạo giao diện Gradio
|
| 173 |
app = gr.Interface(
|
| 174 |
fn=detect_and_classify,
|
| 175 |
inputs=inputs,
|
| 176 |
outputs=outputs,
|
| 177 |
+
title="YOLO + ResNet18 Phát Hiện và Phân Loại Mụn",
|
| 178 |
description=description_md
|
| 179 |
)
|
| 180 |
|
| 181 |
+
# Khởi chạy ứng dụng
|
| 182 |
app.launch(share=True)
|