2024-09-03 13:52:17 +09:00
|
|
|
# ai_service.py
|
|
|
|
|
2024-09-03 15:45:05 +09:00
|
|
|
from ultralytics import YOLO # Ultralytics YOLO 모델을 가져오기
|
2024-09-03 13:52:17 +09:00
|
|
|
import os
|
2024-09-05 10:40:20 +09:00
|
|
|
import torch
|
2024-09-03 13:52:17 +09:00
|
|
|
|
2024-09-25 13:55:44 +09:00
|
|
|
def load_detection_model(project_id:int, model_key:str):
|
|
|
|
default_model_map = {"yolo8": os.path.join("resources","models","yolov8n.pt")}
|
|
|
|
# 디폴트 모델 확인
|
|
|
|
if model_key in default_model_map:
|
|
|
|
model = YOLO(default_model_map[model_key])
|
2024-09-05 11:02:52 +09:00
|
|
|
else:
|
2024-09-25 15:24:14 +09:00
|
|
|
model = load_model(model_path=os.path.join("projects",str(project_id),"models", model_key))
|
2024-09-25 13:55:44 +09:00
|
|
|
|
2024-09-19 16:48:19 +09:00
|
|
|
# Detection 모델인지 검증
|
|
|
|
if model.task != "detect":
|
|
|
|
raise TypeError(f"Invalid model type: {model.task}. Expected a DetectionModel.")
|
2024-09-05 11:02:52 +09:00
|
|
|
return model
|
|
|
|
|
2024-09-25 13:55:44 +09:00
|
|
|
def load_segmentation_model(project_id:int, model_key:str):
|
|
|
|
default_model_map = {"yolo8": os.path.join("resources","models","yolov8n-seg.pt")}
|
|
|
|
# 디폴트 모델 확인
|
|
|
|
if model_key in default_model_map:
|
|
|
|
model = YOLO(default_model_map[model_key])
|
2024-09-05 11:02:52 +09:00
|
|
|
else:
|
2024-09-25 13:55:44 +09:00
|
|
|
model = load_model(model_path=os.path.join("projects",str(project_id),"models",model_key))
|
2024-09-19 16:48:19 +09:00
|
|
|
|
|
|
|
# Segmentation 모델인지 검증
|
|
|
|
if model.task != "segment":
|
|
|
|
raise TypeError(f"Invalid model type: {model.task}. Expected a SegmentationModel.")
|
2024-09-18 01:08:40 +09:00
|
|
|
return model
|
|
|
|
|
|
|
|
def load_model(model_path: str):
|
|
|
|
if not os.path.exists(model_path):
|
|
|
|
raise FileNotFoundError(f"Model file not found at path: {model_path}")
|
|
|
|
|
|
|
|
try:
|
|
|
|
model = YOLO(model_path)
|
|
|
|
if (torch.cuda.is_available()):
|
|
|
|
model.to("cuda")
|
2024-09-19 16:48:19 +09:00
|
|
|
print("gpu 활성화")
|
2024-09-18 01:08:40 +09:00
|
|
|
else:
|
|
|
|
model.to("cpu")
|
|
|
|
return model
|
|
|
|
except:
|
2024-09-19 16:48:19 +09:00
|
|
|
raise Exception("YOLO model conversion failed: Unsupported architecture or invalid configuration.")
|