Compare commits
125 Commits
ff478452a6
...
feat/train
| Author | SHA1 | Date | |
|---|---|---|---|
| 86016da5f4 | |||
| 16f656ae96 | |||
| 96dd76101b | |||
| 9b1bd16d1b | |||
| a94e8e94a0 | |||
| 10319ce0a6 | |||
| fcc5d7a437 | |||
| 0ab0fdc43e | |||
| ad750f0f06 | |||
| 5fc93b64b6 | |||
| cd14e6e3aa | |||
| 0447dd80ed | |||
| 5f4640ea60 | |||
| b85f920f40 | |||
| e4851b1153 | |||
| b73aef5cf8 | |||
| 72c8f6a047 | |||
| c7a49ea4ea | |||
| fbef92af55 | |||
| 154db0ac27 | |||
| 9835170cd7 | |||
| fd51f21ba6 | |||
| 776622e0a2 | |||
|
|
4d2d7a9ad1 | ||
|
|
532fbdbee4 | ||
|
|
a2e5bf4e10 | ||
|
|
de2a2e2c35 | ||
|
|
f75ec77ccf | ||
|
|
9fa549285f | ||
|
|
4fbfb31e97 | ||
| 419b3ccdfc | |||
| afb3f57ef6 | |||
| edff3b0ef8 | |||
| 47e93f0d57 | |||
| 449e1dc142 | |||
| ecca537670 | |||
| ca080bf77b | |||
| e64b1f15ba | |||
| 7db77226b7 | |||
| ce404924fd | |||
| bb48cb8610 | |||
| 8b7ff0162d | |||
|
|
02954aa439 | ||
|
|
e3cf7b8909 | ||
| 59d39a79c3 | |||
|
|
501b4a6f51 | ||
|
|
be3e32a87a | ||
| 61d28c4ce3 | |||
| 593db69245 | |||
| 5651fd7819 | |||
| 71a8b45097 | |||
| 219e17e8ba | |||
| a9260c17f4 | |||
| b546e053b6 | |||
| a66b25dda5 | |||
| bc67753b99 | |||
| 5dc817ecad | |||
| 8043e1a41a | |||
| 98e3c35d9a | |||
| d48e96ba82 | |||
| 3da4b73c59 | |||
| 01a1211e55 | |||
| c0532f230c | |||
| a0f4d0b8e2 | |||
| 38906a5795 | |||
| 051082665d | |||
| 13d9d9176b | |||
| 62398846d3 | |||
| 260569225c | |||
|
|
acdffd99ec | ||
| bd6fe924de | |||
| d7458e3c8b | |||
| 92492ca879 | |||
| a5d79b2504 | |||
| b8c53aae64 | |||
| 348d3d0052 | |||
| b85ead36b4 | |||
| e77eae8f8b | |||
| 570952df7e | |||
| 26d34d88eb | |||
| 46a5d4c2d3 | |||
| 91f022889b | |||
|
|
f00296cf2c | ||
| f98f6cb038 | |||
| d1593e57c3 | |||
| 732dccf2e4 | |||
| f6cd553af8 | |||
| 618dbe4047 | |||
| 5546e8ef89 | |||
| b952ec7b47 | |||
| e93f533c59 | |||
| a5267d8065 | |||
| 71d9835b03 | |||
| 39f39a4f0c | |||
| 1df7142544 | |||
| d99e18b38c | |||
| d6aa612494 | |||
| 8def356323 | |||
|
|
6cc9b54ba9 | ||
|
|
50ad05b53b | ||
|
|
822dbb252f | ||
|
|
5e04df73af | ||
| 650b1695f0 | |||
| 960e4215e0 | |||
| 08a220db4d | |||
| a9b49faa6c | |||
| b760e9874c | |||
| 8698bf61d1 | |||
| 680e137284 | |||
| f4a81a34d6 | |||
| 479ad710e0 | |||
| 3cb9840248 | |||
| fc9543f195 | |||
| 73d0e03b08 | |||
| 50c965cb79 | |||
|
|
abca9467d8 | ||
|
|
4ed03f6e94 | ||
| 04eddfce54 | |||
| f49b7cc850 | |||
| 888c0e314b | |||
| 6c043b0031 | |||
| 531da09c5f | |||
| 4da2a1f0d7 | |||
| 50b3f1ba62 | |||
| f1f88c83e1 |
230
deploy/check-nginx.sh
Executable file
230
deploy/check-nginx.sh
Executable file
@@ -0,0 +1,230 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
NGINX_DIR="/data/training/nginx"
|
||||||
|
PASS=0
|
||||||
|
FAIL=0
|
||||||
|
|
||||||
|
# docker compose v1/v2 자동 감지
|
||||||
|
if command -v docker-compose &>/dev/null; then
|
||||||
|
DOCKER_COMPOSE="docker-compose"
|
||||||
|
elif docker compose version &>/dev/null 2>&1; then
|
||||||
|
DOCKER_COMPOSE="docker compose"
|
||||||
|
else
|
||||||
|
DOCKER_COMPOSE=""
|
||||||
|
fi
|
||||||
|
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
RED='\033[0;31m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
NC='\033[0m'
|
||||||
|
|
||||||
|
ok() { echo -e "${GREEN}[OK]${NC} $1"; ((PASS++)); }
|
||||||
|
fail() { echo -e "${RED}[FAIL]${NC} $1"; ((FAIL++)); }
|
||||||
|
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
|
||||||
|
section() { echo ""; echo "=== $1 ==="; }
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "디렉토리 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
for dir in \
|
||||||
|
/data/training/request \
|
||||||
|
/data/training/request/tmp \
|
||||||
|
/data/training/response \
|
||||||
|
/data/training/response/v6-cls-checkpoints \
|
||||||
|
/data/training/tmp \
|
||||||
|
"$NGINX_DIR" \
|
||||||
|
"$NGINX_DIR/ssl" \
|
||||||
|
"$NGINX_DIR/logs"; do
|
||||||
|
if [ -d "$dir" ]; then
|
||||||
|
ok "$dir"
|
||||||
|
else
|
||||||
|
fail "$dir 없음"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "nginx 파일 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
for f in \
|
||||||
|
"$NGINX_DIR/nginx.conf" \
|
||||||
|
"$NGINX_DIR/docker-compose-nginx.yml" \
|
||||||
|
"$NGINX_DIR/ssl/train-kamco.com.crt" \
|
||||||
|
"$NGINX_DIR/ssl/train-kamco.com.key" \
|
||||||
|
"$NGINX_DIR/ssl/openssl.cnf"; do
|
||||||
|
if [ -f "$f" ]; then
|
||||||
|
ok "$f"
|
||||||
|
else
|
||||||
|
fail "$f 없음"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "파일 권한 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
SSL_DIR_PERM=$(stat -c "%a" "$NGINX_DIR/ssl" 2>/dev/null)
|
||||||
|
KEY_PERM=$(stat -c "%a" "$NGINX_DIR/ssl/train-kamco.com.key" 2>/dev/null)
|
||||||
|
CRT_PERM=$(stat -c "%a" "$NGINX_DIR/ssl/train-kamco.com.crt" 2>/dev/null)
|
||||||
|
|
||||||
|
[ "$SSL_DIR_PERM" = "700" ] && ok "ssl/ 권한 700" || fail "ssl/ 권한 오류 (현재: $SSL_DIR_PERM, 기대: 700)"
|
||||||
|
[ "$KEY_PERM" = "600" ] && ok "train-kamco.com.key 권한 600" || fail "key 권한 오류 (현재: $KEY_PERM, 기대: 600)"
|
||||||
|
[ "$CRT_PERM" = "644" ] && ok "train-kamco.com.crt 권한 644" || fail "crt 권한 오류 (현재: $CRT_PERM, 기대: 644)"
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "소유권 확인 (kcomu:kcomu)"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
OWNER=$(stat -c "%U:%G" /data/training 2>/dev/null)
|
||||||
|
[ "$OWNER" = "kcomu:kcomu" ] && ok "/data/training 소유권 kcomu:kcomu" || fail "/data/training 소유권 오류 (현재: $OWNER)"
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "SSL 인증서 유효성"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
if command -v openssl &>/dev/null && [ -f "$NGINX_DIR/ssl/train-kamco.com.crt" ]; then
|
||||||
|
EXPIRY=$(openssl x509 -in "$NGINX_DIR/ssl/train-kamco.com.crt" -noout -enddate 2>/dev/null | cut -d= -f2)
|
||||||
|
EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null)
|
||||||
|
NOW_EPOCH=$(date +%s)
|
||||||
|
if [ "$EXPIRY_EPOCH" -gt "$NOW_EPOCH" ]; then
|
||||||
|
ok "인증서 유효 (만료: $EXPIRY)"
|
||||||
|
else
|
||||||
|
fail "인증서 만료됨 (만료: $EXPIRY)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
SAN=$(openssl x509 -in "$NGINX_DIR/ssl/train-kamco.com.crt" -noout -text 2>/dev/null | grep -A1 "Subject Alternative Name" | tail -1)
|
||||||
|
echo " SAN: $SAN"
|
||||||
|
else
|
||||||
|
warn "openssl 없음 또는 인증서 파일 없음 - 인증서 검증 스킵"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "Docker 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
|
||||||
|
ok "Docker 실행 중"
|
||||||
|
|
||||||
|
# Docker network
|
||||||
|
if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
|
||||||
|
ok "Docker network kamco-cds 존재"
|
||||||
|
else
|
||||||
|
fail "Docker network kamco-cds 없음 (setup.sh 재실행 필요)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# nginx 컨테이너 상태
|
||||||
|
CONTAINER_STATUS=$(docker inspect --format '{{.State.Status}}' kamco-train-nginx 2>/dev/null)
|
||||||
|
if [ "$CONTAINER_STATUS" = "running" ]; then
|
||||||
|
ok "kamco-train-nginx 컨테이너 실행 중"
|
||||||
|
elif [ -z "$CONTAINER_STATUS" ]; then
|
||||||
|
warn "kamco-train-nginx 컨테이너 없음 (아직 미실행)"
|
||||||
|
else
|
||||||
|
fail "kamco-train-nginx 컨테이너 상태: $CONTAINER_STATUS"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
fail "Docker 미실행 또는 설치 안 됨"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "nginx 설정 문법 검사"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
|
||||||
|
echo " docker run으로 nginx -t 실행 중..."
|
||||||
|
# kamco-cds 네트워크가 있으면 연결 (upstream DNS 조회 가능)
|
||||||
|
NETWORK_OPT=""
|
||||||
|
if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
|
||||||
|
NETWORK_OPT="--network kamco-cds"
|
||||||
|
fi
|
||||||
|
if docker run --rm $NETWORK_OPT \
|
||||||
|
-v "$NGINX_DIR/nginx.conf:/etc/nginx/nginx.conf:ro,Z" \
|
||||||
|
-v "$NGINX_DIR/ssl:/etc/nginx/ssl:ro,Z" \
|
||||||
|
nginx:alpine nginx -t 2>&1; then
|
||||||
|
ok "nginx 설정 문법 OK"
|
||||||
|
else
|
||||||
|
fail "nginx 설정 문법 오류"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
warn "Docker 없음 - nginx 문법 검사 스킵"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "/etc/hosts 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
for domain in api.train-kamco.com train-kamco.com; do
|
||||||
|
HOSTS_LINE=$(grep "$domain" /etc/hosts | grep -v "^#" | head -1)
|
||||||
|
if [ -n "$HOSTS_LINE" ]; then
|
||||||
|
ok "$domain 등록됨 → $HOSTS_LINE"
|
||||||
|
else
|
||||||
|
fail "$domain /etc/hosts 미등록"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "도메인 해석 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
for domain in api.train-kamco.com train-kamco.com; do
|
||||||
|
RESOLVED=$(getent hosts "$domain" 2>/dev/null | awk '{print $1}' | head -1)
|
||||||
|
if [ -n "$RESOLVED" ]; then
|
||||||
|
ok "$domain → $RESOLVED"
|
||||||
|
else
|
||||||
|
fail "$domain 해석 실패 (DNS 또는 hosts 문제)"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "포트 연결 확인 (80 / 443)"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
for port in 80 443; do
|
||||||
|
if command -v nc &>/dev/null; then
|
||||||
|
if nc -z -w3 api.train-kamco.com "$port" 2>/dev/null; then
|
||||||
|
ok "api.train-kamco.com:$port 열림"
|
||||||
|
else
|
||||||
|
warn "api.train-kamco.com:$port 닫힘 (nginx 미실행일 수 있음)"
|
||||||
|
fi
|
||||||
|
elif command -v curl &>/dev/null; then
|
||||||
|
HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" --connect-timeout 3 \
|
||||||
|
"$([ "$port" = "443" ] && echo https || echo http)://api.train-kamco.com/" 2>/dev/null)
|
||||||
|
if [ -n "$HTTP_CODE" ] && [ "$HTTP_CODE" != "000" ]; then
|
||||||
|
ok "api.train-kamco.com:$port 응답 (HTTP $HTTP_CODE)"
|
||||||
|
else
|
||||||
|
warn "api.train-kamco.com:$port 응답 없음 (nginx 미실행일 수 있음)"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
warn "nc/curl 없음 - 포트 확인 스킵"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "HTTPS 헬스체크"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
if command -v curl &>/dev/null; then
|
||||||
|
for url in \
|
||||||
|
"https://api.train-kamco.com/monitor/health" \
|
||||||
|
"https://train-kamco.com/monitor/health"; do
|
||||||
|
HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" --connect-timeout 5 "$url" 2>/dev/null)
|
||||||
|
if [ "$HTTP_CODE" = "200" ]; then
|
||||||
|
ok "$url → HTTP $HTTP_CODE"
|
||||||
|
elif [ "$HTTP_CODE" = "000" ] || [ -z "$HTTP_CODE" ]; then
|
||||||
|
warn "$url → 응답 없음 (nginx 미실행일 수 있음)"
|
||||||
|
else
|
||||||
|
warn "$url → HTTP $HTTP_CODE"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
else
|
||||||
|
warn "curl 없음 - HTTPS 헬스체크 스킵"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "결과 요약"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
echo ""
|
||||||
|
echo -e " ${GREEN}PASS: $PASS${NC} / ${RED}FAIL: $FAIL${NC}"
|
||||||
|
echo ""
|
||||||
|
if [ $FAIL -eq 0 ]; then
|
||||||
|
echo -e "${GREEN}모든 체크 통과. nginx 실행 준비 완료.${NC}"
|
||||||
|
if [ -n "$DOCKER_COMPOSE" ]; then
|
||||||
|
echo " cd $NGINX_DIR && $DOCKER_COMPOSE -f docker-compose-nginx.yml up -d"
|
||||||
|
else
|
||||||
|
echo " [WARN] docker-compose / docker compose 를 찾을 수 없습니다."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo -e "${RED}$FAIL 개 항목 실패. 위 오류를 확인하세요.${NC}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
25
deploy/docker-compose-nginx.yml
Normal file
25
deploy/docker-compose-nginx.yml
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
services:
|
||||||
|
nginx:
|
||||||
|
image: nginx:alpine
|
||||||
|
container_name: kamco-train-nginx
|
||||||
|
user: "1000:1000"
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
- "443:443"
|
||||||
|
volumes:
|
||||||
|
- ./nginx.conf:/etc/nginx/nginx.conf:ro,Z
|
||||||
|
- ./ssl:/etc/nginx/ssl:ro,Z
|
||||||
|
- ./logs:/var/log/nginx:Z
|
||||||
|
networks:
|
||||||
|
- kamco-cds
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "--no-check-certificate", "https://localhost/monitor/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
|
networks:
|
||||||
|
kamco-cds:
|
||||||
|
external: true
|
||||||
170
deploy/nginx.conf
Normal file
170
deploy/nginx.conf
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
pid /var/log/nginx/nginx.pid;
|
||||||
|
|
||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
http {
|
||||||
|
include /etc/nginx/mime.types;
|
||||||
|
default_type application/octet-stream;
|
||||||
|
|
||||||
|
# 로그 설정
|
||||||
|
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
||||||
|
'$status $body_bytes_sent "$http_referer" '
|
||||||
|
'"$http_user_agent" "$http_x_forwarded_for"';
|
||||||
|
|
||||||
|
access_log /var/log/nginx/access.log main;
|
||||||
|
error_log /var/log/nginx/error.log warn;
|
||||||
|
|
||||||
|
sendfile on;
|
||||||
|
keepalive_timeout 65;
|
||||||
|
|
||||||
|
# user 1000:1000 실행 시 /var/cache/nginx 접근 불가 → logs 경로로 우회
|
||||||
|
client_body_temp_path /var/log/nginx/client_temp;
|
||||||
|
proxy_temp_path /var/log/nginx/proxy_temp;
|
||||||
|
fastcgi_temp_path /var/log/nginx/fastcgi_temp;
|
||||||
|
uwsgi_temp_path /var/log/nginx/uwsgi_temp;
|
||||||
|
scgi_temp_path /var/log/nginx/scgi_temp;
|
||||||
|
|
||||||
|
# 업로드 파일 크기 / 타임아웃 (10GB, 10분)
|
||||||
|
client_max_body_size 10G;
|
||||||
|
client_body_timeout 600s;
|
||||||
|
|
||||||
|
# Docker 내부 DNS - 시작 시 upstream 조회 실패 방지
|
||||||
|
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||||
|
|
||||||
|
# HTTP → HTTPS 리다이렉트 서버
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name api.train-kamco.com train-kamco.com;
|
||||||
|
|
||||||
|
# 모든 HTTP 요청을 HTTPS로 리다이렉트
|
||||||
|
return 301 https://$host$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
# HTTPS 서버 설정
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
http2 on;
|
||||||
|
server_name api.train-kamco.com;
|
||||||
|
|
||||||
|
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
|
||||||
|
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
|
||||||
|
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
|
||||||
|
ssl_prefer_server_ciphers off;
|
||||||
|
|
||||||
|
ssl_session_cache shared:SSL:10m;
|
||||||
|
ssl_session_timeout 10m;
|
||||||
|
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
|
||||||
|
# CORS 헤더
|
||||||
|
add_header Access-Control-Allow-Origin "https://train-kamco.com" always;
|
||||||
|
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, PATCH, OPTIONS" always;
|
||||||
|
add_header Access-Control-Allow-Headers "Authorization, Content-Type, Cookie, X-Requested-With" always;
|
||||||
|
add_header Access-Control-Allow-Credentials "true" always;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
if ($request_method = OPTIONS) {
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
|
||||||
|
set $api http://kamco-train-api:8080;
|
||||||
|
proxy_pass $api;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Host $server_name;
|
||||||
|
proxy_pass_request_headers on;
|
||||||
|
proxy_set_header Cookie $http_cookie;
|
||||||
|
proxy_set_header Authorization $http_authorization;
|
||||||
|
|
||||||
|
proxy_connect_timeout 600s;
|
||||||
|
proxy_send_timeout 600s;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_buffering off;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /monitor/health {
|
||||||
|
set $api http://kamco-train-api:8080;
|
||||||
|
proxy_pass $api/monitor/health;
|
||||||
|
access_log off;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# HTTPS 서버 설정 - Next.js Web Application
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
http2 on;
|
||||||
|
server_name train-kamco.com;
|
||||||
|
|
||||||
|
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
|
||||||
|
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
|
||||||
|
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
|
||||||
|
ssl_prefer_server_ciphers off;
|
||||||
|
|
||||||
|
ssl_session_cache shared:SSL:10m;
|
||||||
|
ssl_session_timeout 10m;
|
||||||
|
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
|
||||||
|
location /api/ {
|
||||||
|
set $api http://kamco-train-api:8080;
|
||||||
|
proxy_pass $api/api/;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Host $server_name;
|
||||||
|
proxy_pass_request_headers on;
|
||||||
|
proxy_set_header Cookie $http_cookie;
|
||||||
|
|
||||||
|
proxy_connect_timeout 600s;
|
||||||
|
proxy_send_timeout 600s;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_buffering off;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
set $web http://kamco-train-web:3002;
|
||||||
|
proxy_pass $web;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Host $server_name;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
|
||||||
|
proxy_connect_timeout 600s;
|
||||||
|
proxy_send_timeout 600s;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
|
||||||
|
proxy_buffering on;
|
||||||
|
proxy_buffer_size 4k;
|
||||||
|
proxy_buffers 8 4k;
|
||||||
|
proxy_busy_buffers_size 8k;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
38
deploy/setup-groups.sh
Executable file
38
deploy/setup-groups.sh
Executable file
@@ -0,0 +1,38 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
RED='\033[0;31m'
|
||||||
|
NC='\033[0m'
|
||||||
|
|
||||||
|
ok() { echo -e "${GREEN}[OK]${NC} $1"; }
|
||||||
|
fail() { echo -e "${RED}[FAIL]${NC} $1"; exit 1; }
|
||||||
|
|
||||||
|
echo "=== GID 1000 그룹 설정 ==="
|
||||||
|
|
||||||
|
# GID 1000 그룹 없으면 생성
|
||||||
|
if ! getent group 1000 &>/dev/null; then
|
||||||
|
groupadd -g 1000 docker-users
|
||||||
|
ok "GID 1000 그룹(docker-users) 생성 완료"
|
||||||
|
else
|
||||||
|
GROUP_NAME=$(getent group 1000 | cut -d: -f1)
|
||||||
|
ok "GID 1000 그룹 이미 존재: $GROUP_NAME"
|
||||||
|
fi
|
||||||
|
|
||||||
|
GROUP_NAME=$(getent group 1000 | cut -d: -f1)
|
||||||
|
|
||||||
|
# kcomu, docker 를 GID 1000 그룹에 추가
|
||||||
|
for user in kcomu docker; do
|
||||||
|
if id "$user" &>/dev/null; then
|
||||||
|
usermod -aG "$GROUP_NAME" "$user"
|
||||||
|
ok "$user → $GROUP_NAME($GROUP_NAME) 그룹 추가 완료"
|
||||||
|
else
|
||||||
|
echo " [SKIP] $user 유저 없음"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "현재 $GROUP_NAME 그룹 멤버:"
|
||||||
|
getent group "$GROUP_NAME"
|
||||||
|
echo ""
|
||||||
|
echo "※ 그룹 변경은 재로그인 후 적용됩니다."
|
||||||
97
deploy/setup.sh
Executable file
97
deploy/setup.sh
Executable file
@@ -0,0 +1,97 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
NGINX_DIR="/data/training/nginx"
|
||||||
|
|
||||||
|
# docker compose v1/v2 자동 감지
|
||||||
|
if command -v docker-compose &>/dev/null; then
|
||||||
|
DOCKER_COMPOSE="docker-compose"
|
||||||
|
elif docker compose version &>/dev/null 2>&1; then
|
||||||
|
DOCKER_COMPOSE="docker compose"
|
||||||
|
else
|
||||||
|
DOCKER_COMPOSE=""
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== 디렉토리 생성 ==="
|
||||||
|
mkdir -p /data/training/request
|
||||||
|
mkdir -p /data/training/request/tmp
|
||||||
|
mkdir -p /data/training/response
|
||||||
|
mkdir -p /data/training/response/v6-cls-checkpoints
|
||||||
|
mkdir -p /data/training/tmp
|
||||||
|
mkdir -p "$NGINX_DIR/ssl"
|
||||||
|
mkdir -p "$NGINX_DIR/logs"
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== nginx 파일 복사 ==="
|
||||||
|
cp "$SCRIPT_DIR/nginx.conf" "$NGINX_DIR/"
|
||||||
|
cp "$SCRIPT_DIR/docker-compose-nginx.yml" "$NGINX_DIR/"
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== SSL 파일 복사 ==="
|
||||||
|
cp "$SCRIPT_DIR/ssl/openssl.cnf" "$NGINX_DIR/ssl/"
|
||||||
|
cp "$SCRIPT_DIR/ssl/train-kamco.com.crt" "$NGINX_DIR/ssl/"
|
||||||
|
cp "$SCRIPT_DIR/ssl/train-kamco.com.key" "$NGINX_DIR/ssl/"
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== SSL 권한 설정 ==="
|
||||||
|
chmod 700 "$NGINX_DIR/ssl"
|
||||||
|
chmod 600 "$NGINX_DIR/ssl/train-kamco.com.key"
|
||||||
|
chmod 644 "$NGINX_DIR/ssl/train-kamco.com.crt"
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== 소유권 설정 (kcomu:kcomu) ==="
|
||||||
|
chown -R kcomu:kcomu /data/training
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== 그룹 설정 (setup-groups.sh) ==="
|
||||||
|
bash "$SCRIPT_DIR/setup-groups.sh"
|
||||||
|
|
||||||
|
echo "=== docker-compose-nginx.yml 소유권 설정 (1000:1000) ==="
|
||||||
|
chown 1000:1000 "$NGINX_DIR/docker-compose-nginx.yml"
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== docker-compose 래퍼 설정 ==="
|
||||||
|
if command -v docker-compose &>/dev/null; then
|
||||||
|
echo "docker-compose 이미 설치됨 (스킵)"
|
||||||
|
elif docker compose version &>/dev/null 2>&1; then
|
||||||
|
cat > /usr/local/bin/docker-compose << 'EOF'
|
||||||
|
#!/bin/bash
|
||||||
|
exec docker compose "$@"
|
||||||
|
EOF
|
||||||
|
chmod +x /usr/local/bin/docker-compose
|
||||||
|
echo "docker-compose → docker compose 래퍼 생성 완료"
|
||||||
|
DOCKER_COMPOSE="docker-compose"
|
||||||
|
else
|
||||||
|
echo "[WARN] docker compose 를 찾을 수 없습니다. Docker 설치를 확인하세요."
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== Docker network 설정 ==="
|
||||||
|
if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
|
||||||
|
echo "kamco-cds 네트워크 이미 존재 (스킵)"
|
||||||
|
else
|
||||||
|
docker network create kamco-cds
|
||||||
|
echo "kamco-cds 네트워크 생성 완료"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== /etc/hosts 설정 ==="
|
||||||
|
if grep -q "train-kamco.com" /etc/hosts; then
|
||||||
|
echo "이미 설정되어 있음 (스킵)"
|
||||||
|
else
|
||||||
|
echo "127.0.0.1 api.train-kamco.com train-kamco.com" >> /etc/hosts
|
||||||
|
echo "추가 완료"
|
||||||
|
fi
|
||||||
|
echo "현재 hosts 설정:"
|
||||||
|
grep "train-kamco" /etc/hosts
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=== 설치 완료 ==="
|
||||||
|
echo "생성된 디렉토리:"
|
||||||
|
find /data -type d | sort
|
||||||
|
echo ""
|
||||||
|
echo "=== nginx 실행 방법 ==="
|
||||||
|
if [ -n "$DOCKER_COMPOSE" ]; then
|
||||||
|
echo "cd $NGINX_DIR && $DOCKER_COMPOSE -f docker-compose-nginx.yml up -d"
|
||||||
|
else
|
||||||
|
echo "[WARN] docker-compose / docker compose 를 찾을 수 없습니다. Docker 설치를 확인하세요."
|
||||||
|
fi
|
||||||
21
deploy/ssl/openssl.cnf
Normal file
21
deploy/ssl/openssl.cnf
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
[req]
|
||||||
|
default_bits = 4096
|
||||||
|
prompt = no
|
||||||
|
default_md = sha256
|
||||||
|
distinguished_name = dn
|
||||||
|
req_extensions = v3_req
|
||||||
|
|
||||||
|
[dn]
|
||||||
|
C=KR
|
||||||
|
ST=Seoul
|
||||||
|
L=Seoul
|
||||||
|
O=KAMCO
|
||||||
|
OU=Training
|
||||||
|
CN=api.train-kamco.com
|
||||||
|
|
||||||
|
[v3_req]
|
||||||
|
subjectAltName = @alt_names
|
||||||
|
|
||||||
|
[alt_names]
|
||||||
|
DNS.1 = api.train-kamco.com
|
||||||
|
DNS.2 = train-kamco.com
|
||||||
38
docker-compose-dev-0420.yml
Normal file
38
docker-compose-dev-0420.yml
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
services:
|
||||||
|
kamco-changedetection-api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile-dev
|
||||||
|
image: kamco-cd-training-api:${IMAGE_TAG:-latest}
|
||||||
|
container_name: kamco-cd-training-api
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
reservations:
|
||||||
|
devices:
|
||||||
|
- driver: nvidia
|
||||||
|
count: all
|
||||||
|
capabilities: [gpu]
|
||||||
|
ports:
|
||||||
|
- "7200:8080"
|
||||||
|
environment:
|
||||||
|
- SPRING_PROFILES_ACTIVE=dev
|
||||||
|
- TZ=Asia/Seoul
|
||||||
|
volumes:
|
||||||
|
- /mnt/nfs_share/images:/app/original-images
|
||||||
|
- /mnt/nfs_share/model_output:/app/model-outputs
|
||||||
|
- /mnt/nfs_share/train_dataset:/app/train-dataset
|
||||||
|
- /home/kcomu/data:/home/kcomu/data
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
networks:
|
||||||
|
- kamco-cds
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: [ "CMD", "curl", "-f", "http://localhost:8080/monitor/health" ]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 40s
|
||||||
|
|
||||||
|
networks:
|
||||||
|
kamco-cds:
|
||||||
|
external: true
|
||||||
@@ -18,10 +18,7 @@ services:
|
|||||||
- SPRING_PROFILES_ACTIVE=dev
|
- SPRING_PROFILES_ACTIVE=dev
|
||||||
- TZ=Asia/Seoul
|
- TZ=Asia/Seoul
|
||||||
volumes:
|
volumes:
|
||||||
- /mnt/nfs_share/images:/app/original-images
|
- /backup/data/training:/backup/data/training
|
||||||
- /mnt/nfs_share/model_output:/app/model-outputs
|
|
||||||
- /mnt/nfs_share/train_dataset:/app/train-dataset
|
|
||||||
- /home/kcomu/data:/home/kcomu/data
|
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
networks:
|
networks:
|
||||||
- kamco-cds
|
- kamco-cds
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
services:
|
services:
|
||||||
kamco-train-api:
|
kamco-changedetection-api:
|
||||||
build:
|
image: kamco-train-app:latest
|
||||||
context: .
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
image: kamco-train-api:${IMAGE_TAG:-latest}
|
|
||||||
container_name: kamco-train-api
|
container_name: kamco-train-api
|
||||||
deploy:
|
deploy:
|
||||||
resources:
|
resources:
|
||||||
@@ -17,9 +14,10 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
- SPRING_PROFILES_ACTIVE=prod
|
- SPRING_PROFILES_ACTIVE=prod
|
||||||
- TZ=Asia/Seoul
|
- TZ=Asia/Seoul
|
||||||
|
- cors.allowed-origins=*
|
||||||
|
- cors.allowed-origins[0]=*
|
||||||
volumes:
|
volumes:
|
||||||
- ./app/model_output:/app/model-outputs
|
- /data/training:/data/training
|
||||||
- ./app/train_dataset:/app/train-dataset
|
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
networks:
|
networks:
|
||||||
- kamco-cds
|
- kamco-cds
|
||||||
|
|||||||
@@ -20,14 +20,8 @@ http {
|
|||||||
# 업로드 파일 크기 제한 (10GB)
|
# 업로드 파일 크기 제한 (10GB)
|
||||||
client_max_body_size 10G;
|
client_max_body_size 10G;
|
||||||
|
|
||||||
# Upstream 설정
|
# Docker 내부 DNS - 시작 시 upstream 조회 실패 방지
|
||||||
upstream api_backend {
|
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||||
server kamco-train-api:8080;
|
|
||||||
}
|
|
||||||
|
|
||||||
upstream web_backend {
|
|
||||||
server kamco-train-web:3002;
|
|
||||||
}
|
|
||||||
|
|
||||||
# HTTP → HTTPS 리다이렉트 서버
|
# HTTP → HTTPS 리다이렉트 서버
|
||||||
server {
|
server {
|
||||||
@@ -66,7 +60,8 @@ http {
|
|||||||
|
|
||||||
# 프록시 설정
|
# 프록시 설정
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://api_backend;
|
set $api http://kamco-train-api:8080;
|
||||||
|
proxy_pass $api;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
# 프록시 헤더 설정
|
# 프록시 헤더 설정
|
||||||
@@ -95,7 +90,8 @@ http {
|
|||||||
|
|
||||||
# 헬스체크 엔드포인트
|
# 헬스체크 엔드포인트
|
||||||
location /monitor/health {
|
location /monitor/health {
|
||||||
proxy_pass http://api_backend/monitor/health;
|
set $api http://kamco-train-api:8080;
|
||||||
|
proxy_pass $api/monitor/health;
|
||||||
access_log off;
|
access_log off;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -128,7 +124,8 @@ http {
|
|||||||
|
|
||||||
# API 프록시 설정 (Web에서 API 호출 시)
|
# API 프록시 설정 (Web에서 API 호출 시)
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass http://api_backend/api/;
|
set $api http://kamco-train-api:8080;
|
||||||
|
proxy_pass $api/api/;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
# 프록시 헤더 설정
|
# 프록시 헤더 설정
|
||||||
@@ -150,7 +147,8 @@ http {
|
|||||||
|
|
||||||
# 프록시 설정
|
# 프록시 설정
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://web_backend;
|
set $web http://kamco-train-web:3002;
|
||||||
|
proxy_pass $web;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
# 프록시 헤더 설정
|
# 프록시 헤더 설정
|
||||||
|
|||||||
@@ -125,6 +125,7 @@ public class CommonCodeService {
|
|||||||
return commonCodeCoreService.getCode(parentCodeCd, childCodeCd);
|
return commonCodeCoreService.getCode(parentCodeCd, childCodeCd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 공통코드 이름 조회
|
* 공통코드 이름 조회
|
||||||
*
|
*
|
||||||
@@ -136,6 +137,8 @@ public class CommonCodeService {
|
|||||||
return commonCodeCoreService.getCode(parentCodeCd, childCodeCd);
|
return commonCodeCoreService.getCode(parentCodeCd, childCodeCd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
public List<CodeDto> getTypeCode(String type) {
|
public List<CodeDto> getTypeCode(String type) {
|
||||||
return Enums.getCodes(type);
|
return Enums.getCodes(type);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.common.download;
|
package com.kamco.cd.training.common.download;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.download.dto.DownloadSpec;
|
import com.kamco.cd.training.common.download.dto.DownloadSpec;
|
||||||
@@ -46,3 +47,4 @@ public class DownloadExecutor {
|
|||||||
.body(body);
|
.body(body);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.common.download;
|
package com.kamco.cd.training.common.download;
|
||||||
|
|
||||||
import org.springframework.util.AntPathMatcher;
|
import org.springframework.util.AntPathMatcher;
|
||||||
@@ -17,3 +18,4 @@ public final class DownloadPaths {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package com.kamco.cd.training.common.dto;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class HyperClsParam {
|
||||||
|
|
||||||
|
@Schema(description = "모델", example = "CLS")
|
||||||
|
private ModelType model; // G1, G2, G3, G4, CLS
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Model
|
||||||
|
// -------------------------
|
||||||
|
|
||||||
|
@Schema(description = "입력 이미지 크기", example = "256")
|
||||||
|
private String inputSize; // input_size
|
||||||
|
|
||||||
|
@Schema(description = "배치 크기(Per GPU)", example = "64")
|
||||||
|
private Integer batchSize; // batch_size
|
||||||
|
|
||||||
|
@Schema(description = "워커 수", example = "16")
|
||||||
|
private Integer workers; // batch_size
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Augmentation
|
||||||
|
// -------------------------
|
||||||
|
@Schema(description = "scale", example = "0.5")
|
||||||
|
private Double scale;
|
||||||
|
|
||||||
|
@Schema(description = "translate", example = "0.1")
|
||||||
|
private Double translate;
|
||||||
|
|
||||||
|
@Schema(description = "fliplr", example = "0.5")
|
||||||
|
private Double fliplr;
|
||||||
|
|
||||||
|
@Schema(description = "flipud", example = "0.5")
|
||||||
|
private Double flipud;
|
||||||
|
|
||||||
|
@Schema(description = "erasing")
|
||||||
|
private Double erasing;
|
||||||
|
|
||||||
|
@Schema(description = "mixup", example = "0.1")
|
||||||
|
private Double mixup;
|
||||||
|
|
||||||
|
@Schema(description = "hsv_h")
|
||||||
|
private Double hsvH;
|
||||||
|
|
||||||
|
@Schema(description = "hsv_s")
|
||||||
|
private Double hsvS;
|
||||||
|
|
||||||
|
@Schema(description = "hsv_v")
|
||||||
|
private Double hsvV;
|
||||||
|
|
||||||
|
@Schema(description = "dropout")
|
||||||
|
private Double dropout;
|
||||||
|
|
||||||
|
@Schema(description = "label_smoothing")
|
||||||
|
private Double labelSmoothing;
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Memo
|
||||||
|
// -------------------------
|
||||||
|
@Schema(description = "메모", example = "하이퍼파라미터 신규등록")
|
||||||
|
private String memo; // memo
|
||||||
|
|
||||||
|
private Boolean isDefault = false;
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ import lombok.Setter;
|
|||||||
public class HyperParam {
|
public class HyperParam {
|
||||||
|
|
||||||
@Schema(description = "모델", example = "G1")
|
@Schema(description = "모델", example = "G1")
|
||||||
private ModelType model; // G1, G2, G3
|
private ModelType model; // G1, G2, G3, G4
|
||||||
|
|
||||||
// -------------------------
|
// -------------------------
|
||||||
// Important
|
// Important
|
||||||
@@ -104,7 +104,7 @@ public class HyperParam {
|
|||||||
@Schema(description = "Best 모델 선정 규칙", example = "less")
|
@Schema(description = "Best 모델 선정 규칙", example = "less")
|
||||||
private String saveBestRule; // save_best_rule
|
private String saveBestRule; // save_best_rule
|
||||||
|
|
||||||
@Schema(description = "검증 수행 주기(Epoch)", example = "10")
|
@Schema(description = "검증 수행 주기(Epoch)", example = "1")
|
||||||
private Integer valInterval; // val_interval
|
private Integer valInterval; // val_interval
|
||||||
|
|
||||||
@Schema(description = "로그 기록 주기(Iteration)", example = "400")
|
@Schema(description = "로그 기록 주기(Iteration)", example = "400")
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.common.enums;
|
package com.kamco.cd.training.common.enums;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||||
@@ -17,3 +18,4 @@ public enum DeployTargetType implements EnumType {
|
|||||||
private final String id;
|
private final String id;
|
||||||
private final String text;
|
private final String text;
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.common.enums;
|
package com.kamco.cd.training.common.enums;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||||
@@ -25,3 +26,4 @@ public enum ModelMngStatusType implements EnumType {
|
|||||||
return desc;
|
return desc;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ import lombok.Getter;
|
|||||||
public enum ModelType implements EnumType {
|
public enum ModelType implements EnumType {
|
||||||
G1("G1"),
|
G1("G1"),
|
||||||
G2("G2"),
|
G2("G2"),
|
||||||
G3("G3");
|
G3("G3"),
|
||||||
|
G4("G4"),
|
||||||
|
CLS("CLS");
|
||||||
|
|
||||||
private String desc;
|
private String desc;
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.common.enums;
|
package com.kamco.cd.training.common.enums;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||||
@@ -18,3 +19,4 @@ public enum ProcessStepType implements EnumType {
|
|||||||
private final String id;
|
private final String id;
|
||||||
private final String text;
|
private final String text;
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package com.kamco.cd.training.common.service;
|
|||||||
import jakarta.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import lombok.extern.log4j.Log4j2;
|
import lombok.extern.log4j.Log4j2;
|
||||||
@@ -13,19 +15,34 @@ import org.springframework.stereotype.Component;
|
|||||||
public class GpuDmonReader {
|
public class GpuDmonReader {
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// GPU 사용률 저장소
|
// GPU 사용률 히스토리 저장소
|
||||||
// key: GPU index (0,1,2...)
|
// key: GPU index (0,1,2...)
|
||||||
// value: 현재 GPU 사용률 (%)
|
// value: 최근 WINDOW_SIZE 개의 sm 사용률 샘플 (1초 간격)
|
||||||
// ConcurrentHashMap → 멀티스레드 안전
|
// ConcurrentHashMap → 멀티스레드 안전 (deque 접근은 synchronized)
|
||||||
// =========================
|
// =========================
|
||||||
private final Map<Integer, Integer> gpuUtilMap = new ConcurrentHashMap<>();
|
private static final int WINDOW_SIZE = 10; // 10초 평균
|
||||||
|
|
||||||
|
private final Map<Integer, ArrayDeque<Integer>> historyMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// 외부 조회용
|
// 외부 조회용
|
||||||
|
// GPU 개수만큼 10초 평균값 반환
|
||||||
// SystemMonitorService에서 호출
|
// SystemMonitorService에서 호출
|
||||||
// =========================
|
// =========================
|
||||||
public Map<Integer, Integer> getGpuUtilMap() {
|
public Map<Integer, Integer> getGpuUtilMap() {
|
||||||
return gpuUtilMap;
|
Map<Integer, Integer> result = new HashMap<>();
|
||||||
|
historyMap.forEach(
|
||||||
|
(gpu, deque) -> {
|
||||||
|
synchronized (deque) {
|
||||||
|
int avg =
|
||||||
|
deque.isEmpty()
|
||||||
|
? 0
|
||||||
|
: (int)
|
||||||
|
Math.round(deque.stream().mapToInt(Integer::intValue).average().orElse(0));
|
||||||
|
result.put(gpu, avg);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
@@ -76,10 +93,13 @@ public class GpuDmonReader {
|
|||||||
|
|
||||||
// -s u → GPU utilization만 출력
|
// -s u → GPU utilization만 출력
|
||||||
ProcessBuilder pb = new ProcessBuilder("nvidia-smi", "dmon", "-s", "u");
|
ProcessBuilder pb = new ProcessBuilder("nvidia-smi", "dmon", "-s", "u");
|
||||||
|
// stderr를 stdout에 합쳐서 소비 — 소비하지 않으면 stderr 버퍼가 가득 차
|
||||||
|
// nvidia-smi 프로세스 자체가 block되어 stdout도 멈춤
|
||||||
|
pb.redirectErrorStream(true);
|
||||||
|
|
||||||
|
Process process = pb.start();
|
||||||
// 프로세스 실행 후 stdout 읽기
|
// 프로세스 실행 후 stdout 읽기
|
||||||
try (BufferedReader br =
|
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
|
||||||
new BufferedReader(new InputStreamReader(pb.start().getInputStream()))) {
|
|
||||||
|
|
||||||
String line;
|
String line;
|
||||||
|
|
||||||
@@ -96,21 +116,24 @@ public class GpuDmonReader {
|
|||||||
String[] parts = line.split("\\s+");
|
String[] parts = line.split("\\s+");
|
||||||
|
|
||||||
// 첫 번째 값이 GPU index인지 확인
|
// 첫 번째 값이 GPU index인지 확인
|
||||||
if (!parts[0].matches("\\d+")) continue;
|
if (parts.length < 2 || !parts[0].matches("\\d+")) continue;
|
||||||
|
|
||||||
int index = Integer.parseInt(parts[0]);
|
int index = Integer.parseInt(parts[0]);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 두 번째 값이 GPU 사용률 (sm)
|
// 두 번째 값이 GPU 사용률 (sm), "-"이면 N/A (GPU 미활성)
|
||||||
int util = Integer.parseInt(parts[1]);
|
int util = Integer.parseInt(parts[1]);
|
||||||
|
pushSample(index, util);
|
||||||
|
log.debug("[GpuDmon] gpu={} sm={}%", index, util);
|
||||||
|
|
||||||
// 최신 값 갱신
|
} catch (NumberFormatException e) {
|
||||||
gpuUtilMap.put(index, util);
|
// "-" 등 숫자가 아닌 값 → GPU 비활성 상태이므로 0으로 기록
|
||||||
|
pushSample(index, 0);
|
||||||
} catch (Exception ignored) {
|
log.debug("[GpuDmon] gpu={} sm=N/A (raw={}), stored as 0", index, parts[1]);
|
||||||
// 파싱 실패 시 무시
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
process.destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 여기까지 왔다는 건 dmon 프로세스 종료됨
|
// 여기까지 왔다는 건 dmon 프로세스 종료됨
|
||||||
@@ -118,6 +141,20 @@ public class GpuDmonReader {
|
|||||||
throw new IllegalStateException("dmon stopped");
|
throw new IllegalStateException("dmon stopped");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// =========================
|
||||||
|
// 샘플 추가 — 윈도우 초과 시 가장 오래된 값 제거
|
||||||
|
// =========================
|
||||||
|
private void pushSample(int gpuIndex, int util) {
|
||||||
|
ArrayDeque<Integer> deque =
|
||||||
|
historyMap.computeIfAbsent(gpuIndex, k -> new ArrayDeque<>(WINDOW_SIZE));
|
||||||
|
synchronized (deque) {
|
||||||
|
deque.addLast(util);
|
||||||
|
if (deque.size() > WINDOW_SIZE) {
|
||||||
|
deque.pollFirst();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// nvidia-smi 존재 여부 확인
|
// nvidia-smi 존재 여부 확인
|
||||||
// =========================
|
// =========================
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
package com.kamco.cd.training.common.utils;
|
package com.kamco.cd.training.common.utils;
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.web.context.request.RequestAttributes;
|
||||||
|
import org.springframework.web.context.request.RequestContextHolder;
|
||||||
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
public final class HeaderUtil {
|
public final class HeaderUtil {
|
||||||
|
|
||||||
private HeaderUtil() {}
|
private HeaderUtil() {}
|
||||||
@@ -20,4 +25,20 @@ public final class HeaderUtil {
|
|||||||
public static String getRequired(HttpServletRequest request, String headerName) {
|
public static String getRequired(HttpServletRequest request, String headerName) {
|
||||||
return get(request, headerName);
|
return get(request, headerName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static boolean isEnglishRequest() {
|
||||||
|
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
|
||||||
|
|
||||||
|
if (!(attrs instanceof ServletRequestAttributes servletAttrs)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String acceptLanguage = servletAttrs.getRequest().getHeader("Accept-Language");
|
||||||
|
|
||||||
|
if (acceptLanguage == null || acceptLanguage.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return acceptLanguage.toLowerCase().startsWith("en");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.kamco.cd.training.common.utils.enums;
|
package com.kamco.cd.training.common.utils.enums;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -31,10 +32,11 @@ public class Enums {
|
|||||||
// enum -> CodeDto list
|
// enum -> CodeDto list
|
||||||
public static List<CodeDto> toList(Class<? extends Enum<?>> enumClass) {
|
public static List<CodeDto> toList(Class<? extends Enum<?>> enumClass) {
|
||||||
Object[] enums = enumClass.getEnumConstants();
|
Object[] enums = enumClass.getEnumConstants();
|
||||||
|
boolean english = HeaderUtil.isEnglishRequest();
|
||||||
|
|
||||||
return Arrays.stream(enums)
|
return Arrays.stream(enums)
|
||||||
.map(e -> (EnumType) e)
|
.map(e -> (EnumType) e)
|
||||||
.map(e -> new CodeDto(e.getId(), e.getText()))
|
.map(e -> new CodeDto(e.getId(), english ? e.getId() : e.getText()))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,4 +20,18 @@ public class AsyncConfig {
|
|||||||
executor.initialize();
|
executor.initialize();
|
||||||
return executor;
|
return executor;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean("datasetExecutor")
|
||||||
|
public Executor datasetExecutor() {
|
||||||
|
|
||||||
|
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||||
|
|
||||||
|
executor.setCorePoolSize(5);
|
||||||
|
executor.setMaxPoolSize(10);
|
||||||
|
executor.setQueueCapacity(100);
|
||||||
|
executor.setThreadNamePrefix("dataset-");
|
||||||
|
|
||||||
|
executor.initialize();
|
||||||
|
return executor;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ public class OpenApiConfig {
|
|||||||
@Value("${swagger.dev-url:https://kamco.training-dev-api.gs.dabeeo.com}")
|
@Value("${swagger.dev-url:https://kamco.training-dev-api.gs.dabeeo.com}")
|
||||||
private String devUrl;
|
private String devUrl;
|
||||||
|
|
||||||
@Value("${swagger.prod-url:https://api.training-kamco.com}")
|
@Value("${swagger.prod-url:https://api.train-kamco.com}")
|
||||||
private String prodUrl;
|
private String prodUrl;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -53,10 +53,10 @@ public class OpenApiConfig {
|
|||||||
} else if ("prod".equals(profile)) {
|
} else if ("prod".equals(profile)) {
|
||||||
// servers.add(new Server().url(prodUrl).description("운영 서버"));
|
// servers.add(new Server().url(prodUrl).description("운영 서버"));
|
||||||
servers.add(new Server().url("http://localhost:" + localPort).description("로컬 서버"));
|
servers.add(new Server().url("http://localhost:" + localPort).description("로컬 서버"));
|
||||||
servers.add(new Server().url(devUrl).description("개발 서버"));
|
servers.add(new Server().url(prodUrl).description("개발 서버"));
|
||||||
} else {
|
} else {
|
||||||
servers.add(new Server().url("http://localhost:" + localPort).description("로컬 서버"));
|
servers.add(new Server().url("http://localhost:" + localPort).description("로컬 서버"));
|
||||||
servers.add(new Server().url(devUrl).description("개발 서버"));
|
servers.add(new Server().url(devUrl).description("운영 서버"));
|
||||||
// servers.add(new Server().url(prodUrl).description("운영 서버"));
|
// servers.add(new Server().url(prodUrl).description("운영 서버"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -137,6 +137,6 @@ public class SecurityConfig {
|
|||||||
/** 완전 제외(필터 자체를 안 탐) */
|
/** 완전 제외(필터 자체를 안 탐) */
|
||||||
@Bean
|
@Bean
|
||||||
public WebSecurityCustomizer webSecurityCustomizer() {
|
public WebSecurityCustomizer webSecurityCustomizer() {
|
||||||
return (web) -> web.ignoring().requestMatchers("/api/mapsheet/**");
|
return (web) -> web.ignoring().requestMatchers("/api/mapsheet/**", "/api/file-manager/**");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ public class StartupLogger {
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
╔════════════════════════════════════════════════════════════════════════════════╗
|
╔════════════════════════════════════════════════════════════════════════════════╗
|
||||||
║ 🚀 APPLICATION STARTUP INFORMATION 2 ║
|
║ 🚀 APPLICATION STARTUP INFORMATION 3 ║
|
||||||
╠════════════════════════════════════════════════════════════════════════════════╣
|
╠════════════════════════════════════════════════════════════════════════════════╣
|
||||||
║ PROFILE CONFIGURATION ║
|
║ PROFILE CONFIGURATION ║
|
||||||
╠────────────────────────────────────────────────────────────────────────────────╣
|
╠────────────────────────────────────────────────────────────────────────────────╣
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
package com.kamco.cd.training.dataset;
|
package com.kamco.cd.training.dataset;
|
||||||
|
|
||||||
import com.kamco.cd.training.config.api.ApiResponseDto;
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
import com.kamco.cd.training.config.api.ApiResponseDto.ResponseObj;
|
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.AddDeliveriesReq;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.AddDeliveriesReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetClass;
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetClass;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetStorage;
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetStorage;
|
||||||
|
import com.kamco.cd.training.dataset.service.DatasetAsyncService;
|
||||||
import com.kamco.cd.training.dataset.service.DatasetService;
|
import com.kamco.cd.training.dataset.service.DatasetService;
|
||||||
import com.kamco.cd.training.model.dto.FileDto.FoldersDto;
|
import com.kamco.cd.training.model.dto.FileDto.FoldersDto;
|
||||||
import com.kamco.cd.training.model.dto.FileDto.SrchFoldersDto;
|
import com.kamco.cd.training.model.dto.FileDto.SrchFoldersDto;
|
||||||
@@ -37,6 +37,7 @@ import org.springframework.web.bind.annotation.*;
|
|||||||
public class DatasetApiController {
|
public class DatasetApiController {
|
||||||
|
|
||||||
private final DatasetService datasetService;
|
private final DatasetService datasetService;
|
||||||
|
private final DatasetAsyncService datasetAsyncService;
|
||||||
|
|
||||||
@Operation(summary = "학습데이터 관리 목록 조회", description = "학습데이터 목록을 조회합니다.")
|
@Operation(summary = "학습데이터 관리 목록 조회", description = "학습데이터 목록을 조회합니다.")
|
||||||
@ApiResponses(
|
@ApiResponses(
|
||||||
@@ -262,7 +263,7 @@ public class DatasetApiController {
|
|||||||
content =
|
content =
|
||||||
@Content(
|
@Content(
|
||||||
mediaType = "application/json",
|
mediaType = "application/json",
|
||||||
schema = @Schema(implementation = Page.class))),
|
schema = @Schema(implementation = FoldersDto.class))),
|
||||||
@ApiResponse(responseCode = "404", description = "조회 오류", content = @Content),
|
@ApiResponse(responseCode = "404", description = "조회 오류", content = @Content),
|
||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
})
|
})
|
||||||
@@ -281,12 +282,21 @@ public class DatasetApiController {
|
|||||||
content =
|
content =
|
||||||
@Content(
|
@Content(
|
||||||
mediaType = "application/json",
|
mediaType = "application/json",
|
||||||
schema = @Schema(implementation = Page.class))),
|
schema = @Schema(implementation = String.class))),
|
||||||
@ApiResponse(responseCode = "404", description = "조회 오류", content = @Content),
|
@ApiResponse(responseCode = "404", description = "조회 오류", content = @Content),
|
||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
})
|
})
|
||||||
@PostMapping("/deliveries")
|
@PostMapping("/deliveries")
|
||||||
public ApiResponseDto<ResponseObj> insertDeliveriesDataset(@RequestBody AddDeliveriesReq req) throws IOException {
|
public ApiResponseDto<String> insertDeliveriesDataset(@RequestBody AddDeliveriesReq req) {
|
||||||
return ApiResponseDto.createOK(datasetService.insertDeliveriesDataset(req));
|
|
||||||
|
// 폴더 구조 검증
|
||||||
|
DatasetService.validateTrainValTestDirs(req.getFilePath());
|
||||||
|
// 파일 개수 검증
|
||||||
|
DatasetService.validateDirFileCount(req.getFilePath());
|
||||||
|
// 폴더명(uid)으로 등록한 건이 있는지 체크
|
||||||
|
datasetService.validateExistsUidChk(req.getFilePath());
|
||||||
|
|
||||||
|
datasetAsyncService.insertDeliveriesDatasetAsync(req);
|
||||||
|
return ApiResponseDto.createOK("ok");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
package com.kamco.cd.training.dataset;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetClsObjDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
||||||
|
import com.kamco.cd.training.dataset.service.DatasetClsService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@Tag(name = "분류모델 학습데이터 관리", description = "어드민 홈 > 학습데이터관리 > 분류데이터셋")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/datasets/cls")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DatasetClsApiController {
|
||||||
|
|
||||||
|
private final DatasetClsService datasetClsService;
|
||||||
|
|
||||||
|
@Operation(summary = "분류 학습데이터 관리 목록 조회", description = "분류 학습데이터 목록을 조회합니다.")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = Page.class))),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping
|
||||||
|
public ApiResponseDto<Page<DatasetDto.Basic>> searchDatasets(
|
||||||
|
@Parameter(
|
||||||
|
description = "구분",
|
||||||
|
example = "",
|
||||||
|
schema = @Schema(allowableValues = {"DELIVER", "PRODUCTION"}))
|
||||||
|
@RequestParam(required = false)
|
||||||
|
String dataType,
|
||||||
|
@Parameter(description = "제목", example = "") @RequestParam(required = false) String title,
|
||||||
|
@Parameter(description = "페이지 번호 (0부터 시작)", example = "0") @RequestParam(defaultValue = "0")
|
||||||
|
int page,
|
||||||
|
@Parameter(description = "페이지 크기", example = "20") @RequestParam(defaultValue = "20")
|
||||||
|
int size) {
|
||||||
|
DatasetDto.SearchReq searchReq = new DatasetDto.SearchReq();
|
||||||
|
searchReq.setTitle(title);
|
||||||
|
searchReq.setDataType(dataType);
|
||||||
|
searchReq.setPage(page);
|
||||||
|
searchReq.setSize(size);
|
||||||
|
return ApiResponseDto.ok(datasetClsService.searchDatasets(searchReq));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "학습데이터관리 상세 조회", description = "학습데이터관리 상세 정보를 조회합니다.")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = DatasetDto.Basic.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/{uuid}")
|
||||||
|
public ApiResponseDto<DatasetDto.Basic> getDatasetDetail(@PathVariable UUID uuid) {
|
||||||
|
return ApiResponseDto.ok(datasetClsService.getDatasetDetail(uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "학습데이터 수정", description = "학습데이터 제목, 메모 수정")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "수정 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = Long.class))),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@PutMapping("/{uuid}")
|
||||||
|
public ApiResponseDto<UUID> updateDataset(
|
||||||
|
@PathVariable UUID uuid, @RequestBody DatasetDto.UpdateReq updateReq) {
|
||||||
|
datasetClsService.updateDataset(uuid, updateReq);
|
||||||
|
return ApiResponseDto.ok(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "학습데이터 삭제", description = "학습데이터를 삭제합니다.(납품 데이터는 삭제 불가)")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(responseCode = "201", description = "삭제 성공", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@DeleteMapping("/{uuid}")
|
||||||
|
public ApiResponseDto<UUID> deleteDatasets(@PathVariable UUID uuid) {
|
||||||
|
|
||||||
|
datasetClsService.deleteDatasets(uuid);
|
||||||
|
return ApiResponseDto.ok(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "분류 학습데이터 관리 목록 조회", description = "분류 학습데이터 목록을 조회합니다.")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = Page.class))),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/obj-list")
|
||||||
|
public ApiResponseDto<Page<DatasetClsObjDto.Basic>> searchDatasetObjectList(
|
||||||
|
@Parameter(description = "회차 uuid", example = "edf3812d-4558-4134-ad5f-5cd9dc78a1da")
|
||||||
|
@RequestParam(required = true)
|
||||||
|
UUID uuid,
|
||||||
|
@Parameter(description = "년도", example = "") @RequestParam(required = false) Integer yyyy,
|
||||||
|
@Parameter(description = "분류", example = "") @RequestParam(required = false) String classCd,
|
||||||
|
@Parameter(description = "도엽번호", example = "") @RequestParam(required = false)
|
||||||
|
String mapSheetNum,
|
||||||
|
@RequestParam(defaultValue = "0") int page,
|
||||||
|
@RequestParam(defaultValue = "20") int size) {
|
||||||
|
DatasetClsObjDto.ClsSearchReq searchReq = new DatasetClsObjDto.ClsSearchReq();
|
||||||
|
searchReq.setUuid(uuid);
|
||||||
|
searchReq.setYyyy(yyyy);
|
||||||
|
searchReq.setClassCd(classCd);
|
||||||
|
searchReq.setMapSheetNum(mapSheetNum);
|
||||||
|
searchReq.setPage(page);
|
||||||
|
searchReq.setSize(size);
|
||||||
|
return ApiResponseDto.ok(datasetClsService.searchDatasetClsObjectList(searchReq));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "학습데이터 zip파일 등록", description = "학습데이터 zip파일 등록 합니다.")
|
||||||
|
@PostMapping
|
||||||
|
public ApiResponseDto<ApiResponseDto.ResponseObj> insertDataset(
|
||||||
|
@RequestBody @Valid DatasetDto.AddReq addReq) {
|
||||||
|
|
||||||
|
return ApiResponseDto.okObject(datasetClsService.insertDataset(addReq));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "분류데이터셋 객체별 파일 Path 조회", description = "파일 Path 조회")
|
||||||
|
@GetMapping("/files")
|
||||||
|
public ResponseEntity<Resource> getFile(@RequestParam UUID uuid) throws Exception {
|
||||||
|
|
||||||
|
String path = datasetClsService.getFilePathByUUIDPathTif(uuid);
|
||||||
|
return datasetClsService.getFilePathByFile(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
package com.kamco.cd.training.dataset.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.kamco.cd.training.common.enums.DetectionClassification;
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
|
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||||
|
import com.kamco.cd.training.common.utils.enums.EnumType;
|
||||||
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.*;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
public class DatasetClsObjDto {
|
||||||
|
|
||||||
|
@Schema(name = "DatasetClsObj Basic", description = "분류 데이터셋 객체 Obj 기본 정보")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
public static class Basic {
|
||||||
|
|
||||||
|
private Long objId;
|
||||||
|
private UUID uuid;
|
||||||
|
private Long datasetUid;
|
||||||
|
private String type;
|
||||||
|
private Integer yyyy;
|
||||||
|
private String classCd;
|
||||||
|
private String mapSheetNum;
|
||||||
|
private String tifImgPath;
|
||||||
|
private String fileName;
|
||||||
|
@JsonFormatDttm private ZonedDateTime createdDttm;
|
||||||
|
private Long createdUid;
|
||||||
|
private Boolean deleted;
|
||||||
|
|
||||||
|
public Basic(
|
||||||
|
Long objId,
|
||||||
|
UUID uuid,
|
||||||
|
Long datasetUid,
|
||||||
|
String type,
|
||||||
|
Integer yyyy,
|
||||||
|
String classCd,
|
||||||
|
String mapSheetNum,
|
||||||
|
String tifImgPath,
|
||||||
|
String fileName,
|
||||||
|
ZonedDateTime createdDttm,
|
||||||
|
Long createdUid,
|
||||||
|
Boolean deleted) {
|
||||||
|
this.objId = objId;
|
||||||
|
this.uuid = uuid;
|
||||||
|
this.datasetUid = datasetUid;
|
||||||
|
this.type = type;
|
||||||
|
this.yyyy = yyyy;
|
||||||
|
this.classCd = classCd;
|
||||||
|
this.mapSheetNum = mapSheetNum;
|
||||||
|
this.tifImgPath = tifImgPath;
|
||||||
|
this.fileName = fileName;
|
||||||
|
this.createdDttm = createdDttm;
|
||||||
|
this.createdUid = createdUid;
|
||||||
|
this.deleted = deleted;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Schema(name = "ClsSearchReq", description = "분류 데이터셋 상세 도엽목록 조회 요청")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class ClsSearchReq {
|
||||||
|
@Schema(description = "회차 uuid", example = "e9a6774b-4f81-4402-b080-51d27fac1f01")
|
||||||
|
private UUID uuid;
|
||||||
|
|
||||||
|
@Schema(description = "년도", example = "2021")
|
||||||
|
private Integer yyyy;
|
||||||
|
|
||||||
|
@Schema(description = "분류", example = "waste")
|
||||||
|
private String classCd;
|
||||||
|
|
||||||
|
@Schema(description = "도엽번호", example = "36713060")
|
||||||
|
private String mapSheetNum;
|
||||||
|
|
||||||
|
@Schema(description = "페이지 번호 (0부터 시작)", example = "0")
|
||||||
|
private int page = 0;
|
||||||
|
|
||||||
|
@Schema(description = "페이지 크기", example = "20")
|
||||||
|
private int size = 20;
|
||||||
|
|
||||||
|
public Pageable toPageable() {
|
||||||
|
return PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdDttm"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
public static class DatasetClass {
|
||||||
|
private String classCd;
|
||||||
|
|
||||||
|
public String getClassName() {
|
||||||
|
|
||||||
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? DetectionClassification.fromString(classCd).getId()
|
||||||
|
: DetectionClassification.fromString(classCd).getDesc();
|
||||||
|
// fromString 메서드를 사용하여 안전하게 변환 (미정의 값은 ETC로 처리)
|
||||||
|
// return DetectionClassification.valueOf(classCd.toUpperCase()).getDesc();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public static class DatasetStorage {
|
||||||
|
private String usableBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public static class DatasetObjRegDto {
|
||||||
|
private Long datasetUid;
|
||||||
|
private Integer compareYyyy;
|
||||||
|
private String compareClassCd;
|
||||||
|
private Integer targetYyyy;
|
||||||
|
private String targetClassCd;
|
||||||
|
private String comparePath;
|
||||||
|
private String targetPath;
|
||||||
|
private String labelPath;
|
||||||
|
private String geojsonPath;
|
||||||
|
private String mapSheetNum;
|
||||||
|
private JsonNode geojson;
|
||||||
|
private String fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
@CodeExpose
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public enum FolderType implements EnumType {
|
||||||
|
TRAIN("train"),
|
||||||
|
VAL("val"),
|
||||||
|
TEST("test");
|
||||||
|
|
||||||
|
private String desc;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getId() {
|
||||||
|
return name();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getText() {
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
|
|||||||
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
||||||
import com.kamco.cd.training.common.enums.LearnDataType;
|
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||||
import com.kamco.cd.training.common.enums.ModelType;
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
import com.kamco.cd.training.common.utils.enums.Enums;
|
import com.kamco.cd.training.common.utils.enums.Enums;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
@@ -46,6 +47,7 @@ public class DatasetDto {
|
|||||||
private String statusCd;
|
private String statusCd;
|
||||||
private Boolean deleted;
|
private Boolean deleted;
|
||||||
private String dataType;
|
private String dataType;
|
||||||
|
private String cdClsType;
|
||||||
|
|
||||||
public Basic(
|
public Basic(
|
||||||
Long id,
|
Long id,
|
||||||
@@ -59,7 +61,8 @@ public class DatasetDto {
|
|||||||
ZonedDateTime createdDttm,
|
ZonedDateTime createdDttm,
|
||||||
String status,
|
String status,
|
||||||
Boolean deleted,
|
Boolean deleted,
|
||||||
String dataType) {
|
String dataType,
|
||||||
|
String cdClsType) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.uuid = uuid;
|
this.uuid = uuid;
|
||||||
this.title = title;
|
this.title = title;
|
||||||
@@ -73,6 +76,7 @@ public class DatasetDto {
|
|||||||
this.statusCd = status;
|
this.statusCd = status;
|
||||||
this.deleted = deleted;
|
this.deleted = deleted;
|
||||||
this.dataType = dataType;
|
this.dataType = dataType;
|
||||||
|
this.cdClsType = cdClsType;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getTotalSize(Long totalSize) {
|
public String getTotalSize(Long totalSize) {
|
||||||
@@ -90,7 +94,8 @@ public class DatasetDto {
|
|||||||
|
|
||||||
public String getStatus(String status) {
|
public String getStatus(String status) {
|
||||||
LearnDataRegister type = Enums.fromId(LearnDataRegister.class, status);
|
LearnDataRegister type = Enums.fromId(LearnDataRegister.class, status);
|
||||||
return type == null ? null : type.getText();
|
boolean english = HeaderUtil.isEnglishRequest();
|
||||||
|
return type == null ? null : (english ? type.getId() : type.getText());
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getYear() {
|
public String getYear() {
|
||||||
@@ -99,7 +104,8 @@ public class DatasetDto {
|
|||||||
|
|
||||||
public String getDataTypeName() {
|
public String getDataTypeName() {
|
||||||
LearnDataType type = Enums.fromId(LearnDataType.class, this.dataType);
|
LearnDataType type = Enums.fromId(LearnDataType.class, this.dataType);
|
||||||
return type == null ? null : type.getText();
|
boolean english = HeaderUtil.isEnglishRequest();
|
||||||
|
return type == null ? null : (english ? type.getId() : type.getText());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,6 +151,7 @@ public class DatasetDto {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Schema(name = "DatasetDetailReq", description = "데이터셋 상세 조회 요청")
|
@Schema(name = "DatasetDetailReq", description = "데이터셋 상세 조회 요청")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@@ -157,6 +164,8 @@ public class DatasetDto {
|
|||||||
private Long datasetId;
|
private Long datasetId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Schema(name = "DatasetRegisterReq", description = "데이터셋 등록 요청")
|
@Schema(name = "DatasetRegisterReq", description = "데이터셋 등록 요청")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@@ -245,12 +254,13 @@ public class DatasetDto {
|
|||||||
private Integer targetYyyy;
|
private Integer targetYyyy;
|
||||||
private String memo;
|
private String memo;
|
||||||
@JsonIgnore private Long classCount;
|
@JsonIgnore private Long classCount;
|
||||||
private Integer buildingCnt;
|
private Long buildingCnt;
|
||||||
private Integer containerCnt;
|
private Long containerCnt;
|
||||||
private String dataTypeName;
|
private String dataTypeName;
|
||||||
|
|
||||||
private Long wasteCnt;
|
private Long wasteCnt;
|
||||||
private Long landCoverCnt;
|
private Long landCoverCnt;
|
||||||
|
private Long solarPanelCnt;
|
||||||
|
|
||||||
public SelectDataSet(
|
public SelectDataSet(
|
||||||
String modelNo,
|
String modelNo,
|
||||||
@@ -263,6 +273,7 @@ public class DatasetDto {
|
|||||||
Integer targetYyyy,
|
Integer targetYyyy,
|
||||||
String memo,
|
String memo,
|
||||||
Long classCount) {
|
Long classCount) {
|
||||||
|
this.modelNo = modelNo;
|
||||||
this.datasetId = datasetId;
|
this.datasetId = datasetId;
|
||||||
this.uuid = uuid;
|
this.uuid = uuid;
|
||||||
this.dataType = dataType;
|
this.dataType = dataType;
|
||||||
@@ -277,6 +288,8 @@ public class DatasetDto {
|
|||||||
this.wasteCnt = classCount;
|
this.wasteCnt = classCount;
|
||||||
} else if (modelNo.equals(ModelType.G3.getId())) {
|
} else if (modelNo.equals(ModelType.G3.getId())) {
|
||||||
this.landCoverCnt = classCount;
|
this.landCoverCnt = classCount;
|
||||||
|
} else if (modelNo.equals(ModelType.G4.getId())) {
|
||||||
|
this.solarPanelCnt = classCount;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -290,8 +303,9 @@ public class DatasetDto {
|
|||||||
Integer compareYyyy,
|
Integer compareYyyy,
|
||||||
Integer targetYyyy,
|
Integer targetYyyy,
|
||||||
String memo,
|
String memo,
|
||||||
Integer buildingCnt,
|
Long buildingCnt,
|
||||||
Integer containerCnt) {
|
Long containerCnt) {
|
||||||
|
this.modelNo = modelNo;
|
||||||
this.datasetId = datasetId;
|
this.datasetId = datasetId;
|
||||||
this.uuid = uuid;
|
this.uuid = uuid;
|
||||||
this.dataType = dataType;
|
this.dataType = dataType;
|
||||||
@@ -307,7 +321,7 @@ public class DatasetDto {
|
|||||||
|
|
||||||
public String getDataTypeName(String groupTitleCd) {
|
public String getDataTypeName(String groupTitleCd) {
|
||||||
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
|
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
|
||||||
return type == null ? null : type.getText();
|
return type == null ? null : (HeaderUtil.isEnglishRequest() ? type.getId() : type.getText());
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getYear() {
|
public String getYear() {
|
||||||
@@ -531,6 +545,7 @@ public class DatasetDto {
|
|||||||
private Long totalSize;
|
private Long totalSize;
|
||||||
private Long totalObjectCount;
|
private Long totalObjectCount;
|
||||||
private String datasetPath;
|
private String datasetPath;
|
||||||
|
private String cdClsType;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@@ -540,5 +555,20 @@ public class DatasetDto {
|
|||||||
public static class AddDeliveriesReq {
|
public static class AddDeliveriesReq {
|
||||||
@Schema(description = "경로", example = "/")
|
@Schema(description = "경로", example = "/")
|
||||||
private String filePath;
|
private String filePath;
|
||||||
|
|
||||||
|
@Schema(description = "제목", example = "")
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@Schema(description = "메모", example = "")
|
||||||
|
private String memo;
|
||||||
|
|
||||||
|
@Schema(description = "비교년도", example = "")
|
||||||
|
private Integer compareYyyy;
|
||||||
|
|
||||||
|
@Schema(description = "기준년도", example = "")
|
||||||
|
private Integer targetYyyy;
|
||||||
|
|
||||||
|
@Schema(description = "회차", example = "")
|
||||||
|
private Long roundNo;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
|||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.kamco.cd.training.common.enums.DetectionClassification;
|
import com.kamco.cd.training.common.enums.DetectionClassification;
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
@@ -131,7 +132,12 @@ public class DatasetObjDto {
|
|||||||
private String classCd;
|
private String classCd;
|
||||||
|
|
||||||
public String getClassName() {
|
public String getClassName() {
|
||||||
return DetectionClassification.valueOf(classCd.toUpperCase()).getDesc();
|
|
||||||
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? DetectionClassification.fromString(classCd).getId()
|
||||||
|
: DetectionClassification.fromString(classCd).getDesc();
|
||||||
|
// fromString 메서드를 사용하여 안전하게 변환 (미정의 값은 ETC로 처리)
|
||||||
|
// return DetectionClassification.valueOf(classCd.toUpperCase()).getDesc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,4 +166,19 @@ public class DatasetObjDto {
|
|||||||
private JsonNode geojson;
|
private JsonNode geojson;
|
||||||
private String fileName;
|
private String fileName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public static class DatasetClsObjRegDto {
|
||||||
|
private Long datasetUid;
|
||||||
|
private String type;
|
||||||
|
private Integer yyyy;
|
||||||
|
private String classCd;
|
||||||
|
private String mapSheetNum;
|
||||||
|
private String tifImgPath;
|
||||||
|
private String fileName;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.dataset.dto;
|
package com.kamco.cd.training.dataset.dto;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
@@ -72,6 +73,7 @@ public class MapSheetDto {
|
|||||||
private List<Long> itemIds;
|
private List<Long> itemIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Schema(name = "MapSheetCheckReq", description = "도엽 번호 유효성 검증 요청")
|
@Schema(name = "MapSheetCheckReq", description = "도엽 번호 유효성 검증 요청")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@@ -101,3 +103,4 @@ public class MapSheetDto {
|
|||||||
private boolean duplicate;
|
private boolean duplicate;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
package com.kamco.cd.training.dataset.service;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.AddDeliveriesReq;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
||||||
|
import com.kamco.cd.training.postgres.core.DatasetCoreService;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.log4j.Log4j2;
|
||||||
|
import org.springframework.scheduling.annotation.Async;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Log4j2
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DatasetAsyncService {
|
||||||
|
|
||||||
|
private final DatasetService datasetService;
|
||||||
|
private final DatasetCoreService datasetCoreService;
|
||||||
|
|
||||||
|
private static final String LOG_PREFIX = "[납품 데이터셋]";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 납품 데이터셋 등록 비동기 업로드 처리 1) 데이터셋 구조/파일 검증 2) UID 생성 및 마스터 데이터 저장 3) 상태를 UPLOADING으로 변경 4) 실제
|
||||||
|
* 데이터(train/val/test) 등록 5) 완료 시 COMPLETED 상태로 변경 6) 실패 시 상태를 UPLOAD_FAILED로 변경 후 데이터 정리(삭제)
|
||||||
|
*
|
||||||
|
* @param req
|
||||||
|
*/
|
||||||
|
@Async("datasetExecutor")
|
||||||
|
public void insertDeliveriesDatasetAsync(AddDeliveriesReq req) {
|
||||||
|
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
log.info("{} 업로드 시작 ==========", LOG_PREFIX);
|
||||||
|
log.info(
|
||||||
|
"{} filePath={}, targetYyyy={}, compareYyyy={}, roundNo={}",
|
||||||
|
LOG_PREFIX,
|
||||||
|
req.getFilePath(),
|
||||||
|
req.getTargetYyyy(),
|
||||||
|
req.getCompareYyyy(),
|
||||||
|
req.getRoundNo());
|
||||||
|
|
||||||
|
Long datasetUid = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
// ===== 1. UID 생성 =====
|
||||||
|
// String uid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
|
||||||
|
|
||||||
|
// 26-05-08: UID를 생성하지 않고 folder name 을 uid 로 저장하기 -> req.getFilePath()
|
||||||
|
Path selectedPath = Paths.get(req.getFilePath());
|
||||||
|
String uid = selectedPath.getFileName().toString();
|
||||||
|
log.info("{} 생성된 UID: {}", LOG_PREFIX, uid);
|
||||||
|
|
||||||
|
// ===== 2. 마스터 데이터 생성 =====
|
||||||
|
String title = req.getTitle();
|
||||||
|
|
||||||
|
if (title == null || title.isBlank()) {
|
||||||
|
Integer compareYyyy = req.getCompareYyyy();
|
||||||
|
Integer targetYyyy = req.getTargetYyyy();
|
||||||
|
|
||||||
|
if (compareYyyy != null && targetYyyy != null) {
|
||||||
|
title = compareYyyy + "-" + targetYyyy;
|
||||||
|
} else {
|
||||||
|
title = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
DatasetMngRegDto datasetMngRegDto = new DatasetMngRegDto();
|
||||||
|
datasetMngRegDto.setUid(uid);
|
||||||
|
datasetMngRegDto.setDataType("DELIVER");
|
||||||
|
datasetMngRegDto.setCompareYyyy(req.getCompareYyyy() == null ? 0 : req.getCompareYyyy());
|
||||||
|
datasetMngRegDto.setTargetYyyy(req.getTargetYyyy() == null ? 0 : req.getTargetYyyy());
|
||||||
|
datasetMngRegDto.setRoundNo(req.getRoundNo());
|
||||||
|
datasetMngRegDto.setTitle(title);
|
||||||
|
datasetMngRegDto.setMemo(req.getMemo());
|
||||||
|
datasetMngRegDto.setDatasetPath(req.getFilePath());
|
||||||
|
datasetMngRegDto.setTotalSize(getDirectorySize(req.getFilePath())); // 선택한 폴더 안의 모든 파일 용량 합계
|
||||||
|
|
||||||
|
// 마스터 저장
|
||||||
|
datasetUid = datasetCoreService.insertDatasetMngData(datasetMngRegDto);
|
||||||
|
|
||||||
|
log.info("{} 마스터 저장 완료. datasetUid={}", LOG_PREFIX, datasetUid);
|
||||||
|
|
||||||
|
// ===== 3. 상태 변경 (업로드중) =====
|
||||||
|
datasetCoreService.updateDatasetUploadStatus(datasetUid, LearnDataRegister.UPLOADING);
|
||||||
|
log.info("{} 상태 변경 → UPLOADING. datasetUid={}", LOG_PREFIX, datasetUid);
|
||||||
|
|
||||||
|
// ===== 4. 데이터 등록 =====
|
||||||
|
long insertStart = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// 납품 데이터 obj 등록
|
||||||
|
datasetService.insertDeliveriesDataset(req, datasetUid);
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"{} 데이터 등록 완료. datasetUid={}, 소요시간={} ms",
|
||||||
|
LOG_PREFIX,
|
||||||
|
datasetUid,
|
||||||
|
System.currentTimeMillis() - insertStart);
|
||||||
|
|
||||||
|
// ===== 5. 상태 변경 (완료) =====
|
||||||
|
datasetCoreService.updateDatasetUploadStatus(datasetUid, LearnDataRegister.COMPLETED);
|
||||||
|
log.info("{} 상태 변경 → COMPLETED. datasetUid={}", LOG_PREFIX, datasetUid);
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"{} 업로드 완료. 총 소요시간={} ms ==========", LOG_PREFIX, System.currentTimeMillis() - startTime);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
|
||||||
|
log.error(
|
||||||
|
"{} 업로드 실패. datasetUid={}, filePath={}", LOG_PREFIX, datasetUid, req.getFilePath(), e);
|
||||||
|
|
||||||
|
if (datasetUid != null) {
|
||||||
|
try {
|
||||||
|
// ===== 실패 처리 =====
|
||||||
|
datasetCoreService.updateDatasetUploadStatus(datasetUid, LearnDataRegister.UPLOAD_FAILED);
|
||||||
|
log.error("{} 상태 변경 → 업로드 실패. datasetUid={}", LOG_PREFIX, datasetUid);
|
||||||
|
|
||||||
|
// 실패 시 데이터 정리
|
||||||
|
datasetCoreService.deleteAllDatasetObj(datasetUid);
|
||||||
|
log.error("{} 데이터 정리 완료. datasetUid={}", LOG_PREFIX, datasetUid);
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
log.error("{} 실패 후 정리 작업 중 오류. datasetUid={}", LOG_PREFIX, datasetUid, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long getDirectorySize(String filePath) {
|
||||||
|
Path selectedPath = Paths.get(filePath);
|
||||||
|
|
||||||
|
try (Stream<Path> paths = Files.walk(selectedPath)) {
|
||||||
|
return paths
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.mapToLong(
|
||||||
|
path -> {
|
||||||
|
try {
|
||||||
|
return Files.size(path);
|
||||||
|
} catch (IOException e) {
|
||||||
|
return 0L;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
} catch (IOException e) {
|
||||||
|
return 0L;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
package com.kamco.cd.training.dataset.service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetObjRegDto;
|
||||||
|
import com.kamco.cd.training.postgres.core.DatasetCoreService;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.log4j.Log4j2;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Log4j2
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DatasetBatchService {
|
||||||
|
|
||||||
|
private final DatasetCoreService datasetCoreService;
|
||||||
|
private final ObjectMapper mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 배치 단위 데이터 저장
|
||||||
|
*
|
||||||
|
* <p>- 전달받은 데이터 목록을 순회하며 개별 insert 처리 - batch 단위로 트랜잭션 관리
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void saveBatch(List<Map<String, Object>> batch, Long datasetUid, String type) {
|
||||||
|
for (Map<String, Object> map : batch) {
|
||||||
|
try {
|
||||||
|
insertTrainTestData(map, datasetUid, type);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("파일 단위 실패. skip. file={}", batch, e);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 단일 데이터 처리 및 insert DTO 생성
|
||||||
|
*
|
||||||
|
* <p>처리 흐름: 1) 경로/JSON 데이터 추출 2) 파일명에서 연도 및 도엽번호 파싱 3) label JSON → feature 단위 분리 4) feature별 DTO
|
||||||
|
* 생성 후 DB insert
|
||||||
|
*/
|
||||||
|
private void insertTrainTestData(Map<String, Object> map, Long datasetUid, String subDir) {
|
||||||
|
|
||||||
|
String comparePath = (String) map.get("input1");
|
||||||
|
String targetPath = (String) map.get("input2");
|
||||||
|
String labelPath = (String) map.get("label");
|
||||||
|
String geojsonPath = (String) map.get("geojson_path");
|
||||||
|
Object labelJson = map.get("label-json");
|
||||||
|
|
||||||
|
// JSON 파싱
|
||||||
|
JsonNode json;
|
||||||
|
try {
|
||||||
|
json = parseJson(labelJson);
|
||||||
|
if (json == null) {
|
||||||
|
log.warn("json null. skip. file={}", labelJson);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 실패하면 skip, 다음 진행
|
||||||
|
log.error("GeoJSON 파싱 실패. skip. file={}", geojsonPath, e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 파일명 파싱
|
||||||
|
String fileName = Paths.get(comparePath).getFileName().toString();
|
||||||
|
String[] fileNameStr = fileName.split("_");
|
||||||
|
|
||||||
|
if (fileNameStr.length < 4) {
|
||||||
|
log.error("파일명 파싱 실패: {}", fileName);
|
||||||
|
return;
|
||||||
|
// throw new IllegalArgumentException("잘못된 파일명 형식: " + fileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
int compareYyyy = 0;
|
||||||
|
int targetYyyy = 0;
|
||||||
|
try {
|
||||||
|
compareYyyy = parseInt(fileNameStr[1], "compareYyyy", fileName);
|
||||||
|
targetYyyy = parseInt(fileNameStr[2], "targetYyyy", fileName);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("기준년도 파싱 실패: {}", fileName);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String mapSheetNum = fileNameStr[3];
|
||||||
|
|
||||||
|
// JSON 유효성 체크
|
||||||
|
JsonNode featuresNode = json.path("features");
|
||||||
|
|
||||||
|
// 2. 비어있는지 확인
|
||||||
|
if (featuresNode.isEmpty()) {
|
||||||
|
log.warn("features empty. skip. file={}", geojsonPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!featuresNode.isArray()) {
|
||||||
|
log.warn("features array 아님. skip. file={}", geojsonPath);
|
||||||
|
return; // skip
|
||||||
|
}
|
||||||
|
|
||||||
|
if (featuresNode.isMissingNode() || !featuresNode.isArray() || featuresNode.isEmpty()) {
|
||||||
|
return; // skip
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjectNode base = mapper.createObjectNode();
|
||||||
|
base.put("type", "FeatureCollection");
|
||||||
|
|
||||||
|
for (JsonNode feature : featuresNode) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
JsonNode prop = feature.path("properties");
|
||||||
|
|
||||||
|
String compareClassCd = prop.path("before").asText(null);
|
||||||
|
String targetClassCd = prop.path("after").asText(null);
|
||||||
|
|
||||||
|
// null 방어
|
||||||
|
if (compareClassCd == null || targetClassCd == null) {
|
||||||
|
log.warn("class 값 없음. skip. file={}", fileName);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ArrayNode arr = mapper.createArrayNode();
|
||||||
|
arr.add(feature);
|
||||||
|
|
||||||
|
ObjectNode root = base.deepCopy();
|
||||||
|
root.set("features", arr);
|
||||||
|
|
||||||
|
DatasetObjRegDto objRegDto =
|
||||||
|
DatasetObjRegDto.builder()
|
||||||
|
.datasetUid(datasetUid)
|
||||||
|
.compareYyyy(compareYyyy)
|
||||||
|
.compareClassCd(compareClassCd)
|
||||||
|
.targetYyyy(targetYyyy)
|
||||||
|
.targetClassCd(targetClassCd)
|
||||||
|
.comparePath(comparePath)
|
||||||
|
.targetPath(targetPath)
|
||||||
|
.labelPath(labelPath)
|
||||||
|
.mapSheetNum(mapSheetNum)
|
||||||
|
.geojson(root)
|
||||||
|
.geojsonPath(geojsonPath)
|
||||||
|
.fileName(fileName)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// 데이터 타입별 insert
|
||||||
|
insertByType(subDir, objRegDto);
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 개별 feature skip
|
||||||
|
log.error("feature 처리 실패. skip. file={}", fileName, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 데이터 타입별 insert 처리 - type 값에 따라 대상 테이블 분기 - 잘못된 타입 입력 시 예외 발생 */
|
||||||
|
private void insertByType(String type, DatasetObjRegDto dto) {
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case "train" -> datasetCoreService.insertDatasetObj(dto);
|
||||||
|
case "val" -> datasetCoreService.insertDatasetValObj(dto);
|
||||||
|
case "test" -> datasetCoreService.insertDatasetTestObj(dto);
|
||||||
|
default -> throw new IllegalArgumentException("잘못된 타입: " + type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* label_json → JsonNode 변환
|
||||||
|
*
|
||||||
|
* <p>- JsonNode면 그대로 사용 - 문자열이면 파싱 수행 - 실패 시 로그 후 예외 발생
|
||||||
|
*/
|
||||||
|
private JsonNode parseJson(Object labelJson) {
|
||||||
|
try {
|
||||||
|
if (labelJson instanceof JsonNode jn) {
|
||||||
|
return jn;
|
||||||
|
}
|
||||||
|
return mapper.readTree(labelJson.toString());
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("label_json parse error: {}", labelJson, e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 문자열 → 정수 변환
|
||||||
|
*
|
||||||
|
* <p>- 파싱 실패 시 어떤 필드/파일에서 발생했는지 로그 기록 - 잘못된 데이터는 즉시 예외 처리
|
||||||
|
*/
|
||||||
|
private int parseInt(String value, String field, String fileName) {
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(value);
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
log.error("{} 파싱 실패. fileName={}, value={}", field, fileName, value);
|
||||||
|
throw new IllegalArgumentException(field + " 파싱 실패: " + fileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,825 @@
|
|||||||
|
package com.kamco.cd.training.dataset.service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
||||||
|
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||||
|
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||||
|
import com.kamco.cd.training.common.service.FormatStorage;
|
||||||
|
import com.kamco.cd.training.common.utils.FIleChecker;
|
||||||
|
import com.kamco.cd.training.config.api.ApiResponseDto.ApiResponseCode;
|
||||||
|
import com.kamco.cd.training.config.api.ApiResponseDto.ResponseObj;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetClsObjDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.AddDeliveriesReq;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.AddReq;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetClass;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetObjRegDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetStorage;
|
||||||
|
import com.kamco.cd.training.model.dto.FileDto.FoldersDto;
|
||||||
|
import com.kamco.cd.training.model.dto.FileDto.SrchFoldersDto;
|
||||||
|
import com.kamco.cd.training.postgres.core.DatasetClsCoreService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.core.io.InputStreamResource;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DatasetClsService {
|
||||||
|
|
||||||
|
private final DatasetClsCoreService datasetClsCoreService;
|
||||||
|
private final DatasetBatchService datasetBatchService;
|
||||||
|
|
||||||
|
private static final List<String> LABEL_DIRS = List.of("label-json", "label", "input1", "input2");
|
||||||
|
private static final List<String> REQUIRED_DIRS = Arrays.asList("train", "val", "test");
|
||||||
|
private static final List<String> CHECK_DIRS = List.of("label", "input1", "input2");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 목록 조회
|
||||||
|
*
|
||||||
|
* @param searchReq 검색 조건
|
||||||
|
* @return 데이터셋 목록
|
||||||
|
*/
|
||||||
|
public Page<DatasetDto.Basic> searchDatasets(DatasetDto.SearchReq searchReq) {
|
||||||
|
log.info("데이터셋 목록 조회 - 조건: {}", searchReq);
|
||||||
|
return datasetClsCoreService.findDatasetList(searchReq);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 상세 조회
|
||||||
|
*
|
||||||
|
* @param id 상세 조회할 목록 Id
|
||||||
|
* @return 데이터셋 상세 정보
|
||||||
|
*/
|
||||||
|
public DatasetDto.Basic getDatasetDetail(UUID id) {
|
||||||
|
return datasetClsCoreService.getOneByUuid(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
/**
|
||||||
|
* 데이터셋 등록
|
||||||
|
*
|
||||||
|
* @param registerReq 등록 요청
|
||||||
|
* @return 등록된 데이터셋 ID
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public Long registerDataset(DatasetDto.RegisterReq registerReq) {
|
||||||
|
log.info("데이터셋 등록 - 요청: {}", registerReq);
|
||||||
|
DatasetDto.Basic saved = datasetClsCoreService.save(registerReq);
|
||||||
|
log.info("데이터셋 등록 완료 - ID: {}", saved.getId());
|
||||||
|
return saved.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
/**
|
||||||
|
* 데이터셋 수정
|
||||||
|
*
|
||||||
|
* @param updateReq 수정 요청
|
||||||
|
* @return 수정된 데이터셋 ID
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void updateDataset(UUID uuid, DatasetDto.UpdateReq updateReq) {
|
||||||
|
datasetClsCoreService.update(uuid, updateReq);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 삭제 (다건)
|
||||||
|
*
|
||||||
|
* @param uuid 삭제 요청
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void deleteDatasets(UUID uuid) {
|
||||||
|
datasetClsCoreService.deleteDatasets(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 통계 요약
|
||||||
|
*
|
||||||
|
* @param summaryReq 요약 요청
|
||||||
|
* @return 통계 요약
|
||||||
|
*/
|
||||||
|
public DatasetDto.Summary getDatasetSummary(DatasetDto.SummaryReq summaryReq) {
|
||||||
|
log.info("데이터셋 통계 요약 - 요청: {}", summaryReq);
|
||||||
|
return datasetClsCoreService.getDatasetSummary(summaryReq);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Page<DatasetClsObjDto.Basic> searchDatasetClsObjectList(
|
||||||
|
DatasetClsObjDto.ClsSearchReq searchReq) {
|
||||||
|
return datasetClsCoreService.searchDatasetClsObjectList(searchReq);
|
||||||
|
}
|
||||||
|
|
||||||
|
public UUID deleteDatasetObjByUuid(UUID uuid) {
|
||||||
|
return datasetClsCoreService.deleteDatasetObjByUuid(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 object class 조회
|
||||||
|
*
|
||||||
|
* @param uuid dataset uuid
|
||||||
|
* @param type compare, target
|
||||||
|
*/
|
||||||
|
public List<DatasetClass> getDatasetObjByUuid(UUID uuid, String type) {
|
||||||
|
return datasetClsCoreService.findDatasetObjClassByUuid(uuid, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 사용 가능 공간 조회
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public DatasetStorage getUsableBytes() {
|
||||||
|
// 현재 실행 위치가 속한 디스크 기준
|
||||||
|
try {
|
||||||
|
FormatStorage.DiskUsage usage = FormatStorage.getDiskUsage(Path.of("."));
|
||||||
|
log.debug("경로 : {}", usage.path());
|
||||||
|
log.debug("총 저장공간 : {}", usage.totalText());
|
||||||
|
log.debug("남은 저장공간 : {}", usage.usableText());
|
||||||
|
log.debug("사용률 : {}", usage.usedPercent());
|
||||||
|
|
||||||
|
DatasetStorage datasetStorage = new DatasetStorage();
|
||||||
|
datasetStorage.setUsableBytes(usage.usableText());
|
||||||
|
return datasetStorage;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 분류모델 업로드
|
||||||
|
*
|
||||||
|
* @param addReq
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public ResponseObj insertDataset(@Valid AddReq addReq) {
|
||||||
|
|
||||||
|
Long datasetUid = null; // master id 값, 등록하면서 가져올 예정
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 압축 해제
|
||||||
|
FIleChecker.unzip(addReq.getFileName(), addReq.getFilePath());
|
||||||
|
|
||||||
|
// 압축 해제한 폴더 하위에 train,val,test 폴더 모두 존재하는지 확인
|
||||||
|
validateClsTrainValTestDirs(addReq.getFilePath() + addReq.getFileName().replace(".zip", ""));
|
||||||
|
|
||||||
|
// 해제한 폴더 읽어서 데이터 저장
|
||||||
|
datasetUid =
|
||||||
|
this.processAndInsertDataset(
|
||||||
|
addReq.getFilePath() + addReq.getFileName().replace(".zip", ""), addReq);
|
||||||
|
log.info("######testttest#### datasetUid: {}", datasetUid);
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error(e.getMessage());
|
||||||
|
return new ResponseObj(ApiResponseCode.INTERNAL_SERVER_ERROR, e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
datasetClsCoreService.updateDatasetUploadStatus(datasetUid, LearnDataRegister.COMPLETED);
|
||||||
|
return new ResponseObj(ApiResponseCode.OK, "업로드 성공하였습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Map<String, Object>> getUnzipDatasetFiles(String unzipRootPath, String subDir) {
|
||||||
|
|
||||||
|
Path root = Paths.get(unzipRootPath).resolve(subDir);
|
||||||
|
Map<String, Map<String, Object>> grouped = new HashMap<>();
|
||||||
|
|
||||||
|
for (String dirName : LABEL_DIRS) {
|
||||||
|
Path dir = root.resolve(dirName);
|
||||||
|
|
||||||
|
if (!Files.isDirectory(dir)) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"폴더가 존재하지 않습니다. 업로드 된 파일을 확인하세요. : " + dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
try (Stream<Path> stream = Files.list(dir)) {
|
||||||
|
stream
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.forEach(
|
||||||
|
path -> {
|
||||||
|
String fileName = path.getFileName().toString();
|
||||||
|
String baseName = getBaseName(fileName);
|
||||||
|
|
||||||
|
// baseName 기준 Map 생성
|
||||||
|
Map<String, Object> data =
|
||||||
|
grouped.computeIfAbsent(baseName, k -> new HashMap<>());
|
||||||
|
|
||||||
|
// 공통 메타
|
||||||
|
data.put("baseName", baseName);
|
||||||
|
|
||||||
|
// 폴더별 처리
|
||||||
|
if ("label-json".equals(dirName)) {
|
||||||
|
// json 파일이면 파싱
|
||||||
|
try {
|
||||||
|
data.put("label-json", readJson(path));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("파일 JSON 읽기 실패. skip. file={}", path, e);
|
||||||
|
return; // skip
|
||||||
|
}
|
||||||
|
data.put("geojson_path", path.toAbsolutePath().toString());
|
||||||
|
} else {
|
||||||
|
data.put(dirName, path.toAbsolutePath().toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ArrayList<>(grouped.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Long insertTrainTestData(
|
||||||
|
Map<String, Object> map, AddReq addReq, int idx, Long datasetUid, String subDir) {
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
String comparePath = (String) map.get("input1");
|
||||||
|
String targetPath = (String) map.get("input2");
|
||||||
|
String labelPath = (String) map.get("label");
|
||||||
|
String geojsonPath = (String) map.get("geojson_path");
|
||||||
|
Object labelJson = map.get("label-json");
|
||||||
|
JsonNode json;
|
||||||
|
|
||||||
|
if (labelJson instanceof JsonNode jn) {
|
||||||
|
json = jn;
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
json = mapper.readTree(labelJson.toString());
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException("label_json parse error", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String fileName = Paths.get(comparePath).getFileName().toString();
|
||||||
|
String[] fileNameStr = fileName.split("_");
|
||||||
|
String compareYyyy = fileNameStr[1];
|
||||||
|
String targetYyyy = fileNameStr[2];
|
||||||
|
String mapSheetNum = fileNameStr[3];
|
||||||
|
|
||||||
|
if (idx == 0 && subDir.equals("train")) {
|
||||||
|
String title = compareYyyy + "-" + targetYyyy; // 제목 : 비교년도-기준년도
|
||||||
|
String dataType = LearnDataType.PRODUCTION.getId(); // 만들어 넣는 건 다 제작
|
||||||
|
Long stage =
|
||||||
|
datasetClsCoreService.getDatasetMaxStage(
|
||||||
|
Integer.parseInt(compareYyyy), Integer.parseInt(targetYyyy))
|
||||||
|
+ 1;
|
||||||
|
String uid = addReq.getFileName().replace(".zip", "");
|
||||||
|
|
||||||
|
DatasetMngRegDto mngRegDto =
|
||||||
|
DatasetMngRegDto.builder()
|
||||||
|
.uid(uid)
|
||||||
|
.dataType(dataType)
|
||||||
|
.compareYyyy(Integer.parseInt(compareYyyy))
|
||||||
|
.targetYyyy(Integer.parseInt(targetYyyy))
|
||||||
|
.title(title)
|
||||||
|
.memo(addReq.getMemo())
|
||||||
|
.roundNo(stage)
|
||||||
|
.totalSize(addReq.getFileSize())
|
||||||
|
.datasetPath(addReq.getFilePath() + uid)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
datasetUid = datasetClsCoreService.insertDatasetMngData(mngRegDto); // tb_dataset 에 insert
|
||||||
|
}
|
||||||
|
|
||||||
|
// datasetUid 로 obj 도 등록하기
|
||||||
|
// Json 갯수만큼 for문 돌려서 insert 해야 함, features에 빈값
|
||||||
|
if (json != null && json.path("features") != null && !json.path("features").isEmpty()) {
|
||||||
|
|
||||||
|
for (JsonNode feature : json.path("features")) {
|
||||||
|
JsonNode prop = feature.path("properties");
|
||||||
|
String compareClassCd = prop.path("before").asText(null);
|
||||||
|
String targetClassCd = prop.path("after").asText(null);
|
||||||
|
|
||||||
|
// 한 개씩 자른 geojson을 FeatureCollection 으로 만들어서 넣기
|
||||||
|
ObjectNode root = mapper.createObjectNode();
|
||||||
|
root.put("type", "FeatureCollection");
|
||||||
|
ArrayNode features = mapper.createArrayNode();
|
||||||
|
features.add(feature);
|
||||||
|
root.set("features", features);
|
||||||
|
|
||||||
|
DatasetObjRegDto objRegDto =
|
||||||
|
DatasetObjRegDto.builder()
|
||||||
|
.datasetUid(datasetUid)
|
||||||
|
.compareYyyy(Integer.parseInt(compareYyyy))
|
||||||
|
.compareClassCd(compareClassCd)
|
||||||
|
.targetYyyy(Integer.parseInt(targetYyyy))
|
||||||
|
.targetClassCd(targetClassCd)
|
||||||
|
.comparePath(comparePath)
|
||||||
|
.targetPath(targetPath)
|
||||||
|
.labelPath(labelPath)
|
||||||
|
.mapSheetNum(mapSheetNum)
|
||||||
|
.geojson(root)
|
||||||
|
.geojsonPath(geojsonPath)
|
||||||
|
.fileName(fileName)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
if (subDir.equals("train")) {
|
||||||
|
datasetClsCoreService.insertDatasetObj(objRegDto);
|
||||||
|
} else if (subDir.equals("val")) {
|
||||||
|
datasetClsCoreService.insertDatasetValObj(objRegDto);
|
||||||
|
} else {
|
||||||
|
datasetClsCoreService.insertDatasetTestObj(objRegDto);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return datasetUid;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CLS zip file DB화
|
||||||
|
*
|
||||||
|
* @param unzipRootPath
|
||||||
|
* @param addReq
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public Long processAndInsertDataset(String unzipRootPath, AddReq addReq) {
|
||||||
|
Path datasetRoot = Paths.get(unzipRootPath).resolve("dataset");
|
||||||
|
|
||||||
|
log.info("datasetRoot: {}", datasetRoot);
|
||||||
|
Long datasetUid = null;
|
||||||
|
boolean isMasterInserted = false; // Master(Mng) 테이블에 최초 1회만 등록하기 위한 플래그
|
||||||
|
|
||||||
|
// 1. 순회할 상위 폴더 목록
|
||||||
|
for (String subDir : REQUIRED_DIRS) {
|
||||||
|
Path subDirPath = datasetRoot.resolve(subDir);
|
||||||
|
if (!Files.exists(subDirPath) || !Files.isDirectory(subDirPath)) {
|
||||||
|
continue; // 해당 폴더가 없으면 다음으로 패스
|
||||||
|
}
|
||||||
|
|
||||||
|
try (Stream<Path> classDirs = Files.list(subDirPath)) {
|
||||||
|
// 2. 클래스명 폴더 목록 추출 (예: building, container, water 등)
|
||||||
|
List<Path> classDirList = classDirs.filter(Files::isDirectory).toList();
|
||||||
|
|
||||||
|
for (Path classDir : classDirList) {
|
||||||
|
// DB에 넣을 classCd (폴더명) 추출
|
||||||
|
String classCd = classDir.getFileName().toString();
|
||||||
|
|
||||||
|
try (Stream<Path> files = Files.list(classDir)) {
|
||||||
|
// 3. 해당 클래스 폴더 안의 실제 파일(tif) 목록 추출
|
||||||
|
List<Path> filePaths =
|
||||||
|
files
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.sorted(Comparator.comparing(Path::getFileName)) // 정렬 로직 추가
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
if (filePaths.isEmpty()) continue; // 폴더가 비어있으면 에러 방지를 위해 패스
|
||||||
|
|
||||||
|
// ★ 맨 앞의 첫 번째 파일명에서 compareYyyy 추출 및 targetYyyy 계산
|
||||||
|
String firstFileName = filePaths.getFirst().getFileName().toString();
|
||||||
|
String compareYyyy = firstFileName.split("_")[0]; // 예: "2021"
|
||||||
|
String targetYyyy = String.valueOf(Integer.parseInt(compareYyyy) + 1); // 예: "2022"
|
||||||
|
|
||||||
|
for (Path file : filePaths) {
|
||||||
|
String fileName = file.getFileName().toString();
|
||||||
|
String absolutePath = file.toAbsolutePath().toString();
|
||||||
|
String yyyy = fileName.split("_")[0];
|
||||||
|
|
||||||
|
// 4. 파일명 파싱 (확장자 제거 후 Split)
|
||||||
|
// ※ 주의: 첨부하신 이미지의 파일명(2021_33607077_idx93)을 기준으로 인덱스를 재조정했습니다.
|
||||||
|
String nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
|
||||||
|
String[] fileNameStr = nameWithoutExt.split("_");
|
||||||
|
String mapSheetNum = fileNameStr.length > 1 ? fileNameStr[1] : ""; // 33607077
|
||||||
|
|
||||||
|
// 5. Master(Mng) 데이터 등록 (전체 순회 중 최초 1회만 실행)
|
||||||
|
if (!isMasterInserted) {
|
||||||
|
String title = compareYyyy + "-" + targetYyyy;
|
||||||
|
Long stage =
|
||||||
|
datasetClsCoreService.getDatasetMaxStage(
|
||||||
|
Integer.parseInt(compareYyyy), Integer.parseInt(targetYyyy))
|
||||||
|
+ 1;
|
||||||
|
String uid = addReq.getFileName().replace(".zip", "");
|
||||||
|
|
||||||
|
DatasetMngRegDto mngRegDto =
|
||||||
|
DatasetMngRegDto.builder()
|
||||||
|
.uid(uid)
|
||||||
|
.dataType(LearnDataType.PRODUCTION.getId())
|
||||||
|
.compareYyyy(Integer.parseInt(compareYyyy))
|
||||||
|
.targetYyyy(Integer.parseInt(targetYyyy))
|
||||||
|
.title(title)
|
||||||
|
.memo(addReq.getMemo())
|
||||||
|
.roundNo(stage)
|
||||||
|
.totalSize(addReq.getFileSize())
|
||||||
|
.datasetPath(addReq.getFilePath() + uid)
|
||||||
|
.cdClsType("CLS")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
datasetUid = datasetClsCoreService.insertDatasetMngData(mngRegDto);
|
||||||
|
isMasterInserted = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Obj(상세) 데이터 등록
|
||||||
|
DatasetObjDto.DatasetClsObjRegDto objRegDto =
|
||||||
|
DatasetObjDto.DatasetClsObjRegDto.builder()
|
||||||
|
.datasetUid(datasetUid)
|
||||||
|
.type(subDir)
|
||||||
|
.yyyy(Integer.parseInt(yyyy))
|
||||||
|
.classCd(classCd)
|
||||||
|
.mapSheetNum(mapSheetNum)
|
||||||
|
.tifImgPath(absolutePath) // 실제 파일의 절대 경로
|
||||||
|
.fileName(fileName)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// 7. 폴더 위치(train/val/test)에 맞는 테이블에 Insert
|
||||||
|
datasetClsCoreService.insertDatasetClsObj(objRegDto);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException("디렉토리 읽기 중 오류가 발생했습니다: " + subDirPath, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("$$$$$$$$$$datasetUid: {}", datasetUid);
|
||||||
|
return datasetUid;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cls File 목록
|
||||||
|
*
|
||||||
|
* @param unzipRootPath
|
||||||
|
* @param subDir
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
private List<String> getUnzipDatasetClsFiles(String unzipRootPath, String subDir) {
|
||||||
|
|
||||||
|
Path root = Paths.get(unzipRootPath).resolve("dataset");
|
||||||
|
Map<String, Map<String, Object>> grouped = new HashMap<>();
|
||||||
|
|
||||||
|
Path dir = root.resolve(subDir);
|
||||||
|
|
||||||
|
if (!Files.isDirectory(dir)) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"폴더가 존재하지 않습니다. 업로드 된 파일을 확인하세요. : " + dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
try (Stream<Path> stream = Files.list(dir)) {
|
||||||
|
return stream
|
||||||
|
.filter(Files::isRegularFile) // 파일만 필터링 (하위 폴더 제외)
|
||||||
|
.map(path -> path.toAbsolutePath().toString()) // 절대 경로 문자열로 변환
|
||||||
|
.toList(); // List로 수집 (Java 16 미만인 경우 .collect(Collectors.toList()) 사용)
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getBaseName(String fileName) {
|
||||||
|
int idx = fileName.lastIndexOf('.');
|
||||||
|
return (idx > 0) ? fileName.substring(0, idx) : fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode readJson(Path jsonPath) {
|
||||||
|
try {
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
return mapper.readTree(jsonPath.toFile());
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException("JSON 읽기 실패: " + jsonPath, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFilePathByUUIDPathType(UUID uuid, String pathType) {
|
||||||
|
return datasetClsCoreService.getFilePathByUUIDPathType(uuid, pathType);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String escape(String path) {
|
||||||
|
// 쉘 커맨드에서 안전하게 사용할 수 있도록 문자열을 작은따옴표로 감싸면서, 내부의 작은따옴표를 이스케이프 처리
|
||||||
|
return "'" + path.replace("'", "'\"'\"'") + "'";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalizeLinuxPath(String path) {
|
||||||
|
return path.replace("\\", "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
public ResponseEntity<Resource> getFilePathByFile(String remoteFilePath) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
Path path = Paths.get(remoteFilePath);
|
||||||
|
InputStream inputStream = Files.newInputStream(path);
|
||||||
|
|
||||||
|
InputStreamResource resource =
|
||||||
|
new InputStreamResource(inputStream) {
|
||||||
|
@Override
|
||||||
|
public long contentLength() {
|
||||||
|
return -1; // 알 수 없으면 -1
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
String fileName = Paths.get(remoteFilePath.replace("\\", "/")).getFileName().toString();
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
|
||||||
|
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
|
.body(resource);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** unzipRootDir: 압축 해제된 폴더 경로 (ex: /data/xxx/myzipname) */
|
||||||
|
public static void validateTrainValTestDirs(String unzipRootDir) {
|
||||||
|
Path root = Paths.get(unzipRootDir);
|
||||||
|
|
||||||
|
// 루트 폴더 자체 존재 확인
|
||||||
|
if (!Files.exists(root) || !Files.isDirectory(root)) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"압축 해제 폴더가 존재하지 않습니다: " + unzipRootDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 필요한 폴더들 존재/디렉토리 여부 확인
|
||||||
|
List<String> missing =
|
||||||
|
REQUIRED_DIRS.stream()
|
||||||
|
.filter(d -> !Files.isDirectory(root.resolve(d)))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
if (!missing.isEmpty()) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"데이터 폴더 구조가 올바르지 않습니다. 누락된 폴더: "
|
||||||
|
+ String.join(", ", missing)
|
||||||
|
+ " (필수: train, val, test)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** unzipRootDir: 압축 해제된 폴더 경로 (ex: /zip파일폴더/dataset/train,val,test) */
|
||||||
|
public static void validateClsTrainValTestDirs(String unzipRootDir) {
|
||||||
|
Path root = Paths.get(unzipRootDir).resolve("dataset");
|
||||||
|
|
||||||
|
// 루트 폴더 자체 존재 확인
|
||||||
|
if (!Files.exists(root) || !Files.isDirectory(root)) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"압축 해제 폴더가 존재하지 않습니다: " + root.toAbsolutePath().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 필요한 폴더들 존재/디렉토리 여부 확인
|
||||||
|
List<String> missing =
|
||||||
|
REQUIRED_DIRS.stream()
|
||||||
|
.filter(d -> !Files.isDirectory(root.resolve(d)))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
if (!missing.isEmpty()) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"데이터 폴더 구조가 올바르지 않습니다. 누락된 폴더: "
|
||||||
|
+ String.join(", ", missing)
|
||||||
|
+ " (필수: train, val, test)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void validateDirFileCount(String unzipRootDir) {
|
||||||
|
Path root = Paths.get(unzipRootDir);
|
||||||
|
|
||||||
|
for (String split : REQUIRED_DIRS) {
|
||||||
|
|
||||||
|
Path splitPath = root.resolve(split);
|
||||||
|
|
||||||
|
Map<String, Long> fileCountMap = new HashMap<>();
|
||||||
|
|
||||||
|
for (String subDir : CHECK_DIRS) { // input1, input2, label 폴더만 수행하기
|
||||||
|
|
||||||
|
Path subDirPath = splitPath.resolve(subDir);
|
||||||
|
|
||||||
|
if (!Files.isDirectory(subDirPath)) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
split + " 폴더 하위에 " + subDir + " 폴더가 존재하지 않습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
long count;
|
||||||
|
try (Stream<Path> files = Files.list(subDirPath)) {
|
||||||
|
count = files.filter(Files::isRegularFile).count();
|
||||||
|
log.info("dir: " + subDirPath + ", count: " + count);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
split + "/" + subDir + " 파일 개수 확인 중 오류 발생");
|
||||||
|
}
|
||||||
|
|
||||||
|
fileCountMap.put(subDir, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 모든 폴더 파일 개수가 동일한지 확인
|
||||||
|
Set<Long> uniqueCounts = new HashSet<>(fileCountMap.values());
|
||||||
|
|
||||||
|
if (uniqueCounts.size() != 1) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
split + " 데이터 파일 개수가 일치하지 않습니다. " + fileCountMap.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 폴더 조회
|
||||||
|
*
|
||||||
|
* @param srchDto 폴더 경로
|
||||||
|
* @return 폴더 리스트
|
||||||
|
* @throws IOException
|
||||||
|
*/
|
||||||
|
public FoldersDto getFolderAll(SrchFoldersDto srchDto) throws IOException {
|
||||||
|
|
||||||
|
File dir = new File(srchDto.getDirPath() == null ? "/" : srchDto.getDirPath());
|
||||||
|
|
||||||
|
// 존재 + 디렉토리 체크
|
||||||
|
if (!dir.exists() || !dir.isDirectory()) {
|
||||||
|
throw new CustomApiException("BAD_REQUEST", HttpStatus.BAD_REQUEST, "잘못된 경로입니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 권한 없을때
|
||||||
|
if (!dir.canRead()) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.FORBIDDEN.getId(), HttpStatus.FORBIDDEN, "디렉토리에 접근할 권한이 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
String canonicalPath = dir.getCanonicalPath();
|
||||||
|
|
||||||
|
File[] files = dir.listFiles();
|
||||||
|
|
||||||
|
if (files == null) {
|
||||||
|
return new FoldersDto(canonicalPath, 0, 0, Collections.emptyList());
|
||||||
|
}
|
||||||
|
|
||||||
|
List<FIleChecker.Folder> folders = new ArrayList<>();
|
||||||
|
|
||||||
|
int folderTotCnt = 0;
|
||||||
|
int folderErrTotCnt = 0;
|
||||||
|
|
||||||
|
for (File f : files) {
|
||||||
|
|
||||||
|
// 숨김 제외
|
||||||
|
if (f.isHidden()) continue;
|
||||||
|
|
||||||
|
if (f.isDirectory()) {
|
||||||
|
|
||||||
|
// 폴더 개수 증가
|
||||||
|
folderTotCnt++;
|
||||||
|
|
||||||
|
// 폴더 유효성 여부 (기본 true, 이후 검증 로직으로 변경 가능)
|
||||||
|
boolean isValid = true;
|
||||||
|
|
||||||
|
// 유효하지 않은 폴더 카운트 증가
|
||||||
|
if (!isValid) folderErrTotCnt++;
|
||||||
|
|
||||||
|
// 현재 폴더 이름 (ex: train, images 등)
|
||||||
|
String folderNm = f.getName();
|
||||||
|
|
||||||
|
// 부모 경로 (ex: /data/datasets)
|
||||||
|
String parentPath = f.getParent();
|
||||||
|
|
||||||
|
// 부모 폴더 이름 (ex: datasets)
|
||||||
|
String parentFolderNm = new File(parentPath).getName();
|
||||||
|
|
||||||
|
// 전체 절대 경로 (ex: /data/datasets/train)
|
||||||
|
String fullPath = f.getAbsolutePath();
|
||||||
|
|
||||||
|
// 폴더 깊이 (경로 기준 depth)
|
||||||
|
// ex: /a/b/c → depth = 3
|
||||||
|
int depth = f.toPath().getNameCount();
|
||||||
|
|
||||||
|
// 하위 폴더 개수
|
||||||
|
long childCnt = FIleChecker.getChildFolderCount(f);
|
||||||
|
|
||||||
|
// 마지막 수정 시간 (문자열 포맷)
|
||||||
|
String lastModified = FIleChecker.getLastModified(f);
|
||||||
|
|
||||||
|
// Folder DTO 생성 및 리스트에 추가
|
||||||
|
folders.add(
|
||||||
|
new FIleChecker.Folder(
|
||||||
|
folderNm, // 폴더명
|
||||||
|
parentFolderNm, // 부모 폴더명
|
||||||
|
parentPath, // 부모 경로
|
||||||
|
fullPath, // 전체 경로
|
||||||
|
depth, // 깊이
|
||||||
|
childCnt, // 하위 폴더 개수
|
||||||
|
lastModified, // 수정일시
|
||||||
|
isValid // 유효성 여부
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 폴더 정렬
|
||||||
|
folders.sort(
|
||||||
|
Comparator.comparing(FIleChecker.Folder::getFolderNm, String.CASE_INSENSITIVE_ORDER));
|
||||||
|
|
||||||
|
return new FoldersDto(canonicalPath, folderTotCnt, folderErrTotCnt, folders);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 납품 데이터 등록
|
||||||
|
*
|
||||||
|
* @param req 폴더경로, 메모
|
||||||
|
* @return 성공/실패 여부0
|
||||||
|
*/
|
||||||
|
public void insertDeliveriesDataset(AddDeliveriesReq req, Long datasetUid) {
|
||||||
|
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// 처리
|
||||||
|
processType(req.getFilePath(), datasetUid, "train");
|
||||||
|
processType(req.getFilePath(), datasetUid, "val");
|
||||||
|
processType(req.getFilePath(), datasetUid, "test");
|
||||||
|
|
||||||
|
log.info("========== 전체 완료. 총 소요시간: {} ms ==========", System.currentTimeMillis() - startTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 납품 데이터 등록 처리
|
||||||
|
*
|
||||||
|
* @param path
|
||||||
|
* @param datasetUid
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
private void processType(String path, Long datasetUid, String type) {
|
||||||
|
long start = System.currentTimeMillis();
|
||||||
|
|
||||||
|
log.info("[납품 데이터 등록 처리][{}] 시작", type.toUpperCase());
|
||||||
|
|
||||||
|
List<Map<String, Object>> list = getUnzipDatasetFiles(path, type);
|
||||||
|
|
||||||
|
int batchSize = 1000;
|
||||||
|
int total = list.size();
|
||||||
|
int processed = 0;
|
||||||
|
|
||||||
|
for (int i = 0; i < total; i += batchSize) {
|
||||||
|
|
||||||
|
List<Map<String, Object>> batch = list.subList(i, Math.min(i + batchSize, total));
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info("[납품 데이터 등록 처리][{}] batch 시작: {} ~ {}", type, i, i + batch.size());
|
||||||
|
|
||||||
|
datasetBatchService.saveBatch(batch, datasetUid, type);
|
||||||
|
|
||||||
|
processed += batch.size();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("batch 실패 row 데이터: {}", batch);
|
||||||
|
log.error(
|
||||||
|
"[납품 데이터 등록 처리][{}] batch 실패. range: {} ~ {}, datasetUid={}",
|
||||||
|
type,
|
||||||
|
i,
|
||||||
|
i + batch.size(),
|
||||||
|
datasetUid,
|
||||||
|
e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"[납품 데이터 등록 처리][{}] 완료. 총 {}건, 소요시간: {} ms",
|
||||||
|
type,
|
||||||
|
total,
|
||||||
|
System.currentTimeMillis() - start);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void validateExistsUidChk(String filePath) {
|
||||||
|
Path selectedPath = Paths.get(filePath);
|
||||||
|
String uid = selectedPath.getFileName().toString();
|
||||||
|
|
||||||
|
// 같은 uid 로 등록한 파일이 있는지 확인
|
||||||
|
Long existsCnt = datasetClsCoreService.findDatasetByUidExistsCnt(uid);
|
||||||
|
if (existsCnt > 0) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.DUPLICATE_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"이미 등록된 회차 데이터 파일입니다. 확인 부탁드립니다.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFilePathByUUIDPathTif(UUID uuid) {
|
||||||
|
return datasetClsCoreService.getFilePathByUUIDPathTif(uuid);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
|||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
||||||
import com.kamco.cd.training.common.enums.LearnDataType;
|
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||||
import com.kamco.cd.training.common.exception.CustomApiException;
|
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||||
import com.kamco.cd.training.common.service.FormatStorage;
|
import com.kamco.cd.training.common.service.FormatStorage;
|
||||||
@@ -22,8 +23,6 @@ import com.kamco.cd.training.dataset.dto.DatasetObjDto.SearchReq;
|
|||||||
import com.kamco.cd.training.model.dto.FileDto.FoldersDto;
|
import com.kamco.cd.training.model.dto.FileDto.FoldersDto;
|
||||||
import com.kamco.cd.training.model.dto.FileDto.SrchFoldersDto;
|
import com.kamco.cd.training.model.dto.FileDto.SrchFoldersDto;
|
||||||
import com.kamco.cd.training.postgres.core.DatasetCoreService;
|
import com.kamco.cd.training.postgres.core.DatasetCoreService;
|
||||||
import jakarta.persistence.EntityManager;
|
|
||||||
import jakarta.persistence.PersistenceContext;
|
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -45,7 +44,6 @@ import java.util.stream.Collectors;
|
|||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.core.io.InputStreamResource;
|
import org.springframework.core.io.InputStreamResource;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
@@ -62,12 +60,7 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
public class DatasetService {
|
public class DatasetService {
|
||||||
|
|
||||||
private final DatasetCoreService datasetCoreService;
|
private final DatasetCoreService datasetCoreService;
|
||||||
@PersistenceContext
|
private final DatasetBatchService datasetBatchService;
|
||||||
private EntityManager em;
|
|
||||||
private final ObjectMapper mapper = new ObjectMapper();
|
|
||||||
|
|
||||||
@Value("${file.dataset-dir}")
|
|
||||||
private String datasetDir;
|
|
||||||
|
|
||||||
private static final List<String> LABEL_DIRS = List.of("label-json", "label", "input1", "input2");
|
private static final List<String> LABEL_DIRS = List.of("label-json", "label", "input1", "input2");
|
||||||
private static final List<String> REQUIRED_DIRS = Arrays.asList("train", "val", "test");
|
private static final List<String> REQUIRED_DIRS = Arrays.asList("train", "val", "test");
|
||||||
@@ -94,6 +87,7 @@ public class DatasetService {
|
|||||||
return datasetCoreService.getOneByUuid(id);
|
return datasetCoreService.getOneByUuid(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 데이터셋 등록
|
* 데이터셋 등록
|
||||||
*
|
*
|
||||||
@@ -108,6 +102,7 @@ public class DatasetService {
|
|||||||
return saved.getId();
|
return saved.getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
/**
|
/**
|
||||||
* 데이터셋 수정
|
* 데이터셋 수정
|
||||||
*
|
*
|
||||||
@@ -144,7 +139,6 @@ public class DatasetService {
|
|||||||
return datasetCoreService.searchDatasetObjectList(searchReq);
|
return datasetCoreService.searchDatasetObjectList(searchReq);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public UUID deleteDatasetObjByUuid(UUID uuid) {
|
public UUID deleteDatasetObjByUuid(UUID uuid) {
|
||||||
return datasetCoreService.deleteDatasetObjByUuid(uuid);
|
return datasetCoreService.deleteDatasetObjByUuid(uuid);
|
||||||
}
|
}
|
||||||
@@ -242,7 +236,7 @@ public class DatasetService {
|
|||||||
return new ResponseObj(ApiResponseCode.INTERNAL_SERVER_ERROR, e.getMessage());
|
return new ResponseObj(ApiResponseCode.INTERNAL_SERVER_ERROR, e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
datasetCoreService.updateDatasetUploadStatus(datasetUid);
|
datasetCoreService.updateDatasetUploadStatus(datasetUid, LearnDataRegister.COMPLETED);
|
||||||
return new ResponseObj(ApiResponseCode.OK, "업로드 성공하였습니다.");
|
return new ResponseObj(ApiResponseCode.OK, "업로드 성공하였습니다.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -292,7 +286,7 @@ public class DatasetService {
|
|||||||
.memo(addReq.getMemo())
|
.memo(addReq.getMemo())
|
||||||
.roundNo(stage)
|
.roundNo(stage)
|
||||||
.totalSize(addReq.getFileSize())
|
.totalSize(addReq.getFileSize())
|
||||||
.datasetPath(addReq.getFilePath())
|
.datasetPath(addReq.getFilePath() + uid)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
datasetUid = datasetCoreService.insertDatasetMngData(mngRegDto); // tb_dataset 에 insert
|
datasetUid = datasetCoreService.insertDatasetMngData(mngRegDto); // tb_dataset 에 insert
|
||||||
@@ -376,7 +370,12 @@ public class DatasetService {
|
|||||||
// 폴더별 처리
|
// 폴더별 처리
|
||||||
if ("label-json".equals(dirName)) {
|
if ("label-json".equals(dirName)) {
|
||||||
// json 파일이면 파싱
|
// json 파일이면 파싱
|
||||||
|
try {
|
||||||
data.put("label-json", readJson(path));
|
data.put("label-json", readJson(path));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("파일 JSON 읽기 실패. skip. file={}", path, e);
|
||||||
|
return; // skip
|
||||||
|
}
|
||||||
data.put("geojson_path", path.toAbsolutePath().toString());
|
data.put("geojson_path", path.toAbsolutePath().toString());
|
||||||
} else {
|
} else {
|
||||||
data.put(dirName, path.toAbsolutePath().toString());
|
data.put(dirName, path.toAbsolutePath().toString());
|
||||||
@@ -615,175 +614,80 @@ public class DatasetService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 납품 데이터 등록
|
* 납품 데이터 등록
|
||||||
|
*
|
||||||
* @param req 폴더경로, 메모
|
* @param req 폴더경로, 메모
|
||||||
* @return 성공/실패 여부
|
* @return 성공/실패 여부0
|
||||||
*/
|
*/
|
||||||
public ResponseObj insertDeliveriesDataset(AddDeliveriesReq req) {
|
public void insertDeliveriesDataset(AddDeliveriesReq req, Long datasetUid) {
|
||||||
|
|
||||||
long startTime = System.currentTimeMillis();
|
long startTime = System.currentTimeMillis();
|
||||||
|
|
||||||
log.info("========== 납품 데이터셋 업로드 시작 ==========");
|
|
||||||
log.info("filePath: {}", req.getFilePath());
|
|
||||||
|
|
||||||
DatasetMngRegDto datasetMngRegDto = new DatasetMngRegDto();
|
|
||||||
|
|
||||||
String uid = UUID.randomUUID()
|
|
||||||
.toString()
|
|
||||||
.replace("-", "")
|
|
||||||
.toUpperCase();
|
|
||||||
|
|
||||||
datasetMngRegDto.setUid(uid);
|
|
||||||
datasetMngRegDto.setDataType("DELIVER");
|
|
||||||
datasetMngRegDto.setCompareYyyy(0);
|
|
||||||
datasetMngRegDto.setTargetYyyy(0);
|
|
||||||
datasetMngRegDto.setDatasetPath(req.getFilePath());
|
|
||||||
|
|
||||||
// 마스터 저장 (트랜잭션 내부)
|
|
||||||
Long datasetUid = datasetCoreService.insertDatasetMngData(datasetMngRegDto);
|
|
||||||
|
|
||||||
log.info("납품 Dataset 마스터 저장 완료. datasetUid: {}", datasetUid);
|
|
||||||
|
|
||||||
// 검증
|
|
||||||
validateTrainValTestDirs(req.getFilePath());
|
|
||||||
validateDirFileCount(req.getFilePath());
|
|
||||||
|
|
||||||
// 처리
|
// 처리
|
||||||
processType(req.getFilePath(), datasetUid, "train");
|
processType(req.getFilePath(), datasetUid, "train");
|
||||||
processType(req.getFilePath(), datasetUid, "val");
|
processType(req.getFilePath(), datasetUid, "val");
|
||||||
processType(req.getFilePath(), datasetUid, "test");
|
processType(req.getFilePath(), datasetUid, "test");
|
||||||
|
|
||||||
datasetCoreService.updateDatasetUploadStatus(datasetUid);
|
log.info("========== 전체 완료. 총 소요시간: {} ms ==========", System.currentTimeMillis() - startTime);
|
||||||
|
|
||||||
log.info("========== 전체 완료. 총 소요시간: {} ms ==========",
|
|
||||||
System.currentTimeMillis() - startTime);
|
|
||||||
|
|
||||||
return new ResponseObj(ApiResponseCode.OK, "업로드 성공하였습니다.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 납품 데이터 등록 처리
|
||||||
|
*
|
||||||
|
* @param path
|
||||||
|
* @param datasetUid
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
private void processType(String path, Long datasetUid, String type) {
|
private void processType(String path, Long datasetUid, String type) {
|
||||||
|
|
||||||
long start = System.currentTimeMillis();
|
long start = System.currentTimeMillis();
|
||||||
|
|
||||||
log.info("[{}] 데이터 처리 시작", type.toUpperCase());
|
log.info("[납품 데이터 등록 처리][{}] 시작", type.toUpperCase());
|
||||||
|
|
||||||
List<Map<String, Object>> list = getUnzipDatasetFiles(path, type);
|
List<Map<String, Object>> list = getUnzipDatasetFiles(path, type);
|
||||||
|
|
||||||
log.info("[{}] 파일 개수: {}", type.toUpperCase(), list.size());
|
int batchSize = 1000;
|
||||||
|
int total = list.size();
|
||||||
|
int processed = 0;
|
||||||
|
|
||||||
int count = 0;
|
for (int i = 0; i < total; i += batchSize) {
|
||||||
|
|
||||||
for (Map<String, Object> map : list) {
|
List<Map<String, Object>> batch = list.subList(i, Math.min(i + batchSize, total));
|
||||||
insertTrainTestData(map, datasetUid, type);
|
|
||||||
count++;
|
|
||||||
|
|
||||||
if (count % 1000 == 0 || count == list.size()) {
|
|
||||||
log.info("[{}] 진행건수: {}", type.toUpperCase(), count);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
log.info("[{}] 완료. 총 {}건, 소요시간: {} ms",
|
|
||||||
type.toUpperCase(), count, System.currentTimeMillis() - start);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void insertTrainTestData(Map<String, Object> map, Long datasetUid, String subDir) {
|
|
||||||
|
|
||||||
String comparePath = (String) map.get("input1");
|
|
||||||
String targetPath = (String) map.get("input2");
|
|
||||||
String labelPath = (String) map.get("label");
|
|
||||||
String geojsonPath = (String) map.get("geojson_path");
|
|
||||||
Object labelJson = map.get("label-json");
|
|
||||||
|
|
||||||
JsonNode json;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (labelJson instanceof JsonNode jn) {
|
log.info("[납품 데이터 등록 처리][{}] batch 시작: {} ~ {}", type, i, i + batch.size());
|
||||||
json = jn;
|
|
||||||
} else {
|
datasetBatchService.saveBatch(batch, datasetUid, type);
|
||||||
json = mapper.readTree(labelJson.toString());
|
|
||||||
}
|
processed += batch.size();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException("label_json parse error", e);
|
log.error("batch 실패 row 데이터: {}", batch);
|
||||||
}
|
log.error(
|
||||||
|
"[납품 데이터 등록 처리][{}] batch 실패. range: {} ~ {}, datasetUid={}",
|
||||||
String fileName = Paths.get(comparePath).getFileName().toString();
|
type,
|
||||||
String[] fileNameStr = fileName.split("_");
|
i,
|
||||||
|
i + batch.size(),
|
||||||
String compareYyyy = fileNameStr[1];
|
datasetUid,
|
||||||
String targetYyyy = fileNameStr[2];
|
e);
|
||||||
String mapSheetNum = fileNameStr[3];
|
|
||||||
|
|
||||||
int batchSize = 500;
|
|
||||||
int i = 0;
|
|
||||||
|
|
||||||
if (json != null && json.path("features") != null && !json.path("features").isEmpty()) {
|
|
||||||
|
|
||||||
for (JsonNode feature : json.path("features")) {
|
|
||||||
|
|
||||||
JsonNode prop = feature.path("properties");
|
|
||||||
|
|
||||||
String compareClassCd = prop.path("before").asText(null);
|
|
||||||
String targetClassCd = prop.path("after").asText(null);
|
|
||||||
|
|
||||||
ObjectNode root = mapper.createObjectNode();
|
|
||||||
root.put("type", "FeatureCollection");
|
|
||||||
|
|
||||||
ArrayNode features = mapper.createArrayNode();
|
|
||||||
features.add(feature);
|
|
||||||
root.set("features", features);
|
|
||||||
|
|
||||||
DatasetObjRegDto objRegDto =
|
|
||||||
DatasetObjRegDto.builder()
|
|
||||||
.datasetUid(datasetUid)
|
|
||||||
.compareYyyy(Integer.parseInt(compareYyyy))
|
|
||||||
.compareClassCd(compareClassCd)
|
|
||||||
.targetYyyy(Integer.parseInt(targetYyyy))
|
|
||||||
.targetClassCd(targetClassCd)
|
|
||||||
.comparePath(comparePath)
|
|
||||||
.targetPath(targetPath)
|
|
||||||
.labelPath(labelPath)
|
|
||||||
.mapSheetNum(mapSheetNum)
|
|
||||||
.geojson(root)
|
|
||||||
.geojsonPath(geojsonPath)
|
|
||||||
.fileName(fileName)
|
|
||||||
.build();
|
|
||||||
|
|
||||||
// insert
|
|
||||||
if (subDir.equals("train")) {
|
|
||||||
datasetCoreService.insertDatasetObj(objRegDto);
|
|
||||||
} else if (subDir.equals("val")) {
|
|
||||||
datasetCoreService.insertDatasetValObj(objRegDto);
|
|
||||||
} else {
|
|
||||||
datasetCoreService.insertDatasetTestObj(objRegDto);
|
|
||||||
}
|
|
||||||
|
|
||||||
// batch flush
|
|
||||||
if (++i % batchSize == 0) {
|
|
||||||
em.flush();
|
|
||||||
em.clear();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"[납품 데이터 등록 처리][{}] 완료. 총 {}건, 소요시간: {} ms",
|
||||||
|
type,
|
||||||
|
total,
|
||||||
|
System.currentTimeMillis() - start);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void validateExistsUidChk(String filePath) {
|
||||||
|
Path selectedPath = Paths.get(filePath);
|
||||||
|
String uid = selectedPath.getFileName().toString();
|
||||||
|
|
||||||
|
// 같은 uid 로 등록한 파일이 있는지 확인
|
||||||
|
Long existsCnt = datasetCoreService.findDatasetByUidExistsCnt(uid);
|
||||||
|
if (existsCnt > 0) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.DUPLICATE_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"이미 등록된 회차 데이터 파일입니다. 확인 부탁드립니다.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.dataset.service;
|
package com.kamco.cd.training.dataset.service;
|
||||||
|
|
||||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||||
@@ -39,3 +40,4 @@ public class MapSheetService {
|
|||||||
log.info("도엽 삭제 완료 - 개수: {}", deleteReq.getItemIds().size());
|
log.info("도엽 삭제 완료 - 개수: {}", deleteReq.getItemIds().size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -0,0 +1,259 @@
|
|||||||
|
package com.kamco.cd.training.filemanager;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
|
import com.kamco.cd.training.filemanager.dto.FileManagerDto;
|
||||||
|
import com.kamco.cd.training.filemanager.service.FileManagerService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
|
import io.swagger.v3.oas.annotations.media.ExampleObject;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Tag(name = "파일 관리", description = "/data 디렉토리 파일 관리 API")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/file-manager")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class FileManagerApiController {
|
||||||
|
|
||||||
|
private final FileManagerService fileManagerService;
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "파일 목록 조회",
|
||||||
|
description = "/data 디렉토리 내 파일 및 디렉토리 목록을 조회합니다. recursive=true로 설정하면 하위 디렉토리까지 조회합니다.")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = FileManagerDto.ListFilesRes.class))),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 요청 (유효하지 않은 경로)", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "404", description = "디렉토리를 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/files")
|
||||||
|
public ApiResponseDto<FileManagerDto.ListFilesRes> listFiles(
|
||||||
|
@Parameter(description = "조회할 디렉토리 경로 (기본값: /data)", example = "/data/request")
|
||||||
|
@RequestParam(required = false)
|
||||||
|
String directoryPath,
|
||||||
|
@Parameter(description = "하위 디렉토리 포함 여부", example = "false")
|
||||||
|
@RequestParam(required = false, defaultValue = "false")
|
||||||
|
Boolean recursive) {
|
||||||
|
|
||||||
|
FileManagerDto.ListFilesReq request =
|
||||||
|
FileManagerDto.ListFilesReq.builder()
|
||||||
|
.directoryPath(directoryPath)
|
||||||
|
.recursive(recursive)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
FileManagerDto.ListFilesRes response = fileManagerService.listFiles(request);
|
||||||
|
return ApiResponseDto.ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "파일/디렉토리 삭제",
|
||||||
|
description = "지정된 파일 또는 디렉토리를 삭제합니다. recursive=true로 설정하면 디렉토리 내 모든 파일을 삭제합니다.",
|
||||||
|
requestBody =
|
||||||
|
@io.swagger.v3.oas.annotations.parameters.RequestBody(
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = FileManagerDto.DeleteFileReq.class),
|
||||||
|
examples = {
|
||||||
|
@ExampleObject(
|
||||||
|
name = "단일 파일 삭제",
|
||||||
|
value =
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"filePaths": ["/data/request/old_file.zip"],
|
||||||
|
"recursive": false
|
||||||
|
}
|
||||||
|
"""),
|
||||||
|
@ExampleObject(
|
||||||
|
name = "여러 파일 삭제",
|
||||||
|
value =
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"filePaths": ["/data/file1.txt", "/data/file2.txt"],
|
||||||
|
"recursive": false
|
||||||
|
}
|
||||||
|
"""),
|
||||||
|
@ExampleObject(
|
||||||
|
name = "디렉토리 전체 삭제",
|
||||||
|
value =
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"filePaths": ["/data/old_folder"],
|
||||||
|
"recursive": true
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
})))
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "삭제 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = FileManagerDto.DeleteFileRes.class))),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 요청 (유효하지 않은 경로)", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "404", description = "파일을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@DeleteMapping("/files")
|
||||||
|
public ApiResponseDto<FileManagerDto.DeleteFileRes> deleteFiles(
|
||||||
|
@RequestBody FileManagerDto.DeleteFileReq request) {
|
||||||
|
|
||||||
|
FileManagerDto.DeleteFileRes response = fileManagerService.deleteFiles(request);
|
||||||
|
return ApiResponseDto.ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "모델 파일 경로 조회",
|
||||||
|
description =
|
||||||
|
"특정 모델 UUID로 파일 위치 경로와 하위 파일 목록을 조회합니다. "
|
||||||
|
+ "request_path(심볼릭 링크 디렉토리)와 response_path(모델 결과)를 동시에 반환합니다.")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = FileManagerDto.ModelFilePathRes.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "모델을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/model-path/{modelUuid}")
|
||||||
|
public ApiResponseDto<FileManagerDto.ModelFilePathRes> getModelFilePath(
|
||||||
|
@Parameter(description = "모델 UUID", example = "df284755-c0b7-4070-bfee-ef554e8d0fe4")
|
||||||
|
@PathVariable
|
||||||
|
UUID modelUuid) {
|
||||||
|
|
||||||
|
FileManagerDto.ModelFilePathRes response = fileManagerService.getModelFilePath(modelUuid);
|
||||||
|
return ApiResponseDto.ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "데이터셋 파일 경로 조회",
|
||||||
|
description =
|
||||||
|
"특정 데이터셋 UUID로 파일 위치 경로와 하위 파일 목록을 조회합니다. " + "dataset_path 컬럼의 request_dir 경로를 반환합니다.")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = FileManagerDto.DatasetFilePathRes.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/dataset-path/{datasetUuid}")
|
||||||
|
public ApiResponseDto<FileManagerDto.DatasetFilePathRes> getDatasetFilePath(
|
||||||
|
@Parameter(description = "데이터셋 UUID", example = "037b09a0-b315-4e2e-b88d-b9011f9eaa15")
|
||||||
|
@PathVariable
|
||||||
|
UUID datasetUuid) {
|
||||||
|
|
||||||
|
FileManagerDto.DatasetFilePathRes response = fileManagerService.getDatasetFilePath(datasetUuid);
|
||||||
|
return ApiResponseDto.ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "디렉토리 용량 체크",
|
||||||
|
description = "특정 디렉토리의 총 용량, 파일 개수, 디렉토리 개수를 조회합니다. " + "basepath 하위 폴더의 용량을 재귀적으로 계산합니다.")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = FileManagerDto.DirectoryCapacityRes.class))),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 경로", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "404", description = "디렉토리를 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/directory-capacity")
|
||||||
|
public ApiResponseDto<FileManagerDto.DirectoryCapacityRes> checkDirectoryCapacity(
|
||||||
|
@Parameter(
|
||||||
|
description = "디렉토리 경로",
|
||||||
|
example = "/home/kcomu/data/request/037b09a0-b315-4e2e-b88d-b9011f9eaa15")
|
||||||
|
@RequestParam
|
||||||
|
String directoryPath) {
|
||||||
|
|
||||||
|
FileManagerDto.DirectoryCapacityRes response =
|
||||||
|
fileManagerService.checkDirectoryCapacity(directoryPath);
|
||||||
|
return ApiResponseDto.ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "모델별 학습 실행 상태 조회",
|
||||||
|
description =
|
||||||
|
"G1~G4 모델의 현재 학습 실행 상태를 조회합니다. "
|
||||||
|
+ "step1_state, step2_state를 체크하여 어떤 모델이 학습 중인지 확인합니다. "
|
||||||
|
+ "step1과 step2는 동시 진행되지 않습니다.")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema =
|
||||||
|
@Schema(
|
||||||
|
implementation = FileManagerDto.AllModelsExecutionStatusRes.class))),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/models-execution-status")
|
||||||
|
public ApiResponseDto<FileManagerDto.AllModelsExecutionStatusRes> getModelsExecutionStatus() {
|
||||||
|
|
||||||
|
FileManagerDto.AllModelsExecutionStatusRes response =
|
||||||
|
fileManagerService.getModelsExecutionStatus();
|
||||||
|
return ApiResponseDto.ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "저장공간 정보 조회",
|
||||||
|
description =
|
||||||
|
"/home/kcomu/data 경로의 사용 중인 용량, 전체 디스크 용량, 남은 저장공간을 조회합니다. "
|
||||||
|
+ "파라미터 없이 호출하면 자동으로 /home/kcomu/data 경로 정보를 반환합니다.")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = FileManagerDto.StorageSpaceRes.class))),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/storage-space")
|
||||||
|
public ApiResponseDto<FileManagerDto.StorageSpaceRes> getStorageSpaceInfo() {
|
||||||
|
|
||||||
|
FileManagerDto.StorageSpaceRes response = fileManagerService.getStorageSpaceInfo();
|
||||||
|
return ApiResponseDto.ok(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
package com.kamco.cd.training.filemanager.dto;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
public class FileManagerDto {
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "파일 정보")
|
||||||
|
public static class FileInfo {
|
||||||
|
@Schema(description = "파일명", example = "dataset.zip")
|
||||||
|
private String fileName;
|
||||||
|
|
||||||
|
@Schema(description = "파일 전체 경로", example = "/data/request/dataset.zip")
|
||||||
|
private String filePath;
|
||||||
|
|
||||||
|
@Schema(description = "파일 크기 (bytes)", example = "1024000")
|
||||||
|
private Long fileSize;
|
||||||
|
|
||||||
|
@Schema(description = "파일인지 디렉토리인지 여부", example = "true")
|
||||||
|
private Boolean isFile;
|
||||||
|
|
||||||
|
@Schema(description = "디렉토리인지 여부", example = "false")
|
||||||
|
private Boolean isDirectory;
|
||||||
|
|
||||||
|
@Schema(description = "마지막 수정 시간", example = "2026-04-06T15:30:00")
|
||||||
|
private LocalDateTime lastModified;
|
||||||
|
|
||||||
|
@Schema(description = "읽기 권한", example = "true")
|
||||||
|
private Boolean readable;
|
||||||
|
|
||||||
|
@Schema(description = "쓰기 권한", example = "true")
|
||||||
|
private Boolean writable;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "디렉토리 목록 조회 요청")
|
||||||
|
public static class ListFilesReq {
|
||||||
|
@Schema(description = "조회할 디렉토리 경로 (기본값: /data)", example = "/data/request")
|
||||||
|
private String directoryPath;
|
||||||
|
|
||||||
|
@Schema(description = "하위 디렉토리 포함 여부", example = "false")
|
||||||
|
private Boolean recursive;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "디렉토리 목록 조회 응답")
|
||||||
|
public static class ListFilesRes {
|
||||||
|
@Schema(description = "조회된 디렉토리 경로", example = "/data/request")
|
||||||
|
private String directoryPath;
|
||||||
|
|
||||||
|
@Schema(description = "파일 목록")
|
||||||
|
private List<FileInfo> files;
|
||||||
|
|
||||||
|
@Schema(description = "총 파일 개수", example = "10")
|
||||||
|
private Integer totalCount;
|
||||||
|
|
||||||
|
@Schema(description = "총 파일 크기 (bytes)", example = "10240000")
|
||||||
|
private Long totalSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "파일 삭제 요청")
|
||||||
|
public static class DeleteFileReq {
|
||||||
|
@Schema(
|
||||||
|
description = "삭제할 파일 또는 디렉토리 경로 목록",
|
||||||
|
example = "[\"/data/request/old_file.zip\", \"/data/tmp/test_folder\"]")
|
||||||
|
private List<String> filePaths;
|
||||||
|
|
||||||
|
@Schema(description = "디렉토리일 경우 하위 파일 포함 삭제 여부", example = "true")
|
||||||
|
private Boolean recursive;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "파일 삭제 응답")
|
||||||
|
public static class DeleteFileRes {
|
||||||
|
@Schema(description = "삭제 성공한 파일 경로 목록")
|
||||||
|
private List<String> deletedFiles;
|
||||||
|
|
||||||
|
@Schema(description = "삭제 실패한 파일 경로 목록")
|
||||||
|
private List<String> failedFiles;
|
||||||
|
|
||||||
|
@Schema(description = "삭제 성공 개수", example = "5")
|
||||||
|
private Integer successCount;
|
||||||
|
|
||||||
|
@Schema(description = "삭제 실패 개수", example = "0")
|
||||||
|
private Integer failureCount;
|
||||||
|
|
||||||
|
@Schema(description = "전체 메시지", example = "5개 파일 삭제 성공")
|
||||||
|
private String message;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "디스크 사용량 조회 응답")
|
||||||
|
public static class DiskUsageRes {
|
||||||
|
@Schema(description = "디렉토리 경로", example = "/data")
|
||||||
|
private String directoryPath;
|
||||||
|
|
||||||
|
@Schema(description = "총 용량 (bytes)", example = "1000000000000")
|
||||||
|
private Long totalSpace;
|
||||||
|
|
||||||
|
@Schema(description = "사용 가능 용량 (bytes)", example = "500000000000")
|
||||||
|
private Long usableSpace;
|
||||||
|
|
||||||
|
@Schema(description = "사용 중인 용량 (bytes)", example = "500000000000")
|
||||||
|
private Long usedSpace;
|
||||||
|
|
||||||
|
@Schema(description = "사용률 (%)", example = "50.0")
|
||||||
|
private Double usagePercentage;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "모델 파일 경로 정보 응답")
|
||||||
|
public static class ModelFilePathRes {
|
||||||
|
@Schema(description = "모델 UUID", example = "df284755-c0b7-4070-bfee-ef554e8d0fe4")
|
||||||
|
private String modelUuid;
|
||||||
|
|
||||||
|
@Schema(
|
||||||
|
description = "요청 경로 (심볼릭 링크 디렉토리)",
|
||||||
|
example = "/home/kcomu/data/tmp/AE366F3076504FACBF12106986202AB5")
|
||||||
|
private String requestPath;
|
||||||
|
|
||||||
|
@Schema(
|
||||||
|
description = "응답 경로 (모델 결과 저장)",
|
||||||
|
example = "/home/kcomu/data/response/df284755-c0b7-4070-bfee-ef554e8d0fe4")
|
||||||
|
private String responsePath;
|
||||||
|
|
||||||
|
@Schema(description = "요청 경로 파일 목록")
|
||||||
|
private List<FileInfo> requestFiles;
|
||||||
|
|
||||||
|
@Schema(description = "응답 경로 파일 목록")
|
||||||
|
private List<FileInfo> responseFiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "데이터셋 파일 경로 정보 응답")
|
||||||
|
public static class DatasetFilePathRes {
|
||||||
|
@Schema(description = "데이터셋 UUID", example = "037b09a0-b315-4e2e-b88d-b9011f9eaa15")
|
||||||
|
private String datasetUuid;
|
||||||
|
|
||||||
|
@Schema(
|
||||||
|
description = "데이터셋 경로",
|
||||||
|
example = "/home/kcomu/data/request/037b09a0-b315-4e2e-b88d-b9011f9eaa15")
|
||||||
|
private String datasetPath;
|
||||||
|
|
||||||
|
@Schema(description = "데이터셋 파일 목록")
|
||||||
|
private List<FileInfo> files;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "디렉토리 용량 체크 응답")
|
||||||
|
public static class DirectoryCapacityRes {
|
||||||
|
@Schema(description = "디렉토리 경로", example = "/home/kcomu/data/request/dataset-uuid")
|
||||||
|
private String directoryPath;
|
||||||
|
|
||||||
|
@Schema(description = "파일 개수", example = "1234")
|
||||||
|
private Integer fileCount;
|
||||||
|
|
||||||
|
@Schema(description = "디렉토리 개수", example = "56")
|
||||||
|
private Integer directoryCount;
|
||||||
|
|
||||||
|
@Schema(description = "총 용량 (bytes)", example = "10485760000")
|
||||||
|
private Long totalSize;
|
||||||
|
|
||||||
|
@Schema(description = "총 용량 (읽기 쉬운 형식)", example = "9.77 GB")
|
||||||
|
private String totalSizeFormatted;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "모델별 학습 실행 상태 응답")
|
||||||
|
public static class ModelExecutionStatusRes {
|
||||||
|
@Schema(description = "모델 번호", example = "G1")
|
||||||
|
private String modelNo;
|
||||||
|
|
||||||
|
@Schema(description = "실행 상태 메시지", example = "G1 모델에 테스트를 진행중입니다.")
|
||||||
|
private String statusMessage;
|
||||||
|
|
||||||
|
@Schema(description = "1단계 상태", example = "COMPLETED")
|
||||||
|
private String step1State;
|
||||||
|
|
||||||
|
@Schema(description = "2단계 상태", example = "IN_PROGRESS")
|
||||||
|
private String step2State;
|
||||||
|
|
||||||
|
@Schema(description = "현재 실행 중인 단계", example = "2")
|
||||||
|
private Integer currentStep;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "전체 모델 학습 실행 상태 목록 응답")
|
||||||
|
public static class AllModelsExecutionStatusRes {
|
||||||
|
@Schema(description = "모델별 실행 상태 목록")
|
||||||
|
private List<ModelExecutionStatusRes> modelStatuses;
|
||||||
|
|
||||||
|
@Schema(description = "현재 실행 중인 모델 개수", example = "2")
|
||||||
|
private Integer runningCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "저장공간 정보 응답 (남은 공간 포함)")
|
||||||
|
public static class StorageSpaceRes {
|
||||||
|
@Schema(description = "디렉토리 경로", example = "/home/kcomu/data")
|
||||||
|
private String directoryPath;
|
||||||
|
|
||||||
|
@Schema(description = "파일 개수", example = "1234")
|
||||||
|
private Integer fileCount;
|
||||||
|
|
||||||
|
@Schema(description = "디렉토리 개수", example = "56")
|
||||||
|
private Integer directoryCount;
|
||||||
|
|
||||||
|
@Schema(description = "사용 중인 용량 (bytes)", example = "10485760000")
|
||||||
|
private Long usedSize;
|
||||||
|
|
||||||
|
@Schema(description = "사용 중인 용량 (읽기 쉬운 형식)", example = "9.77 GB")
|
||||||
|
private String usedSizeFormatted;
|
||||||
|
|
||||||
|
@Schema(description = "전체 디스크 용량 (bytes)", example = "1000000000000")
|
||||||
|
private Long totalDiskSpace;
|
||||||
|
|
||||||
|
@Schema(description = "전체 디스크 용량 (읽기 쉬운 형식)", example = "931.32 GB")
|
||||||
|
private String totalDiskSpaceFormatted;
|
||||||
|
|
||||||
|
@Schema(description = "남은 저장공간 (bytes)", example = "500000000000")
|
||||||
|
private Long freeSpace;
|
||||||
|
|
||||||
|
@Schema(description = "남은 저장공간 (읽기 쉬운 형식)", example = "465.66 GB")
|
||||||
|
private String freeSpaceFormatted;
|
||||||
|
|
||||||
|
@Schema(description = "사용 가능한 공간 (bytes)", example = "480000000000")
|
||||||
|
private Long usableSpace;
|
||||||
|
|
||||||
|
@Schema(description = "사용 가능한 공간 (읽기 쉬운 형식)", example = "447.03 GB")
|
||||||
|
private String usableSpaceFormatted;
|
||||||
|
|
||||||
|
@Schema(description = "디스크 사용률 (%)", example = "50.5")
|
||||||
|
private Double usagePercentage;
|
||||||
|
|
||||||
|
@JsonFormatDttm private ZonedDateTime lastModifiedDate;
|
||||||
|
|
||||||
|
public ZonedDateTime getLastModifiedDate() {
|
||||||
|
return ZonedDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,710 @@
|
|||||||
|
package com.kamco.cd.training.filemanager.service;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.filemanager.dto.FileManagerDto;
|
||||||
|
import com.kamco.cd.training.postgres.entity.DatasetEntity;
|
||||||
|
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
|
||||||
|
import com.kamco.cd.training.postgres.repository.dataset.DatasetRepository;
|
||||||
|
import com.kamco.cd.training.postgres.repository.model.ModelMngRepository;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.FileVisitResult;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.SimpleFileVisitor;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class FileManagerService {
|
||||||
|
|
||||||
|
private static final String BASE_DATA_PATH = "/data";
|
||||||
|
private static final long MAX_PATH_LENGTH = 500;
|
||||||
|
|
||||||
|
@Value("${train.docker.base_path}")
|
||||||
|
private String basePath;
|
||||||
|
|
||||||
|
@Value("${train.docker.request_dir}")
|
||||||
|
private String requestDir;
|
||||||
|
|
||||||
|
@Value("${train.docker.response_dir}")
|
||||||
|
private String responseDir;
|
||||||
|
|
||||||
|
@Value("${train.docker.symbolic_link_dir}")
|
||||||
|
private String symbolicLinkDir;
|
||||||
|
|
||||||
|
private final ModelMngRepository modelMngRepository;
|
||||||
|
private final DatasetRepository datasetRepository;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 디렉토리 내 파일 목록 조회
|
||||||
|
*
|
||||||
|
* @param request 조회 요청 정보
|
||||||
|
* @return 파일 목록 응답
|
||||||
|
*/
|
||||||
|
public FileManagerDto.ListFilesRes listFiles(FileManagerDto.ListFilesReq request) {
|
||||||
|
String targetPath =
|
||||||
|
request.getDirectoryPath() != null ? request.getDirectoryPath() : BASE_DATA_PATH;
|
||||||
|
|
||||||
|
boolean recursive = request.getRecursive() != null && request.getRecursive();
|
||||||
|
|
||||||
|
// 경로 검증은 수행하되, 예외를 throw하지 않고 빈 데이터 반환
|
||||||
|
try {
|
||||||
|
validatePath(targetPath);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
log.debug("유효하지 않은 경로: {}", targetPath);
|
||||||
|
return FileManagerDto.ListFilesRes.builder()
|
||||||
|
.directoryPath(targetPath)
|
||||||
|
.files(new ArrayList<>())
|
||||||
|
.totalCount(0)
|
||||||
|
.totalSize(0L)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
Path directory = Paths.get(targetPath);
|
||||||
|
if (!Files.exists(directory)) {
|
||||||
|
log.debug("디렉토리가 존재하지 않습니다: {}", targetPath);
|
||||||
|
return FileManagerDto.ListFilesRes.builder()
|
||||||
|
.directoryPath(targetPath)
|
||||||
|
.files(new ArrayList<>())
|
||||||
|
.totalCount(0)
|
||||||
|
.totalSize(0L)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Files.isDirectory(directory)) {
|
||||||
|
log.debug("디렉토리 경로가 아닙니다: {}", targetPath);
|
||||||
|
return FileManagerDto.ListFilesRes.builder()
|
||||||
|
.directoryPath(targetPath)
|
||||||
|
.files(new ArrayList<>())
|
||||||
|
.totalCount(0)
|
||||||
|
.totalSize(0L)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<FileManagerDto.FileInfo> files = new ArrayList<>();
|
||||||
|
long totalSize = 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (recursive) {
|
||||||
|
// 재귀적으로 모든 하위 파일 조회
|
||||||
|
Files.walkFileTree(
|
||||||
|
directory,
|
||||||
|
new SimpleFileVisitor<>() {
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
|
||||||
|
files.add(createFileInfo(file));
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
|
||||||
|
if (!dir.equals(directory)) {
|
||||||
|
files.add(createFileInfo(dir));
|
||||||
|
}
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// 현재 디렉토리의 파일만 조회
|
||||||
|
try (Stream<Path> stream = Files.list(directory)) {
|
||||||
|
stream.forEach(path -> files.add(createFileInfo(path)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 총 파일 크기 계산
|
||||||
|
for (FileManagerDto.FileInfo file : files) {
|
||||||
|
if (file.getIsFile() && file.getFileSize() != null) {
|
||||||
|
totalSize += file.getFileSize();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.debug("파일 목록 조회 중 오류 발생: {}", targetPath, e);
|
||||||
|
return FileManagerDto.ListFilesRes.builder()
|
||||||
|
.directoryPath(targetPath)
|
||||||
|
.files(new ArrayList<>())
|
||||||
|
.totalCount(0)
|
||||||
|
.totalSize(0L)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
return FileManagerDto.ListFilesRes.builder()
|
||||||
|
.directoryPath(targetPath)
|
||||||
|
.files(files)
|
||||||
|
.totalCount(files.size())
|
||||||
|
.totalSize(totalSize)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 파일 또는 디렉토리 삭제
|
||||||
|
*
|
||||||
|
* @param request 삭제 요청 정보
|
||||||
|
* @return 삭제 결과
|
||||||
|
*/
|
||||||
|
public FileManagerDto.DeleteFileRes deleteFiles(FileManagerDto.DeleteFileReq request) {
|
||||||
|
List<String> deletedFiles = new ArrayList<>();
|
||||||
|
List<String> failedFiles = new ArrayList<>();
|
||||||
|
|
||||||
|
boolean recursive = request.getRecursive() != null && request.getRecursive();
|
||||||
|
|
||||||
|
for (String filePath : request.getFilePaths()) {
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
validatePath(filePath);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
log.debug("유효하지 않은 경로: {}", filePath);
|
||||||
|
failedFiles.add(filePath + " (유효하지 않은 경로)");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Path path = Paths.get(filePath);
|
||||||
|
|
||||||
|
if (!Files.exists(path)) {
|
||||||
|
log.debug("삭제하려는 파일이 존재하지 않습니다: {}", filePath);
|
||||||
|
failedFiles.add(filePath + " (파일이 존재하지 않음)");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Files.isDirectory(path)) {
|
||||||
|
if (recursive) {
|
||||||
|
// 디렉토리 및 하위 파일 모두 삭제
|
||||||
|
deleteDirectoryRecursively(path);
|
||||||
|
deletedFiles.add(filePath);
|
||||||
|
} else {
|
||||||
|
// 빈 디렉토리만 삭제
|
||||||
|
if (isDirectoryEmpty(path)) {
|
||||||
|
Files.delete(path);
|
||||||
|
deletedFiles.add(filePath);
|
||||||
|
} else {
|
||||||
|
failedFiles.add(filePath + " (디렉토리가 비어있지 않음)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 파일 삭제
|
||||||
|
Files.delete(path);
|
||||||
|
deletedFiles.add(filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("파일 삭제 성공: {}", filePath);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("파일 삭제 실패: {}", filePath, e);
|
||||||
|
failedFiles.add(filePath + " (" + e.getMessage() + ")");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String message =
|
||||||
|
String.format("%d개 파일 삭제 성공, %d개 파일 삭제 실패", deletedFiles.size(), failedFiles.size());
|
||||||
|
|
||||||
|
return FileManagerDto.DeleteFileRes.builder()
|
||||||
|
.deletedFiles(deletedFiles)
|
||||||
|
.failedFiles(failedFiles)
|
||||||
|
.successCount(deletedFiles.size())
|
||||||
|
.failureCount(failedFiles.size())
|
||||||
|
.message(message)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** FileInfo 객체 생성 */
|
||||||
|
private FileManagerDto.FileInfo createFileInfo(Path path) {
|
||||||
|
try {
|
||||||
|
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
|
||||||
|
|
||||||
|
return FileManagerDto.FileInfo.builder()
|
||||||
|
.fileName(path.getFileName().toString())
|
||||||
|
.filePath(path.toString())
|
||||||
|
.fileSize(attrs.isRegularFile() ? attrs.size() : null)
|
||||||
|
.isFile(attrs.isRegularFile())
|
||||||
|
.isDirectory(attrs.isDirectory())
|
||||||
|
.lastModified(
|
||||||
|
LocalDateTime.ofInstant(
|
||||||
|
Instant.ofEpochMilli(attrs.lastModifiedTime().toMillis()),
|
||||||
|
ZoneId.systemDefault()))
|
||||||
|
.readable(Files.isReadable(path))
|
||||||
|
.writable(Files.isWritable(path))
|
||||||
|
.build();
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("파일 정보 조회 실패: {}", path, e);
|
||||||
|
return FileManagerDto.FileInfo.builder()
|
||||||
|
.fileName(path.getFileName().toString())
|
||||||
|
.filePath(path.toString())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 디렉토리 재귀 삭제 */
|
||||||
|
private void deleteDirectoryRecursively(Path directory) throws IOException {
|
||||||
|
Files.walkFileTree(
|
||||||
|
directory,
|
||||||
|
new SimpleFileVisitor<>() {
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||||
|
throws IOException {
|
||||||
|
Files.delete(file);
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
|
||||||
|
Files.delete(dir);
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 디렉토리가 비어있는지 확인 */
|
||||||
|
private boolean isDirectoryEmpty(Path directory) throws IOException {
|
||||||
|
try (Stream<Path> stream = Files.list(directory)) {
|
||||||
|
return stream.findFirst().isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 경로 검증 (보안) */
|
||||||
|
private void validatePath(String path) {
|
||||||
|
if (path == null || path.trim().isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("경로가 비어있습니다");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path.length() > MAX_PATH_LENGTH) {
|
||||||
|
throw new IllegalArgumentException("경로가 너무 깁니다");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 경로 순회 공격 방지 - 상대경로 패턴만 제한
|
||||||
|
if (path.contains("..")) {
|
||||||
|
throw new IllegalArgumentException("상대 경로(..)는 사용할 수 없습니다");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델 파일 경로 조회
|
||||||
|
*
|
||||||
|
* @param modelUuid 모델 UUID
|
||||||
|
* @return 모델 파일 경로 및 파일 목록
|
||||||
|
*/
|
||||||
|
public FileManagerDto.ModelFilePathRes getModelFilePath(UUID modelUuid) {
|
||||||
|
// tb_model_master 테이블에서 모델 조회
|
||||||
|
ModelMasterEntity model = modelMngRepository.findByUuid(modelUuid).orElse(null);
|
||||||
|
|
||||||
|
// 모델이 존재하지 않으면 빈 데이터 반환
|
||||||
|
if (model == null) {
|
||||||
|
return FileManagerDto.ModelFilePathRes.builder()
|
||||||
|
.modelUuid(modelUuid.toString())
|
||||||
|
.requestPath(null)
|
||||||
|
.responsePath(null)
|
||||||
|
.requestFiles(new ArrayList<>())
|
||||||
|
.responseFiles(new ArrayList<>())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
// request_path: tb_model_master.request_path 컬럼 값 사용
|
||||||
|
// request_path 컬럼에는 'AE366F3076504FACBF12106986202AB5' 형태의 값이 저장되어 있음
|
||||||
|
String requestPathFromDb = model.getRequestPath();
|
||||||
|
String requestPath;
|
||||||
|
if (requestPathFromDb != null && !requestPathFromDb.isEmpty()) {
|
||||||
|
// DB에 저장된 값이 있으면 symbolic_link_dir + request_path 조합
|
||||||
|
requestPath = symbolicLinkDir + "/" + requestPathFromDb;
|
||||||
|
} else {
|
||||||
|
// 없으면 기본값: symbolic_link_dir + model_uuid
|
||||||
|
requestPath = symbolicLinkDir + "/" + modelUuid;
|
||||||
|
}
|
||||||
|
|
||||||
|
// response_path: response_dir + model_uuid (UUID 사용)
|
||||||
|
String responsePath = responseDir + "/" + modelUuid;
|
||||||
|
|
||||||
|
// 파일 목록 조회
|
||||||
|
List<FileManagerDto.FileInfo> requestFiles = getFilesInDirectory(requestPath);
|
||||||
|
List<FileManagerDto.FileInfo> responseFiles = getFilesInDirectory(responsePath);
|
||||||
|
|
||||||
|
return FileManagerDto.ModelFilePathRes.builder()
|
||||||
|
.modelUuid(modelUuid.toString())
|
||||||
|
.requestPath(requestPath)
|
||||||
|
.responsePath(responsePath)
|
||||||
|
.requestFiles(requestFiles)
|
||||||
|
.responseFiles(responseFiles)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 파일 경로 조회
|
||||||
|
*
|
||||||
|
* @param datasetUuid 데이터셋 UUID
|
||||||
|
* @return 데이터셋 파일 경로 및 파일 목록
|
||||||
|
*/
|
||||||
|
public FileManagerDto.DatasetFilePathRes getDatasetFilePath(UUID datasetUuid) {
|
||||||
|
// tb_dataset 테이블에서 데이터셋 조회
|
||||||
|
DatasetEntity dataset = datasetRepository.findByUuid(datasetUuid).orElse(null);
|
||||||
|
|
||||||
|
// 데이터셋이 존재하지 않으면 빈 데이터 반환
|
||||||
|
if (dataset == null) {
|
||||||
|
return FileManagerDto.DatasetFilePathRes.builder()
|
||||||
|
.datasetUuid(datasetUuid.toString())
|
||||||
|
.datasetPath(null)
|
||||||
|
.files(new ArrayList<>())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
// dataset_path 컬럼이 있으면 사용, 없으면 request_dir + uuid 사용
|
||||||
|
String datasetPath = dataset.getDatasetPath();
|
||||||
|
if (datasetPath == null || datasetPath.isEmpty()) {
|
||||||
|
datasetPath = requestDir + "/" + datasetUuid;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 파일 목록 조회
|
||||||
|
List<FileManagerDto.FileInfo> files = getFilesInDirectory(datasetPath);
|
||||||
|
|
||||||
|
return FileManagerDto.DatasetFilePathRes.builder()
|
||||||
|
.datasetUuid(datasetUuid.toString())
|
||||||
|
.datasetPath(datasetPath)
|
||||||
|
.files(files)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 디렉토리 용량 체크
|
||||||
|
*
|
||||||
|
* @param directoryPath 디렉토리 경로
|
||||||
|
* @return 디렉토리 용량 정보
|
||||||
|
*/
|
||||||
|
public FileManagerDto.DirectoryCapacityRes checkDirectoryCapacity(String directoryPath) {
|
||||||
|
// 경로 검증은 수행하되, 예외를 throw하지 않고 빈 데이터 반환
|
||||||
|
try {
|
||||||
|
validatePath(directoryPath);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
log.debug("유효하지 않은 경로: {}", directoryPath);
|
||||||
|
return FileManagerDto.DirectoryCapacityRes.builder()
|
||||||
|
.directoryPath(directoryPath)
|
||||||
|
.fileCount(0)
|
||||||
|
.directoryCount(0)
|
||||||
|
.totalSize(0L)
|
||||||
|
.totalSizeFormatted("0 B")
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
Path directory = Paths.get(directoryPath);
|
||||||
|
if (!Files.exists(directory)) {
|
||||||
|
log.debug("디렉토리가 존재하지 않습니다: {}", directoryPath);
|
||||||
|
return FileManagerDto.DirectoryCapacityRes.builder()
|
||||||
|
.directoryPath(directoryPath)
|
||||||
|
.fileCount(0)
|
||||||
|
.directoryCount(0)
|
||||||
|
.totalSize(0L)
|
||||||
|
.totalSizeFormatted("0 B")
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Files.isDirectory(directory)) {
|
||||||
|
log.debug("디렉토리 경로가 아닙니다: {}", directoryPath);
|
||||||
|
return FileManagerDto.DirectoryCapacityRes.builder()
|
||||||
|
.directoryPath(directoryPath)
|
||||||
|
.fileCount(0)
|
||||||
|
.directoryCount(0)
|
||||||
|
.totalSize(0L)
|
||||||
|
.totalSizeFormatted("0 B")
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
final long[] totalSize = {0};
|
||||||
|
final int[] fileCount = {0};
|
||||||
|
final int[] directoryCount = {0};
|
||||||
|
|
||||||
|
try {
|
||||||
|
Files.walkFileTree(
|
||||||
|
directory,
|
||||||
|
new SimpleFileVisitor<>() {
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
|
||||||
|
totalSize[0] += attrs.size();
|
||||||
|
fileCount[0]++;
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
|
||||||
|
if (!dir.equals(directory)) {
|
||||||
|
directoryCount[0]++;
|
||||||
|
}
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.debug("디렉토리 용량 체크 중 오류 발생: {}", directoryPath, e);
|
||||||
|
return FileManagerDto.DirectoryCapacityRes.builder()
|
||||||
|
.directoryPath(directoryPath)
|
||||||
|
.fileCount(0)
|
||||||
|
.directoryCount(0)
|
||||||
|
.totalSize(0L)
|
||||||
|
.totalSizeFormatted("0 B")
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
return FileManagerDto.DirectoryCapacityRes.builder()
|
||||||
|
.directoryPath(directoryPath)
|
||||||
|
.fileCount(fileCount[0])
|
||||||
|
.directoryCount(directoryCount[0])
|
||||||
|
.totalSize(totalSize[0])
|
||||||
|
.totalSizeFormatted(formatFileSize(totalSize[0]))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델별 학습 실행 상태 조회
|
||||||
|
*
|
||||||
|
* @return 모델별 학습 실행 상태 목록
|
||||||
|
*/
|
||||||
|
public FileManagerDto.AllModelsExecutionStatusRes getModelsExecutionStatus() {
|
||||||
|
// G1 ~ G4 모델 조회
|
||||||
|
List<String> modelNumbers = Arrays.asList("G1", "G2", "G3", "G4");
|
||||||
|
List<FileManagerDto.ModelExecutionStatusRes> modelStatuses = new ArrayList<>();
|
||||||
|
int runningCount = 0;
|
||||||
|
|
||||||
|
for (String modelNo : modelNumbers) {
|
||||||
|
// model_no로 가장 최근 모델 조회 (del_yn = false)
|
||||||
|
List<ModelMasterEntity> models =
|
||||||
|
modelMngRepository.findByModelNoAndDelYnOrderByCreatedDttmDesc(modelNo, false);
|
||||||
|
|
||||||
|
if (models.isEmpty()) {
|
||||||
|
// 모델이 없으면 대기 상태
|
||||||
|
modelStatuses.add(
|
||||||
|
FileManagerDto.ModelExecutionStatusRes.builder()
|
||||||
|
.modelNo(modelNo)
|
||||||
|
.statusMessage(modelNo + " 모델은 대기 중입니다.")
|
||||||
|
.step1State(null)
|
||||||
|
.step2State(null)
|
||||||
|
.currentStep(null)
|
||||||
|
.build());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ModelMasterEntity model = models.getFirst();
|
||||||
|
String step1State = model.getStep1State();
|
||||||
|
String step2State = model.getStep2State();
|
||||||
|
|
||||||
|
String statusMessage;
|
||||||
|
Integer currentStep = null;
|
||||||
|
|
||||||
|
// step1, step2 상태 확인
|
||||||
|
boolean step1Running = "IN_PROGRESS".equals(step1State);
|
||||||
|
boolean step2Running = "IN_PROGRESS".equals(step2State);
|
||||||
|
|
||||||
|
if (step1Running) {
|
||||||
|
statusMessage = modelNo + " 모델에 학습(1단계)을 진행중입니다.";
|
||||||
|
currentStep = 1;
|
||||||
|
runningCount++;
|
||||||
|
} else if (step2Running) {
|
||||||
|
statusMessage = modelNo + " 모델에 테스트(2단계)를 진행중입니다.";
|
||||||
|
currentStep = 2;
|
||||||
|
runningCount++;
|
||||||
|
} else if ("COMPLETED".equals(step1State) && "COMPLETED".equals(step2State)) {
|
||||||
|
statusMessage = modelNo + " 모델은 학습이 완료되었습니다.";
|
||||||
|
} else if ("COMPLETED".equals(step1State)) {
|
||||||
|
statusMessage = modelNo + " 모델은 1단계 학습이 완료되었습니다.";
|
||||||
|
} else {
|
||||||
|
statusMessage = modelNo + " 모델은 대기 중입니다.";
|
||||||
|
}
|
||||||
|
|
||||||
|
modelStatuses.add(
|
||||||
|
FileManagerDto.ModelExecutionStatusRes.builder()
|
||||||
|
.modelNo(modelNo)
|
||||||
|
.statusMessage(statusMessage)
|
||||||
|
.step1State(step1State)
|
||||||
|
.step2State(step2State)
|
||||||
|
.currentStep(currentStep)
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
return FileManagerDto.AllModelsExecutionStatusRes.builder()
|
||||||
|
.modelStatuses(modelStatuses)
|
||||||
|
.runningCount(runningCount)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 디렉토리 내 파일 목록 조회 (내부 사용) */
|
||||||
|
private List<FileManagerDto.FileInfo> getFilesInDirectory(String directoryPath) {
|
||||||
|
List<FileManagerDto.FileInfo> files = new ArrayList<>();
|
||||||
|
|
||||||
|
Path directory = Paths.get(directoryPath);
|
||||||
|
if (!Files.exists(directory)) {
|
||||||
|
log.debug("디렉토리가 존재하지 않습니다: {}", directoryPath);
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Files.isDirectory(directory)) {
|
||||||
|
log.debug("디렉토리 경로가 아닙니다: {}", directoryPath);
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
try (Stream<Path> stream = Files.list(directory)) {
|
||||||
|
stream.forEach(path -> files.add(createFileInfo(path)));
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.debug("파일 목록 조회 중 오류 발생: {}", directoryPath, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 파일 크기 포맷팅 (읽기 쉬운 형식) */
|
||||||
|
private String formatFileSize(long size) {
|
||||||
|
if (size < 1024) {
|
||||||
|
return size + " B";
|
||||||
|
} else if (size < 1024 * 1024) {
|
||||||
|
return String.format("%.2f KB", size / 1024.0);
|
||||||
|
} else if (size < 1024 * 1024 * 1024) {
|
||||||
|
return String.format("%.2f MB", size / (1024.0 * 1024.0));
|
||||||
|
} else {
|
||||||
|
return String.format("%.2f GB", size / (1024.0 * 1024.0 * 1024.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 저장공간 정보 조회 (남은 공간 포함) 고정 경로: train.docker.base_path 설정값 사용
|
||||||
|
*
|
||||||
|
* @return 저장공간 정보 (사용량, 남은 공간, 디스크 용량)
|
||||||
|
*/
|
||||||
|
public FileManagerDto.StorageSpaceRes getStorageSpaceInfo() {
|
||||||
|
// 설정값에서 경로 가져오기 (train.docker.base_path)
|
||||||
|
|
||||||
|
log.info("basePath = {}", basePath);
|
||||||
|
String directoryPath = basePath;
|
||||||
|
|
||||||
|
Path directory = Paths.get(directoryPath);
|
||||||
|
if (!Files.exists(directory)) {
|
||||||
|
log.info("디렉토리가 존재하지 않습니다: {}", directoryPath);
|
||||||
|
return FileManagerDto.StorageSpaceRes.builder()
|
||||||
|
.directoryPath(directoryPath)
|
||||||
|
.fileCount(0)
|
||||||
|
.directoryCount(0)
|
||||||
|
.usedSize(0L)
|
||||||
|
.usedSizeFormatted("0 B")
|
||||||
|
.totalDiskSpace(0L)
|
||||||
|
.totalDiskSpaceFormatted("0 B")
|
||||||
|
.freeSpace(0L)
|
||||||
|
.freeSpaceFormatted("0 B")
|
||||||
|
.usableSpace(0L)
|
||||||
|
.usableSpaceFormatted("0 B")
|
||||||
|
.usagePercentage(0.0)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Files.isDirectory(directory)) {
|
||||||
|
log.info("디렉토리 경로가 아닙니다: {}", directoryPath);
|
||||||
|
return FileManagerDto.StorageSpaceRes.builder()
|
||||||
|
.directoryPath(directoryPath)
|
||||||
|
.fileCount(0)
|
||||||
|
.directoryCount(0)
|
||||||
|
.usedSize(0L)
|
||||||
|
.usedSizeFormatted("0 B")
|
||||||
|
.totalDiskSpace(0L)
|
||||||
|
.totalDiskSpaceFormatted("0 B")
|
||||||
|
.freeSpace(0L)
|
||||||
|
.freeSpaceFormatted("0 B")
|
||||||
|
.usableSpace(0L)
|
||||||
|
.usableSpaceFormatted("0 B")
|
||||||
|
.usagePercentage(0.0)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 디렉토리 사용량 계산 — du -sb 사용 (walkFileTree 대비 수배 빠름)
|
||||||
|
// fileCount/directoryCount는 du가 제공하지 않으므로 -1(미집계) 반환
|
||||||
|
long usedSize = 0;
|
||||||
|
|
||||||
|
log.info("[StorageSpace] du 시작 - path={}", directoryPath);
|
||||||
|
try {
|
||||||
|
ProcessBuilder duPb = new ProcessBuilder("du", "-sb", directoryPath);
|
||||||
|
duPb.redirectErrorStream(true);
|
||||||
|
Process duProcess = duPb.start();
|
||||||
|
try (java.io.BufferedReader br =
|
||||||
|
new java.io.BufferedReader(new java.io.InputStreamReader(duProcess.getInputStream()))) {
|
||||||
|
String line = br.readLine();
|
||||||
|
if (line != null) {
|
||||||
|
// du -sb 출력 형식: "12345678\t/path/to/dir"
|
||||||
|
String[] parts = line.split("\t", 2);
|
||||||
|
usedSize = Long.parseLong(parts[0].trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int exitCode = duProcess.waitFor();
|
||||||
|
log.info(
|
||||||
|
"[StorageSpace] du 완료 - exitCode={}, usedSize={} bytes ({})",
|
||||||
|
exitCode,
|
||||||
|
usedSize,
|
||||||
|
formatFileSize(usedSize));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[StorageSpace] du 실행 실패: {}", directoryPath, e);
|
||||||
|
return FileManagerDto.StorageSpaceRes.builder()
|
||||||
|
.directoryPath(directoryPath)
|
||||||
|
.fileCount(-1)
|
||||||
|
.directoryCount(-1)
|
||||||
|
.usedSize(0L)
|
||||||
|
.usedSizeFormatted("0 B")
|
||||||
|
.totalDiskSpace(0L)
|
||||||
|
.totalDiskSpaceFormatted("0 B")
|
||||||
|
.freeSpace(0L)
|
||||||
|
.freeSpaceFormatted("0 B")
|
||||||
|
.usableSpace(0L)
|
||||||
|
.usableSpaceFormatted("0 B")
|
||||||
|
.usagePercentage(0.0)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 디스크 공간 정보 조회 (FileStore 사용) — basePath가 속한 파티션/NFS 마운트 전체 기준
|
||||||
|
long totalDiskSpace = 0;
|
||||||
|
long freeSpace = 0;
|
||||||
|
long usableSpace = 0;
|
||||||
|
double usagePercentage = 0.0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
java.nio.file.FileStore fileStore = Files.getFileStore(directory);
|
||||||
|
totalDiskSpace = fileStore.getTotalSpace();
|
||||||
|
freeSpace = fileStore.getUnallocatedSpace(); // OS 미할당 공간 (root 예약 블록 포함 가능)
|
||||||
|
usableSpace = fileStore.getUsableSpace(); // 실제 프로세스가 사용 가능한 공간
|
||||||
|
log.info(
|
||||||
|
"[StorageSpace] FileStore - name={}, type={}, total={} bytes ({}), unallocated={} bytes ({}), usable={} bytes ({})",
|
||||||
|
fileStore.name(),
|
||||||
|
fileStore.type(),
|
||||||
|
totalDiskSpace,
|
||||||
|
formatFileSize(totalDiskSpace),
|
||||||
|
freeSpace,
|
||||||
|
formatFileSize(freeSpace),
|
||||||
|
usableSpace,
|
||||||
|
formatFileSize(usableSpace));
|
||||||
|
|
||||||
|
// 사용률은 usableSpace 기준으로 계산 (더 정확한 실사용 가능 공간 반영)
|
||||||
|
if (totalDiskSpace > 0) {
|
||||||
|
long usedDiskSpace = totalDiskSpace - usableSpace;
|
||||||
|
usagePercentage = (usedDiskSpace * 100.0) / totalDiskSpace;
|
||||||
|
}
|
||||||
|
log.info("[StorageSpace] usagePercentage={}%", Math.round(usagePercentage * 100.0) / 100.0);
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("[StorageSpace] 디스크 공간 정보 조회 실패: {}", directoryPath, e);
|
||||||
|
// 디스크 정보 조회 실패 시에도 디렉토리 용량은 반환
|
||||||
|
}
|
||||||
|
|
||||||
|
return FileManagerDto.StorageSpaceRes.builder()
|
||||||
|
.directoryPath(directoryPath)
|
||||||
|
.fileCount(-1)
|
||||||
|
.directoryCount(-1)
|
||||||
|
.usedSize(usedSize)
|
||||||
|
.usedSizeFormatted(formatFileSize(usedSize))
|
||||||
|
.totalDiskSpace(totalDiskSpace)
|
||||||
|
.totalDiskSpaceFormatted(formatFileSize(totalDiskSpace))
|
||||||
|
.freeSpace(freeSpace)
|
||||||
|
.freeSpaceFormatted(formatFileSize(freeSpace))
|
||||||
|
.usableSpace(usableSpace)
|
||||||
|
.usableSpaceFormatted(formatFileSize(usableSpace))
|
||||||
|
.usagePercentage(Math.round(usagePercentage * 100.0) / 100.0)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
package com.kamco.cd.training.hyperparam;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.dto.HyperClsParam;
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperClsParamDto;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.List;
|
||||||
|
import com.kamco.cd.training.hyperparam.service.HyperClsParamService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@Tag(name = "분류 하이퍼파라미터 관리", description = "분류 하이퍼파라미터 관리 API")
|
||||||
|
@RestController
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@RequestMapping("/api/hyper-param/cls")
|
||||||
|
public class HyperClsParamApiController {
|
||||||
|
|
||||||
|
private final HyperClsParamService hyperClsParamService;
|
||||||
|
|
||||||
|
@Operation(summary = "하이퍼파라미터 등록", description = "파라미터를 신규 저장")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "등록 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = String.class))),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@PostMapping
|
||||||
|
public ApiResponseDto<String> createHyperParam(@Valid @RequestBody HyperClsParam createReq) {
|
||||||
|
String newVersion = hyperClsParamService.createHyperParam(createReq);
|
||||||
|
return ApiResponseDto.ok(newVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "하이퍼파라미터 수정", description = "파라미터를 수정")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "등록 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = String.class))),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "422", description = "default는 삭제불가", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@PutMapping("/{uuid}")
|
||||||
|
public ApiResponseDto<String> updateHyperParam(
|
||||||
|
@PathVariable UUID uuid, @Valid @RequestBody HyperClsParam createReq) {
|
||||||
|
return ApiResponseDto.ok(hyperClsParamService.updateHyperParam(uuid, createReq));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "하이퍼파라미터 목록 조회", description = "하이퍼파라미터 목록 조회")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = Page.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "하이퍼파라미터를 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/list")
|
||||||
|
public ApiResponseDto<Page<List>> getHyperParam(
|
||||||
|
@Parameter(
|
||||||
|
description = "구분 CREATE_DATE(생성일), LAST_USED_DATE(최근사용일)",
|
||||||
|
example = "CREATE_DATE")
|
||||||
|
@RequestParam(required = false)
|
||||||
|
String type,
|
||||||
|
@Parameter(description = "시작일", example = "2026-07-01") @RequestParam(required = false)
|
||||||
|
LocalDate startDate,
|
||||||
|
@Parameter(description = "종료일", example = "2026-12-31") @RequestParam(required = false)
|
||||||
|
LocalDate endDate,
|
||||||
|
@Parameter(description = "버전명", example = "CLS_000001") @RequestParam(required = false)
|
||||||
|
String hyperVer,
|
||||||
|
@Parameter(description = "모델 타입 (G1, G2, G3, G4, CLS 중 하나)", example = "CLS")
|
||||||
|
@RequestParam(required = false)
|
||||||
|
ModelType model,
|
||||||
|
@Parameter(
|
||||||
|
description = "정렬",
|
||||||
|
example = "createdDttm desc",
|
||||||
|
schema =
|
||||||
|
@Schema(
|
||||||
|
allowableValues = {
|
||||||
|
"createdDttm,desc",
|
||||||
|
"lastUsedDttm,desc",
|
||||||
|
"totalUseCnt,desc"
|
||||||
|
}))
|
||||||
|
@RequestParam(required = false)
|
||||||
|
String sort,
|
||||||
|
@Parameter(description = "페이지 번호 (0부터 시작)", example = "0") @RequestParam(defaultValue = "0")
|
||||||
|
int page,
|
||||||
|
@Parameter(description = "페이지 크기", example = "20") @RequestParam(defaultValue = "20")
|
||||||
|
int size) {
|
||||||
|
HyperParamDto.SearchReq searchReq = new HyperParamDto.SearchReq();
|
||||||
|
searchReq.setType(type);
|
||||||
|
searchReq.setStartDate(startDate);
|
||||||
|
searchReq.setEndDate(endDate);
|
||||||
|
searchReq.setHyperVer(hyperVer);
|
||||||
|
searchReq.setSort(sort);
|
||||||
|
searchReq.setPage(page);
|
||||||
|
searchReq.setSize(size);
|
||||||
|
Page<List> list = hyperClsParamService.getHyperParamList(model, searchReq);
|
||||||
|
|
||||||
|
return ApiResponseDto.ok(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "하이퍼파라미터 삭제", description = "하이퍼파라미터 삭제")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(responseCode = "200", description = "삭제 성공", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "422", description = "default 삭제 불가", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "404", description = "하이퍼파라미터를 찾을 수 없음", content = @Content),
|
||||||
|
})
|
||||||
|
@DeleteMapping("/{uuid}")
|
||||||
|
public ApiResponseDto<Void> deleteHyperParam(
|
||||||
|
@Parameter(description = "하이퍼파라미터 uuid", example = "57fc9170-64c1-4128-aa7b-0657f08d6d10")
|
||||||
|
@PathVariable
|
||||||
|
UUID uuid) {
|
||||||
|
hyperClsParamService.deleteHyperParam(uuid);
|
||||||
|
return ApiResponseDto.ok(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "하이퍼파라미터 상세 조회", description = "특정 버전의 하이퍼파라미터 상세 정보를 조회합니다")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = HyperParamDto.Basic.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "하이퍼파라미터를 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/{uuid}")
|
||||||
|
public ApiResponseDto<HyperClsParamDto.Basic> getHyperParam(
|
||||||
|
@Parameter(description = "하이퍼파라미터 uuid", example = "57fc9170-64c1-4128-aa7b-0657f08d6d10")
|
||||||
|
@PathVariable
|
||||||
|
UUID uuid) {
|
||||||
|
return ApiResponseDto.ok(hyperClsParamService.getHyperParam(uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "하이퍼파라미터 최적화 값 조회", description = "하이퍼파라미터 최적화 값 조회 API")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = Page.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "하이퍼파라미터를 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/init/{model}")
|
||||||
|
public ApiResponseDto<HyperClsParamDto.Basic> getInitHyperParam(@PathVariable ModelType model) {
|
||||||
|
|
||||||
|
return ApiResponseDto.ok(hyperClsParamService.getInitHyperParam(model));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -101,7 +101,7 @@ public class HyperParamApiController {
|
|||||||
LocalDate endDate,
|
LocalDate endDate,
|
||||||
@Parameter(description = "버전명", example = "G1_000019") @RequestParam(required = false)
|
@Parameter(description = "버전명", example = "G1_000019") @RequestParam(required = false)
|
||||||
String hyperVer,
|
String hyperVer,
|
||||||
@Parameter(description = "모델 타입 (G1, G2, G3 중 하나)", example = "G1")
|
@Parameter(description = "모델 타입 (G1, G2, G3, G4 중 하나)", example = "G1")
|
||||||
@RequestParam(required = false)
|
@RequestParam(required = false)
|
||||||
ModelType model,
|
ModelType model,
|
||||||
@Parameter(
|
@Parameter(
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package com.kamco.cd.training.hyperparam.dto;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||||
|
import com.kamco.cd.training.common.utils.enums.EnumType;
|
||||||
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
|
||||||
|
public class HyperClsParamDto {
|
||||||
|
|
||||||
|
@Schema(name = "Basic", description = "하이퍼파라미터 조회")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class Basic {
|
||||||
|
|
||||||
|
private ModelType model; // 20250212 modeltype추가
|
||||||
|
private UUID uuid;
|
||||||
|
private String hyperVer;
|
||||||
|
@JsonFormatDttm private ZonedDateTime createdDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime lastUsedDttm;
|
||||||
|
private Integer totalUseCnt;
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Model
|
||||||
|
// -------------------------
|
||||||
|
private String inputSize;
|
||||||
|
private Integer batchSize;
|
||||||
|
private Integer workers;
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Augmentation
|
||||||
|
// -------------------------
|
||||||
|
private Double scale;
|
||||||
|
private Double translate;
|
||||||
|
private Double fliplr;
|
||||||
|
private Double flipud;
|
||||||
|
private Double erasing;
|
||||||
|
private Double mixup;
|
||||||
|
private Double hsvH;
|
||||||
|
private Double hsvS;
|
||||||
|
private Double hsvV;
|
||||||
|
private Double dropout;
|
||||||
|
private Double labelSmoothing;
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Memo
|
||||||
|
// -------------------------
|
||||||
|
private String memo;
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Hardware
|
||||||
|
// -------------------------
|
||||||
|
private Boolean isDefault;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class List {
|
||||||
|
private UUID uuid;
|
||||||
|
private ModelType model;
|
||||||
|
private String hyperVer;
|
||||||
|
@JsonFormatDttm private ZonedDateTime createDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime lastUsedDttm;
|
||||||
|
private String memo;
|
||||||
|
private Integer totalUseCnt;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class SearchReq {
|
||||||
|
private String type;
|
||||||
|
private LocalDate startDate;
|
||||||
|
private LocalDate endDate;
|
||||||
|
private String hyperVer;
|
||||||
|
|
||||||
|
// 페이징 파라미터
|
||||||
|
private int page = 0;
|
||||||
|
private int size = 20;
|
||||||
|
private String sort;
|
||||||
|
|
||||||
|
public Pageable toPageable() {
|
||||||
|
if (sort != null && !sort.isEmpty()) {
|
||||||
|
String[] sortParams = sort.split(",");
|
||||||
|
String property = sortParams[0];
|
||||||
|
Sort.Direction direction =
|
||||||
|
sortParams.length > 1 ? Sort.Direction.fromString(sortParams[1]) : Sort.Direction.ASC;
|
||||||
|
return PageRequest.of(page, size, Sort.by(direction, property));
|
||||||
|
}
|
||||||
|
return PageRequest.of(page, size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@CodeExpose
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public enum HyperType implements EnumType {
|
||||||
|
CREATE_DATE("생성일"),
|
||||||
|
LAST_USED_DATE("최근 사용일");
|
||||||
|
|
||||||
|
private final String desc;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getId() {
|
||||||
|
return name();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getText() {
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package com.kamco.cd.training.hyperparam.service;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.dto.HyperClsParam;
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperClsParamDto;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.List;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.SearchReq;
|
||||||
|
import com.kamco.cd.training.postgres.core.HyperClsParamCoreService;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class HyperClsParamService {
|
||||||
|
|
||||||
|
private final HyperClsParamCoreService hyperClsParamCoreService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼 파라미터 목록 조회
|
||||||
|
*
|
||||||
|
* @param model
|
||||||
|
* @param req
|
||||||
|
* @return 목록
|
||||||
|
*/
|
||||||
|
public Page<List> getHyperParamList(ModelType model, SearchReq req) {
|
||||||
|
return hyperClsParamCoreService.findByHyperVerList(model, req);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 등록
|
||||||
|
*
|
||||||
|
* @param createReq 등록 요청
|
||||||
|
* @return 생성된 버전명
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public String createHyperParam(HyperClsParam createReq) {
|
||||||
|
return hyperClsParamCoreService.createHyperParam(createReq).getHyperVer();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 수정
|
||||||
|
*
|
||||||
|
* @param createReq
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public String updateHyperParam(UUID uuid, HyperClsParam createReq) {
|
||||||
|
return hyperClsParamCoreService.updateHyperParam(uuid, createReq);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 삭제
|
||||||
|
*
|
||||||
|
* @param uuid
|
||||||
|
*/
|
||||||
|
public void deleteHyperParam(UUID uuid) {
|
||||||
|
hyperClsParamCoreService.deleteHyperParam(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 하이퍼파라미터 최적화 설정값 조회 */
|
||||||
|
public HyperClsParamDto.Basic getInitHyperParam(ModelType model) {
|
||||||
|
return hyperClsParamCoreService.getInitHyperParam(model);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 상세 조회
|
||||||
|
*
|
||||||
|
* @param uuid
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public HyperClsParamDto.Basic getHyperParam(UUID uuid) {
|
||||||
|
return hyperClsParamCoreService.getHyperParam(uuid);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,9 +11,9 @@ import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelTrainMetrics;
|
|||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelValidationMetrics;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelValidationMetrics;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.TransferDetailDto;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.TransferDetailDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.CleanupResult;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
|
||||||
import com.kamco.cd.training.model.service.ModelTrainDetailService;
|
import com.kamco.cd.training.model.service.ModelTrainDetailService;
|
||||||
import com.kamco.cd.training.model.service.ModelTrainMngService;
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||||
@@ -34,8 +34,10 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import org.apache.coyote.BadRequestException;
|
import org.apache.coyote.BadRequestException;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestHeader;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
@@ -45,10 +47,9 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
@RequestMapping("/api/models")
|
@RequestMapping("/api/models")
|
||||||
public class ModelTrainDetailApiController {
|
public class ModelTrainDetailApiController {
|
||||||
private final ModelTrainDetailService modelTrainDetailService;
|
private final ModelTrainDetailService modelTrainDetailService;
|
||||||
private final ModelTrainMngService modelTrainMngService;
|
|
||||||
private final RangeDownloadResponder rangeDownloadResponder;
|
private final RangeDownloadResponder rangeDownloadResponder;
|
||||||
|
|
||||||
@Value("${train.docker.responseDir}")
|
@Value("${train.docker.response_dir}")
|
||||||
private String responseDir;
|
private String responseDir;
|
||||||
|
|
||||||
@Operation(summary = "모델학습관리> 모델관리 > 상세정보탭 > 학습 진행정보", description = "학습 진행정보, 모델학습 정보 API")
|
@Operation(summary = "모델학습관리> 모델관리 > 상세정보탭 > 학습 진행정보", description = "학습 진행정보, 모델학습 정보 API")
|
||||||
@@ -326,4 +327,83 @@ public class ModelTrainDetailApiController {
|
|||||||
UUID uuid) {
|
UUID uuid) {
|
||||||
return ApiResponseDto.ok(modelTrainDetailService.findModelTrainProgressInfo(uuid));
|
return ApiResponseDto.ok(modelTrainDetailService.findModelTrainProgressInfo(uuid));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "모델관리 > 모델 상세 > best epoch 제외 삭제 될 파일 미리보기",
|
||||||
|
description = "best epoch 제외 삭제 될 파일 미리보기 API")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = CleanupResult.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/{uuid}/cleanup/preview")
|
||||||
|
public ApiResponseDto<CleanupResult> previewCleanup(
|
||||||
|
@Parameter(description = "모델 uuid") @PathVariable UUID uuid) {
|
||||||
|
return ApiResponseDto.ok(modelTrainDetailService.previewCleanup(uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "모델관리 > 모델 상세 > best epoch 제외 삭제", description = "best epoch 제외 파일 삭제 API")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "삭제 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = CleanupResult.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@DeleteMapping("/{uuid}/cleanup")
|
||||||
|
public ApiResponseDto<CleanupResult> cleanup(
|
||||||
|
@Parameter(description = "모델 uuid") @PathVariable UUID uuid) {
|
||||||
|
return ApiResponseDto.ok(modelTrainDetailService.cleanup(uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "학습 결과 ZIP 파일 목록 조회",
|
||||||
|
description = "모델 UUID에 해당하는 모든 ZIP 파일 목록과 개별 다운로드 링크 반환",
|
||||||
|
parameters = {
|
||||||
|
@Parameter(
|
||||||
|
name = "kamco-download-uuid",
|
||||||
|
in = ParameterIn.HEADER,
|
||||||
|
required = true,
|
||||||
|
description = "다운로드 요청 UUID",
|
||||||
|
schema =
|
||||||
|
@Schema(
|
||||||
|
type = "string",
|
||||||
|
format = "uuid",
|
||||||
|
example = "6d8d49dc-0c9d-4124-adc7-b9ca610cc394"))
|
||||||
|
})
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "ZIP 파일 목록 조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema =
|
||||||
|
@Schema(implementation = ModelTrainDetailDto.ZipFileListResponse.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "모델 또는 파일 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/downloadzip/{uuid}")
|
||||||
|
public ResponseEntity<?> downloadZip(
|
||||||
|
@Parameter(description = "모델 UUID") @PathVariable UUID uuid,
|
||||||
|
@Parameter(hidden = true) @RequestHeader("kamco-download-uuid") String downloadUuid,
|
||||||
|
HttpServletRequest request)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
modelTrainDetailService.getZipFileListWithFullUrl(uuid, downloadUuid, request));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.kamco.cd.training.model;
|
package com.kamco.cd.training.model;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.dto.MonitorDto;
|
import com.kamco.cd.training.common.dto.MonitorDto;
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.common.service.SystemMonitorService;
|
import com.kamco.cd.training.common.service.SystemMonitorService;
|
||||||
import com.kamco.cd.training.config.api.ApiResponseDto;
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
||||||
@@ -68,7 +69,7 @@ public class ModelTrainMngApiController {
|
|||||||
@Parameter(
|
@Parameter(
|
||||||
description = "모델",
|
description = "모델",
|
||||||
example = "G1",
|
example = "G1",
|
||||||
schema = @Schema(allowableValues = {"G1", "G2", "G3"}))
|
schema = @Schema(allowableValues = {"G1", "G2", "G3", "G4"}))
|
||||||
@RequestParam(required = false)
|
@RequestParam(required = false)
|
||||||
String modelNo,
|
String modelNo,
|
||||||
@Parameter(description = "페이지 번호") @RequestParam(defaultValue = "0") int page,
|
@Parameter(description = "페이지 번호") @RequestParam(defaultValue = "0") int page,
|
||||||
@@ -143,9 +144,9 @@ public class ModelTrainMngApiController {
|
|||||||
@Parameter(
|
@Parameter(
|
||||||
description = "모델 구분",
|
description = "모델 구분",
|
||||||
example = "",
|
example = "",
|
||||||
schema = @Schema(allowableValues = {"G1", "G2", "G3"}))
|
schema = @Schema(allowableValues = {"G1", "G2", "G3", "G4"}))
|
||||||
@RequestParam
|
@RequestParam
|
||||||
String modelType,
|
ModelType modelType,
|
||||||
@Parameter(
|
@Parameter(
|
||||||
description = "선택 구분",
|
description = "선택 구분",
|
||||||
example = "",
|
example = "",
|
||||||
@@ -153,7 +154,7 @@ public class ModelTrainMngApiController {
|
|||||||
@RequestParam
|
@RequestParam
|
||||||
String selectType) {
|
String selectType) {
|
||||||
DatasetReq req = new DatasetReq();
|
DatasetReq req = new DatasetReq();
|
||||||
req.setModelNo(modelType);
|
req.setModelNo(modelType.getId());
|
||||||
req.setDataType(selectType);
|
req.setDataType(selectType);
|
||||||
return ApiResponseDto.ok(modelTrainMngService.getDatasetSelectList(req));
|
return ApiResponseDto.ok(modelTrainMngService.getDatasetSelectList(req));
|
||||||
}
|
}
|
||||||
@@ -235,4 +236,41 @@ public class ModelTrainMngApiController {
|
|||||||
public ApiResponseDto<MonitorDto> getSystem() throws IOException {
|
public ApiResponseDto<MonitorDto> getSystem() throws IOException {
|
||||||
return ApiResponseDto.ok(systemMonitorService.get());
|
return ApiResponseDto.ok(systemMonitorService.get());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "모델학습 1단계/2단계 실행중인 것 id 정보", description = "모델학습 1단계/2단계 실행중인 것 id 정보")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "검색 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = Long.class))),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/ing-model")
|
||||||
|
public ApiResponseDto<ModelTrainMngDto.InProgressModel> findInprogressModel() {
|
||||||
|
return ApiResponseDto.ok(modelTrainMngService.findInprogressModel());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "모델학습 진행율 퍼센트", description = "모델학습 진행율 퍼센트")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "검색 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = Long.class))),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/progress-percent/{uuid}")
|
||||||
|
public ApiResponseDto<ModelTrainMngDto.ProgressPercent> findTrainProgressPercent(
|
||||||
|
@PathVariable UUID uuid) {
|
||||||
|
return ApiResponseDto.ok(modelTrainMngService.findTrainProgressPercent(uuid));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ public class FileDto {
|
|||||||
private Integer endPos;
|
private Integer endPos;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@@ -89,6 +90,8 @@ public class FileDto {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Schema(name = "FoldersDto", description = "폴더목록 정보")
|
@Schema(name = "FoldersDto", description = "폴더목록 정보")
|
||||||
@Getter
|
@Getter
|
||||||
public static class FoldersDto {
|
public static class FoldersDto {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonInclude;
|
|||||||
import com.kamco.cd.training.common.enums.LearnDataType;
|
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.common.enums.TrainType;
|
import com.kamco.cd.training.common.enums.TrainType;
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
import com.kamco.cd.training.common.utils.enums.Enums;
|
import com.kamco.cd.training.common.utils.enums.Enums;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
||||||
@@ -32,6 +33,8 @@ public class ModelTrainDetailDto {
|
|||||||
private String modelNo;
|
private String modelNo;
|
||||||
private String modelVer;
|
private String modelVer;
|
||||||
@JsonFormatDttm private ZonedDateTime step1StrtDttm;
|
@JsonFormatDttm private ZonedDateTime step1StrtDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime step1EndDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime step2StrtDttm;
|
||||||
@JsonFormatDttm private ZonedDateTime step2EndDttm;
|
@JsonFormatDttm private ZonedDateTime step2EndDttm;
|
||||||
private String statusCd;
|
private String statusCd;
|
||||||
private String trainType;
|
private String trainType;
|
||||||
@@ -40,7 +43,9 @@ public class ModelTrainDetailDto {
|
|||||||
public String getStatusName() {
|
public String getStatusName() {
|
||||||
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.statusCd).getId()
|
||||||
|
: TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -49,18 +54,16 @@ public class ModelTrainDetailDto {
|
|||||||
public String getTrainTypeName() {
|
public String getTrainTypeName() {
|
||||||
if (this.trainType == null || this.trainType.isBlank()) return null;
|
if (this.trainType == null || this.trainType.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainType.valueOf(this.trainType).getId()
|
||||||
|
: TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String formatDuration(ZonedDateTime start, ZonedDateTime end) {
|
private String formatDuration(ZonedDateTime start, ZonedDateTime end) {
|
||||||
if (end == null) {
|
if (start == null || end == null) {
|
||||||
end = ZonedDateTime.now();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (start == null) {
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,11 +73,42 @@ public class ModelTrainDetailDto {
|
|||||||
long minutes = (totalSeconds % 3600) / 60;
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
long seconds = totalSeconds % 60;
|
long seconds = totalSeconds % 60;
|
||||||
|
|
||||||
|
if (HeaderUtil.isEnglishRequest()) {
|
||||||
|
return String.format("%dh %dm %ds", hours, minutes, seconds);
|
||||||
|
} else {
|
||||||
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public String getStepAllDuration() {
|
public String getStepAllDuration() {
|
||||||
return formatDuration(this.step1StrtDttm, this.step2EndDttm);
|
if (this.step2EndDttm != null) {
|
||||||
|
// step1 + step2 실제 소요시간 합산
|
||||||
|
long step1Seconds = 0;
|
||||||
|
long step2Seconds = 0;
|
||||||
|
|
||||||
|
if (this.step1StrtDttm != null && this.step1EndDttm != null) {
|
||||||
|
step1Seconds =
|
||||||
|
Math.abs(Duration.between(this.step1StrtDttm, this.step1EndDttm).getSeconds());
|
||||||
|
}
|
||||||
|
if (this.step2StrtDttm != null && this.step2EndDttm != null) {
|
||||||
|
step2Seconds =
|
||||||
|
Math.abs(Duration.between(this.step2StrtDttm, this.step2EndDttm).getSeconds());
|
||||||
|
}
|
||||||
|
|
||||||
|
long totalSeconds = step1Seconds + step2Seconds;
|
||||||
|
long hours = totalSeconds / 3600;
|
||||||
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
|
long seconds = totalSeconds % 60;
|
||||||
|
|
||||||
|
if (HeaderUtil.isEnglishRequest()) {
|
||||||
|
return String.format("%dh %dm %ds", hours, minutes, seconds);
|
||||||
|
} else {
|
||||||
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// step2 없으면 step1만
|
||||||
|
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,6 +176,9 @@ public class ModelTrainDetailDto {
|
|||||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
private Long landCoverCnt;
|
private Long landCoverCnt;
|
||||||
|
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
|
private Long solarPanelCnt;
|
||||||
|
|
||||||
public MappingDataset(
|
public MappingDataset(
|
||||||
Long modelId,
|
Long modelId,
|
||||||
Long datasetId,
|
Long datasetId,
|
||||||
@@ -152,26 +189,33 @@ public class ModelTrainDetailDto {
|
|||||||
Long buildingCnt,
|
Long buildingCnt,
|
||||||
Long containerCnt,
|
Long containerCnt,
|
||||||
Long wasteCnt,
|
Long wasteCnt,
|
||||||
Long landCoverCnt) {
|
Long landCoverCnt,
|
||||||
|
Long solarPanelCnt) {
|
||||||
this.modelId = modelId;
|
this.modelId = modelId;
|
||||||
this.datasetId = datasetId;
|
this.datasetId = datasetId;
|
||||||
this.dataType = dataType;
|
this.dataType = dataType;
|
||||||
this.compareYyyy = compareYyyy;
|
this.compareYyyy = compareYyyy;
|
||||||
this.targetYyyy = targetYyyy;
|
this.targetYyyy = targetYyyy;
|
||||||
this.roundNo = roundNo;
|
this.roundNo = roundNo;
|
||||||
this.buildingCnt = buildingCnt;
|
this.buildingCnt = toNullIfZero(buildingCnt);
|
||||||
this.containerCnt = containerCnt;
|
this.containerCnt = toNullIfZero(containerCnt);
|
||||||
this.wasteCnt = wasteCnt;
|
this.wasteCnt = toNullIfZero(wasteCnt);
|
||||||
this.landCoverCnt = landCoverCnt;
|
this.landCoverCnt = toNullIfZero(landCoverCnt);
|
||||||
|
this.solarPanelCnt = toNullIfZero(solarPanelCnt);
|
||||||
|
|
||||||
this.dataTypeName = getDataTypeName(this.dataType);
|
this.dataTypeName = getDataTypeName(this.dataType);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDataTypeName(String groupTitleCd) {
|
public String getDataTypeName(String groupTitleCd) {
|
||||||
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
|
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
|
||||||
return type == null ? null : type.getText();
|
return type == null ? null : (HeaderUtil.isEnglishRequest() ? type.getId() : type.getText());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Long toNullIfZero(Long value) {
|
||||||
|
return (value == null || value == 0L) ? null : value;
|
||||||
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@@ -256,4 +300,73 @@ public class ModelTrainDetailDto {
|
|||||||
private Boolean fileExistsYn;
|
private Boolean fileExistsYn;
|
||||||
private String fileName;
|
private String fileName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
@Schema(name = "ZipFileListResponse", description = "ZIP 파일 목록 조회 응답")
|
||||||
|
public static class ZipFileListResponse {
|
||||||
|
|
||||||
|
@Schema(description = "모델 UUID", example = "2c5cdd07-5b9b-44ad-a063-8dead628b45f")
|
||||||
|
private String modelUuid;
|
||||||
|
|
||||||
|
@Schema(description = "모델 번호", example = "G2")
|
||||||
|
private String modelNo;
|
||||||
|
|
||||||
|
@Schema(description = "현재 모델 버전", example = "G2_000001")
|
||||||
|
private String modelVer;
|
||||||
|
|
||||||
|
@Schema(
|
||||||
|
description = "기본 경로",
|
||||||
|
example = "/home/kcomu/data/response/2c5cdd07-5b9b-44ad-a063-8dead628b45f")
|
||||||
|
private String basePath;
|
||||||
|
|
||||||
|
@Schema(description = "ZIP 파일 목록")
|
||||||
|
private List<ZipFileInfo> zipFiles;
|
||||||
|
|
||||||
|
@Schema(description = "총 파일 개수", example = "3")
|
||||||
|
private Integer totalFiles;
|
||||||
|
|
||||||
|
@Schema(description = "전체 파일 크기 (bytes)", example = "4048640000")
|
||||||
|
private Long totalSize;
|
||||||
|
|
||||||
|
@Schema(description = "전체 파일 크기 (포맷)", example = "3.77 GB")
|
||||||
|
private String totalSizeFormatted;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
@Schema(name = "ZipFileInfo", description = "ZIP 파일 상세 정보")
|
||||||
|
public static class ZipFileInfo {
|
||||||
|
|
||||||
|
@Schema(description = "파일명", example = "G2.G2_000001.{uuid}.zip")
|
||||||
|
private String fileName;
|
||||||
|
|
||||||
|
@Schema(description = "파일 전체 경로")
|
||||||
|
private String filePath;
|
||||||
|
|
||||||
|
@Schema(description = "모델 버전", example = "G2_000001")
|
||||||
|
private String version;
|
||||||
|
|
||||||
|
@Schema(description = "파일 크기 (bytes)", example = "1349516895")
|
||||||
|
private Long fileSize;
|
||||||
|
|
||||||
|
@Schema(description = "파일 크기 (포맷)", example = "1.26 GB")
|
||||||
|
private String fileSizeFormatted;
|
||||||
|
|
||||||
|
@Schema(description = "최종 수정 시간", example = "2026-03-10T23:19:24.347+09:00")
|
||||||
|
@JsonFormatDttm
|
||||||
|
private ZonedDateTime lastModified;
|
||||||
|
|
||||||
|
@Schema(description = "현재 모델 버전 여부", example = "true")
|
||||||
|
private Boolean isCurrent;
|
||||||
|
|
||||||
|
@Schema(description = "다운로드 URL")
|
||||||
|
private String downloadUrl;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.kamco.cd.training.model.dto;
|
|||||||
import com.kamco.cd.training.common.dto.HyperParam;
|
import com.kamco.cd.training.common.dto.HyperParam;
|
||||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.common.enums.TrainType;
|
import com.kamco.cd.training.common.enums.TrainType;
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
@@ -44,15 +45,20 @@ public class ModelTrainMngDto {
|
|||||||
private String requestPath;
|
private String requestPath;
|
||||||
|
|
||||||
private String packingState;
|
private String packingState;
|
||||||
private ZonedDateTime packingStrtDttm;
|
@JsonFormatDttm private ZonedDateTime packingStrtDttm;
|
||||||
private ZonedDateTime packingEndDttm;
|
@JsonFormatDttm private ZonedDateTime packingEndDttm;
|
||||||
|
|
||||||
private Long beforeModelId;
|
private Long beforeModelId;
|
||||||
|
private Integer bestEpoch;
|
||||||
|
|
||||||
|
private UUID beforeModelUuid;
|
||||||
|
|
||||||
public String getStatusName() {
|
public String getStatusName() {
|
||||||
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
return (HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.statusCd).getId()
|
||||||
|
: TrainStatusType.valueOf(this.statusCd).getText()); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -61,7 +67,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStep1StatusName() {
|
public String getStep1StatusName() {
|
||||||
if (this.step1Status == null || this.step1Status.isBlank()) return null;
|
if (this.step1Status == null || this.step1Status.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
|
return (HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.step1Status).getId()
|
||||||
|
: TrainStatusType.valueOf(this.step1Status).getText()); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -70,7 +78,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStep2StatusName() {
|
public String getStep2StatusName() {
|
||||||
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
return (HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.step2Status).getId()
|
||||||
|
: TrainStatusType.valueOf(this.step2Status).getText()); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -79,7 +89,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getTrainTypeName() {
|
public String getTrainTypeName() {
|
||||||
if (this.trainType == null || this.trainType.isBlank()) return null;
|
if (this.trainType == null || this.trainType.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
return (HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainType.valueOf(this.trainType).getId()
|
||||||
|
: TrainType.valueOf(this.trainType).getText()); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -96,8 +108,12 @@ public class ModelTrainMngDto {
|
|||||||
long minutes = (totalSeconds % 3600) / 60;
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
long seconds = totalSeconds % 60;
|
long seconds = totalSeconds % 60;
|
||||||
|
|
||||||
|
if (HeaderUtil.isEnglishRequest()) {
|
||||||
|
return String.format("%dh %dm %ds", hours, minutes, seconds);
|
||||||
|
} else {
|
||||||
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public String getStep1Duration() {
|
public String getStep1Duration() {
|
||||||
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
||||||
@@ -138,7 +154,7 @@ public class ModelTrainMngDto {
|
|||||||
public static class AddReq {
|
public static class AddReq {
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Schema(description = "모델 종류 G1, G2, G3", example = "G1")
|
@Schema(description = "모델 종류 G1, G2, G3, G4", example = "G1")
|
||||||
private String modelNo;
|
private String modelNo;
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@@ -175,6 +191,8 @@ public class ModelTrainMngDto {
|
|||||||
|
|
||||||
private String requestPath;
|
private String requestPath;
|
||||||
private String responsePath;
|
private String responsePath;
|
||||||
|
private String tmpFileStatus;
|
||||||
|
private ZonedDateTime tmpFileEndDttm;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@@ -196,10 +214,11 @@ public class ModelTrainMngDto {
|
|||||||
@Schema(description = "폐기물", example = "0")
|
@Schema(description = "폐기물", example = "0")
|
||||||
private Long wasteCnt;
|
private Long wasteCnt;
|
||||||
|
|
||||||
@Schema(
|
@Schema(description = "도로, 비닐하우스, 밭, 과수원, 초지, 숲, 물, 모재/자갈, 토분(무덤), 일반토지, 기타", example = "0")
|
||||||
description = "도로, 비닐하우스, 밭, 과수원, 초지, 숲, 물, 모재/자갈, 토분(무덤), 일반토지, 태양광, 기타",
|
|
||||||
example = "0")
|
|
||||||
private Long LandCoverCnt;
|
private Long LandCoverCnt;
|
||||||
|
|
||||||
|
@Schema(description = "태양광", example = "0")
|
||||||
|
private Long solarPanelCnt;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@@ -256,7 +275,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStatusName() {
|
public String getStatusName() {
|
||||||
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.statusCd).getId()
|
||||||
|
: TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -265,7 +286,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStep1StatusName() {
|
public String getStep1StatusName() {
|
||||||
if (this.step1Status == null || this.step1Status.isBlank()) return null;
|
if (this.step1Status == null || this.step1Status.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.step1Status).getId()
|
||||||
|
: TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -274,7 +297,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStep2StatusName() {
|
public String getStep2StatusName() {
|
||||||
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.step2Status).getId()
|
||||||
|
: TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -283,7 +308,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getTrainTypeName() {
|
public String getTrainTypeName() {
|
||||||
if (this.trainType == null || this.trainType.isBlank()) return null;
|
if (this.trainType == null || this.trainType.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainType.valueOf(this.trainType).getId()
|
||||||
|
: TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -300,8 +327,12 @@ public class ModelTrainMngDto {
|
|||||||
long minutes = (totalSeconds % 3600) / 60;
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
long seconds = totalSeconds % 60;
|
long seconds = totalSeconds % 60;
|
||||||
|
|
||||||
|
if (HeaderUtil.isEnglishRequest()) {
|
||||||
|
return String.format("%dh %dm %ds", hours, minutes, seconds);
|
||||||
|
} else {
|
||||||
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public String getStep1Duration() {
|
public String getStep1Duration() {
|
||||||
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
||||||
@@ -327,4 +358,48 @@ public class ModelTrainMngDto {
|
|||||||
@JsonFormatDttm private ZonedDateTime endTime;
|
@JsonFormatDttm private ZonedDateTime endTime;
|
||||||
private boolean isError;
|
private boolean isError;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public static class CleanupResult {
|
||||||
|
// cleanup 대상 전체 파일 수 (삭제 대상 + 유지 파일 포함)
|
||||||
|
private int totalCount;
|
||||||
|
|
||||||
|
// 실제로 삭제된 파일 개수
|
||||||
|
private int deletedCount;
|
||||||
|
|
||||||
|
// 삭제 실패한 파일 개수
|
||||||
|
private int failedCount;
|
||||||
|
|
||||||
|
// 삭제 실패한 파일명 목록
|
||||||
|
private List<String> failedFiles;
|
||||||
|
|
||||||
|
// 유지된 파일명 (best epoch 기준)
|
||||||
|
private String keptFile;
|
||||||
|
|
||||||
|
// 삭제 될 파일
|
||||||
|
private List<String> deleteTargets;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Builder
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class InProgressModel {
|
||||||
|
|
||||||
|
private String modelNo;
|
||||||
|
private UUID uuid;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Builder
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class ProgressPercent {
|
||||||
|
|
||||||
|
private Long modelId;
|
||||||
|
private String jobType;
|
||||||
|
private String statusCd;
|
||||||
|
private Integer totalEpoch;
|
||||||
|
private Integer currentEpoch;
|
||||||
|
private Double percent;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package com.kamco.cd.training.model.service;
|
package com.kamco.cd.training.model.service;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.download.RangeDownloadResponder;
|
||||||
import com.kamco.cd.training.common.enums.ModelType;
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
|
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
||||||
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
||||||
@@ -14,15 +17,38 @@ import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelTrainMetrics;
|
|||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelValidationMetrics;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelValidationMetrics;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.TransferDetailDto;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.TransferDetailDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.TransferHyperSummary;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.TransferHyperSummary;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ZipFileInfo;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ZipFileListResponse;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.CleanupResult;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
|
||||||
import com.kamco.cd.training.postgres.core.ModelTrainDetailCoreService;
|
import com.kamco.cd.training.postgres.core.ModelTrainDetailCoreService;
|
||||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.AccessDeniedException;
|
||||||
|
import java.nio.file.FileVisitOption;
|
||||||
|
import java.nio.file.FileVisitResult;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.LinkOption;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.SimpleFileVisitor;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
import java.nio.file.attribute.FileTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.EnumSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Stream;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -34,6 +60,10 @@ public class ModelTrainDetailService {
|
|||||||
|
|
||||||
private final ModelTrainDetailCoreService modelTrainDetailCoreService;
|
private final ModelTrainDetailCoreService modelTrainDetailCoreService;
|
||||||
private final ModelTrainMngCoreService mngCoreService;
|
private final ModelTrainMngCoreService mngCoreService;
|
||||||
|
private final RangeDownloadResponder rangeDownloadResponder;
|
||||||
|
|
||||||
|
@Value("${train.docker.response_dir}")
|
||||||
|
private String responseDir;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델 상세정보 요약
|
* 모델 상세정보 요약
|
||||||
@@ -63,6 +93,7 @@ public class ModelTrainDetailService {
|
|||||||
return modelTrainDetailCoreService.findByModelByUUID(uuid);
|
return modelTrainDetailCoreService.findByModelByUUID(uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 전이학습 모델선택 정보
|
* 전이학습 모델선택 정보
|
||||||
*
|
*
|
||||||
@@ -129,6 +160,8 @@ public class ModelTrainDetailService {
|
|||||||
return transferDetailDto;
|
return transferDetailDto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
public List<ModelTrainMetrics> getModelTrainMetricResult(UUID uuid) {
|
public List<ModelTrainMetrics> getModelTrainMetricResult(UUID uuid) {
|
||||||
return modelTrainDetailCoreService.getModelTrainMetricResult(uuid);
|
return modelTrainDetailCoreService.getModelTrainMetricResult(uuid);
|
||||||
}
|
}
|
||||||
@@ -152,4 +185,915 @@ public class ModelTrainDetailService {
|
|||||||
public List<ModelProgressStepDto> findModelTrainProgressInfo(UUID uuid) {
|
public List<ModelProgressStepDto> findModelTrainProgressInfo(UUID uuid) {
|
||||||
return modelTrainDetailCoreService.findModelTrainProgressInfo(uuid);
|
return modelTrainDetailCoreService.findModelTrainProgressInfo(uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 삭제될 파일목록 및 유지될 파일 목록
|
||||||
|
*
|
||||||
|
* @param uuid
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public CleanupResult previewCleanup(UUID uuid) {
|
||||||
|
|
||||||
|
CleanupResult result = new CleanupResult();
|
||||||
|
|
||||||
|
// ===== 모델 조회 =====
|
||||||
|
ModelTrainMngDto.Basic model = modelTrainDetailCoreService.findByModelByUUID(uuid);
|
||||||
|
|
||||||
|
if (model == null) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
"NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다. UUID: " + uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
Path dir = Paths.get(responseDir, model.getUuid().toString()).toAbsolutePath().normalize();
|
||||||
|
|
||||||
|
if (!Files.exists(dir) || !Files.isDirectory(dir)) {
|
||||||
|
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "디렉토리가 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Files.isReadable(dir)) {
|
||||||
|
throw new CustomApiException("FORBIDDEN", HttpStatus.FORBIDDEN, "디렉토리 읽기 권한이 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
try (Stream<Path> stream = Files.list(dir)) {
|
||||||
|
|
||||||
|
List<Path> files = stream.toList();
|
||||||
|
|
||||||
|
if (files.isEmpty()) {
|
||||||
|
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "파일이 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== keep 파일 찾기 =====
|
||||||
|
Path keep =
|
||||||
|
files.stream()
|
||||||
|
.filter(
|
||||||
|
p -> {
|
||||||
|
String name = p.getFileName().toString();
|
||||||
|
return name.endsWith(".zip") && name.contains(model.getUuid().toString());
|
||||||
|
})
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(
|
||||||
|
() ->
|
||||||
|
new CustomApiException(
|
||||||
|
"NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "zip 파일이 없습니다."));
|
||||||
|
|
||||||
|
log.info("유지 파일: {}", keep.getFileName());
|
||||||
|
|
||||||
|
// ===== 결과 세팅 =====
|
||||||
|
result.setTotalCount(files.size());
|
||||||
|
result.setKeptFile(keep.getFileName().toString());
|
||||||
|
|
||||||
|
// ===== 삭제 대상 =====
|
||||||
|
List<String> deleteTargets =
|
||||||
|
files.stream()
|
||||||
|
.filter(
|
||||||
|
p -> !p.toAbsolutePath().normalize().equals(keep.toAbsolutePath().normalize()))
|
||||||
|
.map(p -> p.getFileName().toString())
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
result.setDeleteTargets(deleteTargets);
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"previewCleanup 완료. total={}, deleteTargets={}",
|
||||||
|
result.getTotalCount(),
|
||||||
|
deleteTargets.size());
|
||||||
|
|
||||||
|
return result;
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("파일 목록 조회 실패: {}", dir, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "파일 목록 조회 실패");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public CleanupResult cleanup(UUID uuid) {
|
||||||
|
// ===== 모델 조회 =====
|
||||||
|
ModelTrainMngDto.Basic model = modelTrainDetailCoreService.findByModelByUUID(uuid);
|
||||||
|
|
||||||
|
if (model == null) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
"NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다. UUID: " + uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!TrainStatusType.COMPLETED.getId().equals(model.getStep2Status())) {
|
||||||
|
throw new CustomApiException("CONFLICT", HttpStatus.CONFLICT, "테스트가 완료되지 않았습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 경로 =====
|
||||||
|
Path dir = Paths.get(responseDir, model.getUuid().toString()).toAbsolutePath().normalize();
|
||||||
|
|
||||||
|
return executeCleanup(model, dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 베스트 에폭 제외 파일 삭제, 베스트 에폭 zip 파일만 남김
|
||||||
|
*
|
||||||
|
* @param model model 정보
|
||||||
|
* @param dir response 폴더 경로
|
||||||
|
* @return 삭제 정보
|
||||||
|
*/
|
||||||
|
public CleanupResult executeCleanup(ModelTrainMngDto.Basic model, Path dir) {
|
||||||
|
CleanupResult result = new CleanupResult();
|
||||||
|
|
||||||
|
if (!Files.exists(dir) || !Files.isDirectory(dir)) {
|
||||||
|
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "디렉토리가 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Files.isReadable(dir)) {
|
||||||
|
throw new CustomApiException("FORBIDDEN", HttpStatus.FORBIDDEN, "디렉토리 읽기 권한이 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Files.isWritable(dir)) {
|
||||||
|
throw new CustomApiException("FORBIDDEN", HttpStatus.FORBIDDEN, "디렉토리 삭제 권한이 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
int bestEpoch = model.getBestEpoch();
|
||||||
|
|
||||||
|
if (bestEpoch <= 0) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
"BAD_REQUEST", HttpStatus.BAD_REQUEST, "잘못된 bestEpoch 값 입니다. : " + bestEpoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("cleanup 시작. dir={}, bestEpoch={}", dir, bestEpoch);
|
||||||
|
|
||||||
|
try (Stream<Path> stream = Files.list(dir)) {
|
||||||
|
|
||||||
|
List<Path> files = stream.toList();
|
||||||
|
|
||||||
|
if (files.isEmpty()) {
|
||||||
|
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "파일이 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== keep 파일 찾기 =====
|
||||||
|
Path keep = null;
|
||||||
|
|
||||||
|
for (Path p : files) {
|
||||||
|
String name = p.getFileName().toString();
|
||||||
|
if (name.endsWith(".zip") && name.contains(model.getUuid().toString())) {
|
||||||
|
keep = p;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (keep == null) {
|
||||||
|
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "zip 파일이 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("유지 파일: {}", keep.getFileName());
|
||||||
|
|
||||||
|
result.setTotalCount(files.size());
|
||||||
|
result.setKeptFile(keep.getFileName().toString());
|
||||||
|
|
||||||
|
int deletedCount = 0;
|
||||||
|
List<String> failed = new ArrayList<>();
|
||||||
|
|
||||||
|
// ===== 삭제 =====
|
||||||
|
for (Path p : files) {
|
||||||
|
|
||||||
|
if (p.equals(keep)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
// 심볼릭 링크 → 링크만 삭제
|
||||||
|
if (Files.isSymbolicLink(p)) {
|
||||||
|
Files.deleteIfExists(p);
|
||||||
|
log.info("심볼릭 링크 삭제: {}", p.getFileName());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 디렉토리 → 재귀 삭제
|
||||||
|
else if (Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS)) {
|
||||||
|
log.info("디렉토리 재귀 삭제: {}", p.getFileName());
|
||||||
|
deleteDirectory(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 일반 파일
|
||||||
|
else {
|
||||||
|
Files.deleteIfExists(p);
|
||||||
|
log.info("파일 삭제: {}", p.getFileName());
|
||||||
|
}
|
||||||
|
|
||||||
|
deletedCount++;
|
||||||
|
|
||||||
|
} catch (AccessDeniedException e) {
|
||||||
|
failed.add(p.getFileName().toString());
|
||||||
|
log.error("권한 없음: {}", p.getFileName(), e);
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
failed.add(p.getFileName().toString());
|
||||||
|
log.error("삭제 실패: {}", p.getFileName(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.setDeletedCount(deletedCount);
|
||||||
|
result.setFailedCount(failed.size());
|
||||||
|
result.setFailedFiles(failed);
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("파일 목록 조회 실패: {}", dir, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "파일 목록 조회 실패");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"cleanup 완료. total={}, deleted={}, failed={}",
|
||||||
|
result.getTotalCount(),
|
||||||
|
result.getDeletedCount(),
|
||||||
|
result.getFailedCount());
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 디렉토리 재귀 삭제
|
||||||
|
private void deleteDirectory(Path dir) throws IOException {
|
||||||
|
|
||||||
|
if (!Files.exists(dir, LinkOption.NOFOLLOW_LINKS)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// dir 자체가 심볼릭 링크면 링크만 삭제
|
||||||
|
if (Files.isSymbolicLink(dir)) {
|
||||||
|
Files.delete(dir);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Files.walkFileTree(
|
||||||
|
dir,
|
||||||
|
EnumSet.noneOf(FileVisitOption.class), // NOFOLLOW_LINKS
|
||||||
|
Integer.MAX_VALUE,
|
||||||
|
new SimpleFileVisitor<>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
Files.delete(file); // 링크면 링크만 삭제됨
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult postVisitDirectory(Path directory, IOException exc)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
if (exc != null) throw exc;
|
||||||
|
|
||||||
|
Files.delete(directory);
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델 UUID로 ZIP 파일 목록 조회 및 전체 URL 다운로드 링크 생성
|
||||||
|
*
|
||||||
|
* @param uuid 모델 UUID
|
||||||
|
* @param downloadUuid 다운로드 추적 UUID
|
||||||
|
* @param request HTTP 요청
|
||||||
|
* @return ZIP 파일 목록 및 전체 URL 다운로드 링크
|
||||||
|
*/
|
||||||
|
public ZipFileListResponse getZipFileListWithFullUrl(
|
||||||
|
UUID uuid, String downloadUuid, HttpServletRequest request) {
|
||||||
|
log.info("=== ZIP 파일 목록 조회 시작: modelUuid={}, downloadUuid={} ===", uuid, downloadUuid);
|
||||||
|
|
||||||
|
// 1. 모델 정보 조회
|
||||||
|
Basic modelInfo;
|
||||||
|
try {
|
||||||
|
modelInfo = findByModelByUUID(uuid);
|
||||||
|
if (modelInfo == null) {
|
||||||
|
log.warn("모델을 찾을 수 없음: modelUuid={}", uuid);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
||||||
|
}
|
||||||
|
log.debug(
|
||||||
|
"모델 정보 조회 성공: modelNo={}, modelVer={}", modelInfo.getModelNo(), modelInfo.getModelVer());
|
||||||
|
} catch (NullPointerException e) {
|
||||||
|
log.error("모델 조회 중 NullPointerException 발생: modelUuid={}", uuid, e);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
||||||
|
} catch (CustomApiException e) {
|
||||||
|
// CustomApiException은 그대로 재throw
|
||||||
|
throw e;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("모델 조회 중 예상치 못한 오류 발생: modelUuid={}", uuid, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "모델 조회 중 오류가 발생했습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 실제 디렉토리 경로 찾기 (uuid 또는 uuid-out)
|
||||||
|
Path baseDir;
|
||||||
|
try {
|
||||||
|
baseDir = findActualBasePath(uuid);
|
||||||
|
|
||||||
|
if (baseDir == null || !Files.exists(baseDir)) {
|
||||||
|
log.warn(
|
||||||
|
"모델 결과 디렉토리를 찾을 수 없음: modelUuid={}, 시도한 경로: {} 또는 {}-out",
|
||||||
|
uuid,
|
||||||
|
responseDir + "/" + uuid,
|
||||||
|
responseDir + "/" + uuid);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델 결과 디렉토리가 존재하지 않습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug("디렉토리 발견: basePath={}", baseDir.toString());
|
||||||
|
} catch (CustomApiException e) {
|
||||||
|
// CustomApiException은 그대로 재throw
|
||||||
|
throw e;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("디렉토리 경로 확인 중 오류 발생: modelUuid={}", uuid, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "디렉토리 경로 확인 중 오류가 발생했습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 요청에서 도메인 정보 추출
|
||||||
|
String scheme = request.getScheme(); // http 또는 https
|
||||||
|
String serverName = request.getServerName(); // localhost 또는 도메인
|
||||||
|
int serverPort = request.getServerPort(); // 8080 등
|
||||||
|
String contextPath = request.getContextPath(); // /api 등
|
||||||
|
|
||||||
|
// 기본 URL 구성
|
||||||
|
String baseUrl;
|
||||||
|
if ((scheme.equals("http") && serverPort == 80)
|
||||||
|
|| (scheme.equals("https") && serverPort == 443)) {
|
||||||
|
baseUrl = scheme + "://" + serverName + contextPath;
|
||||||
|
} else {
|
||||||
|
baseUrl = scheme + "://" + serverName + ":" + serverPort + contextPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug("다운로드 URL 베이스: {}", baseUrl);
|
||||||
|
|
||||||
|
// 3. ZIP 파일 목록 검색
|
||||||
|
List<ZipFileInfo> zipFiles = new ArrayList<>();
|
||||||
|
long totalSize = 0L;
|
||||||
|
|
||||||
|
try (Stream<Path> stream = Files.list(baseDir)) {
|
||||||
|
List<Path> files =
|
||||||
|
stream
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.filter(p -> p.getFileName().toString().endsWith(".zip"))
|
||||||
|
.filter(p -> p.getFileName().toString().contains(uuid.toString()))
|
||||||
|
.sorted(
|
||||||
|
Comparator.comparing(p -> p.getFileName().toString(), Comparator.reverseOrder()))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
log.debug("ZIP 파일 필터링 완료: 발견된 파일 개수={}", files.size());
|
||||||
|
|
||||||
|
for (Path file : files) {
|
||||||
|
try {
|
||||||
|
String fileName = file.getFileName().toString();
|
||||||
|
long fileSize = Files.size(file);
|
||||||
|
totalSize += fileSize;
|
||||||
|
|
||||||
|
// 파일명에서 버전 추출
|
||||||
|
String version = extractVersionFromZipFileName(fileName);
|
||||||
|
boolean isCurrent = version.equals(modelInfo.getModelVer());
|
||||||
|
|
||||||
|
// 전체 도메인 URL 포함한 다운로드 링크 생성
|
||||||
|
String downloadUrl = baseUrl + "/api/models/download/" + uuid + "?file=" + fileName;
|
||||||
|
|
||||||
|
zipFiles.add(
|
||||||
|
ZipFileInfo.builder()
|
||||||
|
.fileName(fileName)
|
||||||
|
.filePath(file.toString())
|
||||||
|
.version(version)
|
||||||
|
.fileSize(fileSize)
|
||||||
|
.fileSizeFormatted(formatFileSize(fileSize))
|
||||||
|
.lastModified(
|
||||||
|
Files.getLastModifiedTime(file).toInstant().atZone(ZoneId.systemDefault()))
|
||||||
|
.isCurrent(isCurrent)
|
||||||
|
.downloadUrl(downloadUrl)
|
||||||
|
.build());
|
||||||
|
|
||||||
|
log.debug(
|
||||||
|
"ZIP 파일 정보 추가: fileName={}, size={}, version={}, isCurrent={}",
|
||||||
|
fileName,
|
||||||
|
formatFileSize(fileSize),
|
||||||
|
version,
|
||||||
|
isCurrent);
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("ZIP 파일 정보 조회 실패 (건너뜀): file={}", file.getFileName(), e);
|
||||||
|
// 개별 파일 실패 시 전체 프로세스를 중단하지 않고 계속 진행
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("ZIP 파일 정보 처리 중 예상치 못한 오류 (건너뜀): file={}", file.getFileName(), e);
|
||||||
|
// 예상치 못한 오류도 전체 프로세스를 중단하지 않음
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info(" ZIP 파일 목록 조회 완료: 총 {}개 파일, 전체 크기={}", zipFiles.size(), formatFileSize(totalSize));
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("ZIP 파일 목록 조회 중 IO 오류 발생: basePath={}", baseDir, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR",
|
||||||
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
"ZIP 파일 목록 조회 중 IO 오류가 발생했습니다.");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("ZIP 파일 목록 조회 중 예상치 못한 오류 발생: basePath={}", baseDir, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "ZIP 파일 목록 조회 중 오류가 발생했습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return ZipFileListResponse.builder()
|
||||||
|
.modelUuid(uuid.toString())
|
||||||
|
.modelNo(modelInfo.getModelNo())
|
||||||
|
.modelVer(modelInfo.getModelVer())
|
||||||
|
.basePath(baseDir.toString())
|
||||||
|
.zipFiles(zipFiles)
|
||||||
|
.totalFiles(zipFiles.size())
|
||||||
|
.totalSize(totalSize)
|
||||||
|
.totalSizeFormatted(formatFileSize(totalSize))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델 UUID로 ZIP 파일 목록 조회 및 다운로드 링크 생성
|
||||||
|
*
|
||||||
|
* @param uuid 모델 UUID
|
||||||
|
* @param downloadUuid 다운로드 추적 UUID
|
||||||
|
* @return ZIP 파일 목록 및 다운로드 링크
|
||||||
|
*/
|
||||||
|
public ZipFileListResponse getZipFileList(UUID uuid, String downloadUuid) {
|
||||||
|
log.info("ZIP 파일 목록 조회 시작: modelUuid={}, downloadUuid={}", uuid, downloadUuid);
|
||||||
|
|
||||||
|
// 1. 모델 정보 조회
|
||||||
|
Basic modelInfo;
|
||||||
|
try {
|
||||||
|
modelInfo = findByModelByUUID(uuid);
|
||||||
|
if (modelInfo == null) {
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
||||||
|
}
|
||||||
|
} catch (NullPointerException e) {
|
||||||
|
log.error("모델 조회 실패: {}", uuid, e);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 실제 디렉토리 경로 찾기 (uuid 또는 uuid-out)
|
||||||
|
Path baseDir = findActualBasePath(uuid);
|
||||||
|
|
||||||
|
if (baseDir == null || !Files.exists(baseDir)) {
|
||||||
|
log.warn(
|
||||||
|
"디렉토리를 찾을 수 없음: modelUuid={}, 시도한 경로: {} 또는 {}-out",
|
||||||
|
uuid,
|
||||||
|
responseDir + "/" + uuid,
|
||||||
|
responseDir + "/" + uuid);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델 결과 디렉토리가 존재하지 않습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("디렉토리 발견: basePath={}", baseDir.toString());
|
||||||
|
|
||||||
|
// 3. ZIP 파일 목록 검색
|
||||||
|
List<ZipFileInfo> zipFiles = new ArrayList<>();
|
||||||
|
long totalSize = 0L;
|
||||||
|
|
||||||
|
try (Stream<Path> stream = Files.list(baseDir)) {
|
||||||
|
List<Path> files =
|
||||||
|
stream
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.filter(p -> p.getFileName().toString().endsWith(".zip"))
|
||||||
|
.filter(p -> p.getFileName().toString().contains(uuid.toString()))
|
||||||
|
.sorted(
|
||||||
|
Comparator.comparing(p -> p.getFileName().toString(), Comparator.reverseOrder()))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
for (Path file : files) {
|
||||||
|
String fileName = file.getFileName().toString();
|
||||||
|
long fileSize = Files.size(file);
|
||||||
|
totalSize += fileSize;
|
||||||
|
|
||||||
|
// 파일명에서 버전 추출
|
||||||
|
String version = extractVersionFromZipFileName(fileName);
|
||||||
|
boolean isCurrent = version.equals(modelInfo.getModelVer());
|
||||||
|
|
||||||
|
// 다운로드 URL 생성
|
||||||
|
String downloadUrl = String.format("/api/models/download/%s?file=%s", uuid, fileName);
|
||||||
|
|
||||||
|
zipFiles.add(
|
||||||
|
ZipFileInfo.builder()
|
||||||
|
.fileName(fileName)
|
||||||
|
.filePath(file.toString())
|
||||||
|
.version(version)
|
||||||
|
.fileSize(fileSize)
|
||||||
|
.fileSizeFormatted(formatFileSize(fileSize))
|
||||||
|
.lastModified(
|
||||||
|
Files.getLastModifiedTime(file).toInstant().atZone(ZoneId.systemDefault()))
|
||||||
|
.isCurrent(isCurrent)
|
||||||
|
.downloadUrl(downloadUrl)
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("ZIP 파일 {}개 발견", zipFiles.size());
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("ZIP 파일 목록 조회 실패: {}", baseDir, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "ZIP 파일 목록 조회 실패");
|
||||||
|
}
|
||||||
|
|
||||||
|
return ZipFileListResponse.builder()
|
||||||
|
.modelUuid(uuid.toString())
|
||||||
|
.modelNo(modelInfo.getModelNo())
|
||||||
|
.modelVer(modelInfo.getModelVer())
|
||||||
|
.basePath(baseDir.toString())
|
||||||
|
.zipFiles(zipFiles)
|
||||||
|
.totalFiles(zipFiles.size())
|
||||||
|
.totalSize(totalSize)
|
||||||
|
.totalSizeFormatted(formatFileSize(totalSize))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 실제 디렉토리 경로 찾기 (uuid 또는 uuid-out)
|
||||||
|
*
|
||||||
|
* @param uuid 모델 UUID
|
||||||
|
* @return 실제 경로 또는 null
|
||||||
|
*/
|
||||||
|
private Path findActualBasePath(UUID uuid) {
|
||||||
|
// 1순위: {uuid}-out
|
||||||
|
Path pathWithSuffix = Paths.get(responseDir, uuid + "-out");
|
||||||
|
if (Files.exists(pathWithSuffix) && Files.isDirectory(pathWithSuffix)) {
|
||||||
|
log.debug("경로 발견: {} (suffix -out 포함)", pathWithSuffix);
|
||||||
|
return pathWithSuffix;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2순위: {uuid}
|
||||||
|
Path pathWithoutSuffix = Paths.get(responseDir, uuid.toString());
|
||||||
|
if (Files.exists(pathWithoutSuffix) && Files.isDirectory(pathWithoutSuffix)) {
|
||||||
|
log.debug("경로 발견: {} (suffix 없음)", pathWithoutSuffix);
|
||||||
|
return pathWithoutSuffix;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ZIP 파일명에서 버전 추출 예: G2.G2_000001.{uuid}.zip → G2_000001
|
||||||
|
*
|
||||||
|
* @param fileName ZIP 파일명
|
||||||
|
* @return 모델 버전
|
||||||
|
*/
|
||||||
|
private String extractVersionFromZipFileName(String fileName) {
|
||||||
|
// 패턴: {modelNo}.{modelVer}.{uuid}.zip
|
||||||
|
// 예: G2.G2_000001.d7dd54e9-1f20-46a7-9c26-89287a7d61b0.zip
|
||||||
|
|
||||||
|
String[] parts = fileName.split("\\.");
|
||||||
|
|
||||||
|
// parts[0] = G2 (modelNo)
|
||||||
|
// parts[1] = G2_000001 (modelVer)
|
||||||
|
// parts[2-7] = uuid parts
|
||||||
|
// parts[8] = zip
|
||||||
|
|
||||||
|
if (parts.length >= 2) {
|
||||||
|
return parts[1]; // G2_000001
|
||||||
|
}
|
||||||
|
|
||||||
|
// fallback: 전체 파일명에서 .zip 제거
|
||||||
|
return fileName.replace(".zip", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 파일 크기를 읽기 쉬운 형식으로 변환
|
||||||
|
*
|
||||||
|
* @param size 파일 크기 (bytes)
|
||||||
|
* @return 포맷된 문자열 (예: "1.26 GB")
|
||||||
|
*/
|
||||||
|
private String formatFileSize(long size) {
|
||||||
|
if (size < 1024) {
|
||||||
|
return size + " B";
|
||||||
|
} else if (size < 1024 * 1024) {
|
||||||
|
return String.format("%.2f KB", size / 1024.0);
|
||||||
|
} else if (size < 1024 * 1024 * 1024) {
|
||||||
|
return String.format("%.2f MB", size / (1024.0 * 1024.0));
|
||||||
|
} else {
|
||||||
|
return String.format("%.2f GB", size / (1024.0 * 1024.0 * 1024.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델 UUID로 모든 ZIP 파일 다운로드 또는 목록 조회
|
||||||
|
*
|
||||||
|
* @param uuid 모델 UUID
|
||||||
|
* @param downloadUuid 다운로드 추적 UUID
|
||||||
|
* @param fileName 개별 파일명 (선택)
|
||||||
|
* @param accept Accept 헤더 (application/json 또는 application/octet-stream)
|
||||||
|
* @param request HTTP 요청
|
||||||
|
* @return JSON 응답 또는 ZIP 파일 Binary 응답
|
||||||
|
*/
|
||||||
|
public ResponseEntity<?> downloadZipFile(
|
||||||
|
UUID uuid, String downloadUuid, String fileName, String accept, HttpServletRequest request)
|
||||||
|
throws IOException {
|
||||||
|
log.info(
|
||||||
|
"ZIP 파일 다운로드/조회 시작: modelUuid={}, downloadUuid={}, file={}, accept={}",
|
||||||
|
uuid,
|
||||||
|
downloadUuid,
|
||||||
|
fileName,
|
||||||
|
accept);
|
||||||
|
|
||||||
|
// 1. 모델 정보 조회
|
||||||
|
Basic modelInfo;
|
||||||
|
try {
|
||||||
|
modelInfo = findByModelByUUID(uuid);
|
||||||
|
if (modelInfo == null) {
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
||||||
|
}
|
||||||
|
} catch (NullPointerException e) {
|
||||||
|
log.warn("모델 조회 실패: {}", uuid);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 실제 디렉토리 경로 찾기 (uuid 또는 uuid-out)
|
||||||
|
Path baseDir = findActualBasePath(uuid);
|
||||||
|
|
||||||
|
if (baseDir == null || !Files.exists(baseDir)) {
|
||||||
|
log.warn(
|
||||||
|
"디렉토리를 찾을 수 없음: modelUuid={}, 시도한 경로: {} 또는 {}-out",
|
||||||
|
uuid,
|
||||||
|
responseDir + "/" + uuid,
|
||||||
|
responseDir + "/" + uuid);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델 결과 디렉토리가 존재하지 않습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("디렉토리 발견: basePath={}", baseDir);
|
||||||
|
|
||||||
|
// 3. 모든 ZIP 파일 찾기
|
||||||
|
List<Path> zipFiles = findAllZipFiles(baseDir, uuid);
|
||||||
|
|
||||||
|
if (zipFiles.isEmpty()) {
|
||||||
|
log.warn("ZIP 파일을 찾을 수 없음: modelUuid={}, basePath={}", uuid, baseDir);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "ZIP 파일을 찾을 수 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"ZIP 파일 {}개 발견: basePath={}, files={}",
|
||||||
|
zipFiles.size(),
|
||||||
|
baseDir,
|
||||||
|
zipFiles.stream().map(p -> p.getFileName().toString()).toList());
|
||||||
|
|
||||||
|
// 4. Accept 헤더에 따라 분기
|
||||||
|
if (accept != null && accept.contains("application/json")) {
|
||||||
|
// JSON 응답: ZIP 파일 목록과 다운로드 링크 반환
|
||||||
|
log.info("JSON 응답 모드: ZIP 파일 목록 반환");
|
||||||
|
return ResponseEntity.ok(buildZipFileListResponse(modelInfo, baseDir, zipFiles, request));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Binary 응답: 파일 다운로드
|
||||||
|
return handleBinaryDownload(modelInfo, baseDir, zipFiles, fileName, uuid, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ZIP 파일 목록 응답 생성 (JSON)
|
||||||
|
*
|
||||||
|
* @param modelInfo 모델 정보
|
||||||
|
* @param baseDir 기본 디렉토리
|
||||||
|
* @param zipFiles ZIP 파일 목록
|
||||||
|
* @param request HTTP 요청
|
||||||
|
* @return ZipFileListResponse
|
||||||
|
*/
|
||||||
|
private ZipFileListResponse buildZipFileListResponse(
|
||||||
|
Basic modelInfo, Path baseDir, List<Path> zipFiles, HttpServletRequest request)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
// 요청에서 도메인 정보 추출
|
||||||
|
String scheme = request.getScheme(); // http 또는 https
|
||||||
|
String serverName = request.getServerName(); // localhost 또는 도메인
|
||||||
|
int serverPort = request.getServerPort(); // 8080 등
|
||||||
|
String contextPath = request.getContextPath(); // /api 등
|
||||||
|
|
||||||
|
// 기본 URL 구성
|
||||||
|
String baseUrl;
|
||||||
|
if ((scheme.equals("http") && serverPort == 80)
|
||||||
|
|| (scheme.equals("https") && serverPort == 443)) {
|
||||||
|
baseUrl = scheme + "://" + serverName + contextPath;
|
||||||
|
} else {
|
||||||
|
baseUrl = scheme + "://" + serverName + ":" + serverPort + contextPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<ZipFileInfo> zipFileInfos = new ArrayList<>();
|
||||||
|
long totalSize = 0L;
|
||||||
|
|
||||||
|
for (Path zipFile : zipFiles) {
|
||||||
|
String zipFileName = zipFile.getFileName().toString();
|
||||||
|
long fileSize = Files.size(zipFile);
|
||||||
|
totalSize += fileSize;
|
||||||
|
|
||||||
|
// 파일명에서 버전 추출
|
||||||
|
String version = extractVersionFromZipFileName(zipFileName);
|
||||||
|
boolean isCurrent = version.equals(modelInfo.getModelVer());
|
||||||
|
|
||||||
|
// 전체 도메인 URL 포함한 다운로드 링크 생성
|
||||||
|
String downloadUrl =
|
||||||
|
baseUrl + "/api/models/downloadzip/" + modelInfo.getUuid() + "?file=" + zipFileName;
|
||||||
|
|
||||||
|
zipFileInfos.add(
|
||||||
|
ZipFileInfo.builder()
|
||||||
|
.fileName(zipFileName)
|
||||||
|
.filePath(zipFile.toString())
|
||||||
|
.version(version)
|
||||||
|
.fileSize(fileSize)
|
||||||
|
.fileSizeFormatted(formatFileSize(fileSize))
|
||||||
|
.lastModified(
|
||||||
|
Files.getLastModifiedTime(zipFile).toInstant().atZone(ZoneId.systemDefault()))
|
||||||
|
.isCurrent(isCurrent)
|
||||||
|
.downloadUrl(downloadUrl)
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
return ZipFileListResponse.builder()
|
||||||
|
.modelUuid(modelInfo.getUuid().toString())
|
||||||
|
.modelNo(modelInfo.getModelNo())
|
||||||
|
.modelVer(modelInfo.getModelVer())
|
||||||
|
.basePath(baseDir.toString())
|
||||||
|
.zipFiles(zipFileInfos)
|
||||||
|
.totalFiles(zipFileInfos.size())
|
||||||
|
.totalSize(totalSize)
|
||||||
|
.totalSizeFormatted(formatFileSize(totalSize))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Binary 다운로드 처리
|
||||||
|
*
|
||||||
|
* @param modelInfo 모델 정보
|
||||||
|
* @param baseDir 기본 디렉토리
|
||||||
|
* @param zipFiles ZIP 파일 목록
|
||||||
|
* @param fileName 개별 파일명 (선택)
|
||||||
|
* @param uuid 모델 UUID
|
||||||
|
* @param request HTTP 요청
|
||||||
|
* @return Binary 응답
|
||||||
|
*/
|
||||||
|
private ResponseEntity<?> handleBinaryDownload(
|
||||||
|
Basic modelInfo,
|
||||||
|
Path baseDir,
|
||||||
|
List<Path> zipFiles,
|
||||||
|
String fileName,
|
||||||
|
UUID uuid,
|
||||||
|
HttpServletRequest request)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
// file 파라미터가 있으면 개별 파일 다운로드
|
||||||
|
if (fileName != null && !fileName.isEmpty()) {
|
||||||
|
log.info("개별 파일 다운로드 요청: fileName={}", fileName);
|
||||||
|
|
||||||
|
Path targetFile =
|
||||||
|
zipFiles.stream()
|
||||||
|
.filter(p -> p.getFileName().toString().equals(fileName))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (targetFile == null) {
|
||||||
|
log.warn("요청한 파일을 찾을 수 없음: fileName={}, basePath={}", fileName, baseDir);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"NOT_FOUND", HttpStatus.NOT_FOUND, "요청한 파일을 찾을 수 없습니다: " + fileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"개별 ZIP 파일 다운로드: fileName={}, fileSize={} bytes, basePath={}",
|
||||||
|
targetFile.getFileName(),
|
||||||
|
Files.size(targetFile),
|
||||||
|
baseDir);
|
||||||
|
|
||||||
|
return rangeDownloadResponder.buildZipResponse(targetFile, fileName, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
// file 파라미터가 없으면 모든 파일 다운로드
|
||||||
|
// 파일이 1개면 바로 다운로드
|
||||||
|
if (zipFiles.size() == 1) {
|
||||||
|
Path zipPath = zipFiles.get(0);
|
||||||
|
log.info(
|
||||||
|
"ZIP 파일 1개 다운로드: fileName={}, fileSize={} bytes, basePath={}",
|
||||||
|
zipPath.getFileName(),
|
||||||
|
Files.size(zipPath),
|
||||||
|
baseDir);
|
||||||
|
String downloadFileName = zipPath.getFileName().toString();
|
||||||
|
return rangeDownloadResponder.buildZipResponse(zipPath, downloadFileName, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 파일이 여러 개면 하나의 zip으로 묶어서 다운로드
|
||||||
|
log.info("여러 ZIP 파일을 하나로 묶어서 다운로드: 총 {}개 파일", zipFiles.size());
|
||||||
|
|
||||||
|
String combinedZipName = modelInfo.getModelNo() + "." + modelInfo.getModelVer() + ".all.zip";
|
||||||
|
Path tempZipPath = createCombinedZipFile(zipFiles, combinedZipName, uuid, baseDir);
|
||||||
|
|
||||||
|
try {
|
||||||
|
long totalSize = Files.size(tempZipPath);
|
||||||
|
log.info(
|
||||||
|
"통합 ZIP 파일 생성 완료: fileName={}, fileSize={} bytes, basePath={}",
|
||||||
|
tempZipPath.getFileName(),
|
||||||
|
totalSize,
|
||||||
|
baseDir);
|
||||||
|
|
||||||
|
ResponseEntity<?> response =
|
||||||
|
rangeDownloadResponder.buildZipResponse(tempZipPath, combinedZipName, request);
|
||||||
|
|
||||||
|
// 다운로드 완료 후 임시 파일 삭제 (비동기)
|
||||||
|
deleteTempFileAsync(tempZipPath);
|
||||||
|
|
||||||
|
return response;
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("통합 ZIP 파일 처리 실패: {}", tempZipPath, e);
|
||||||
|
// 에러 발생 시 임시 파일 삭제
|
||||||
|
try {
|
||||||
|
Files.deleteIfExists(tempZipPath);
|
||||||
|
Path tempDir = tempZipPath.getParent();
|
||||||
|
if (tempDir != null && Files.exists(tempDir)) {
|
||||||
|
Files.deleteIfExists(tempDir);
|
||||||
|
}
|
||||||
|
} catch (IOException ex) {
|
||||||
|
log.warn("임시 파일 삭제 실패: {}", tempZipPath, ex);
|
||||||
|
}
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "ZIP 파일 생성 실패");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모든 ZIP 파일 찾기
|
||||||
|
*
|
||||||
|
* @param baseDir 기본 디렉토리
|
||||||
|
* @param uuid 모델 UUID
|
||||||
|
* @return ZIP 파일 목록 (최신순 정렬)
|
||||||
|
*/
|
||||||
|
private List<Path> findAllZipFiles(Path baseDir, UUID uuid) {
|
||||||
|
try (Stream<Path> stream = Files.list(baseDir)) {
|
||||||
|
return stream
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.filter(p -> p.getFileName().toString().endsWith(".zip"))
|
||||||
|
.filter(p -> p.getFileName().toString().contains(uuid.toString()))
|
||||||
|
.sorted(
|
||||||
|
Comparator.comparing(
|
||||||
|
p -> {
|
||||||
|
try {
|
||||||
|
return Files.getLastModifiedTime(p);
|
||||||
|
} catch (IOException e) {
|
||||||
|
return FileTime.fromMillis(0);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Comparator.reverseOrder()))
|
||||||
|
.toList();
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("ZIP 파일 검색 실패: basePath={}", baseDir, e);
|
||||||
|
return new ArrayList<>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 여러 ZIP 파일을 하나의 ZIP으로 묶기
|
||||||
|
*
|
||||||
|
* @param zipFiles 원본 ZIP 파일 목록
|
||||||
|
* @param combinedZipName 통합 ZIP 파일명
|
||||||
|
* @param uuid 모델 UUID
|
||||||
|
* @param baseDir 기본 디렉토리 (로그용)
|
||||||
|
* @return 통합 ZIP 파일 경로
|
||||||
|
*/
|
||||||
|
private Path createCombinedZipFile(
|
||||||
|
List<Path> zipFiles, String combinedZipName, UUID uuid, Path baseDir) throws IOException {
|
||||||
|
// 임시 디렉토리에 통합 ZIP 생성
|
||||||
|
Path tempDir = Files.createTempDirectory("kamco-download-" + uuid);
|
||||||
|
Path combinedZipPath = tempDir.resolve(combinedZipName);
|
||||||
|
|
||||||
|
log.debug("통합 ZIP 생성 시작: tempPath={}, 원본 파일 {}개", combinedZipPath, zipFiles.size());
|
||||||
|
|
||||||
|
try (java.util.zip.ZipOutputStream zos =
|
||||||
|
new java.util.zip.ZipOutputStream(Files.newOutputStream(combinedZipPath))) {
|
||||||
|
|
||||||
|
for (Path zipFile : zipFiles) {
|
||||||
|
String entryName = zipFile.getFileName().toString();
|
||||||
|
log.debug("ZIP에 파일 추가: {}", entryName);
|
||||||
|
|
||||||
|
java.util.zip.ZipEntry entry = new java.util.zip.ZipEntry(entryName);
|
||||||
|
zos.putNextEntry(entry);
|
||||||
|
|
||||||
|
Files.copy(zipFile, zos);
|
||||||
|
zos.closeEntry();
|
||||||
|
}
|
||||||
|
|
||||||
|
zos.finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug("통합 ZIP 생성 완료: {}", combinedZipPath);
|
||||||
|
return combinedZipPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 임시 파일 비동기 삭제
|
||||||
|
*
|
||||||
|
* @param tempFile 삭제할 임시 파일
|
||||||
|
*/
|
||||||
|
private void deleteTempFileAsync(Path tempFile) {
|
||||||
|
new Thread(
|
||||||
|
() -> {
|
||||||
|
try {
|
||||||
|
// 다운로드 완료 후 대기
|
||||||
|
Thread.sleep(10000); // 10초 대기
|
||||||
|
Files.deleteIfExists(tempFile);
|
||||||
|
// 임시 디렉토리도 삭제
|
||||||
|
Path tempDir = tempFile.getParent();
|
||||||
|
if (tempDir != null && Files.exists(tempDir)) {
|
||||||
|
Files.deleteIfExists(tempDir);
|
||||||
|
}
|
||||||
|
log.debug("임시 파일 삭제 완료: {}", tempFile);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("임시 파일 삭제 실패: {}", tempFile, e);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.start();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.kamco.cd.training.model.service;
|
|||||||
import com.kamco.cd.training.common.dto.HyperParam;
|
import com.kamco.cd.training.common.dto.HyperParam;
|
||||||
import com.kamco.cd.training.common.enums.HyperParamSelectType;
|
import com.kamco.cd.training.common.enums.HyperParamSelectType;
|
||||||
import com.kamco.cd.training.common.enums.ModelType;
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.common.enums.TrainType;
|
import com.kamco.cd.training.common.enums.TrainType;
|
||||||
import com.kamco.cd.training.common.exception.CustomApiException;
|
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||||
@@ -14,10 +15,21 @@ import com.kamco.cd.training.model.dto.ModelTrainMngDto.SearchReq;
|
|||||||
import com.kamco.cd.training.postgres.core.HyperParamCoreService;
|
import com.kamco.cd.training.postgres.core.HyperParamCoreService;
|
||||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
||||||
import com.kamco.cd.training.train.service.TrainJobService;
|
import com.kamco.cd.training.train.service.TrainJobService;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.FileVisitOption;
|
||||||
|
import java.nio.file.FileVisitResult;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.LinkOption;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.SimpleFileVisitor;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
import java.util.EnumSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -32,6 +44,16 @@ public class ModelTrainMngService {
|
|||||||
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
||||||
private final HyperParamCoreService hyperParamCoreService;
|
private final HyperParamCoreService hyperParamCoreService;
|
||||||
private final TrainJobService trainJobService;
|
private final TrainJobService trainJobService;
|
||||||
|
private final ModelTrainDetailService modelTrainDetailService;
|
||||||
|
|
||||||
|
@Value("${train.docker.base_path}")
|
||||||
|
private String basePath;
|
||||||
|
|
||||||
|
@Value("${train.docker.response_dir}")
|
||||||
|
private String responseDir;
|
||||||
|
|
||||||
|
@Value("${train.docker.symbolic_link_dir}")
|
||||||
|
private String symbolicDir;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델학습 조회
|
* 모델학습 조회
|
||||||
@@ -46,11 +68,199 @@ public class ModelTrainMngService {
|
|||||||
/**
|
/**
|
||||||
* 모델학습 삭제
|
* 모델학습 삭제
|
||||||
*
|
*
|
||||||
* @param uuid
|
* <p>순서: 1. tmp 구조 검증 (예외 발생 가능) 2. DB 삭제 (트랜잭션) 3. 파일 삭제 (실패해도 로그만)
|
||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public void deleteModelTrain(UUID uuid) {
|
public void deleteModelTrain(UUID uuid) {
|
||||||
|
|
||||||
|
log.info("deleteModelTrain 시작. uuid={}", uuid);
|
||||||
|
|
||||||
|
// ===== 1. 모델 조회 =====
|
||||||
|
ModelTrainMngDto.Basic model = modelTrainMngCoreService.findModelByUuid(uuid);
|
||||||
|
|
||||||
|
if (model == null) {
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델 없음");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (model.getRequestPath() == null) {
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "임시파일 경로 없음");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 2. 경로 생성 =====
|
||||||
|
Path tmpBase = Path.of(symbolicDir).toAbsolutePath().normalize();
|
||||||
|
Path tmp = tmpBase.resolve(model.getRequestPath()).normalize();
|
||||||
|
|
||||||
|
Path responseBase = Paths.get(responseDir).toAbsolutePath().normalize();
|
||||||
|
Path response = responseBase.resolve(model.getUuid().toString()).normalize();
|
||||||
|
|
||||||
|
// ===== 3. 경로 탈출 방지 =====
|
||||||
|
if (!tmp.startsWith(tmpBase)) {
|
||||||
|
throw new CustomApiException("INVALID_PATH", HttpStatus.BAD_REQUEST, "잘못된 tmp 경로");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.startsWith(responseBase)) {
|
||||||
|
throw new CustomApiException("INVALID_PATH", HttpStatus.BAD_REQUEST, "잘못된 response 경로");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 4. 상태 로그 =====
|
||||||
|
log.info(
|
||||||
|
"tmp 상태: exists={}, isDir={}, isSymlink={}",
|
||||||
|
Files.exists(tmp, LinkOption.NOFOLLOW_LINKS),
|
||||||
|
Files.isDirectory(tmp, LinkOption.NOFOLLOW_LINKS),
|
||||||
|
Files.isSymbolicLink(tmp));
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"response 상태: exists={}, isDir={}, isSymlink={}",
|
||||||
|
Files.exists(response, LinkOption.NOFOLLOW_LINKS),
|
||||||
|
Files.isDirectory(response, LinkOption.NOFOLLOW_LINKS),
|
||||||
|
Files.isSymbolicLink(response));
|
||||||
|
|
||||||
|
// ===== 5. tmp 구조 검증 =====
|
||||||
|
validateTmpStructure(tmp);
|
||||||
|
|
||||||
|
// ===== 6. DB 삭제 =====
|
||||||
modelTrainMngCoreService.deleteModel(uuid);
|
modelTrainMngCoreService.deleteModel(uuid);
|
||||||
|
log.info("DB 삭제 완료. uuid={}", uuid);
|
||||||
|
|
||||||
|
// ===== 7. tmp 삭제 =====
|
||||||
|
log.info("tmp 삭제 시작: {}", tmp);
|
||||||
|
try {
|
||||||
|
deleteTmpDirectory(tmp);
|
||||||
|
log.info("tmp 삭제 완료: {}", tmp);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("tmp 삭제 실패 (DB는 이미 삭제됨): {}", tmp, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 8. response 삭제 =====
|
||||||
|
log.info("response 삭제 시작: {}", response);
|
||||||
|
try {
|
||||||
|
// 테스트 완료되었으면 베스트 에폭은 삭제안함
|
||||||
|
if (TrainStatusType.COMPLETED.getId().equals(model.getStep2Status())) {
|
||||||
|
modelTrainDetailService.executeCleanup(model, response);
|
||||||
|
} else {
|
||||||
|
deleteResponseDirectory(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("response 삭제 완료: {}", response);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("response 삭제 실패 (DB는 이미 삭제됨): {}", response, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("deleteModelTrain 완료. uuid={}", uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** tmp 디렉토리 삭제 */
|
||||||
|
private void deleteTmpDirectory(Path dir) throws IOException {
|
||||||
|
|
||||||
|
if (!Files.exists(dir, LinkOption.NOFOLLOW_LINKS)) {
|
||||||
|
log.warn("삭제 대상 없음: {}", dir);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Files.walkFileTree(
|
||||||
|
dir,
|
||||||
|
EnumSet.noneOf(FileVisitOption.class),
|
||||||
|
Integer.MAX_VALUE,
|
||||||
|
new SimpleFileVisitor<>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
Files.delete(file);
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult postVisitDirectory(Path directory, IOException exc)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
if (exc != null) {
|
||||||
|
throw exc;
|
||||||
|
}
|
||||||
|
|
||||||
|
Files.delete(directory);
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** response 디렉토리 삭제 */
|
||||||
|
private void deleteResponseDirectory(Path dir) throws IOException {
|
||||||
|
|
||||||
|
if (!Files.exists(dir, LinkOption.NOFOLLOW_LINKS)) {
|
||||||
|
log.warn("삭제 대상 없음: {}", dir);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Files.walkFileTree(
|
||||||
|
dir,
|
||||||
|
EnumSet.noneOf(FileVisitOption.class),
|
||||||
|
Integer.MAX_VALUE,
|
||||||
|
new SimpleFileVisitor<>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
Files.delete(file);
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult postVisitDirectory(Path directory, IOException exc)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
if (exc != null) {
|
||||||
|
throw exc;
|
||||||
|
}
|
||||||
|
|
||||||
|
Files.delete(directory);
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** tmp 내부 구조 검증 - 내부는 반드시 symlink만 허용 */
|
||||||
|
private void validateTmpStructure(Path dir) {
|
||||||
|
|
||||||
|
if (!Files.exists(dir, LinkOption.NOFOLLOW_LINKS)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Files.walkFileTree(
|
||||||
|
dir,
|
||||||
|
EnumSet.noneOf(FileVisitOption.class),
|
||||||
|
Integer.MAX_VALUE,
|
||||||
|
new SimpleFileVisitor<>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
// 파일은 전부 허용 (일반 + symlink)
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attrs)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
// 루트 제외 + symlink 디렉토리 금지
|
||||||
|
if (!directory.equals(dir) && Files.isSymbolicLink(directory)) {
|
||||||
|
log.error("tmp 내부에 symlink 디렉토리 존재: {}", directory);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"BAD_REQUEST", HttpStatus.BAD_REQUEST, "tmp 내부에 symlink 디렉토리는 허용되지 않습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "tmp 구조 검증 실패");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -95,7 +305,19 @@ public class ModelTrainMngService {
|
|||||||
modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());
|
modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());
|
||||||
|
|
||||||
// 데이터셋 임시파일 생성
|
// 데이터셋 임시파일 생성
|
||||||
|
List<Long> datasetList = null;
|
||||||
|
if (req.getTrainingDataset() != null) {
|
||||||
|
datasetList = req.getTrainingDataset().getDatasetList();
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSingleDataset = datasetList != null && datasetList.size() == 1;
|
||||||
|
|
||||||
|
// 데이터셋 1개만 선택한 경우는 symbolic link 미생성 해도 됨 -> train 호출 시 그냥 데이터셋 request 경로로 호출
|
||||||
|
if (isSingleDataset) {
|
||||||
|
trainJobService.updateRequestPath(modelUuid, datasetList);
|
||||||
|
} else {
|
||||||
trainJobService.createTmpFile(modelUuid);
|
trainJobService.createTmpFile(modelUuid);
|
||||||
|
}
|
||||||
return modelUuid;
|
return modelUuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,6 +340,8 @@ public class ModelTrainMngService {
|
|||||||
public List<SelectDataSet> getDatasetSelectList(DatasetReq req) {
|
public List<SelectDataSet> getDatasetSelectList(DatasetReq req) {
|
||||||
if (req.getModelNo().equals(ModelType.G1.getId())) {
|
if (req.getModelNo().equals(ModelType.G1.getId())) {
|
||||||
return modelTrainMngCoreService.getDatasetSelectG1List(req);
|
return modelTrainMngCoreService.getDatasetSelectG1List(req);
|
||||||
|
} else if (req.getModelNo().equals(ModelType.G4.getId())) {
|
||||||
|
return modelTrainMngCoreService.getDatasetSelectG4List(req);
|
||||||
} else {
|
} else {
|
||||||
return modelTrainMngCoreService.getDatasetSelectG2G3List(req);
|
return modelTrainMngCoreService.getDatasetSelectG2G3List(req);
|
||||||
}
|
}
|
||||||
@@ -126,4 +350,12 @@ public class ModelTrainMngService {
|
|||||||
public Long findModelStep1InProgressCnt() {
|
public Long findModelStep1InProgressCnt() {
|
||||||
return modelTrainMngCoreService.findModelStep1InProgressCnt();
|
return modelTrainMngCoreService.findModelStep1InProgressCnt();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ModelTrainMngDto.InProgressModel findInprogressModel() {
|
||||||
|
return modelTrainMngCoreService.findInprogressModel();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModelTrainMngDto.ProgressPercent findTrainProgressPercent(UUID uuid) {
|
||||||
|
return modelTrainMngCoreService.findTrainProgressPercent(uuid);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,282 @@
|
|||||||
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
||||||
|
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||||
|
import com.kamco.cd.training.common.exception.NotFoundException;
|
||||||
|
import com.kamco.cd.training.common.service.BaseCoreService;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetClsObjDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetClass;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetObjRegDto;
|
||||||
|
import com.kamco.cd.training.postgres.entity.DatasetClsObjEntity;
|
||||||
|
import com.kamco.cd.training.postgres.entity.DatasetEntity;
|
||||||
|
import com.kamco.cd.training.postgres.entity.DatasetObjEntity;
|
||||||
|
import com.kamco.cd.training.postgres.repository.dataset.DatasetClsRepository;
|
||||||
|
import com.kamco.cd.training.postgres.repository.dataset.DatasetObjRepository;
|
||||||
|
import jakarta.transaction.Transactional;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Slf4j
|
||||||
|
public class DatasetClsCoreService
|
||||||
|
implements BaseCoreService<DatasetDto.Basic, Long, DatasetDto.SearchReq> {
|
||||||
|
|
||||||
|
private final DatasetClsRepository datasetClsRepository;
|
||||||
|
private final DatasetObjRepository datasetObjRepository;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 학습 데이터 삭제
|
||||||
|
*
|
||||||
|
* @param id 데이터셋 ID
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void remove(Long id) {
|
||||||
|
DatasetEntity entity =
|
||||||
|
datasetClsRepository
|
||||||
|
.findById(id)
|
||||||
|
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. ID: " + id));
|
||||||
|
entity.setDeleted(true);
|
||||||
|
datasetClsRepository.save(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void remove(UUID id) {
|
||||||
|
DatasetEntity entity =
|
||||||
|
datasetClsRepository
|
||||||
|
.findByUuid(id)
|
||||||
|
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. ID: " + id));
|
||||||
|
entity.setDeleted(true);
|
||||||
|
datasetClsRepository.save(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public DatasetDto.Basic getOneById(Long id) {
|
||||||
|
DatasetEntity entity =
|
||||||
|
datasetClsRepository
|
||||||
|
.findById(id)
|
||||||
|
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. ID: " + id));
|
||||||
|
|
||||||
|
if (entity.getDeleted()) {
|
||||||
|
throw new NotFoundException("삭제된 데이터셋입니다. ID: " + id);
|
||||||
|
}
|
||||||
|
|
||||||
|
return entity.toDto();
|
||||||
|
}
|
||||||
|
|
||||||
|
public DatasetDto.Basic getOneByUuid(UUID id) {
|
||||||
|
DatasetEntity entity =
|
||||||
|
datasetClsRepository
|
||||||
|
.findByUuid(id)
|
||||||
|
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. uuid: " + id));
|
||||||
|
return entity.toDto();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Page<DatasetDto.Basic> search(DatasetDto.SearchReq searchReq) {
|
||||||
|
Page<DatasetEntity> entityPage = datasetClsRepository.findDatasetList(searchReq);
|
||||||
|
return entityPage.map(DatasetEntity::toDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 학습데이터 조회
|
||||||
|
*
|
||||||
|
* @param searchReq 검색 조건
|
||||||
|
* @return 페이징 처리된 데이터셋 목록
|
||||||
|
*/
|
||||||
|
public Page<DatasetDto.Basic> findDatasetList(DatasetDto.SearchReq searchReq) {
|
||||||
|
return search(searchReq);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
/**
|
||||||
|
* 학습데이터 등록
|
||||||
|
*
|
||||||
|
* @param registerReq 등록 요청 데이터
|
||||||
|
* @return 등록된 데이터셋 정보
|
||||||
|
*/
|
||||||
|
public DatasetDto.Basic save(DatasetDto.RegisterReq registerReq) {
|
||||||
|
// 먼저 id1 필드를 임시값(0)으로 설정하여 저장
|
||||||
|
DatasetEntity entity = new DatasetEntity();
|
||||||
|
entity.setTitle(registerReq.getTitle());
|
||||||
|
// entity.setYear(registerReq.getYear());
|
||||||
|
entity.setDataType(LearnDataType.PRODUCTION.getId());
|
||||||
|
entity.setCompareYyyy(registerReq.getCompareYear());
|
||||||
|
entity.setTargetYyyy(registerReq.getTargetYyyy());
|
||||||
|
entity.setRoundNo(registerReq.getRoundNo() != null ? registerReq.getRoundNo() : 1L);
|
||||||
|
entity.setMemo(registerReq.getMemo());
|
||||||
|
entity.setStatus(LearnDataRegister.READY.getId());
|
||||||
|
entity.setDataType("CREATE");
|
||||||
|
entity.setTotalItems(0L);
|
||||||
|
entity.setTotalSize(0L);
|
||||||
|
entity.setItemCount(0L);
|
||||||
|
entity.setDeleted(false);
|
||||||
|
entity.setCreatedDttm(ZonedDateTime.now());
|
||||||
|
// entity.setId1(0L); // 임시값
|
||||||
|
|
||||||
|
DatasetEntity savedEntity = datasetClsRepository.save(entity);
|
||||||
|
|
||||||
|
// 저장 후 id1을 dataset_uid와 동일하게 업데이트
|
||||||
|
// savedEntity.setId1(savedEntity.getId());
|
||||||
|
// savedEntity = datasetClsRepository.save(savedEntity);
|
||||||
|
|
||||||
|
return savedEntity.toDto();
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
/**
|
||||||
|
* 학습 데이터 수정
|
||||||
|
*
|
||||||
|
* @param updateReq 수정 요청 데이터
|
||||||
|
* @return 수정된 데이터셋 정보
|
||||||
|
*/
|
||||||
|
public void update(UUID uuid, DatasetDto.UpdateReq updateReq) {
|
||||||
|
DatasetEntity entity =
|
||||||
|
datasetClsRepository
|
||||||
|
.findByUuid(uuid)
|
||||||
|
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. uuid: " + uuid));
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(updateReq.getTitle())) {
|
||||||
|
entity.setTitle(updateReq.getTitle());
|
||||||
|
}
|
||||||
|
if (StringUtils.isNotBlank(updateReq.getMemo())) {
|
||||||
|
entity.setMemo(updateReq.getMemo());
|
||||||
|
}
|
||||||
|
|
||||||
|
datasetClsRepository.save(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 학습데이터 삭제
|
||||||
|
*
|
||||||
|
* @param uuid 삭제 요청 (데이터셋 ID 목록)
|
||||||
|
*/
|
||||||
|
public void deleteDatasets(UUID uuid) {
|
||||||
|
remove(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public DatasetDto.Summary getDatasetSummary(DatasetDto.SummaryReq summaryReq) {
|
||||||
|
long totalMapSheets = 0;
|
||||||
|
long totalFileSize = 0;
|
||||||
|
|
||||||
|
for (Long datasetId : summaryReq.getDatasetIds()) {
|
||||||
|
DatasetEntity entity =
|
||||||
|
datasetClsRepository
|
||||||
|
.findById(datasetId)
|
||||||
|
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. ID: " + datasetId));
|
||||||
|
|
||||||
|
if (!entity.getDeleted()) {
|
||||||
|
totalMapSheets += entity.getTotalItems() != null ? entity.getTotalItems() : 0;
|
||||||
|
totalFileSize += entity.getTotalSize() != null ? entity.getTotalSize() : 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
double averageMapSheets =
|
||||||
|
!summaryReq.getDatasetIds().isEmpty()
|
||||||
|
? (double) totalMapSheets / summaryReq.getDatasetIds().size()
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return new DatasetDto.Summary(
|
||||||
|
summaryReq.getDatasetIds().size(), totalMapSheets, totalFileSize, averageMapSheets);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Page<DatasetClsObjDto.Basic> searchDatasetClsObjectList(
|
||||||
|
DatasetClsObjDto.ClsSearchReq searchReq) {
|
||||||
|
Page<DatasetClsObjEntity> entityPage =
|
||||||
|
datasetClsRepository.searchDatasetClsObjectList(searchReq);
|
||||||
|
return entityPage.map(DatasetClsObjEntity::toDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
public UUID deleteDatasetObjByUuid(UUID uuid) {
|
||||||
|
DatasetObjEntity entity =
|
||||||
|
datasetObjRepository
|
||||||
|
.findByUuid(uuid)
|
||||||
|
.orElseThrow(() -> new NotFoundException("데이터셋 obj를 찾을 수 없습니다. ID: " + uuid));
|
||||||
|
entity.setDeleted(true);
|
||||||
|
datasetObjRepository.save(entity);
|
||||||
|
return entity.getUuid();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 object class 조회
|
||||||
|
*
|
||||||
|
* @param uuid dataset uuid
|
||||||
|
* @param type compare, target
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public List<DatasetClass> findDatasetObjClassByUuid(UUID uuid, String type) {
|
||||||
|
return datasetObjRepository.findDatasetObjClassByUuid(uuid, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getDatasetMaxStage(int compareYyyy, int targetYyyy) {
|
||||||
|
return datasetClsRepository.getDatasetMaxStage(compareYyyy, targetYyyy);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Long insertDatasetMngData(DatasetMngRegDto mngRegDto) {
|
||||||
|
return datasetClsRepository.insertDatasetMngData(mngRegDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
||||||
|
datasetObjRepository.insertDatasetObj(objRegDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFilePathByUUIDPathType(UUID uuid, String pathType) {
|
||||||
|
return datasetObjRepository.getFilePathByUUIDPathType(uuid, pathType);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertDatasetTestObj(DatasetObjRegDto objRegDto) {
|
||||||
|
datasetObjRepository.insertDatasetTestObj(objRegDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 학습데이터셋 마스터 상태 변경
|
||||||
|
*
|
||||||
|
* @param datasetUid 학습데이터셋 마스터 id
|
||||||
|
* @param register 상태
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void updateDatasetUploadStatus(Long datasetUid, LearnDataRegister register) {
|
||||||
|
DatasetEntity entity =
|
||||||
|
datasetClsRepository
|
||||||
|
.findById(datasetUid)
|
||||||
|
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. ID: " + datasetUid));
|
||||||
|
|
||||||
|
entity.setStatus(register.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertDatasetValObj(DatasetObjRegDto objRegDto) {
|
||||||
|
datasetObjRepository.insertDatasetValObj(objRegDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long findDatasetByUidExistsCnt(String uid) {
|
||||||
|
return datasetClsRepository.findDatasetByUidExistsCnt(uid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 등록 실패시 Obj 데이터 정리
|
||||||
|
*
|
||||||
|
* @param datasetUid 모델 마스터 id
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void deleteAllDatasetObj(Long datasetUid) {
|
||||||
|
int cnt = datasetObjRepository.deleteAllDatasetObj(datasetUid);
|
||||||
|
log.info("datasetUid={} 데이터셋 실패 - 전체 삭제 완료. 총 {}건", datasetUid, cnt);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertDatasetClsObj(DatasetObjDto.DatasetClsObjRegDto objRegDto) {
|
||||||
|
datasetClsRepository.insertDatasetClsObj(objRegDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFilePathByUUIDPathTif(UUID uuid) {
|
||||||
|
return datasetClsRepository.getFilePathByUUIDPathType(uuid);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
package com.kamco.cd.training.postgres.core;
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
||||||
import com.kamco.cd.training.common.enums.LearnDataType;
|
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||||
import com.kamco.cd.training.common.exception.NotFoundException;
|
import com.kamco.cd.training.common.exception.NotFoundException;
|
||||||
@@ -15,6 +14,7 @@ import com.kamco.cd.training.postgres.entity.DatasetEntity;
|
|||||||
import com.kamco.cd.training.postgres.entity.DatasetObjEntity;
|
import com.kamco.cd.training.postgres.entity.DatasetObjEntity;
|
||||||
import com.kamco.cd.training.postgres.repository.dataset.DatasetObjRepository;
|
import com.kamco.cd.training.postgres.repository.dataset.DatasetObjRepository;
|
||||||
import com.kamco.cd.training.postgres.repository.dataset.DatasetRepository;
|
import com.kamco.cd.training.postgres.repository.dataset.DatasetRepository;
|
||||||
|
import jakarta.transaction.Transactional;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
@@ -23,17 +23,15 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class DatasetCoreService
|
public class DatasetCoreService
|
||||||
implements BaseCoreService<DatasetDto.Basic, Long, DatasetDto.SearchReq> {
|
implements BaseCoreService<DatasetDto.Basic, Long, DatasetDto.SearchReq> {
|
||||||
|
|
||||||
private final DatasetRepository datasetRepository;
|
private final DatasetRepository datasetRepository;
|
||||||
private final DatasetObjRepository datasetObjRepository;
|
private final DatasetObjRepository datasetObjRepository;
|
||||||
private final ObjectMapper objectMapper;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 학습 데이터 삭제
|
* 학습 데이터 삭제
|
||||||
@@ -97,6 +95,7 @@ public class DatasetCoreService
|
|||||||
return search(searchReq);
|
return search(searchReq);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 학습데이터 등록
|
* 학습데이터 등록
|
||||||
*
|
*
|
||||||
@@ -131,6 +130,7 @@ public class DatasetCoreService
|
|||||||
return savedEntity.toDto();
|
return savedEntity.toDto();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
/**
|
/**
|
||||||
* 학습 데이터 수정
|
* 학습 데이터 수정
|
||||||
*
|
*
|
||||||
@@ -222,7 +222,6 @@ public class DatasetCoreService
|
|||||||
return datasetRepository.insertDatasetMngData(mngRegDto);
|
return datasetRepository.insertDatasetMngData(mngRegDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
||||||
datasetObjRepository.insertDatasetObj(objRegDto);
|
datasetObjRepository.insertDatasetObj(objRegDto);
|
||||||
}
|
}
|
||||||
@@ -231,22 +230,26 @@ public class DatasetCoreService
|
|||||||
return datasetObjRepository.getFilePathByUUIDPathType(uuid, pathType);
|
return datasetObjRepository.getFilePathByUUIDPathType(uuid, pathType);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void insertDatasetTestObj(DatasetObjRegDto objRegDto) {
|
public void insertDatasetTestObj(DatasetObjRegDto objRegDto) {
|
||||||
datasetObjRepository.insertDatasetTestObj(objRegDto);
|
datasetObjRepository.insertDatasetTestObj(objRegDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 학습데이터셋 마스터 상태 변경
|
||||||
|
*
|
||||||
|
* @param datasetUid 학습데이터셋 마스터 id
|
||||||
|
* @param register 상태
|
||||||
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public void updateDatasetUploadStatus(Long datasetUid) {
|
public void updateDatasetUploadStatus(Long datasetUid, LearnDataRegister register) {
|
||||||
DatasetEntity entity =
|
DatasetEntity entity =
|
||||||
datasetRepository
|
datasetRepository
|
||||||
.findById(datasetUid)
|
.findById(datasetUid)
|
||||||
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. ID: " + datasetUid));
|
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. ID: " + datasetUid));
|
||||||
|
|
||||||
entity.setStatus(LearnDataRegister.COMPLETED.getId());
|
entity.setStatus(register.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void insertDatasetValObj(DatasetObjRegDto objRegDto) {
|
public void insertDatasetValObj(DatasetObjRegDto objRegDto) {
|
||||||
datasetObjRepository.insertDatasetValObj(objRegDto);
|
datasetObjRepository.insertDatasetValObj(objRegDto);
|
||||||
}
|
}
|
||||||
@@ -254,4 +257,15 @@ public class DatasetCoreService
|
|||||||
public Long findDatasetByUidExistsCnt(String uid) {
|
public Long findDatasetByUidExistsCnt(String uid) {
|
||||||
return datasetRepository.findDatasetByUidExistsCnt(uid);
|
return datasetRepository.findDatasetByUidExistsCnt(uid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 등록 실패시 Obj 데이터 정리
|
||||||
|
*
|
||||||
|
* @param datasetUid 모델 마스터 id
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void deleteAllDatasetObj(Long datasetUid) {
|
||||||
|
int cnt = datasetObjRepository.deleteAllDatasetObj(datasetUid);
|
||||||
|
log.info("datasetUid={} 데이터셋 실패 - 전체 삭제 완료. 총 {}건", datasetUid, cnt);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.dto.HyperClsParam;
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||||
|
import com.kamco.cd.training.common.utils.UserUtil;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperClsParamDto;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.SearchReq;
|
||||||
|
import com.kamco.cd.training.postgres.entity.ModelHyperClsParamEntity;
|
||||||
|
import com.kamco.cd.training.postgres.repository.hyperparam.HyperClsParamRepository;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class HyperClsParamCoreService {
|
||||||
|
|
||||||
|
private final HyperClsParamRepository hyperClsParamRepository;
|
||||||
|
private final UserUtil userUtil;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 등록
|
||||||
|
*
|
||||||
|
* @param createReq ModelTrainMngDto.HyperParamDto
|
||||||
|
* @return 등록된 버전명
|
||||||
|
*/
|
||||||
|
public HyperClsParamDto.Basic createHyperParam(HyperClsParam createReq) {
|
||||||
|
String firstVersion = getFirstHyperParamVersion(createReq.getModel());
|
||||||
|
|
||||||
|
ModelHyperClsParamEntity entity = new ModelHyperClsParamEntity();
|
||||||
|
entity.setHyperVer(firstVersion);
|
||||||
|
applyHyperParam(entity, createReq);
|
||||||
|
|
||||||
|
// user
|
||||||
|
entity.setCreatedUid(userUtil.getId());
|
||||||
|
|
||||||
|
ModelHyperClsParamEntity resultEntity = hyperClsParamRepository.save(entity);
|
||||||
|
HyperClsParamDto.Basic basic = new HyperClsParamDto.Basic();
|
||||||
|
basic.setUuid(resultEntity.getUuid());
|
||||||
|
basic.setHyperVer(resultEntity.getHyperVer());
|
||||||
|
return basic;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 수정
|
||||||
|
*
|
||||||
|
* @param uuid uuid
|
||||||
|
* @param createReq 등록 요청
|
||||||
|
* @return ver
|
||||||
|
*/
|
||||||
|
public String updateHyperParam(UUID uuid, HyperClsParam createReq) {
|
||||||
|
ModelHyperClsParamEntity entity =
|
||||||
|
hyperClsParamRepository
|
||||||
|
.findHyperParamByUuid(uuid)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
if (entity.getIsDefault()) {
|
||||||
|
throw new CustomApiException("UNPROCESSABLE_ENTITY_UPDATE", HttpStatus.UNPROCESSABLE_ENTITY);
|
||||||
|
}
|
||||||
|
applyHyperParam(entity, createReq);
|
||||||
|
|
||||||
|
// user
|
||||||
|
entity.setUpdatedUid(userUtil.getId());
|
||||||
|
entity.setUpdatedDttm(ZonedDateTime.now());
|
||||||
|
|
||||||
|
return entity.getHyperVer();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 삭제
|
||||||
|
*
|
||||||
|
* @param uuid
|
||||||
|
*/
|
||||||
|
public void deleteHyperParam(UUID uuid) {
|
||||||
|
ModelHyperClsParamEntity entity =
|
||||||
|
hyperClsParamRepository
|
||||||
|
.findHyperParamByUuid(uuid)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
// 디폴트면 삭제불가
|
||||||
|
if (entity.getIsDefault()) {
|
||||||
|
throw new CustomApiException("UNPROCESSABLE_ENTITY", HttpStatus.UNPROCESSABLE_ENTITY);
|
||||||
|
}
|
||||||
|
|
||||||
|
entity.setDelYn(true);
|
||||||
|
entity.setUpdatedUid(userUtil.getId());
|
||||||
|
entity.setUpdatedDttm(ZonedDateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 최적화 설정값 조회
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public HyperClsParamDto.Basic getInitHyperParam(ModelType model) {
|
||||||
|
ModelHyperClsParamEntity entity =
|
||||||
|
hyperClsParamRepository.getHyperParamByType(model).stream()
|
||||||
|
.filter(e -> e.getIsDefault() == Boolean.TRUE)
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
return entity.toDto();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 상세 조회
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public HyperClsParamDto.Basic getHyperParam(UUID uuid) {
|
||||||
|
ModelHyperClsParamEntity entity =
|
||||||
|
hyperClsParamRepository
|
||||||
|
.findHyperParamByUuid(uuid)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
return entity.toDto();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 목록 조회
|
||||||
|
*
|
||||||
|
* @param model
|
||||||
|
* @param req
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Page<HyperParamDto.List> findByHyperVerList(ModelType model, SearchReq req) {
|
||||||
|
return hyperClsParamRepository.findByHyperVerList(model, req);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 버전 조회
|
||||||
|
*
|
||||||
|
* @param model 모델 타입
|
||||||
|
* @return ver
|
||||||
|
*/
|
||||||
|
public String getFirstHyperParamVersion(ModelType model) {
|
||||||
|
return hyperClsParamRepository
|
||||||
|
.findHyperParamVerByModelType(model)
|
||||||
|
.map(ModelHyperClsParamEntity::getHyperVer)
|
||||||
|
.map(ver -> increase(ver, model))
|
||||||
|
.orElse(model.name() + "_000001");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼 파라미터의 버전을 증가시킨다.
|
||||||
|
*
|
||||||
|
* @param hyperVer 현재 버전
|
||||||
|
* @param modelType 모델 타입
|
||||||
|
* @return 증가된 버전
|
||||||
|
*/
|
||||||
|
private String increase(String hyperVer, ModelType modelType) {
|
||||||
|
String prefix = modelType.name() + "_";
|
||||||
|
int num = Integer.parseInt(hyperVer.substring(prefix.length()));
|
||||||
|
return prefix + String.format("%06d", num + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void applyHyperParam(ModelHyperClsParamEntity entity, HyperClsParam src) {
|
||||||
|
|
||||||
|
ModelType model = src.getModel();
|
||||||
|
|
||||||
|
entity.setInputSize(src.getInputSize());
|
||||||
|
|
||||||
|
// Model
|
||||||
|
entity.setModelType(model);
|
||||||
|
entity.setInputSize(src.getInputSize());
|
||||||
|
entity.setBatchSize(src.getBatchSize());
|
||||||
|
entity.setInputSize(src.getInputSize());
|
||||||
|
|
||||||
|
// Argument
|
||||||
|
entity.setScale(src.getScale());
|
||||||
|
entity.setTranslate(src.getTranslate());
|
||||||
|
entity.setFliplr(src.getFliplr());
|
||||||
|
entity.setFlipud(src.getFlipud());
|
||||||
|
entity.setErasing(src.getErasing());
|
||||||
|
entity.setMixup(src.getMixup());
|
||||||
|
entity.setHsvH(src.getHsvH());
|
||||||
|
entity.setHsvS(src.getHsvS());
|
||||||
|
entity.setHsvV(src.getHsvV());
|
||||||
|
entity.setDropout(src.getDropout());
|
||||||
|
entity.setLabelSmoothing(src.getLabelSmoothing());
|
||||||
|
|
||||||
|
// memo
|
||||||
|
entity.setMemo(src.getMemo());
|
||||||
|
entity.setIsDefault(src.getIsDefault());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.core;
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.exception.NotFoundException;
|
import com.kamco.cd.training.common.exception.NotFoundException;
|
||||||
@@ -70,3 +71,4 @@ public class MapSheetCoreService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.kamco.cd.training.postgres.repository.train.ModelTestMetricsJobReposi
|
|||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleMetricJsonDto;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -26,6 +27,10 @@ public class ModelTestMetricsJobCoreService {
|
|||||||
return modelTestMetricsJobRepository.getTestMetricSaveNotYetModelIds();
|
return modelTestMetricsJobRepository.getTestMetricSaveNotYetModelIds();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ResponsePathDto getTestMetricSaveNotYetModelId(Long modelId) {
|
||||||
|
return modelTestMetricsJobRepository.getTestMetricSaveNotYetModelId(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
public void insertModelMetricsTest(List<Object[]> batchArgs) {
|
public void insertModelMetricsTest(List<Object[]> batchArgs) {
|
||||||
modelTestMetricsJobRepository.insertModelMetricsTest(batchArgs);
|
modelTestMetricsJobRepository.insertModelMetricsTest(batchArgs);
|
||||||
}
|
}
|
||||||
@@ -34,6 +39,10 @@ public class ModelTestMetricsJobCoreService {
|
|||||||
return modelTestMetricsJobRepository.getTestMetricPackingInfo(modelId);
|
return modelTestMetricsJobRepository.getTestMetricPackingInfo(modelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public SimpleMetricJsonDto getSimpleTestMetricPackingInfo(Long modelId) {
|
||||||
|
return modelTestMetricsJobRepository.getSimpleTestMetricPackingInfo(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
public ModelTestFileName findModelTestFileNames(Long modelId) {
|
public ModelTestFileName findModelTestFileNames(Long modelId) {
|
||||||
return modelTestMetricsJobRepository.findModelTestFileNames(modelId);
|
return modelTestMetricsJobRepository.findModelTestFileNames(modelId);
|
||||||
}
|
}
|
||||||
@@ -47,4 +56,16 @@ public class ModelTestMetricsJobCoreService {
|
|||||||
public void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState) {
|
public void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState) {
|
||||||
modelTestMetricsJobRepository.updatePackingEnd(modelId, now, failSuccState);
|
modelTestMetricsJobRepository.updatePackingEnd(modelId, now, failSuccState);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 특정 Epoch의 메트릭 정보 조회 (하이퍼파라미터별 ZIP 생성용)
|
||||||
|
*
|
||||||
|
* @param modelId 모델 ID
|
||||||
|
* @param epoch Epoch 번호
|
||||||
|
* @param metricType 메트릭 타입 (fscore, precision, recall)
|
||||||
|
* @return 메트릭 JSON DTO
|
||||||
|
*/
|
||||||
|
public ModelMetricJsonDto getMetricsByEpoch(Long modelId, Integer epoch, String metricType) {
|
||||||
|
return modelTestMetricsJobRepository.getMetricsByEpoch(modelId, epoch, metricType);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,10 +67,13 @@ public class ModelTrainDetailCoreService {
|
|||||||
return modelDetailRepository.getByModelHyperParamSummary(uuid);
|
return modelDetailRepository.getByModelHyperParamSummary(uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
public TransferHyperSummary getTransferHyperSummary(UUID uuid) {
|
public TransferHyperSummary getTransferHyperSummary(UUID uuid) {
|
||||||
return modelDetailRepository.getByModelTransferHyperParamSummary(uuid);
|
return modelDetailRepository.getByModelTransferHyperParamSummary(uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
public List<MappingDataset> getByModelMappingDataset(UUID uuid) {
|
public List<MappingDataset> getByModelMappingDataset(UUID uuid) {
|
||||||
return modelDetailRepository.getByModelMappingDataset(uuid);
|
return modelDetailRepository.getByModelMappingDataset(uuid);
|
||||||
}
|
}
|
||||||
@@ -80,6 +83,7 @@ public class ModelTrainDetailCoreService {
|
|||||||
return entity.toDto();
|
return entity.toDto();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 모델 학습별 config 정보 조회
|
* 모델 학습별 config 정보 조회
|
||||||
*
|
*
|
||||||
@@ -90,6 +94,7 @@ public class ModelTrainDetailCoreService {
|
|||||||
return modelConfigRepository.findModelConfigByModelId(modelId).orElse(null);
|
return modelConfigRepository.findModelConfigByModelId(modelId).orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
public List<ModelTrainMetrics> getModelTrainMetricResult(UUID uuid) {
|
public List<ModelTrainMetrics> getModelTrainMetricResult(UUID uuid) {
|
||||||
return modelDetailRepository.getModelTrainMetricResult(uuid);
|
return modelDetailRepository.getModelTrainMetricResult(uuid);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -80,6 +80,17 @@ public class ModelTrainJobCoreService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 실행 시작 처리 수정 */
|
||||||
|
@Transactional
|
||||||
|
public void updateJobStatus(Long jobId, String jobStatus) {
|
||||||
|
ModelTrainJobEntity job =
|
||||||
|
modelTrainJobRepository
|
||||||
|
.findById(jobId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
job.setStatusCd(jobStatus);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 성공 처리
|
* 성공 처리
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -17,6 +17,10 @@ public class ModelTrainMetricsJobCoreService {
|
|||||||
return modelTrainMetricsJobRepository.getTrainMetricSaveNotYetModelIds();
|
return modelTrainMetricsJobRepository.getTrainMetricSaveNotYetModelIds();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ResponsePathDto getTrainMetricSaveNotYetModelId(Long modelId) {
|
||||||
|
return modelTrainMetricsJobRepository.getTrainMetricSaveNotYetModelId(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
public void insertModelMetricsTrain(List<Object[]> batchArgs) {
|
public void insertModelMetricsTrain(List<Object[]> batchArgs) {
|
||||||
modelTrainMetricsJobRepository.insertModelMetricsTrain(batchArgs);
|
modelTrainMetricsJobRepository.insertModelMetricsTrain(batchArgs);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -120,6 +120,15 @@ public class ModelTrainMngCoreService {
|
|||||||
entity.setTrainType(addReq.getTrainType()); // 일반, 전이
|
entity.setTrainType(addReq.getTrainType()); // 일반, 전이
|
||||||
entity.setBeforeModelId(addReq.getBeforeModelId());
|
entity.setBeforeModelId(addReq.getBeforeModelId());
|
||||||
|
|
||||||
|
// 전이학습일 때 beforeModelUuid 추가하기
|
||||||
|
if (addReq.getBeforeModelId() != null) {
|
||||||
|
ModelMasterEntity beforeModel =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(addReq.getBeforeModelId())
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
entity.setBeforeModelUuid(beforeModel.getUuid());
|
||||||
|
}
|
||||||
|
|
||||||
entity.setStatusCd(TrainStatusType.READY.getId());
|
entity.setStatusCd(TrainStatusType.READY.getId());
|
||||||
entity.setStep1State(TrainStatusType.READY.getId());
|
entity.setStep1State(TrainStatusType.READY.getId());
|
||||||
|
|
||||||
@@ -140,6 +149,7 @@ public class ModelTrainMngCoreService {
|
|||||||
* @param addReq 요청 파라미터
|
* @param addReq 요청 파라미터
|
||||||
*/
|
*/
|
||||||
public void saveModelDataset(Long modelId, ModelTrainMngDto.AddReq addReq) {
|
public void saveModelDataset(Long modelId, ModelTrainMngDto.AddReq addReq) {
|
||||||
|
|
||||||
TrainingDataset dataset = addReq.getTrainingDataset();
|
TrainingDataset dataset = addReq.getTrainingDataset();
|
||||||
ModelMasterEntity modelMasterEntity = new ModelMasterEntity();
|
ModelMasterEntity modelMasterEntity = new ModelMasterEntity();
|
||||||
ModelDatasetEntity datasetEntity = new ModelDatasetEntity();
|
ModelDatasetEntity datasetEntity = new ModelDatasetEntity();
|
||||||
@@ -154,6 +164,8 @@ public class ModelTrainMngCoreService {
|
|||||||
datasetEntity.setWasteCnt(dataset.getSummary().getWasteCnt());
|
datasetEntity.setWasteCnt(dataset.getSummary().getWasteCnt());
|
||||||
} else if (addReq.getModelNo().equals(ModelType.G3.getId())) {
|
} else if (addReq.getModelNo().equals(ModelType.G3.getId())) {
|
||||||
datasetEntity.setLandCoverCnt(dataset.getSummary().getLandCoverCnt());
|
datasetEntity.setLandCoverCnt(dataset.getSummary().getLandCoverCnt());
|
||||||
|
} else if (addReq.getModelNo().equals(ModelType.G4.getId())) {
|
||||||
|
datasetEntity.setSolarCnt(dataset.getSummary().getSolarPanelCnt());
|
||||||
}
|
}
|
||||||
|
|
||||||
datasetEntity.setCreatedUid(userUtil.getId());
|
datasetEntity.setCreatedUid(userUtil.getId());
|
||||||
@@ -177,6 +189,9 @@ public class ModelTrainMngCoreService {
|
|||||||
if (req.getRequestPath() != null && !req.getRequestPath().isEmpty()) {
|
if (req.getRequestPath() != null && !req.getRequestPath().isEmpty()) {
|
||||||
entity.setRequestPath(req.getRequestPath());
|
entity.setRequestPath(req.getRequestPath());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
entity.setTmpFileStatus(req.getTmpFileStatus());
|
||||||
|
entity.setTmpFileEndDttm(req.getTmpFileEndDttm());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -219,6 +234,7 @@ public class ModelTrainMngCoreService {
|
|||||||
modelConfigRepository.save(entity);
|
modelConfigRepository.save(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 데이터셋 매핑 생성
|
* 데이터셋 매핑 생성
|
||||||
*
|
*
|
||||||
@@ -235,6 +251,8 @@ public class ModelTrainMngCoreService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* UUID로 모델 조회
|
* UUID로 모델 조회
|
||||||
*
|
*
|
||||||
@@ -278,6 +296,7 @@ public class ModelTrainMngCoreService {
|
|||||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
public ModelConfigDto.TransferBasic findModelTransferConfigByModelId(UUID uuid) {
|
public ModelConfigDto.TransferBasic findModelTransferConfigByModelId(UUID uuid) {
|
||||||
ModelMasterEntity modelEntity = findByUuid(uuid);
|
ModelMasterEntity modelEntity = findByUuid(uuid);
|
||||||
return modelConfigRepository
|
return modelConfigRepository
|
||||||
@@ -285,6 +304,8 @@ public class ModelTrainMngCoreService {
|
|||||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 데이터셋 G1 목록
|
* 데이터셋 G1 목록
|
||||||
*
|
*
|
||||||
@@ -295,6 +316,7 @@ public class ModelTrainMngCoreService {
|
|||||||
return datasetRepository.getDatasetSelectG1List(req);
|
return datasetRepository.getDatasetSelectG1List(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 전이학습 데이터셋 G1 목록
|
* 전이학습 데이터셋 G1 목록
|
||||||
*
|
*
|
||||||
@@ -305,6 +327,8 @@ public class ModelTrainMngCoreService {
|
|||||||
return datasetRepository.getDatasetTransferSelectG1List(modelId);
|
return datasetRepository.getDatasetTransferSelectG1List(modelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 데이터셋 G2, G3 목록
|
* 데이터셋 G2, G3 목록
|
||||||
*
|
*
|
||||||
@@ -315,6 +339,7 @@ public class ModelTrainMngCoreService {
|
|||||||
return datasetRepository.getDatasetSelectG2G3List(req);
|
return datasetRepository.getDatasetSelectG2G3List(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 전이학습 데이터셋 G2, G3 목록
|
* 전이학습 데이터셋 G2, G3 목록
|
||||||
*
|
*
|
||||||
@@ -327,6 +352,18 @@ public class ModelTrainMngCoreService {
|
|||||||
return datasetRepository.getDatasetTransferSelectG2G3List(modelId, modelNo);
|
return datasetRepository.getDatasetTransferSelectG2G3List(modelId, modelNo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 G4 목록
|
||||||
|
*
|
||||||
|
* @param req
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public List<SelectDataSet> getDatasetSelectG4List(DatasetReq req) {
|
||||||
|
return datasetRepository.getDatasetSelectG4List(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델관리 조회
|
* 모델관리 조회
|
||||||
*
|
*
|
||||||
@@ -341,6 +378,20 @@ public class ModelTrainMngCoreService {
|
|||||||
return entity.toDto();
|
return entity.toDto();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델관리 조회
|
||||||
|
*
|
||||||
|
* @param uuid
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public ModelTrainMngDto.Basic findModelByUuid(UUID uuid) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findByUuid(uuid)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + uuid));
|
||||||
|
return entity.toDto();
|
||||||
|
}
|
||||||
|
|
||||||
/** 마스터를 IN_PROGRESS로 전환하고, 현재 실행 jobId를 연결 - UI/중단/상태조회 모두 currentAttemptId를 기준으로 동작 */
|
/** 마스터를 IN_PROGRESS로 전환하고, 현재 실행 jobId를 연결 - UI/중단/상태조회 모두 currentAttemptId를 기준으로 동작 */
|
||||||
@Transactional
|
@Transactional
|
||||||
public void markInProgress(Long modelId, Long jobId) {
|
public void markInProgress(Long modelId, Long jobId) {
|
||||||
@@ -377,6 +428,11 @@ public class ModelTrainMngCoreService {
|
|||||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
master.setStatusCd(TrainStatusType.STOPPED.getId());
|
master.setStatusCd(TrainStatusType.STOPPED.getId());
|
||||||
|
if (master.getStep2StrtDttm() != null) {
|
||||||
|
master.setStep2State(TrainStatusType.STOPPED.getId());
|
||||||
|
} else {
|
||||||
|
master.setStep1State(TrainStatusType.STOPPED.getId());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 완료 처리(옵션) - Worker가 성공 시 호출 */
|
/** 완료 처리(옵션) - Worker가 성공 시 호출 */
|
||||||
@@ -634,4 +690,49 @@ public class ModelTrainMngCoreService {
|
|||||||
public List<ModelTrainLinkDto> findDatasetTestPath(Long modelId) {
|
public List<ModelTrainLinkDto> findDatasetTestPath(Long modelId) {
|
||||||
return modelDatasetMapRepository.findDatasetTestPath(modelId);
|
return modelDatasetMapRepository.findDatasetTestPath(modelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void updateTrainRequestPath(Long modelId, String datasetUid) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
// 임시폴더 UID업데이트
|
||||||
|
entity.setRequestPath(datasetUid);
|
||||||
|
entity.setReqTmpYn(false); // false 인 것은 train, test 실행 시 docker 명령어에 request 폴더를 바라보게 할 예정
|
||||||
|
}
|
||||||
|
|
||||||
|
public void updateTmpFileStatusStart(Long modelId) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
entity.setReqTmpYn(true);
|
||||||
|
entity.setTmpFileStatus("IN_PROGRESS");
|
||||||
|
entity.setTmpFileStartDttm(ZonedDateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void updateTmpFileStatusFail(Long modelId, String message) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
entity.setTmpFileStatus("FAIL");
|
||||||
|
entity.setTmpFileErrMessage(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModelTrainMngDto.InProgressModel findInprogressModel() {
|
||||||
|
return modelMngRepository.findInprogressModel();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModelTrainMngDto.ProgressPercent findTrainProgressPercent(UUID uuid) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findByUuid(uuid)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
return modelMngRepository.findTrainProgressPercent(entity.getId());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.core;
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
import com.kamco.cd.training.postgres.entity.SystemMetricsEntity;
|
import com.kamco.cd.training.postgres.entity.SystemMetricsEntity;
|
||||||
@@ -64,3 +65,4 @@ public class SystemMetricsCoreService {
|
|||||||
return isAvailable;
|
return isAvailable;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetClsObjDto.Basic;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.hibernate.annotations.ColumnDefault;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Entity
|
||||||
|
@Table(name = "tb_dataset_cls_obj")
|
||||||
|
public class DatasetClsObjEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
@Column(name = "obj_id", nullable = false)
|
||||||
|
private Long objId;
|
||||||
|
|
||||||
|
@Column(name = "uuid")
|
||||||
|
private UUID uuid;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "dataset_uid", nullable = false)
|
||||||
|
private Long datasetUid;
|
||||||
|
|
||||||
|
@Column(name = "type")
|
||||||
|
private String type;
|
||||||
|
|
||||||
|
@Column(name = "yyyy")
|
||||||
|
private Integer yyyy;
|
||||||
|
|
||||||
|
@Size(max = 255)
|
||||||
|
@Column(name = "class_cd")
|
||||||
|
private String classCd;
|
||||||
|
|
||||||
|
@Size(max = 255)
|
||||||
|
@Column(name = "map_sheet_num")
|
||||||
|
private String mapSheetNum;
|
||||||
|
|
||||||
|
@Column(name = "tif_img_path")
|
||||||
|
private String tifImgPath;
|
||||||
|
|
||||||
|
@Column(name = "file_name")
|
||||||
|
private String fileName;
|
||||||
|
|
||||||
|
@ColumnDefault("now()")
|
||||||
|
@Column(name = "created_dttm")
|
||||||
|
private ZonedDateTime createdDttm;
|
||||||
|
|
||||||
|
@Column(name = "created_uid")
|
||||||
|
private Long createdUid;
|
||||||
|
|
||||||
|
@ColumnDefault("false")
|
||||||
|
@Column(name = "deleted")
|
||||||
|
private Boolean deleted;
|
||||||
|
|
||||||
|
public Basic toDto() {
|
||||||
|
return new Basic(
|
||||||
|
this.objId,
|
||||||
|
this.uuid,
|
||||||
|
this.datasetUid,
|
||||||
|
this.type,
|
||||||
|
this.yyyy,
|
||||||
|
this.classCd,
|
||||||
|
this.mapSheetNum,
|
||||||
|
this.tifImgPath,
|
||||||
|
this.fileName,
|
||||||
|
this.createdDttm,
|
||||||
|
this.createdUid,
|
||||||
|
this.deleted);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -117,14 +117,19 @@ public class DatasetEntity {
|
|||||||
@Column(name = "dataset_path", length = 1000)
|
@Column(name = "dataset_path", length = 1000)
|
||||||
private String datasetPath;
|
private String datasetPath;
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Column(name = "class_counts")
|
@Column(name = "class_counts")
|
||||||
@JdbcTypeCode(SqlTypes.JSON)
|
@JdbcTypeCode(SqlTypes.JSON)
|
||||||
private Map<String, Integer> classCounts;
|
private Map<String, Integer> classCounts;
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
@Size(max = 32)
|
@Size(max = 32)
|
||||||
@Column(name = "uid")
|
@Column(name = "uid")
|
||||||
private String uid;
|
private String uid;
|
||||||
|
|
||||||
|
@Column(name = "cd_cls_type")
|
||||||
|
private String cdClsType;
|
||||||
|
|
||||||
public DatasetDto.Basic toDto() {
|
public DatasetDto.Basic toDto() {
|
||||||
return new DatasetDto.Basic(
|
return new DatasetDto.Basic(
|
||||||
this.id,
|
this.id,
|
||||||
@@ -138,6 +143,7 @@ public class DatasetEntity {
|
|||||||
this.createdDttm,
|
this.createdDttm,
|
||||||
this.status,
|
this.status,
|
||||||
this.deleted,
|
this.deleted,
|
||||||
this.dataType);
|
this.dataType,
|
||||||
|
this.cdClsType);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.entity;
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||||
@@ -103,3 +104,4 @@ public class MapSheetEntity {
|
|||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -43,6 +43,9 @@ public class ModelDatasetEntity {
|
|||||||
@Column(name = "land_cover_cnt")
|
@Column(name = "land_cover_cnt")
|
||||||
private Long landCoverCnt;
|
private Long landCoverCnt;
|
||||||
|
|
||||||
|
@Column(name = "solar_cnt")
|
||||||
|
private Long solarCnt;
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
@ColumnDefault("now()")
|
||||||
@Column(name = "created_dttm")
|
@Column(name = "created_dttm")
|
||||||
private ZonedDateTime createdDttm = ZonedDateTime.now();
|
private ZonedDateTime createdDttm = ZonedDateTime.now();
|
||||||
|
|||||||
@@ -32,10 +32,13 @@ public class ModelDatasetMappEntity {
|
|||||||
@Column(name = "dataset_uid", nullable = false)
|
@Column(name = "dataset_uid", nullable = false)
|
||||||
private Long datasetUid;
|
private Long datasetUid;
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Size(max = 20)
|
@Size(max = 20)
|
||||||
@Column(name = "dataset_type", length = 20)
|
@Column(name = "dataset_type", length = 20)
|
||||||
private String datasetType;
|
private String datasetType;
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
|
|||||||
@@ -0,0 +1,177 @@
|
|||||||
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperClsParamDto;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.hibernate.annotations.ColumnDefault;
|
||||||
|
import org.hibernate.annotations.UuidGenerator;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Entity
|
||||||
|
@Table(
|
||||||
|
name = "tb_model_cls_hyper_params",
|
||||||
|
indexes = {@Index(name = "idx_hyper_cls_params_hyper_ver", columnList = "hyper_ver")})
|
||||||
|
public class ModelHyperClsParamEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
@Column(name = "hyper_param_id", nullable = false)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@UuidGenerator
|
||||||
|
@Column(name = "uuid", nullable = false, updatable = false)
|
||||||
|
private UUID uuid = UUID.randomUUID();
|
||||||
|
|
||||||
|
@Size(max = 50)
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "hyper_ver", nullable = false, length = 50)
|
||||||
|
private String hyperVer;
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Important (Default 반영)
|
||||||
|
// -------------------------
|
||||||
|
|
||||||
|
/** Choices: 256,256 or 512,512. Default: 256,256 */
|
||||||
|
@Size(max = 15)
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "input_size", nullable = false, length = 15)
|
||||||
|
private String inputSize = "256,256";
|
||||||
|
|
||||||
|
/** Range: >=1. Default: 16 (per GPU) */
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "batch_size", nullable = false)
|
||||||
|
private Integer batchSize = 16;
|
||||||
|
|
||||||
|
/** Range: >=1. Default: 16 */
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "workers", nullable = false)
|
||||||
|
private Integer workers = 16;
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Augmentation (Default 반영)
|
||||||
|
// -------------------------
|
||||||
|
|
||||||
|
@Column(name = "scale")
|
||||||
|
private Double scale = 0.5;
|
||||||
|
|
||||||
|
@Column(name = "translate")
|
||||||
|
private Double translate = 0.1;
|
||||||
|
|
||||||
|
@Column(name = "fliplr")
|
||||||
|
private Double fliplr = 0.5;
|
||||||
|
|
||||||
|
@Column(name = "flipud")
|
||||||
|
private Double flipud = 0.5;
|
||||||
|
|
||||||
|
@Column(name = "erasing")
|
||||||
|
private Double erasing;
|
||||||
|
|
||||||
|
@Column(name = "mixup")
|
||||||
|
private Double mixup = 0.1;
|
||||||
|
|
||||||
|
@Column(name = "hsv_h")
|
||||||
|
private Double hsvH;
|
||||||
|
|
||||||
|
@Column(name = "hsv_s")
|
||||||
|
private Double hsvS;
|
||||||
|
|
||||||
|
@Column(name = "hsv_v")
|
||||||
|
private Double hsvV;
|
||||||
|
|
||||||
|
@Column(name = "dropout")
|
||||||
|
private Double dropout;
|
||||||
|
|
||||||
|
@Column(name = "label_smoothing")
|
||||||
|
private Double labelSmoothing;
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Common
|
||||||
|
// -------------------------
|
||||||
|
|
||||||
|
@Column(name = "memo")
|
||||||
|
private String memo;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@ColumnDefault("false")
|
||||||
|
@Column(name = "del_yn", nullable = false, length = 1)
|
||||||
|
private Boolean delYn = false;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@ColumnDefault("CURRENT_TIMESTAMP")
|
||||||
|
@Column(name = "created_dttm", nullable = false)
|
||||||
|
private ZonedDateTime createdDttm = ZonedDateTime.now();
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "created_uid", nullable = false)
|
||||||
|
private Long createdUid;
|
||||||
|
|
||||||
|
@ColumnDefault("CURRENT_TIMESTAMP")
|
||||||
|
@Column(name = "updated_dttm")
|
||||||
|
private ZonedDateTime updatedDttm;
|
||||||
|
|
||||||
|
@Column(name = "updated_uid")
|
||||||
|
private Long updatedUid;
|
||||||
|
|
||||||
|
@ColumnDefault("CURRENT_TIMESTAMP")
|
||||||
|
@Column(name = "last_used_dttm")
|
||||||
|
private ZonedDateTime lastUsedDttm;
|
||||||
|
|
||||||
|
@Column(name = "model_type")
|
||||||
|
@Enumerated(EnumType.STRING)
|
||||||
|
private ModelType modelType;
|
||||||
|
|
||||||
|
@Column(name = "default_param")
|
||||||
|
private Boolean isDefault = false;
|
||||||
|
|
||||||
|
@Column(name = "total_use_cnt")
|
||||||
|
private Integer totalUseCnt = 0;
|
||||||
|
|
||||||
|
public HyperClsParamDto.Basic toDto() {
|
||||||
|
return new HyperClsParamDto.Basic(
|
||||||
|
this.modelType,
|
||||||
|
this.uuid,
|
||||||
|
this.hyperVer,
|
||||||
|
this.createdDttm,
|
||||||
|
this.lastUsedDttm,
|
||||||
|
this.totalUseCnt,
|
||||||
|
// -------------------------
|
||||||
|
// Model
|
||||||
|
// -------------------------
|
||||||
|
this.inputSize,
|
||||||
|
this.batchSize,
|
||||||
|
this.workers,
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Argument
|
||||||
|
// -------------------------
|
||||||
|
this.scale,
|
||||||
|
this.translate,
|
||||||
|
this.fliplr,
|
||||||
|
this.flipud,
|
||||||
|
this.erasing,
|
||||||
|
this.mixup,
|
||||||
|
this.hsvH,
|
||||||
|
this.hsvS,
|
||||||
|
this.hsvV,
|
||||||
|
this.dropout,
|
||||||
|
this.labelSmoothing,
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Memo
|
||||||
|
// -------------------------
|
||||||
|
this.memo,
|
||||||
|
|
||||||
|
// -------------------------
|
||||||
|
// Hardware
|
||||||
|
// -------------------------
|
||||||
|
this.isDefault);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -181,15 +181,15 @@ public class ModelHyperParamEntity {
|
|||||||
private String metrics = "mFscore,mIoU";
|
private String metrics = "mFscore,mIoU";
|
||||||
|
|
||||||
/** Default: changed_fscore */
|
/** Default: changed_fscore */
|
||||||
@Size(max = 30)
|
@Size(max = 50)
|
||||||
@NotNull
|
@NotNull
|
||||||
@Column(name = "save_best", nullable = false, length = 30)
|
@Column(name = "save_best", nullable = false, length = 50)
|
||||||
private String saveBest = "changed_fscore";
|
private String saveBest = "changed_fscore";
|
||||||
|
|
||||||
/** Default: greater */
|
/** Default: greater */
|
||||||
@Size(max = 10)
|
@Size(max = 50)
|
||||||
@NotNull
|
@NotNull
|
||||||
@Column(name = "save_best_rule", nullable = false, length = 10)
|
@Column(name = "save_best_rule", nullable = false, length = 50)
|
||||||
private String saveBestRule = "greater";
|
private String saveBestRule = "greater";
|
||||||
|
|
||||||
/** Default: 1 */
|
/** Default: 1 */
|
||||||
|
|||||||
@@ -121,6 +121,24 @@ public class ModelMasterEntity {
|
|||||||
@Column(name = "packing_end_dttm")
|
@Column(name = "packing_end_dttm")
|
||||||
private ZonedDateTime packingEndDttm;
|
private ZonedDateTime packingEndDttm;
|
||||||
|
|
||||||
|
@Column(name = "req_tmp_yn")
|
||||||
|
private Boolean reqTmpYn;
|
||||||
|
|
||||||
|
@Column(name = "tmp_file_status")
|
||||||
|
private String tmpFileStatus;
|
||||||
|
|
||||||
|
@Column(name = "tmp_file_start_dttm")
|
||||||
|
private ZonedDateTime tmpFileStartDttm;
|
||||||
|
|
||||||
|
@Column(name = "tmp_file_end_dttm")
|
||||||
|
private ZonedDateTime tmpFileEndDttm;
|
||||||
|
|
||||||
|
@Column(name = "tmp_file_err_message", columnDefinition = "TEXT")
|
||||||
|
private String tmpFileErrMessage;
|
||||||
|
|
||||||
|
@Column(name = "before_model_uuid")
|
||||||
|
private UUID beforeModelUuid;
|
||||||
|
|
||||||
public ModelTrainMngDto.Basic toDto() {
|
public ModelTrainMngDto.Basic toDto() {
|
||||||
return new ModelTrainMngDto.Basic(
|
return new ModelTrainMngDto.Basic(
|
||||||
this.id,
|
this.id,
|
||||||
@@ -141,6 +159,8 @@ public class ModelMasterEntity {
|
|||||||
this.packingState,
|
this.packingState,
|
||||||
this.packingStrtDttm,
|
this.packingStrtDttm,
|
||||||
this.packingEndDttm,
|
this.packingEndDttm,
|
||||||
this.beforeModelId);
|
this.beforeModelId,
|
||||||
|
this.bestEpoch,
|
||||||
|
this.beforeModelUuid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.entity;
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
@@ -92,3 +93,4 @@ public class ModelMngEntity {
|
|||||||
return this.uuid != null ? this.uuid.toString() : null;
|
return this.uuid != null ? this.uuid.toString() : null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.entity;
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
@@ -53,3 +54,4 @@ public class SystemMetricsEntity {
|
|||||||
@Column(name = "memused")
|
@Column(name = "memused")
|
||||||
private Float memused;
|
private Float memused;
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.repository;
|
package com.kamco.cd.training.postgres.repository;
|
||||||
|
|
||||||
import com.kamco.cd.training.postgres.entity.SystemMetricsEntity;
|
import com.kamco.cd.training.postgres.entity.SystemMetricsEntity;
|
||||||
@@ -17,3 +18,4 @@ public interface SystemMetricsRepository extends JpaRepository<SystemMetricsEnti
|
|||||||
@Query("SELECT s FROM SystemMetricsEntity s ORDER BY s.timestamp DESC LIMIT 1")
|
@Query("SELECT s FROM SystemMetricsEntity s ORDER BY s.timestamp DESC LIMIT 1")
|
||||||
Optional<SystemMetricsEntity> findLatestMetrics();
|
Optional<SystemMetricsEntity> findLatestMetrics();
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.kamco.cd.training.postgres.repository.dataset;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.postgres.entity.DatasetEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
public interface DatasetClsRepository
|
||||||
|
extends JpaRepository<DatasetEntity, Long>, DatasetClsRepositoryCustom {}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package com.kamco.cd.training.postgres.repository.dataset;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetClsObjDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
|
||||||
|
import com.kamco.cd.training.postgres.entity.DatasetClsObjEntity;
|
||||||
|
import com.kamco.cd.training.postgres.entity.DatasetEntity;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
|
||||||
|
public interface DatasetClsRepositoryCustom {
|
||||||
|
Page<DatasetEntity> findDatasetList(DatasetDto.SearchReq searchReq);
|
||||||
|
|
||||||
|
Optional<DatasetEntity> findByUuid(UUID id);
|
||||||
|
|
||||||
|
List<SelectDataSet> getDatasetSelectG1List(DatasetReq req);
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
public List<SelectTransferDataSet> getDatasetTransferSelectG1List(Long modelId);
|
||||||
|
|
||||||
|
public List<SelectTransferDataSet> getDatasetTransferSelectG2G3List(Long modelId, String modelNo);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req);
|
||||||
|
|
||||||
|
List<SelectDataSet> getDatasetSelectG4List(DatasetReq req);
|
||||||
|
|
||||||
|
Long getDatasetMaxStage(int compareYyyy, int targetYyyy);
|
||||||
|
|
||||||
|
Long insertDatasetMngData(DatasetMngRegDto mngRegDto);
|
||||||
|
|
||||||
|
List<String> findDatasetUid(List<Long> datasetIds);
|
||||||
|
|
||||||
|
Long findDatasetByUidExistsCnt(String uid);
|
||||||
|
|
||||||
|
Page<DatasetClsObjEntity> searchDatasetClsObjectList(DatasetClsObjDto.ClsSearchReq searchReq);
|
||||||
|
|
||||||
|
void insertDatasetClsObj(DatasetObjDto.DatasetClsObjRegDto objRegDto);
|
||||||
|
|
||||||
|
String getFilePathByUUIDPathType(UUID uuid);
|
||||||
|
}
|
||||||
@@ -0,0 +1,668 @@
|
|||||||
|
package com.kamco.cd.training.postgres.repository.dataset;
|
||||||
|
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QDatasetClsObjEntity.datasetClsObjEntity;
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QDatasetEntity.datasetEntity;
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QDatasetObjEntity.datasetObjEntity;
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity.modelDatasetMappEntity;
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.DetectionClassification;
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetClsObjDto;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.*;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
|
||||||
|
import com.kamco.cd.training.postgres.entity.*;
|
||||||
|
import com.querydsl.core.BooleanBuilder;
|
||||||
|
import com.querydsl.core.types.Projections;
|
||||||
|
import com.querydsl.core.types.dsl.CaseBuilder;
|
||||||
|
import com.querydsl.core.types.dsl.Expressions;
|
||||||
|
import com.querydsl.core.types.dsl.NumberExpression;
|
||||||
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
|
import jakarta.persistence.EntityManager;
|
||||||
|
import jakarta.persistence.EntityNotFoundException;
|
||||||
|
import jakarta.persistence.PersistenceContext;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DatasetClsRepositoryImpl implements DatasetClsRepositoryCustom {
|
||||||
|
|
||||||
|
private final JPAQueryFactory queryFactory;
|
||||||
|
private final QDatasetEntity dataset = QDatasetEntity.datasetEntity;
|
||||||
|
|
||||||
|
@PersistenceContext private final EntityManager em;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 목록 조회
|
||||||
|
*
|
||||||
|
* @param searchReq 검색 조건
|
||||||
|
* @return 페이징 처리된 데이터셋 Entity 목록
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public Page<DatasetEntity> findDatasetList(SearchReq searchReq) {
|
||||||
|
Pageable pageable = searchReq.toPageable();
|
||||||
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
|
||||||
|
// 제목
|
||||||
|
if (StringUtils.isNotBlank(searchReq.getTitle())) {
|
||||||
|
String contains = "%" + searchReq.getTitle() + "%";
|
||||||
|
builder.and(dataset.title.likeIgnoreCase(contains));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 구분
|
||||||
|
if (StringUtils.isNotBlank(searchReq.getDataType())) {
|
||||||
|
builder.and(dataset.dataType.eq(searchReq.getDataType()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entity 직접 조회 (Projections 사용 지양)
|
||||||
|
List<DatasetEntity> content =
|
||||||
|
queryFactory
|
||||||
|
.selectFrom(dataset)
|
||||||
|
.where(builder.and(dataset.deleted.isFalse()).and(dataset.cdClsType.eq("CLS")))
|
||||||
|
.offset(pageable.getOffset())
|
||||||
|
.limit(pageable.getPageSize())
|
||||||
|
.orderBy(dataset.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
|
||||||
|
// Count 쿼리 별도 실행 (null safe handling)
|
||||||
|
long total =
|
||||||
|
Optional.ofNullable(
|
||||||
|
queryFactory
|
||||||
|
.select(dataset.count())
|
||||||
|
.from(dataset)
|
||||||
|
.where(builder.and(dataset.deleted.isFalse()).and(dataset.cdClsType.eq("CLS")))
|
||||||
|
.fetchOne())
|
||||||
|
.orElse(0L);
|
||||||
|
|
||||||
|
return new PageImpl<>(content, pageable, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<DatasetEntity> findByUuid(UUID id) {
|
||||||
|
return Optional.ofNullable(
|
||||||
|
queryFactory
|
||||||
|
.select(dataset)
|
||||||
|
.from(dataset)
|
||||||
|
.where(dataset.uuid.eq(id), dataset.deleted.isFalse())
|
||||||
|
.fetchOne());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SelectDataSet> getDatasetSelectG1List(DatasetReq req) {
|
||||||
|
|
||||||
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
|
||||||
|
builder.and(dataset.deleted.isFalse());
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
|
||||||
|
builder.and(dataset.dataType.eq(req.getDataType()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.getIds() != null) {
|
||||||
|
builder.and(dataset.id.in(req.getIds()));
|
||||||
|
}
|
||||||
|
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
SelectDataSet.class,
|
||||||
|
Expressions.constant(req.getModelNo()),
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(
|
||||||
|
datasetObjEntity.targetClassCd.eq(DetectionClassification.BUILDING.getId()))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum(),
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(
|
||||||
|
datasetObjEntity.targetClassCd.eq(
|
||||||
|
DetectionClassification.CONTAINER.getId()))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum()))
|
||||||
|
.from(dataset)
|
||||||
|
.leftJoin(datasetObjEntity)
|
||||||
|
.on(dataset.id.eq(datasetObjEntity.datasetUid))
|
||||||
|
.where(builder) // datasetObjEntity.targetClassCd.in("building", "container").and(
|
||||||
|
.groupBy(
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.memo)
|
||||||
|
.orderBy(dataset.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
@Override
|
||||||
|
public List<SelectTransferDataSet> getDatasetTransferSelectG1List(Long modelId) {
|
||||||
|
|
||||||
|
QModelMasterEntity beforeMaster = new QModelMasterEntity("beforeMaster");
|
||||||
|
QModelDatasetMappEntity beforeMapp = new QModelDatasetMappEntity("beforeMapp");
|
||||||
|
QDatasetEntity beforeDataset = new QDatasetEntity("beforeDataset");
|
||||||
|
QDatasetObjEntity beforeObj = new QDatasetObjEntity("beforeObj");
|
||||||
|
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
SelectTransferDataSet.class,
|
||||||
|
|
||||||
|
// ===== 현재 =====
|
||||||
|
modelMasterEntity.modelNo,
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(datasetObjEntity.targetClassCd.eq("building"))
|
||||||
|
.then(1)
|
||||||
|
.otherwise(0)
|
||||||
|
.sum(),
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(datasetObjEntity.targetClassCd.eq("container"))
|
||||||
|
.then(1)
|
||||||
|
.otherwise(0)
|
||||||
|
.sum(),
|
||||||
|
|
||||||
|
// ===== before (join으로) =====
|
||||||
|
beforeMaster.modelNo,
|
||||||
|
beforeDataset.id,
|
||||||
|
beforeDataset.uuid,
|
||||||
|
beforeDataset.dataType,
|
||||||
|
beforeDataset.title,
|
||||||
|
beforeDataset.roundNo,
|
||||||
|
beforeDataset.compareYyyy,
|
||||||
|
beforeDataset.targetYyyy,
|
||||||
|
beforeDataset.memo,
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(beforeObj.targetClassCd.eq("building"))
|
||||||
|
.then(1)
|
||||||
|
.otherwise(0)
|
||||||
|
.sum(),
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(beforeObj.targetClassCd.eq("container"))
|
||||||
|
.then(1)
|
||||||
|
.otherwise(0)
|
||||||
|
.sum()))
|
||||||
|
.from(modelMasterEntity)
|
||||||
|
|
||||||
|
// ===== 현재 dataset join =====
|
||||||
|
.leftJoin(modelDatasetMappEntity)
|
||||||
|
.on(modelDatasetMappEntity.modelUid.eq(modelMasterEntity.id))
|
||||||
|
.leftJoin(dataset)
|
||||||
|
.on(modelDatasetMappEntity.datasetUid.eq(dataset.id))
|
||||||
|
.leftJoin(datasetObjEntity)
|
||||||
|
.on(dataset.id.eq(datasetObjEntity.datasetUid))
|
||||||
|
|
||||||
|
// ===== before 모델 join =====
|
||||||
|
.leftJoin(beforeMaster)
|
||||||
|
.on(beforeMaster.id.eq(modelMasterEntity.beforeModelId))
|
||||||
|
.leftJoin(beforeMapp)
|
||||||
|
.on(beforeMapp.modelUid.eq(beforeMaster.id))
|
||||||
|
.leftJoin(beforeDataset)
|
||||||
|
.on(beforeMapp.datasetUid.eq(beforeDataset.id))
|
||||||
|
.leftJoin(beforeObj)
|
||||||
|
.on(beforeDataset.id.eq(beforeObj.datasetUid))
|
||||||
|
.where(modelMasterEntity.id.eq(modelId))
|
||||||
|
.groupBy(
|
||||||
|
modelMasterEntity.modelNo,
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
beforeMaster.modelNo,
|
||||||
|
beforeDataset.id,
|
||||||
|
beforeDataset.uuid,
|
||||||
|
beforeDataset.dataType,
|
||||||
|
beforeDataset.title,
|
||||||
|
beforeDataset.roundNo,
|
||||||
|
beforeDataset.compareYyyy,
|
||||||
|
beforeDataset.targetYyyy,
|
||||||
|
beforeDataset.memo)
|
||||||
|
.orderBy(dataset.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) {
|
||||||
|
|
||||||
|
String building = DetectionClassification.BUILDING.getId();
|
||||||
|
String container = DetectionClassification.CONTAINER.getId();
|
||||||
|
String waste = DetectionClassification.WASTE.getId();
|
||||||
|
String solar = DetectionClassification.SOLAR.getId();
|
||||||
|
|
||||||
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
builder.and(dataset.deleted.isFalse());
|
||||||
|
|
||||||
|
NumberExpression<Long> selectedCnt = null;
|
||||||
|
// G2
|
||||||
|
NumberExpression<Long> wasteCnt =
|
||||||
|
datasetObjEntity
|
||||||
|
.targetClassCd
|
||||||
|
.when(DetectionClassification.WASTE.getId())
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
// G3 (G1, G2, G4 제외)
|
||||||
|
NumberExpression<Long> elseCnt =
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(datasetObjEntity.targetClassCd.notIn(building, container, waste, solar))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
if (req.getModelNo().equals(ModelType.G2.getId())) {
|
||||||
|
selectedCnt = wasteCnt;
|
||||||
|
} else {
|
||||||
|
selectedCnt = elseCnt;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(req.getDataType())) {
|
||||||
|
if (!"CURRENT".equals(req.getDataType())) {
|
||||||
|
builder.and(dataset.dataType.eq(req.getDataType()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.getIds() != null) {
|
||||||
|
builder.and(dataset.id.in(req.getIds()));
|
||||||
|
}
|
||||||
|
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
SelectDataSet.class,
|
||||||
|
Expressions.constant(req.getModelNo()),
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
selectedCnt.as("cnt")))
|
||||||
|
.from(dataset)
|
||||||
|
.leftJoin(datasetObjEntity)
|
||||||
|
.on(dataset.id.eq(datasetObjEntity.datasetUid))
|
||||||
|
.where(builder)
|
||||||
|
.groupBy(
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.memo)
|
||||||
|
.orderBy(dataset.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
@Override
|
||||||
|
public List<SelectTransferDataSet> getDatasetTransferSelectG2G3List(
|
||||||
|
Long modelId, String modelNo) {
|
||||||
|
|
||||||
|
// before join용
|
||||||
|
QModelMasterEntity beforeMaster = new QModelMasterEntity("beforeMaster");
|
||||||
|
QModelDatasetMappEntity beforeMapp = new QModelDatasetMappEntity("beforeMapp");
|
||||||
|
QDatasetEntity beforeDataset = new QDatasetEntity("beforeDataset");
|
||||||
|
QDatasetObjEntity beforeObj = new QDatasetObjEntity("beforeObj");
|
||||||
|
|
||||||
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
|
||||||
|
NumberExpression<Long> wasteCnt =
|
||||||
|
datasetObjEntity.targetClassCd.when("waste").then(1L).otherwise(0L).sum();
|
||||||
|
|
||||||
|
NumberExpression<Long> elseCnt =
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(datasetObjEntity.targetClassCd.notIn("building", "container", "waste"))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
NumberExpression<Long> selectedCnt = ModelType.G2.getId().equals(modelNo) ? wasteCnt : elseCnt;
|
||||||
|
|
||||||
|
// before도 동일 로직으로 cnt 계산
|
||||||
|
NumberExpression<Long> beforeWasteCnt =
|
||||||
|
beforeObj.targetClassCd.when("waste").then(1L).otherwise(0L).sum();
|
||||||
|
|
||||||
|
NumberExpression<Long> beforeElseCnt =
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(beforeObj.targetClassCd.notIn("building", "container", "waste"))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
NumberExpression<Long> beforeSelectedCnt =
|
||||||
|
ModelType.G2.getId().equals(modelNo) ? beforeWasteCnt : beforeElseCnt;
|
||||||
|
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
SelectTransferDataSet.class,
|
||||||
|
|
||||||
|
// ===== 현재 =====
|
||||||
|
modelMasterEntity.modelNo, // modelNo 파라미터 사용 (req.getModelNo() 제거)
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
selectedCnt, // classCount 자리에 들어가는 cnt (Long)
|
||||||
|
|
||||||
|
// ===== before =====
|
||||||
|
beforeMaster.modelNo,
|
||||||
|
beforeDataset.id,
|
||||||
|
beforeDataset.uuid,
|
||||||
|
beforeDataset.dataType,
|
||||||
|
beforeDataset.title,
|
||||||
|
beforeDataset.roundNo,
|
||||||
|
beforeDataset.compareYyyy,
|
||||||
|
beforeDataset.targetYyyy,
|
||||||
|
beforeDataset.memo,
|
||||||
|
beforeSelectedCnt))
|
||||||
|
.from(modelMasterEntity)
|
||||||
|
|
||||||
|
// ===== 현재 dataset =====
|
||||||
|
.leftJoin(modelDatasetMappEntity)
|
||||||
|
.on(modelDatasetMappEntity.modelUid.eq(modelMasterEntity.id))
|
||||||
|
.leftJoin(dataset)
|
||||||
|
.on(modelDatasetMappEntity.datasetUid.eq(dataset.id))
|
||||||
|
.leftJoin(datasetObjEntity)
|
||||||
|
.on(dataset.id.eq(datasetObjEntity.datasetUid))
|
||||||
|
|
||||||
|
// ===== before dataset =====
|
||||||
|
.leftJoin(beforeMaster)
|
||||||
|
.on(beforeMaster.id.eq(modelMasterEntity.beforeModelId))
|
||||||
|
.leftJoin(beforeMapp)
|
||||||
|
.on(beforeMapp.modelUid.eq(beforeMaster.id))
|
||||||
|
.leftJoin(beforeDataset)
|
||||||
|
.on(beforeMapp.datasetUid.eq(beforeDataset.id))
|
||||||
|
.leftJoin(beforeObj)
|
||||||
|
.on(beforeDataset.id.eq(beforeObj.datasetUid))
|
||||||
|
.where(modelMasterEntity.id.eq(modelId).and(builder))
|
||||||
|
|
||||||
|
// sum() 때문에 groupBy 필요
|
||||||
|
.groupBy(
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
beforeMaster.modelNo,
|
||||||
|
beforeDataset.id,
|
||||||
|
beforeDataset.uuid,
|
||||||
|
beforeDataset.dataType,
|
||||||
|
beforeDataset.title,
|
||||||
|
beforeDataset.roundNo,
|
||||||
|
beforeDataset.compareYyyy,
|
||||||
|
beforeDataset.targetYyyy,
|
||||||
|
beforeDataset.memo)
|
||||||
|
.orderBy(dataset.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Long getDatasetMaxStage(int compareYyyy, int targetYyyy) {
|
||||||
|
return queryFactory
|
||||||
|
.select(dataset.roundNo.max().coalesce(0L))
|
||||||
|
.from(dataset)
|
||||||
|
.where(dataset.compareYyyy.eq(compareYyyy), dataset.targetYyyy.eq(targetYyyy))
|
||||||
|
.fetchOne();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Long insertDatasetMngData(DatasetMngRegDto mngRegDto) {
|
||||||
|
|
||||||
|
UUID uuid = UUID.randomUUID();
|
||||||
|
// 1. 기본 생성자로 빈 엔티티 객체 생성
|
||||||
|
// DatasetEntity datasetEntity = new DatasetEntity();
|
||||||
|
//
|
||||||
|
// // 2. Setter를 이용해 데이터 채우기
|
||||||
|
// datasetEntity.setUid(mngRegDto.getUid());
|
||||||
|
// datasetEntity.setDataType(mngRegDto.getDataType());
|
||||||
|
// datasetEntity.setCompareYyyy(mngRegDto.getCompareYyyy());
|
||||||
|
// datasetEntity.setTargetYyyy(mngRegDto.getTargetYyyy());
|
||||||
|
// datasetEntity.setRoundNo(mngRegDto.getRoundNo());
|
||||||
|
// datasetEntity.setTotalSize(mngRegDto.getTotalSize());
|
||||||
|
// datasetEntity.setTitle(mngRegDto.getTitle());
|
||||||
|
// datasetEntity.setMemo(mngRegDto.getMemo());
|
||||||
|
// datasetEntity.setDatasetPath(mngRegDto.getDatasetPath());
|
||||||
|
// datasetEntity.setCdClsType(mngRegDto.getCdClsType());
|
||||||
|
//
|
||||||
|
// datasetEntity.setUuid(UUID.randomUUID());
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// // 2. JPA 영속성 컨텍스트에 저장 (이 시점에 DB에 들어가거나 ID가 생성됨)
|
||||||
|
// em.persist(datasetEntity);
|
||||||
|
|
||||||
|
queryFactory
|
||||||
|
.insert(dataset)
|
||||||
|
.columns(
|
||||||
|
dataset.uid,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.totalSize,
|
||||||
|
dataset.title,
|
||||||
|
dataset.memo,
|
||||||
|
dataset.datasetPath,
|
||||||
|
dataset.cdClsType)
|
||||||
|
.values(
|
||||||
|
mngRegDto.getUid(),
|
||||||
|
uuid,
|
||||||
|
mngRegDto.getDataType(),
|
||||||
|
mngRegDto.getCompareYyyy(),
|
||||||
|
mngRegDto.getTargetYyyy(),
|
||||||
|
mngRegDto.getRoundNo(),
|
||||||
|
mngRegDto.getTotalSize(),
|
||||||
|
mngRegDto.getTitle(),
|
||||||
|
mngRegDto.getMemo(),
|
||||||
|
mngRegDto.getDatasetPath(),
|
||||||
|
mngRegDto.getCdClsType())
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
// 3. uid 조회 필요 없이, 생성된 Key를 안전하게 바로 리턴
|
||||||
|
// return datasetEntity.getId();
|
||||||
|
return queryFactory.select(dataset.id).from(dataset).where(dataset.uuid.eq(uuid)).fetchOne();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> findDatasetUid(List<Long> datasetIds) {
|
||||||
|
return queryFactory.select(dataset.uid).from(dataset).where(dataset.id.in(datasetIds)).fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Long findDatasetByUidExistsCnt(String uid) {
|
||||||
|
return queryFactory
|
||||||
|
.select(dataset.id.count())
|
||||||
|
.from(dataset)
|
||||||
|
.where(dataset.uid.eq(uid), dataset.deleted.isFalse())
|
||||||
|
.fetchOne();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SelectDataSet> getDatasetSelectG4List(DatasetReq req) {
|
||||||
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
|
||||||
|
builder.and(dataset.deleted.isFalse());
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
|
||||||
|
builder.and(dataset.dataType.eq(req.getDataType()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.getIds() != null) {
|
||||||
|
builder.and(dataset.id.in(req.getIds()));
|
||||||
|
}
|
||||||
|
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
SelectDataSet.class,
|
||||||
|
Expressions.constant(req.getModelNo()),
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(datasetObjEntity.targetClassCd.eq(DetectionClassification.SOLAR.getId()))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum()))
|
||||||
|
.from(dataset)
|
||||||
|
.leftJoin(datasetObjEntity)
|
||||||
|
.on(dataset.id.eq(datasetObjEntity.datasetUid))
|
||||||
|
.where(builder)
|
||||||
|
.groupBy(
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.memo)
|
||||||
|
.orderBy(dataset.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Page<DatasetClsObjEntity> searchDatasetClsObjectList(
|
||||||
|
DatasetClsObjDto.ClsSearchReq searchReq) {
|
||||||
|
{
|
||||||
|
Pageable pageable = searchReq.toPageable();
|
||||||
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(searchReq.getClassCd())) {
|
||||||
|
builder.and(datasetClsObjEntity.classCd.equalsIgnoreCase(searchReq.getClassCd()));
|
||||||
|
}
|
||||||
|
if (searchReq.getYyyy() != null) {
|
||||||
|
builder.and(datasetClsObjEntity.yyyy.eq(searchReq.getYyyy()));
|
||||||
|
}
|
||||||
|
if (StringUtils.isNotBlank(searchReq.getMapSheetNum())) {
|
||||||
|
builder.and(datasetClsObjEntity.mapSheetNum.eq(searchReq.getMapSheetNum()));
|
||||||
|
}
|
||||||
|
|
||||||
|
DatasetEntity entity =
|
||||||
|
queryFactory
|
||||||
|
.selectFrom(datasetEntity)
|
||||||
|
.where(datasetEntity.uuid.eq(searchReq.getUuid()))
|
||||||
|
.fetchOne();
|
||||||
|
|
||||||
|
if (Objects.isNull(entity)) {
|
||||||
|
throw new EntityNotFoundException(
|
||||||
|
"DatasetEntity not found for uuid: " + searchReq.getUuid());
|
||||||
|
}
|
||||||
|
|
||||||
|
List<DatasetClsObjEntity> content =
|
||||||
|
queryFactory
|
||||||
|
.selectFrom(datasetClsObjEntity)
|
||||||
|
.where(
|
||||||
|
datasetClsObjEntity
|
||||||
|
.deleted
|
||||||
|
.isFalse()
|
||||||
|
.and(datasetClsObjEntity.datasetUid.eq(entity.getId()))
|
||||||
|
.and(builder)
|
||||||
|
.and(
|
||||||
|
datasetClsObjEntity.type.eq(DatasetClsObjDto.FolderType.TRAIN.getText())))
|
||||||
|
.offset(pageable.getOffset())
|
||||||
|
.limit(pageable.getPageSize())
|
||||||
|
.fetch();
|
||||||
|
|
||||||
|
// Count 쿼리 별도 실행 (null safe handling)
|
||||||
|
long total =
|
||||||
|
Optional.ofNullable(
|
||||||
|
queryFactory
|
||||||
|
.select(datasetClsObjEntity.count())
|
||||||
|
.from(datasetClsObjEntity)
|
||||||
|
.where(
|
||||||
|
datasetClsObjEntity
|
||||||
|
.deleted
|
||||||
|
.isFalse()
|
||||||
|
.and(datasetClsObjEntity.datasetUid.eq(entity.getId()))
|
||||||
|
.and(builder)
|
||||||
|
.and(
|
||||||
|
datasetClsObjEntity.type.eq(
|
||||||
|
DatasetClsObjDto.FolderType.TRAIN.getText())))
|
||||||
|
.fetchOne())
|
||||||
|
.orElse(0L);
|
||||||
|
|
||||||
|
return new PageImpl<>(content, pageable, total);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void insertDatasetClsObj(DatasetObjDto.DatasetClsObjRegDto objRegDto) {
|
||||||
|
try {
|
||||||
|
em.createNativeQuery(
|
||||||
|
"""
|
||||||
|
insert into tb_dataset_cls_obj
|
||||||
|
(uuid, dataset_uid, type, yyyy, class_cd,
|
||||||
|
map_sheet_num, tif_img_path, file_name)
|
||||||
|
values
|
||||||
|
(?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""")
|
||||||
|
.setParameter(1, UUID.randomUUID())
|
||||||
|
.setParameter(2, objRegDto.getDatasetUid())
|
||||||
|
.setParameter(3, objRegDto.getType())
|
||||||
|
.setParameter(4, objRegDto.getYyyy())
|
||||||
|
.setParameter(5, objRegDto.getClassCd())
|
||||||
|
.setParameter(6, objRegDto.getMapSheetNum())
|
||||||
|
.setParameter(7, objRegDto.getTifImgPath())
|
||||||
|
.setParameter(8, objRegDto.getFileName())
|
||||||
|
.executeUpdate();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getFilePathByUUIDPathType(UUID uuid) {
|
||||||
|
return queryFactory
|
||||||
|
.select(datasetClsObjEntity.tifImgPath)
|
||||||
|
.from(datasetClsObjEntity)
|
||||||
|
.where(datasetClsObjEntity.uuid.eq(uuid))
|
||||||
|
.fetchOne();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,4 +24,12 @@ public interface DatasetObjRepositoryCustom {
|
|||||||
void insertDatasetTestObj(DatasetObjRegDto objRegDto);
|
void insertDatasetTestObj(DatasetObjRegDto objRegDto);
|
||||||
|
|
||||||
void insertDatasetValObj(DatasetObjRegDto objRegDto);
|
void insertDatasetValObj(DatasetObjRegDto objRegDto);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 등록 실패시 Obj 데이터 정리
|
||||||
|
*
|
||||||
|
* @param datasetUid
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
int deleteAllDatasetObj(Long datasetUid);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
|||||||
|
|
||||||
private final JPAQueryFactory queryFactory;
|
private final JPAQueryFactory queryFactory;
|
||||||
private final QDatasetEntity dataset = datasetEntity;
|
private final QDatasetEntity dataset = datasetEntity;
|
||||||
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
@PersistenceContext EntityManager em;
|
@PersistenceContext EntityManager em;
|
||||||
|
|
||||||
@@ -55,7 +56,6 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void insertDatasetTestObj(DatasetObjRegDto objRegDto) {
|
public void insertDatasetTestObj(DatasetObjRegDto objRegDto) {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
String json;
|
String json;
|
||||||
Geometry geometry;
|
Geometry geometry;
|
||||||
String geometryJson;
|
String geometryJson;
|
||||||
@@ -99,7 +99,6 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void insertDatasetValObj(DatasetObjRegDto objRegDto) {
|
public void insertDatasetValObj(DatasetObjRegDto objRegDto) {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
String json;
|
String json;
|
||||||
String geometryJson;
|
String geometryJson;
|
||||||
try {
|
try {
|
||||||
@@ -219,7 +218,6 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
String json;
|
String json;
|
||||||
String geometryJson;
|
String geometryJson;
|
||||||
try {
|
try {
|
||||||
@@ -276,4 +274,38 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
|||||||
.where(datasetObjEntity.uuid.eq(uuid))
|
.where(datasetObjEntity.uuid.eq(uuid))
|
||||||
.fetchOne();
|
.fetchOne();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int deleteAllDatasetObj(Long datasetUid) {
|
||||||
|
int cnt = 0;
|
||||||
|
cnt =
|
||||||
|
em.createNativeQuery(
|
||||||
|
"""
|
||||||
|
delete from tb_dataset_obj
|
||||||
|
where dataset_uid = ?
|
||||||
|
""")
|
||||||
|
.setParameter(1, datasetUid)
|
||||||
|
.executeUpdate();
|
||||||
|
|
||||||
|
cnt +=
|
||||||
|
em.createNativeQuery(
|
||||||
|
"""
|
||||||
|
delete from tb_dataset_val_obj
|
||||||
|
where dataset_uid = ?
|
||||||
|
""")
|
||||||
|
.setParameter(1, datasetUid)
|
||||||
|
.executeUpdate();
|
||||||
|
|
||||||
|
cnt +=
|
||||||
|
em.createNativeQuery(
|
||||||
|
"""
|
||||||
|
delete from tb_dataset_test_obj
|
||||||
|
where dataset_uid = ?
|
||||||
|
""")
|
||||||
|
.setParameter(1, datasetUid)
|
||||||
|
.executeUpdate();
|
||||||
|
|
||||||
|
em.clear();
|
||||||
|
return cnt;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
|||||||
|
|
||||||
public interface DatasetRepository
|
public interface DatasetRepository
|
||||||
extends JpaRepository<DatasetEntity, Long>, DatasetRepositoryCustom {
|
extends JpaRepository<DatasetEntity, Long>, DatasetRepositoryCustom {
|
||||||
|
// TODO 미사용시작
|
||||||
List<DatasetEntity> findByDeletedOrderByCreatedDttmDesc(Boolean deleted);
|
List<DatasetEntity> findByDeletedOrderByCreatedDttmDesc(Boolean deleted);
|
||||||
|
// TODO 미사용 끝
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,12 +18,17 @@ public interface DatasetRepositoryCustom {
|
|||||||
|
|
||||||
List<SelectDataSet> getDatasetSelectG1List(DatasetReq req);
|
List<SelectDataSet> getDatasetSelectG1List(DatasetReq req);
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
public List<SelectTransferDataSet> getDatasetTransferSelectG1List(Long modelId);
|
public List<SelectTransferDataSet> getDatasetTransferSelectG1List(Long modelId);
|
||||||
|
|
||||||
public List<SelectTransferDataSet> getDatasetTransferSelectG2G3List(Long modelId, String modelNo);
|
public List<SelectTransferDataSet> getDatasetTransferSelectG2G3List(Long modelId, String modelNo);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req);
|
List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req);
|
||||||
|
|
||||||
|
List<SelectDataSet> getDatasetSelectG4List(DatasetReq req);
|
||||||
|
|
||||||
Long getDatasetMaxStage(int compareYyyy, int targetYyyy);
|
Long getDatasetMaxStage(int compareYyyy, int targetYyyy);
|
||||||
|
|
||||||
Long insertDatasetMngData(DatasetMngRegDto mngRegDto);
|
Long insertDatasetMngData(DatasetMngRegDto mngRegDto);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import static com.kamco.cd.training.postgres.entity.QDatasetObjEntity.datasetObj
|
|||||||
import static com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity.modelDatasetMappEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity.modelDatasetMappEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.DetectionClassification;
|
||||||
import com.kamco.cd.training.common.enums.ModelType;
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||||
@@ -64,7 +65,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
List<DatasetEntity> content =
|
List<DatasetEntity> content =
|
||||||
queryFactory
|
queryFactory
|
||||||
.selectFrom(dataset)
|
.selectFrom(dataset)
|
||||||
.where(builder.and(dataset.deleted.isFalse()))
|
.where(builder.and(dataset.deleted.isFalse()).and(dataset.cdClsType.isNull()))
|
||||||
.offset(pageable.getOffset())
|
.offset(pageable.getOffset())
|
||||||
.limit(pageable.getPageSize())
|
.limit(pageable.getPageSize())
|
||||||
.orderBy(dataset.createdDttm.desc())
|
.orderBy(dataset.createdDttm.desc())
|
||||||
@@ -76,7 +77,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
queryFactory
|
queryFactory
|
||||||
.select(dataset.count())
|
.select(dataset.count())
|
||||||
.from(dataset)
|
.from(dataset)
|
||||||
.where(builder.and(dataset.deleted.isFalse()))
|
.where(builder.and(dataset.deleted.isFalse()).and(dataset.cdClsType.isNull()))
|
||||||
.fetchOne())
|
.fetchOne())
|
||||||
.orElse(0L);
|
.orElse(0L);
|
||||||
|
|
||||||
@@ -104,10 +105,6 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
builder.and(dataset.dataType.eq(req.getDataType()));
|
builder.and(dataset.dataType.eq(req.getDataType()));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
|
|
||||||
builder.and(dataset.dataType.eq(req.getDataType()));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (req.getIds() != null) {
|
if (req.getIds() != null) {
|
||||||
builder.and(dataset.id.in(req.getIds()));
|
builder.and(dataset.id.in(req.getIds()));
|
||||||
}
|
}
|
||||||
@@ -126,14 +123,17 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
dataset.targetYyyy,
|
dataset.targetYyyy,
|
||||||
dataset.memo,
|
dataset.memo,
|
||||||
new CaseBuilder()
|
new CaseBuilder()
|
||||||
.when(datasetObjEntity.targetClassCd.eq("building"))
|
.when(
|
||||||
.then(1)
|
datasetObjEntity.targetClassCd.eq(DetectionClassification.BUILDING.getId()))
|
||||||
.otherwise(0)
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
.sum(),
|
.sum(),
|
||||||
new CaseBuilder()
|
new CaseBuilder()
|
||||||
.when(datasetObjEntity.targetClassCd.eq("container"))
|
.when(
|
||||||
.then(1)
|
datasetObjEntity.targetClassCd.eq(
|
||||||
.otherwise(0)
|
DetectionClassification.CONTAINER.getId()))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
.sum()))
|
.sum()))
|
||||||
.from(dataset)
|
.from(dataset)
|
||||||
.leftJoin(datasetObjEntity)
|
.leftJoin(datasetObjEntity)
|
||||||
@@ -150,6 +150,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Override
|
@Override
|
||||||
public List<SelectTransferDataSet> getDatasetTransferSelectG1List(Long modelId) {
|
public List<SelectTransferDataSet> getDatasetTransferSelectG1List(Long modelId) {
|
||||||
|
|
||||||
@@ -247,30 +248,42 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) {
|
public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) {
|
||||||
|
|
||||||
|
String building = DetectionClassification.BUILDING.getId();
|
||||||
|
String container = DetectionClassification.CONTAINER.getId();
|
||||||
|
String waste = DetectionClassification.WASTE.getId();
|
||||||
|
String solar = DetectionClassification.SOLAR.getId();
|
||||||
|
|
||||||
BooleanBuilder builder = new BooleanBuilder();
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
builder.and(dataset.deleted.isFalse());
|
builder.and(dataset.deleted.isFalse());
|
||||||
|
|
||||||
NumberExpression<Long> selectedCnt = null;
|
NumberExpression<Long> selectedCnt = null;
|
||||||
|
// G2
|
||||||
NumberExpression<Long> wasteCnt =
|
NumberExpression<Long> wasteCnt =
|
||||||
datasetObjEntity.targetClassCd.when("waste").then(1L).otherwise(0L).sum();
|
datasetObjEntity
|
||||||
|
.targetClassCd
|
||||||
NumberExpression<Long> elseCnt =
|
.when(DetectionClassification.WASTE.getId())
|
||||||
new CaseBuilder()
|
.then(1L)
|
||||||
.when(datasetObjEntity.targetClassCd.notIn("building", "container", "waste"))
|
.otherwise(0L)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
// G3 (G1, G2, G4 제외)
|
||||||
|
NumberExpression<Long> elseCnt =
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(datasetObjEntity.targetClassCd.notIn(building, container, waste, solar))
|
||||||
.then(1L)
|
.then(1L)
|
||||||
.otherwise(0L)
|
.otherwise(0L)
|
||||||
.sum();
|
.sum();
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(req.getModelNo())) {
|
|
||||||
if (req.getModelNo().equals(ModelType.G2.getId())) {
|
if (req.getModelNo().equals(ModelType.G2.getId())) {
|
||||||
selectedCnt = wasteCnt;
|
selectedCnt = wasteCnt;
|
||||||
} else {
|
} else {
|
||||||
selectedCnt = elseCnt;
|
selectedCnt = elseCnt;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(req.getDataType())) {
|
if (StringUtils.isNotBlank(req.getDataType())) {
|
||||||
if (!"CURRENT".equals(req.getDataType())) {
|
if (!"CURRENT".equals(req.getDataType())) {
|
||||||
@@ -311,6 +324,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Override
|
@Override
|
||||||
public List<SelectTransferDataSet> getDatasetTransferSelectG2G3List(
|
public List<SelectTransferDataSet> getDatasetTransferSelectG2G3List(
|
||||||
Long modelId, String modelNo) {
|
Long modelId, String modelNo) {
|
||||||
@@ -421,6 +435,8 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Long getDatasetMaxStage(int compareYyyy, int targetYyyy) {
|
public Long getDatasetMaxStage(int compareYyyy, int targetYyyy) {
|
||||||
return queryFactory
|
return queryFactory
|
||||||
@@ -476,4 +492,51 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
.where(dataset.uid.eq(uid), dataset.deleted.isFalse())
|
.where(dataset.uid.eq(uid), dataset.deleted.isFalse())
|
||||||
.fetchOne();
|
.fetchOne();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<SelectDataSet> getDatasetSelectG4List(DatasetReq req) {
|
||||||
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
|
||||||
|
builder.and(dataset.deleted.isFalse());
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
|
||||||
|
builder.and(dataset.dataType.eq(req.getDataType()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.getIds() != null) {
|
||||||
|
builder.and(dataset.id.in(req.getIds()));
|
||||||
|
}
|
||||||
|
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
SelectDataSet.class,
|
||||||
|
Expressions.constant(req.getModelNo()),
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(datasetObjEntity.targetClassCd.eq(DetectionClassification.SOLAR.getId()))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum()))
|
||||||
|
.from(dataset)
|
||||||
|
.leftJoin(datasetObjEntity)
|
||||||
|
.on(dataset.id.eq(datasetObjEntity.datasetUid))
|
||||||
|
.where(builder)
|
||||||
|
.groupBy(
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.memo)
|
||||||
|
.orderBy(dataset.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.repository.dataset;
|
package com.kamco.cd.training.postgres.repository.dataset;
|
||||||
|
|
||||||
import com.kamco.cd.training.postgres.entity.MapSheetEntity;
|
import com.kamco.cd.training.postgres.entity.MapSheetEntity;
|
||||||
@@ -11,3 +12,4 @@ public interface MapSheetRepository
|
|||||||
|
|
||||||
long countByDatasetIdAndDeletedFalse(Long datasetId);
|
long countByDatasetIdAndDeletedFalse(Long datasetId);
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.repository.dataset;
|
package com.kamco.cd.training.postgres.repository.dataset;
|
||||||
|
|
||||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||||
@@ -7,3 +8,4 @@ import org.springframework.data.domain.Page;
|
|||||||
public interface MapSheetRepositoryCustom {
|
public interface MapSheetRepositoryCustom {
|
||||||
Page<MapSheetEntity> findMapSheetList(MapSheetDto.SearchReq searchReq);
|
Page<MapSheetEntity> findMapSheetList(MapSheetDto.SearchReq searchReq);
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.repository.dataset;
|
package com.kamco.cd.training.postgres.repository.dataset;
|
||||||
|
|
||||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||||
@@ -52,3 +53,4 @@ public class MapSheetRepositoryImpl implements MapSheetRepositoryCustom {
|
|||||||
return new PageImpl<>(content, pageable, total);
|
return new PageImpl<>(content, pageable, total);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.kamco.cd.training.postgres.repository.hyperparam;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.postgres.entity.ModelHyperClsParamEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface HyperClsParamRepository
|
||||||
|
extends JpaRepository<ModelHyperClsParamEntity, Long>, HyperClsParamRepositoryCustom {}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.kamco.cd.training.postgres.repository.hyperparam;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.SearchReq;
|
||||||
|
import com.kamco.cd.training.postgres.entity.ModelHyperClsParamEntity;
|
||||||
|
import com.kamco.cd.training.postgres.entity.ModelHyperParamEntity;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
|
||||||
|
public interface HyperClsParamRepositoryCustom {
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
/**
|
||||||
|
* 마지막 버전 조회
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
Optional<ModelHyperParamEntity> findHyperParamVer();
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델 타입별 마지막 버전 조회
|
||||||
|
*
|
||||||
|
* @param modelType 모델 타입
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
Optional<ModelHyperClsParamEntity> findHyperParamVerByModelType(ModelType modelType);
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼 파라미터 상세조회
|
||||||
|
*
|
||||||
|
* @param uuid
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
Optional<ModelHyperClsParamEntity> findHyperParamByUuid(UUID uuid);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼 파라미터 목록 조회
|
||||||
|
*
|
||||||
|
* @param model
|
||||||
|
* @param req
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
Page<HyperParamDto.List> findByHyperVerList(ModelType model, SearchReq req);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼 파라미터 모델타입으로 조회
|
||||||
|
*
|
||||||
|
* @param modelType
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
List<ModelHyperClsParamEntity> getHyperParamByType(ModelType modelType);
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
package com.kamco.cd.training.postgres.repository.hyperparam;
|
||||||
|
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QModelHyperClsParamEntity.modelHyperClsParamEntity;
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QModelHyperParamEntity.modelHyperParamEntity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.HyperType;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.SearchReq;
|
||||||
|
import com.kamco.cd.training.postgres.entity.ModelHyperClsParamEntity;
|
||||||
|
import com.kamco.cd.training.postgres.entity.ModelHyperParamEntity;
|
||||||
|
import com.querydsl.core.BooleanBuilder;
|
||||||
|
import com.querydsl.core.types.Projections;
|
||||||
|
import com.querydsl.jpa.impl.JPAQuery;
|
||||||
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class HyperClsParamRepositoryImpl implements HyperClsParamRepositoryCustom {
|
||||||
|
|
||||||
|
private final JPAQueryFactory queryFactory;
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
@Override
|
||||||
|
public Optional<ModelHyperParamEntity> findHyperParamVer() {
|
||||||
|
|
||||||
|
return Optional.ofNullable(
|
||||||
|
queryFactory
|
||||||
|
.select(modelHyperParamEntity)
|
||||||
|
.from(modelHyperParamEntity)
|
||||||
|
.where(modelHyperParamEntity.delYn.isFalse())
|
||||||
|
.orderBy(modelHyperParamEntity.hyperVer.desc())
|
||||||
|
.limit(1)
|
||||||
|
.fetchOne());
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<ModelHyperClsParamEntity> findHyperParamVerByModelType(ModelType modelType) {
|
||||||
|
|
||||||
|
return Optional.ofNullable(
|
||||||
|
queryFactory
|
||||||
|
.select(modelHyperClsParamEntity)
|
||||||
|
.from(modelHyperClsParamEntity)
|
||||||
|
.where(
|
||||||
|
modelHyperClsParamEntity
|
||||||
|
.delYn
|
||||||
|
.isFalse()
|
||||||
|
.and(modelHyperClsParamEntity.modelType.eq(modelType)))
|
||||||
|
.orderBy(modelHyperClsParamEntity.hyperVer.desc())
|
||||||
|
.limit(1)
|
||||||
|
.fetchOne());
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
@Override
|
||||||
|
public Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer) {
|
||||||
|
|
||||||
|
return Optional.ofNullable(
|
||||||
|
queryFactory
|
||||||
|
.select(modelHyperParamEntity)
|
||||||
|
.from(modelHyperParamEntity)
|
||||||
|
.where(
|
||||||
|
modelHyperParamEntity
|
||||||
|
.delYn
|
||||||
|
.isFalse()
|
||||||
|
.and(modelHyperParamEntity.hyperVer.eq(hyperVer)))
|
||||||
|
.limit(1)
|
||||||
|
.fetchOne());
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<ModelHyperClsParamEntity> findHyperParamByUuid(UUID uuid) {
|
||||||
|
return Optional.ofNullable(
|
||||||
|
queryFactory
|
||||||
|
.select(modelHyperClsParamEntity)
|
||||||
|
.from(modelHyperClsParamEntity)
|
||||||
|
.where(modelHyperClsParamEntity.uuid.eq(uuid))
|
||||||
|
.fetchOne());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Page<HyperParamDto.List> findByHyperVerList(ModelType model, SearchReq req) {
|
||||||
|
Pageable pageable = req.toPageable();
|
||||||
|
|
||||||
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
|
||||||
|
builder.and(modelHyperClsParamEntity.delYn.isFalse());
|
||||||
|
|
||||||
|
if (model != null) {
|
||||||
|
builder.and(modelHyperClsParamEntity.modelType.eq(model));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.getHyperVer() != null && !req.getHyperVer().isEmpty()) {
|
||||||
|
// 버전
|
||||||
|
builder.and(modelHyperClsParamEntity.hyperVer.contains(req.getHyperVer()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.getStartDate() != null && req.getEndDate() != null) {
|
||||||
|
|
||||||
|
ZoneId zoneId = ZoneId.systemDefault();
|
||||||
|
|
||||||
|
ZonedDateTime start = req.getStartDate().atStartOfDay(zoneId);
|
||||||
|
|
||||||
|
ZonedDateTime end = req.getEndDate().atTime(23, 59, 59).atZone(zoneId);
|
||||||
|
|
||||||
|
if (HyperType.CREATE_DATE.getId().equals(req.getType())) {
|
||||||
|
// 생성일
|
||||||
|
builder.and(modelHyperClsParamEntity.createdDttm.between(start, end));
|
||||||
|
} else if (HyperType.LAST_USED_DATE.getId().equals(req.getType())) {
|
||||||
|
// 최종 사용일
|
||||||
|
builder.and(modelHyperClsParamEntity.lastUsedDttm.between(start, end));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JPAQuery<HyperParamDto.List> query =
|
||||||
|
queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
HyperParamDto.List.class,
|
||||||
|
modelHyperClsParamEntity.uuid,
|
||||||
|
modelHyperClsParamEntity.modelType.as("model"),
|
||||||
|
modelHyperClsParamEntity.hyperVer,
|
||||||
|
modelHyperClsParamEntity.createdDttm,
|
||||||
|
modelHyperClsParamEntity.lastUsedDttm,
|
||||||
|
modelHyperClsParamEntity.memo,
|
||||||
|
modelHyperClsParamEntity.totalUseCnt))
|
||||||
|
.from(modelHyperClsParamEntity)
|
||||||
|
.where(builder);
|
||||||
|
|
||||||
|
Sort.Order sortOrder = pageable.getSort().stream().findFirst().orElse(null);
|
||||||
|
|
||||||
|
if (sortOrder == null) {
|
||||||
|
// 기본값
|
||||||
|
query.orderBy(modelHyperClsParamEntity.createdDttm.desc());
|
||||||
|
} else {
|
||||||
|
String property = sortOrder.getProperty();
|
||||||
|
boolean asc = sortOrder.isAscending();
|
||||||
|
|
||||||
|
switch (property) {
|
||||||
|
case "createdDttm" ->
|
||||||
|
query.orderBy(
|
||||||
|
asc
|
||||||
|
? modelHyperClsParamEntity.createdDttm.asc()
|
||||||
|
: modelHyperClsParamEntity.createdDttm.desc());
|
||||||
|
|
||||||
|
case "lastUsedDttm" ->
|
||||||
|
query.orderBy(
|
||||||
|
asc
|
||||||
|
? modelHyperClsParamEntity.lastUsedDttm.asc()
|
||||||
|
: modelHyperClsParamEntity.lastUsedDttm.desc());
|
||||||
|
case "totalUseCnt" ->
|
||||||
|
query.orderBy(
|
||||||
|
asc
|
||||||
|
? modelHyperClsParamEntity.totalUseCnt.asc()
|
||||||
|
: modelHyperClsParamEntity.totalUseCnt.desc());
|
||||||
|
|
||||||
|
default -> query.orderBy(modelHyperClsParamEntity.createdDttm.desc());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<HyperParamDto.List> content =
|
||||||
|
query.offset(pageable.getOffset()).limit(pageable.getPageSize()).fetch();
|
||||||
|
|
||||||
|
Long total =
|
||||||
|
queryFactory
|
||||||
|
.select(modelHyperClsParamEntity.count())
|
||||||
|
.from(modelHyperClsParamEntity)
|
||||||
|
.where(builder)
|
||||||
|
.fetchOne();
|
||||||
|
|
||||||
|
long totalCount = (total != null) ? total : 0L;
|
||||||
|
|
||||||
|
return new PageImpl<>(content, pageable, totalCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<ModelHyperClsParamEntity> getHyperParamByType(ModelType modelType) {
|
||||||
|
return queryFactory
|
||||||
|
.select(modelHyperClsParamEntity)
|
||||||
|
.from(modelHyperClsParamEntity)
|
||||||
|
.where(
|
||||||
|
modelHyperClsParamEntity
|
||||||
|
.delYn
|
||||||
|
.isFalse()
|
||||||
|
.and(modelHyperClsParamEntity.modelType.eq(modelType)))
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,5 +8,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
@Repository
|
@Repository
|
||||||
public interface HyperParamRepository
|
public interface HyperParamRepository
|
||||||
extends JpaRepository<ModelHyperParamEntity, Long>, HyperParamRepositoryCustom {
|
extends JpaRepository<ModelHyperParamEntity, Long>, HyperParamRepositoryCustom {
|
||||||
|
// TODO 미사용시작
|
||||||
Optional<ModelHyperParamEntity> findByHyperVer(String hyperVer);
|
Optional<ModelHyperParamEntity> findByHyperVer(String hyperVer);
|
||||||
|
// TODO 미사용 끝
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import org.springframework.data.domain.Page;
|
|||||||
|
|
||||||
public interface HyperParamRepositoryCustom {
|
public interface HyperParamRepositoryCustom {
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 마지막 버전 조회
|
* 마지막 버전 조회
|
||||||
*
|
*
|
||||||
@@ -19,6 +20,8 @@ public interface HyperParamRepositoryCustom {
|
|||||||
@Deprecated
|
@Deprecated
|
||||||
Optional<ModelHyperParamEntity> findHyperParamVer();
|
Optional<ModelHyperParamEntity> findHyperParamVer();
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델 타입별 마지막 버전 조회
|
* 모델 타입별 마지막 버전 조회
|
||||||
*
|
*
|
||||||
@@ -27,8 +30,11 @@ public interface HyperParamRepositoryCustom {
|
|||||||
*/
|
*/
|
||||||
Optional<ModelHyperParamEntity> findHyperParamVerByModelType(ModelType modelType);
|
Optional<ModelHyperParamEntity> findHyperParamVerByModelType(ModelType modelType);
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer);
|
Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 하이퍼 파라미터 상세조회
|
* 하이퍼 파라미터 상세조회
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
|||||||
|
|
||||||
private final JPAQueryFactory queryFactory;
|
private final JPAQueryFactory queryFactory;
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Override
|
@Override
|
||||||
public Optional<ModelHyperParamEntity> findHyperParamVer() {
|
public Optional<ModelHyperParamEntity> findHyperParamVer() {
|
||||||
|
|
||||||
@@ -42,6 +43,8 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
|||||||
.fetchOne());
|
.fetchOne());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Optional<ModelHyperParamEntity> findHyperParamVerByModelType(ModelType modelType) {
|
public Optional<ModelHyperParamEntity> findHyperParamVerByModelType(ModelType modelType) {
|
||||||
|
|
||||||
@@ -59,6 +62,7 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
|||||||
.fetchOne());
|
.fetchOne());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Override
|
@Override
|
||||||
public Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer) {
|
public Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer) {
|
||||||
|
|
||||||
@@ -75,6 +79,8 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
|||||||
.fetchOne());
|
.fetchOne());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Optional<ModelHyperParamEntity> findHyperParamByUuid(UUID uuid) {
|
public Optional<ModelHyperParamEntity> findHyperParamByUuid(UUID uuid) {
|
||||||
return Optional.ofNullable(
|
return Optional.ofNullable(
|
||||||
|
|||||||
@@ -7,14 +7,18 @@ import java.util.UUID;
|
|||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
|
|
||||||
public interface MembersRepositoryCustom {
|
public interface MembersRepositoryCustom {
|
||||||
|
// TODO 미사용시작
|
||||||
boolean existsByUserId(String userId);
|
boolean existsByUserId(String userId);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
boolean existsByEmployeeNo(String employeeNo);
|
boolean existsByEmployeeNo(String employeeNo);
|
||||||
|
|
||||||
Optional<MemberEntity> findByEmployeeNo(String employeeNo);
|
Optional<MemberEntity> findByEmployeeNo(String employeeNo);
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
Optional<MemberEntity> findByUserId(String userId);
|
Optional<MemberEntity> findByUserId(String userId);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
Optional<MemberEntity> findByUUID(UUID uuid);
|
Optional<MemberEntity> findByUUID(UUID uuid);
|
||||||
|
|
||||||
Page<MemberEntity> findByMembers(MembersDto.SearchReq searchReq);
|
Page<MemberEntity> findByMembers(MembersDto.SearchReq searchReq);
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ public class MembersRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
this.queryFactory = queryFactory;
|
this.queryFactory = queryFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 사용자 ID 조회
|
* 사용자 ID 조회
|
||||||
*
|
*
|
||||||
@@ -43,6 +44,8 @@ public class MembersRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
!= null;
|
!= null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 사용자 사번 조회
|
* 사용자 사번 조회
|
||||||
*
|
*
|
||||||
@@ -59,6 +62,7 @@ public class MembersRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
!= null;
|
!= null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 사용자 조회 user id
|
* 사용자 조회 user id
|
||||||
*
|
*
|
||||||
@@ -71,6 +75,8 @@ public class MembersRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
queryFactory.selectFrom(memberEntity).where(memberEntity.userId.eq(userId)).fetchOne());
|
queryFactory.selectFrom(memberEntity).where(memberEntity.userId.eq(userId)).fetchOne());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 사용자 조회 employeed no
|
* 사용자 조회 employeed no
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -6,5 +6,7 @@ import java.util.Optional;
|
|||||||
public interface ModelConfigRepositoryCustom {
|
public interface ModelConfigRepositoryCustom {
|
||||||
Optional<ModelConfigDto.Basic> findModelConfigByModelId(Long modelId);
|
Optional<ModelConfigDto.Basic> findModelConfigByModelId(Long modelId);
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
Optional<ModelConfigDto.TransferBasic> findModelTransferConfigByModelId(Long modelId);
|
Optional<ModelConfigDto.TransferBasic> findModelTransferConfigByModelId(Long modelId);
|
||||||
|
// TODO 미사용 끝
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ public class ModelConfigRepositoryImpl implements ModelConfigRepositoryCustom {
|
|||||||
.fetchOne());
|
.fetchOne());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Override
|
@Override
|
||||||
public Optional<TransferBasic> findModelTransferConfigByModelId(Long modelId) {
|
public Optional<TransferBasic> findModelTransferConfigByModelId(Long modelId) {
|
||||||
QModelConfigEntity beforeConfig = new QModelConfigEntity("beforeConfig");
|
QModelConfigEntity beforeConfig = new QModelConfigEntity("beforeConfig");
|
||||||
@@ -78,4 +79,5 @@ public class ModelConfigRepositoryImpl implements ModelConfigRepositoryCustom {
|
|||||||
.where(modelMasterEntity.id.eq(modelId))
|
.where(modelMasterEntity.id.eq(modelId))
|
||||||
.fetchOne());
|
.fetchOne());
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
package com.kamco.cd.training.postgres.repository.model;
|
package com.kamco.cd.training.postgres.repository.model;
|
||||||
|
|
||||||
import static com.kamco.cd.training.postgres.entity.QDatasetEntity.datasetEntity;
|
import static com.kamco.cd.training.postgres.entity.QDatasetEntity.datasetEntity;
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QDatasetObjEntity.datasetObjEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity.modelDatasetMappEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity.modelDatasetMappEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.DetectionClassification;
|
||||||
import com.kamco.cd.training.common.enums.ModelType;
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.postgres.entity.ModelDatasetMappEntity;
|
import com.kamco.cd.training.postgres.entity.ModelDatasetMappEntity;
|
||||||
import com.kamco.cd.training.postgres.entity.QDatasetObjEntity;
|
import com.kamco.cd.training.postgres.entity.QDatasetObjEntity;
|
||||||
@@ -11,6 +13,7 @@ import com.kamco.cd.training.postgres.entity.QDatasetTestObjEntity;
|
|||||||
import com.kamco.cd.training.postgres.entity.QDatasetValObjEntity;
|
import com.kamco.cd.training.postgres.entity.QDatasetValObjEntity;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
|
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
|
||||||
import com.querydsl.core.types.Projections;
|
import com.querydsl.core.types.Projections;
|
||||||
|
import com.querydsl.core.types.dsl.BooleanExpression;
|
||||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -33,9 +36,44 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<ModelTrainLinkDto> findDatasetTrainPath(Long modelId) {
|
public List<ModelTrainLinkDto> findDatasetTrainPath(Long modelId) {
|
||||||
|
|
||||||
QDatasetObjEntity datasetObjEntity = QDatasetObjEntity.datasetObjEntity;
|
QDatasetObjEntity datasetObjEntity = QDatasetObjEntity.datasetObjEntity;
|
||||||
|
|
||||||
|
// =====================
|
||||||
|
// 조건 분리
|
||||||
|
// =====================
|
||||||
|
BooleanExpression g1 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G1.getId())
|
||||||
|
.and(
|
||||||
|
datasetObjEntity.targetClassCd.in(
|
||||||
|
DetectionClassification.CONTAINER.getId(),
|
||||||
|
DetectionClassification.BUILDING.getId()));
|
||||||
|
|
||||||
|
BooleanExpression g2 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G2.getId())
|
||||||
|
.and(datasetObjEntity.targetClassCd.eq(DetectionClassification.WASTE.getId()));
|
||||||
|
|
||||||
|
BooleanExpression g4 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G4.getId())
|
||||||
|
.and(datasetObjEntity.targetClassCd.eq(DetectionClassification.SOLAR.getId()));
|
||||||
|
|
||||||
|
// G3 = 전체 허용 (fallback)
|
||||||
|
BooleanExpression g3 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G3.getId())
|
||||||
|
.and(
|
||||||
|
datasetObjEntity.targetClassCd.notIn(
|
||||||
|
DetectionClassification.CONTAINER.getId(),
|
||||||
|
DetectionClassification.BUILDING.getId(),
|
||||||
|
DetectionClassification.WASTE.getId(),
|
||||||
|
DetectionClassification.SOLAR.getId()));
|
||||||
|
|
||||||
return queryFactory
|
return queryFactory
|
||||||
.select(
|
.select(
|
||||||
Projections.constructor(
|
Projections.constructor(
|
||||||
@@ -60,17 +98,7 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
|
|||||||
datasetObjEntity
|
datasetObjEntity
|
||||||
.datasetUid
|
.datasetUid
|
||||||
.eq(modelDatasetMappEntity.datasetUid)
|
.eq(modelDatasetMappEntity.datasetUid)
|
||||||
.and(
|
.and(g1.or(g2).or(g4).or(g3)))
|
||||||
modelMasterEntity
|
|
||||||
.modelNo
|
|
||||||
.eq(ModelType.G1.getId())
|
|
||||||
.and(datasetObjEntity.targetClassCd.upper().in("CONTAINER", "BUILDING"))
|
|
||||||
.or(
|
|
||||||
modelMasterEntity
|
|
||||||
.modelNo
|
|
||||||
.eq(ModelType.G2.getId())
|
|
||||||
.and(datasetObjEntity.targetClassCd.upper().eq("WASTE")))
|
|
||||||
.or(modelMasterEntity.modelNo.eq(ModelType.G3.getId()))))
|
|
||||||
.where(modelMasterEntity.id.eq(modelId))
|
.where(modelMasterEntity.id.eq(modelId))
|
||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
@@ -80,6 +108,42 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
|
|||||||
|
|
||||||
QDatasetValObjEntity datasetValObjEntity = QDatasetValObjEntity.datasetValObjEntity;
|
QDatasetValObjEntity datasetValObjEntity = QDatasetValObjEntity.datasetValObjEntity;
|
||||||
|
|
||||||
|
// =====================
|
||||||
|
// 조건 분리
|
||||||
|
// =====================
|
||||||
|
BooleanExpression g1 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G1.getId())
|
||||||
|
.and(
|
||||||
|
datasetValObjEntity.targetClassCd.in(
|
||||||
|
DetectionClassification.CONTAINER.getId(),
|
||||||
|
DetectionClassification.BUILDING.getId()));
|
||||||
|
|
||||||
|
BooleanExpression g2 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G2.getId())
|
||||||
|
.and(datasetValObjEntity.targetClassCd.eq(DetectionClassification.WASTE.getId()));
|
||||||
|
|
||||||
|
BooleanExpression g4 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G4.getId())
|
||||||
|
.and(datasetValObjEntity.targetClassCd.eq(DetectionClassification.SOLAR.getId()));
|
||||||
|
|
||||||
|
// G3 = 전체 허용 (fallback)
|
||||||
|
BooleanExpression g3 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G3.getId())
|
||||||
|
.and(
|
||||||
|
datasetValObjEntity.targetClassCd.notIn(
|
||||||
|
DetectionClassification.CONTAINER.getId(),
|
||||||
|
DetectionClassification.BUILDING.getId(),
|
||||||
|
DetectionClassification.WASTE.getId(),
|
||||||
|
DetectionClassification.SOLAR.getId()));
|
||||||
|
|
||||||
return queryFactory
|
return queryFactory
|
||||||
.select(
|
.select(
|
||||||
Projections.constructor(
|
Projections.constructor(
|
||||||
@@ -104,17 +168,7 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
|
|||||||
datasetValObjEntity
|
datasetValObjEntity
|
||||||
.datasetUid
|
.datasetUid
|
||||||
.eq(modelDatasetMappEntity.datasetUid)
|
.eq(modelDatasetMappEntity.datasetUid)
|
||||||
.and(
|
.and(g1.or(g2).or(g4).or(g3)))
|
||||||
modelMasterEntity
|
|
||||||
.modelNo
|
|
||||||
.eq(ModelType.G1.getId())
|
|
||||||
.and(datasetValObjEntity.targetClassCd.upper().in("CONTAINER", "BUILDING"))
|
|
||||||
.or(
|
|
||||||
modelMasterEntity
|
|
||||||
.modelNo
|
|
||||||
.eq(ModelType.G2.getId())
|
|
||||||
.and(datasetValObjEntity.targetClassCd.upper().eq("WASTE")))
|
|
||||||
.or(modelMasterEntity.modelNo.eq(ModelType.G3.getId()))))
|
|
||||||
.where(modelMasterEntity.id.eq(modelId))
|
.where(modelMasterEntity.id.eq(modelId))
|
||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
@@ -124,6 +178,42 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
|
|||||||
|
|
||||||
QDatasetTestObjEntity datasetTestObjEntity = QDatasetTestObjEntity.datasetTestObjEntity;
|
QDatasetTestObjEntity datasetTestObjEntity = QDatasetTestObjEntity.datasetTestObjEntity;
|
||||||
|
|
||||||
|
// =====================
|
||||||
|
// 조건 분리
|
||||||
|
// =====================
|
||||||
|
BooleanExpression g1 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G1.getId())
|
||||||
|
.and(
|
||||||
|
datasetTestObjEntity.targetClassCd.in(
|
||||||
|
DetectionClassification.CONTAINER.getId(),
|
||||||
|
DetectionClassification.BUILDING.getId()));
|
||||||
|
|
||||||
|
BooleanExpression g2 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G2.getId())
|
||||||
|
.and(datasetTestObjEntity.targetClassCd.eq(DetectionClassification.WASTE.getId()));
|
||||||
|
|
||||||
|
BooleanExpression g4 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G4.getId())
|
||||||
|
.and(datasetTestObjEntity.targetClassCd.eq(DetectionClassification.SOLAR.getId()));
|
||||||
|
|
||||||
|
// G3 = 전체 허용 (fallback)
|
||||||
|
BooleanExpression g3 =
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G3.getId())
|
||||||
|
.and(
|
||||||
|
datasetTestObjEntity.targetClassCd.notIn(
|
||||||
|
DetectionClassification.CONTAINER.getId(),
|
||||||
|
DetectionClassification.BUILDING.getId(),
|
||||||
|
DetectionClassification.WASTE.getId(),
|
||||||
|
DetectionClassification.SOLAR.getId()));
|
||||||
|
|
||||||
return queryFactory
|
return queryFactory
|
||||||
.select(
|
.select(
|
||||||
Projections.constructor(
|
Projections.constructor(
|
||||||
@@ -148,17 +238,7 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
|
|||||||
datasetTestObjEntity
|
datasetTestObjEntity
|
||||||
.datasetUid
|
.datasetUid
|
||||||
.eq(modelDatasetMappEntity.datasetUid)
|
.eq(modelDatasetMappEntity.datasetUid)
|
||||||
.and(
|
.and(g1.or(g2).or(g4).or(g3)))
|
||||||
modelMasterEntity
|
|
||||||
.modelNo
|
|
||||||
.eq(ModelType.G1.getId())
|
|
||||||
.and(datasetTestObjEntity.targetClassCd.upper().in("CONTAINER", "BUILDING"))
|
|
||||||
.or(
|
|
||||||
modelMasterEntity
|
|
||||||
.modelNo
|
|
||||||
.eq(ModelType.G2.getId())
|
|
||||||
.and(datasetTestObjEntity.targetClassCd.upper().eq("WASTE")))
|
|
||||||
.or(modelMasterEntity.modelNo.eq(ModelType.G3.getId()))))
|
|
||||||
.where(modelMasterEntity.id.eq(modelId))
|
.where(modelMasterEntity.id.eq(modelId))
|
||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,8 +23,11 @@ public interface ModelDetailRepositoryCustom {
|
|||||||
|
|
||||||
HyperSummary getByModelHyperParamSummary(UUID uuid);
|
HyperSummary getByModelHyperParamSummary(UUID uuid);
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
TransferHyperSummary getByModelTransferHyperParamSummary(UUID uuid);
|
TransferHyperSummary getByModelTransferHyperParamSummary(UUID uuid);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
List<MappingDataset> getByModelMappingDataset(UUID uuid);
|
List<MappingDataset> getByModelMappingDataset(UUID uuid);
|
||||||
|
|
||||||
ModelMasterEntity findByModelByUUID(UUID uuid);
|
ModelMasterEntity findByModelByUUID(UUID uuid);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.kamco.cd.training.postgres.repository.model;
|
package com.kamco.cd.training.postgres.repository.model;
|
||||||
|
|
||||||
import static com.kamco.cd.training.postgres.entity.QDatasetEntity.datasetEntity;
|
import static com.kamco.cd.training.postgres.entity.QDatasetEntity.datasetEntity;
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QDatasetObjEntity.datasetObjEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelDatasetEntity.modelDatasetEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelDatasetEntity.modelDatasetEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity.modelDatasetMappEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity.modelDatasetMappEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelHyperParamEntity.modelHyperParamEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelHyperParamEntity.modelHyperParamEntity;
|
||||||
@@ -9,6 +10,8 @@ import static com.kamco.cd.training.postgres.entity.QModelMetricsTestEntity.mode
|
|||||||
import static com.kamco.cd.training.postgres.entity.QModelMetricsTrainEntity.modelMetricsTrainEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMetricsTrainEntity.modelMetricsTrainEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelMetricsValidationEntity.modelMetricsValidationEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMetricsValidationEntity.modelMetricsValidationEntity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.DetectionClassification;
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.DetailSummary;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.DetailSummary;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.HyperSummary;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.HyperSummary;
|
||||||
@@ -25,6 +28,7 @@ import com.kamco.cd.training.postgres.entity.QModelHyperParamEntity;
|
|||||||
import com.kamco.cd.training.postgres.entity.QModelMasterEntity;
|
import com.kamco.cd.training.postgres.entity.QModelMasterEntity;
|
||||||
import com.querydsl.core.types.Expression;
|
import com.querydsl.core.types.Expression;
|
||||||
import com.querydsl.core.types.Projections;
|
import com.querydsl.core.types.Projections;
|
||||||
|
import com.querydsl.core.types.dsl.CaseBuilder;
|
||||||
import com.querydsl.jpa.JPAExpressions;
|
import com.querydsl.jpa.JPAExpressions;
|
||||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -76,6 +80,8 @@ public class ModelDetailRepositoryImpl implements ModelDetailRepositoryCustom {
|
|||||||
modelMasterEntity.modelNo,
|
modelMasterEntity.modelNo,
|
||||||
modelMasterEntity.modelVer,
|
modelMasterEntity.modelVer,
|
||||||
modelMasterEntity.step1StrtDttm,
|
modelMasterEntity.step1StrtDttm,
|
||||||
|
modelMasterEntity.step1EndDttm,
|
||||||
|
modelMasterEntity.step2StrtDttm,
|
||||||
modelMasterEntity.step2EndDttm,
|
modelMasterEntity.step2EndDttm,
|
||||||
modelMasterEntity.statusCd,
|
modelMasterEntity.statusCd,
|
||||||
modelMasterEntity.trainType,
|
modelMasterEntity.trainType,
|
||||||
@@ -154,10 +160,78 @@ public class ModelDetailRepositoryImpl implements ModelDetailRepositoryCustom {
|
|||||||
datasetEntity.compareYyyy,
|
datasetEntity.compareYyyy,
|
||||||
datasetEntity.targetYyyy,
|
datasetEntity.targetYyyy,
|
||||||
datasetEntity.roundNo,
|
datasetEntity.roundNo,
|
||||||
modelDatasetEntity.buildingCnt,
|
|
||||||
modelDatasetEntity.containerCnt,
|
// G1 - building
|
||||||
modelDatasetEntity.wasteCnt,
|
new CaseBuilder()
|
||||||
modelDatasetEntity.landCoverCnt))
|
.when(
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G1.getId())
|
||||||
|
.and(
|
||||||
|
datasetObjEntity.targetClassCd.eq(
|
||||||
|
DetectionClassification.BUILDING.getId())))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum(),
|
||||||
|
|
||||||
|
// G1 - container
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G1.getId())
|
||||||
|
.and(
|
||||||
|
datasetObjEntity.targetClassCd.eq(
|
||||||
|
DetectionClassification.CONTAINER.getId())))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum(),
|
||||||
|
|
||||||
|
// G2 - waste
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G2.getId())
|
||||||
|
.and(
|
||||||
|
datasetObjEntity.targetClassCd.eq(
|
||||||
|
DetectionClassification.WASTE.getId())))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum(),
|
||||||
|
|
||||||
|
// G3 - 나머지
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G3.getId())
|
||||||
|
.and(
|
||||||
|
datasetObjEntity
|
||||||
|
.targetClassCd
|
||||||
|
.isNotNull()
|
||||||
|
.and(
|
||||||
|
datasetObjEntity.targetClassCd.notIn(
|
||||||
|
DetectionClassification.BUILDING.getId(),
|
||||||
|
DetectionClassification.CONTAINER.getId(),
|
||||||
|
DetectionClassification.WASTE.getId(),
|
||||||
|
DetectionClassification.SOLAR.getId()))))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum(),
|
||||||
|
|
||||||
|
// G4 - solar
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(
|
||||||
|
modelMasterEntity
|
||||||
|
.modelNo
|
||||||
|
.eq(ModelType.G4.getId())
|
||||||
|
.and(
|
||||||
|
datasetObjEntity.targetClassCd.eq(
|
||||||
|
DetectionClassification.SOLAR.getId())))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum()))
|
||||||
.from(modelMasterEntity)
|
.from(modelMasterEntity)
|
||||||
.innerJoin(modelDatasetEntity)
|
.innerJoin(modelDatasetEntity)
|
||||||
.on(modelMasterEntity.id.eq(modelDatasetEntity.model.id))
|
.on(modelMasterEntity.id.eq(modelDatasetEntity.model.id))
|
||||||
@@ -165,7 +239,16 @@ public class ModelDetailRepositoryImpl implements ModelDetailRepositoryCustom {
|
|||||||
.on(modelMasterEntity.id.eq(modelDatasetMappEntity.modelUid))
|
.on(modelMasterEntity.id.eq(modelDatasetMappEntity.modelUid))
|
||||||
.innerJoin(datasetEntity)
|
.innerJoin(datasetEntity)
|
||||||
.on(modelDatasetMappEntity.datasetUid.eq(datasetEntity.id))
|
.on(modelDatasetMappEntity.datasetUid.eq(datasetEntity.id))
|
||||||
|
.leftJoin(datasetObjEntity)
|
||||||
|
.on(datasetEntity.id.eq(datasetObjEntity.datasetUid))
|
||||||
.where(modelMasterEntity.uuid.eq(uuid))
|
.where(modelMasterEntity.uuid.eq(uuid))
|
||||||
|
.groupBy(
|
||||||
|
modelMasterEntity.id,
|
||||||
|
datasetEntity.id,
|
||||||
|
datasetEntity.dataType,
|
||||||
|
datasetEntity.compareYyyy,
|
||||||
|
datasetEntity.targetYyyy,
|
||||||
|
datasetEntity.roundNo)
|
||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
|||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ListDto;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ListDto;
|
||||||
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
|
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
|
||||||
import com.kamco.cd.training.train.dto.TrainRunRequest;
|
import com.kamco.cd.training.train.dto.TrainRunRequest;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
@@ -20,9 +21,39 @@ public interface ModelMngRepositoryCustom {
|
|||||||
|
|
||||||
Optional<ModelMasterEntity> findByUuid(UUID uuid);
|
Optional<ModelMasterEntity> findByUuid(UUID uuid);
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
Optional<ModelMasterEntity> findFirstByStatusCdAndDelYn(String statusCd, Boolean delYn);
|
Optional<ModelMasterEntity> findFirstByStatusCdAndDelYn(String statusCd, Boolean delYn);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
TrainRunRequest findTrainRunRequest(Long modelId);
|
TrainRunRequest findTrainRunRequest(Long modelId);
|
||||||
|
|
||||||
Long findModelStep1InProgressCnt();
|
Long findModelStep1InProgressCnt();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델 번호와 삭제 여부로 모델 조회 (최신순)
|
||||||
|
*
|
||||||
|
* @param modelNo 모델 번호 (G1, G2, G3, G4)
|
||||||
|
* @param delYn 삭제 여부
|
||||||
|
* @return 모델 목록
|
||||||
|
*/
|
||||||
|
List<ModelMasterEntity> findByModelNoAndDelYnOrderByCreatedDttmDesc(
|
||||||
|
String modelNo, Boolean delYn);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 ID로 모델 조회
|
||||||
|
*
|
||||||
|
* @param hyperParamId 하이퍼파라미터 ID
|
||||||
|
* @return 모델 목록
|
||||||
|
*/
|
||||||
|
List<ModelMasterEntity> findByHyperParamId(Long hyperParamId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 학습 진행중인 모델 type, uuid 조회
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
ModelTrainMngDto.InProgressModel findInprogressModel();
|
||||||
|
|
||||||
|
ModelTrainMngDto.ProgressPercent findTrainProgressPercent(Long id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import static com.kamco.cd.training.postgres.entity.QMemberEntity.memberEntity;
|
|||||||
import static com.kamco.cd.training.postgres.entity.QModelConfigEntity.modelConfigEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelConfigEntity.modelConfigEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelHyperParamEntity.modelHyperParamEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelHyperParamEntity.modelHyperParamEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QModelTrainJobEntity.modelTrainJobEntity;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||||
@@ -14,7 +15,9 @@ import com.kamco.cd.training.train.dto.TrainRunRequest;
|
|||||||
import com.querydsl.core.BooleanBuilder;
|
import com.querydsl.core.BooleanBuilder;
|
||||||
import com.querydsl.core.types.Expression;
|
import com.querydsl.core.types.Expression;
|
||||||
import com.querydsl.core.types.Projections;
|
import com.querydsl.core.types.Projections;
|
||||||
|
import com.querydsl.core.types.dsl.CaseBuilder;
|
||||||
import com.querydsl.core.types.dsl.Expressions;
|
import com.querydsl.core.types.dsl.Expressions;
|
||||||
|
import com.querydsl.core.types.dsl.NumberExpression;
|
||||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -133,13 +136,18 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
|
|||||||
.fetchOne());
|
.fetchOne());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Override
|
@Override
|
||||||
public Optional<ModelMasterEntity> findFirstByStatusCdAndDelYn(String statusCd, Boolean delYn) {
|
public Optional<ModelMasterEntity> findFirstByStatusCdAndDelYn(String statusCd, Boolean delYn) {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TrainRunRequest findTrainRunRequest(Long modelId) {
|
public TrainRunRequest findTrainRunRequest(Long modelId) {
|
||||||
|
QModelMasterEntity beforeModel = new QModelMasterEntity("beforeModel");
|
||||||
|
|
||||||
return queryFactory
|
return queryFactory
|
||||||
.select(
|
.select(
|
||||||
Projections.constructor(
|
Projections.constructor(
|
||||||
@@ -186,12 +194,18 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
|
|||||||
modelHyperParamEntity.hueDelta,
|
modelHyperParamEntity.hueDelta,
|
||||||
Expressions.nullExpression(Integer.class),
|
Expressions.nullExpression(Integer.class),
|
||||||
Expressions.nullExpression(String.class),
|
Expressions.nullExpression(String.class),
|
||||||
modelHyperParamEntity.uuid))
|
modelHyperParamEntity.uuid,
|
||||||
|
modelMasterEntity.reqTmpYn,
|
||||||
|
modelMasterEntity.trainType,
|
||||||
|
beforeModel.uuid,
|
||||||
|
beforeModel.bestEpoch))
|
||||||
.from(modelMasterEntity)
|
.from(modelMasterEntity)
|
||||||
.leftJoin(modelHyperParamEntity)
|
.leftJoin(modelHyperParamEntity)
|
||||||
.on(modelHyperParamEntity.id.eq(modelMasterEntity.hyperParamId))
|
.on(modelHyperParamEntity.id.eq(modelMasterEntity.hyperParamId))
|
||||||
.leftJoin(modelConfigEntity)
|
.leftJoin(modelConfigEntity)
|
||||||
.on(modelConfigEntity.model.id.eq(modelMasterEntity.id))
|
.on(modelConfigEntity.model.id.eq(modelMasterEntity.id))
|
||||||
|
.leftJoin(beforeModel)
|
||||||
|
.on(modelMasterEntity.beforeModelId.eq(beforeModel.id))
|
||||||
.where(modelMasterEntity.id.eq(modelId))
|
.where(modelMasterEntity.id.eq(modelId))
|
||||||
.fetchOne();
|
.fetchOne();
|
||||||
}
|
}
|
||||||
@@ -208,4 +222,77 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
|
|||||||
.or(modelMasterEntity.step2State.eq(TrainStatusType.IN_PROGRESS.getId())))
|
.or(modelMasterEntity.step2State.eq(TrainStatusType.IN_PROGRESS.getId())))
|
||||||
.fetchOne();
|
.fetchOne();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<ModelMasterEntity> findByModelNoAndDelYnOrderByCreatedDttmDesc(
|
||||||
|
String modelNo, Boolean delYn) {
|
||||||
|
return queryFactory
|
||||||
|
.selectFrom(modelMasterEntity)
|
||||||
|
.where(modelMasterEntity.modelNo.eq(modelNo), modelMasterEntity.delYn.eq(delYn))
|
||||||
|
.orderBy(modelMasterEntity.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<ModelMasterEntity> findByHyperParamId(Long hyperParamId) {
|
||||||
|
return queryFactory
|
||||||
|
.selectFrom(modelMasterEntity)
|
||||||
|
.where(modelMasterEntity.hyperParamId.eq(hyperParamId), modelMasterEntity.delYn.eq(false))
|
||||||
|
.orderBy(modelMasterEntity.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ModelTrainMngDto.InProgressModel findInprogressModel() {
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
ModelTrainMngDto.InProgressModel.class,
|
||||||
|
modelMasterEntity.modelNo,
|
||||||
|
modelMasterEntity.uuid))
|
||||||
|
.from(modelMasterEntity)
|
||||||
|
.where(
|
||||||
|
modelMasterEntity
|
||||||
|
.step1State
|
||||||
|
.eq(TrainStatusType.IN_PROGRESS.getId())
|
||||||
|
.or(modelMasterEntity.step2State.eq(TrainStatusType.IN_PROGRESS.getId())))
|
||||||
|
.fetchOne();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ModelTrainMngDto.ProgressPercent findTrainProgressPercent(Long id) {
|
||||||
|
NumberExpression<Integer> currentEpoch =
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(
|
||||||
|
modelTrainJobEntity
|
||||||
|
.jobType
|
||||||
|
.eq("TEST")
|
||||||
|
.and(modelTrainJobEntity.statusCd.eq("SUCCESS")))
|
||||||
|
.then(1)
|
||||||
|
.otherwise(modelTrainJobEntity.currentEpoch.coalesce(0));
|
||||||
|
|
||||||
|
NumberExpression<Integer> totalEpoch = modelTrainJobEntity.totalEpoch.coalesce(1);
|
||||||
|
|
||||||
|
// per 계산
|
||||||
|
NumberExpression<Double> per =
|
||||||
|
currentEpoch
|
||||||
|
.castToNum(Double.class)
|
||||||
|
.divide(totalEpoch.castToNum(Double.class))
|
||||||
|
.multiply(100);
|
||||||
|
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
ModelTrainMngDto.ProgressPercent.class,
|
||||||
|
modelTrainJobEntity.modelId,
|
||||||
|
modelTrainJobEntity.jobType,
|
||||||
|
modelTrainJobEntity.statusCd,
|
||||||
|
totalEpoch.as("totalEpoch"),
|
||||||
|
currentEpoch.as("currentEpoch"),
|
||||||
|
per.as("per")))
|
||||||
|
.from(modelTrainJobEntity)
|
||||||
|
.where(modelTrainJobEntity.modelId.eq(id))
|
||||||
|
.orderBy(modelTrainJobEntity.attemptNo.desc())
|
||||||
|
.fetchFirst();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.kamco.cd.training.postgres.repository.train;
|
|||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleMetricJsonDto;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -12,13 +13,33 @@ public interface ModelTestMetricsJobRepositoryCustom {
|
|||||||
|
|
||||||
List<ResponsePathDto> getTestMetricSaveNotYetModelIds();
|
List<ResponsePathDto> getTestMetricSaveNotYetModelIds();
|
||||||
|
|
||||||
|
ResponsePathDto getTestMetricSaveNotYetModelId(Long modelId);
|
||||||
|
|
||||||
void insertModelMetricsTest(List<Object[]> batchArgs);
|
void insertModelMetricsTest(List<Object[]> batchArgs);
|
||||||
|
|
||||||
ModelMetricJsonDto getTestMetricPackingInfo(Long modelId);
|
ModelMetricJsonDto getTestMetricPackingInfo(Long modelId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 간단한 형식의 테스트 메트릭 정보 조회 (ZIP 파일용)
|
||||||
|
*
|
||||||
|
* @param modelId 모델 ID
|
||||||
|
* @return 간단한 JSON 형식 DTO
|
||||||
|
*/
|
||||||
|
SimpleMetricJsonDto getSimpleTestMetricPackingInfo(Long modelId);
|
||||||
|
|
||||||
ModelTestFileName findModelTestFileNames(Long modelId);
|
ModelTestFileName findModelTestFileNames(Long modelId);
|
||||||
|
|
||||||
void updatePackingStart(Long modelId, ZonedDateTime now);
|
void updatePackingStart(Long modelId, ZonedDateTime now);
|
||||||
|
|
||||||
void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState);
|
void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 특정 Epoch의 메트릭 정보 조회 (하이퍼파라미터별 ZIP 생성용)
|
||||||
|
*
|
||||||
|
* @param modelId 모델 ID
|
||||||
|
* @param epoch Epoch 번호
|
||||||
|
* @param metricType 메트릭 타입 (fscore, precision, recall)
|
||||||
|
* @return 메트릭 JSON DTO
|
||||||
|
*/
|
||||||
|
ModelMetricJsonDto getMetricsByEpoch(Long modelId, Integer epoch, String metricType);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.kamco.cd.training.postgres.repository.train;
|
|||||||
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelMetricsTestEntity.modelMetricsTestEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMetricsTestEntity.modelMetricsTestEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelMetricsTrainEntity.modelMetricsTrainEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMetricsTrainEntity.modelMetricsTrainEntity;
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QModelMetricsValidationEntity.modelMetricsValidationEntity;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.postgres.entity.ModelMetricsTestEntity;
|
import com.kamco.cd.training.postgres.entity.ModelMetricsTestEntity;
|
||||||
@@ -10,6 +11,8 @@ import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
|||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.Properties;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.Properties;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleMetricJsonDto;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleProperties;
|
||||||
import com.querydsl.core.types.Projections;
|
import com.querydsl.core.types.Projections;
|
||||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
@@ -63,6 +66,25 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ResponsePathDto getTestMetricSaveNotYetModelId(Long modelId) {
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
ResponsePathDto.class,
|
||||||
|
modelMasterEntity.id,
|
||||||
|
modelMasterEntity.responsePath,
|
||||||
|
modelMasterEntity.uuid))
|
||||||
|
.from(modelMasterEntity)
|
||||||
|
.where(
|
||||||
|
modelMasterEntity.id.eq(modelId),
|
||||||
|
modelMasterEntity
|
||||||
|
.step2MetricSaveYn
|
||||||
|
.isNull()
|
||||||
|
.or(modelMasterEntity.step2MetricSaveYn.isFalse()))
|
||||||
|
.fetchOne();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void insertModelMetricsTest(List<Object[]> batchArgs) {
|
public void insertModelMetricsTest(List<Object[]> batchArgs) {
|
||||||
// AS-IS
|
// AS-IS
|
||||||
@@ -84,7 +106,7 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
SET tp=?, fp=?, fn=?, precisions=?, recall=?, f1_score=?, accuracy=?, iou=?,
|
SET tp=?, fp=?, fn=?, precisions=?, recall=?, f1_score=?, accuracy=?, iou=?,
|
||||||
detection_count=?, gt_count=?
|
detection_count=?, gt_count=?
|
||||||
WHERE model_id=? AND model=?
|
WHERE model_id=? AND model=?
|
||||||
""";
|
""";
|
||||||
|
|
||||||
String insertSql =
|
String insertSql =
|
||||||
"""
|
"""
|
||||||
@@ -92,7 +114,7 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
(model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
|
(model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
|
||||||
detection_count, gt_count)
|
detection_count, gt_count)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
""";
|
""";
|
||||||
|
|
||||||
// row 단위 처리 (batch 안에서 upsert)
|
// row 단위 처리 (batch 안에서 upsert)
|
||||||
for (Object[] row : batchArgs) {
|
for (Object[] row : batchArgs) {
|
||||||
@@ -136,6 +158,33 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
.fetchFirst();
|
.fetchFirst();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SimpleMetricJsonDto getSimpleTestMetricPackingInfo(Long modelId) {
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
SimpleMetricJsonDto.class,
|
||||||
|
modelMasterEntity.modelNo,
|
||||||
|
modelMasterEntity.modelVer,
|
||||||
|
Projections.constructor(
|
||||||
|
SimpleProperties.class,
|
||||||
|
modelMetricsTestEntity.f1Score,
|
||||||
|
modelMetricsTestEntity.precisions,
|
||||||
|
modelMetricsTestEntity.recall,
|
||||||
|
modelMetricsTestEntity.iou,
|
||||||
|
modelMetricsTrainEntity.loss)))
|
||||||
|
.from(modelMetricsTestEntity)
|
||||||
|
.innerJoin(modelMasterEntity)
|
||||||
|
.on(modelMetricsTestEntity.model.id.eq(modelMasterEntity.id))
|
||||||
|
.innerJoin(modelMetricsTrainEntity)
|
||||||
|
.on(
|
||||||
|
modelMetricsTestEntity.model.eq(modelMetricsTrainEntity.model),
|
||||||
|
modelMasterEntity.bestEpoch.eq(modelMetricsTrainEntity.epoch))
|
||||||
|
.where(modelMetricsTestEntity.model.id.eq(modelId))
|
||||||
|
.orderBy(modelMetricsTestEntity.createdDttm.desc())
|
||||||
|
.fetchFirst();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ModelTestFileName findModelTestFileNames(Long modelId) {
|
public ModelTestFileName findModelTestFileNames(Long modelId) {
|
||||||
return queryFactory
|
return queryFactory
|
||||||
@@ -168,4 +217,64 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
.where(modelMasterEntity.id.eq(modelId))
|
.where(modelMasterEntity.id.eq(modelId))
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ModelMetricJsonDto getMetricsByEpoch(Long modelId, Integer epoch, String metricType) {
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
ModelMetricJsonDto.class,
|
||||||
|
modelMasterEntity.modelNo,
|
||||||
|
modelMasterEntity.modelVer,
|
||||||
|
com.querydsl.core.types.dsl.Expressions.constant(metricType),
|
||||||
|
com.querydsl.core.types.dsl.Expressions.constant(epoch),
|
||||||
|
Projections.constructor(
|
||||||
|
Properties.class,
|
||||||
|
// Changed 메트릭
|
||||||
|
modelMetricsValidationEntity.changedFscore,
|
||||||
|
modelMetricsValidationEntity.changedPrecision,
|
||||||
|
modelMetricsValidationEntity.changedRecall,
|
||||||
|
// Unchanged 메트릭
|
||||||
|
modelMetricsValidationEntity.unchangedFscore,
|
||||||
|
modelMetricsValidationEntity.unchangedPrecision,
|
||||||
|
modelMetricsValidationEntity.unchangedRecall,
|
||||||
|
// Mean 메트릭
|
||||||
|
modelMetricsValidationEntity.mFscore,
|
||||||
|
modelMetricsValidationEntity.mPrecision,
|
||||||
|
modelMetricsValidationEntity.mRecall,
|
||||||
|
modelMetricsValidationEntity.mIou,
|
||||||
|
modelMetricsValidationEntity.mAcc,
|
||||||
|
// Overall Accuracy
|
||||||
|
modelMetricsValidationEntity.aAcc,
|
||||||
|
// Train 메트릭 (Loss, LR, Duration)
|
||||||
|
modelMetricsTrainEntity.loss,
|
||||||
|
modelMetricsTrainEntity.lr,
|
||||||
|
modelMetricsTrainEntity.durationTime),
|
||||||
|
Projections.constructor(
|
||||||
|
com.kamco.cd.training.train.dto.ModelTrainMetricsDto.TestMetrics.class,
|
||||||
|
modelMetricsTestEntity.model1,
|
||||||
|
modelMetricsTestEntity.tp,
|
||||||
|
modelMetricsTestEntity.fp,
|
||||||
|
modelMetricsTestEntity.fn,
|
||||||
|
modelMetricsTestEntity.precisions,
|
||||||
|
modelMetricsTestEntity.recall,
|
||||||
|
modelMetricsTestEntity.f1Score,
|
||||||
|
modelMetricsTestEntity.accuracy,
|
||||||
|
modelMetricsTestEntity.iou,
|
||||||
|
modelMetricsTestEntity.detectionCount,
|
||||||
|
modelMetricsTestEntity.gtCount)))
|
||||||
|
.from(modelMetricsValidationEntity)
|
||||||
|
.innerJoin(modelMasterEntity)
|
||||||
|
.on(modelMetricsValidationEntity.model.id.eq(modelMasterEntity.id))
|
||||||
|
.leftJoin(modelMetricsTrainEntity)
|
||||||
|
.on(
|
||||||
|
modelMetricsTrainEntity.model.id.eq(modelMasterEntity.id),
|
||||||
|
modelMetricsTrainEntity.epoch.eq(epoch))
|
||||||
|
.leftJoin(modelMetricsTestEntity)
|
||||||
|
.on(modelMetricsTestEntity.model.id.eq(modelId))
|
||||||
|
.where(
|
||||||
|
modelMetricsValidationEntity.model.id.eq(modelId),
|
||||||
|
modelMetricsValidationEntity.epoch.eq(epoch))
|
||||||
|
.fetchOne();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user