# Physical AI Intelligent Platform v3.2 — Feature Guide

> AI-powered Physical Intelligence Platform for Welding Structures & Quality Inspection
> finetheAi | Rainbow Robotics

---

## Table of Contents

1. [Platform Overview](#1-platform-overview)
2. [DASHBOARD & PRODUCTION — Dashboard & Inspection](#2-dashboard--production)
3. [AI STUDIO — AI Model Training](#3-ai-studio)
4. [DATA — Dataset, Labeling & Quick Training](#4-data)
5. [MODELS — Model Hub, Deployment & Monitoring](#5-models)
6. [SYSTEM — Platform Management](#6-system)
7. [ROBOT — Control, Teaching, Telemetry & Simulation](#7-robot)
7.5. [ANALYTICS — Analytics & Reports](#75-analytics)
7.6. [WELDING — Shipbuilding Collaborative Robot](#76-welding)
7.7. [3D STUDIO — CAD Viewer, Modeling & Drawing](#77-3d-studio)
7.8. [AGRI-FARM — Mushroom Cube Farm Automation](#78-agri-farm)
7.9. [EDUCATION — Online Learning Platform](#79-education)
8. [AI Engine — Anomaly Detection & Object Detection](#8-ai-engine)
9. [Authentication & Security](#9-authentication--security)
10. [WebSocket Real-time Communication](#10-websocket-real-time)
11. [Data Storage Paths](#11-data-storage-paths)
12. [API Endpoint Reference](#12-api-endpoint-reference)
13. [Configuration & Settings](#13-configuration--settings)
14. [MULTI-AGENT — Orchestration, Harness Teams & 용접 AI Agent](#14-multi-agent)
15. [Edge Device Streaming & Updates](#15-edge-device-streaming)
16. [UI Updates](#16-ui-updates)
17. [OPS BOARD — Operations & Daily Reports](#17-ops-board)
18. [Pricing & API Keys](#18-pricing--api-keys)
19. [VLM — Vision-Language Inference](#19-vlm)

---

> **What's New (v3.2)** — v3.0 이후 추가된 주요 기능:
> **3D Studio** (CAD Viewer/Design, Format Converter, Measurement, Assembly, URDF Viewer, 2D Drawing) ·
> **Agri-Farm** (표고버섯 큐브팜 AMR 자동화 도메인) · **Education** (온라인 교육 플랫폼) ·
> **Quick Training** (Teachable Machine 방식 YOLO 학습, 23종 모델) · **Robot Telemetry** (실시간 100Hz 스트리밍) ·
> **Auto / Autonomous Teaching** (로봇 동작 녹화·재생, 패턴 생성) · **Digital Twin Recording** (키프레임 기반 녹화/재생) ·
> **Factory 3D Simulator** (드래그앤드롭 레이아웃 + USD/SDF Export) · **Master Orchestrator + Harness Teams** (LangGraph 5팀) ·
> **Ops Board** (AI 일일 운영 리포트) · **API Keys** (X-API-Key 인증) · **Pricing** (요금 정책/시뮬레이터) ·
> **VLM** (Vision-Language 추론) · **Model Monitoring** (PSI 드리프트) · **Threshold Analysis / DOCX Report** ·
> **AI Daily Briefing** (대시보드 위젯) · **Edge Devices** (등록/하트비트/지도/모델 업데이트)

---

## 1. Platform Overview

finetheAi Physical AI Intelligent Platform은 협동 로봇(Rainbow Robotics RB5-850 등)과 연동되는 AI 기반 품질 검사 시스템입니다.

### Architecture

```
┌────────────────────────────────────────────────────────────────────┐
│                        Web Browser (Vue 3 SPA)                       │
│  Dashboard │ AI Studio │ Data │ Models │ 3D Studio │ Robot │ Welding  │
│  Agri-Farm │ Analytics │ Education │ Multi-Agent │ Ops Board │ System  │
└───────────────────────────┬──────────────────────────────────────────┘
                            │ REST API + WebSocket  (X-API-Key / Session)
┌───────────────────────────┴──────────────────────────────────────────┐
│                      FastAPI Server (server/app.py)                    │
│  ┌─────────┐ ┌──────────┐ ┌──────────┐ ┌─────────┐ ┌──────────────┐   │
│  │ Routers │ │ Services │ │ DB (ORM) │ │  Auth   │ │ Multi-Agent  │   │
│  │  (50+)  │ │  (80+)   │ │  SQLite  │ │ API Key │ │  LangGraph   │   │
│  └─────────┘ └──────────┘ └──────────┘ └─────────┘ └──────────────┘   │
└──────┬─────────────┬─────────────┬─────────────┬─────────────┬────────┘
   ┌───┴────┐   ┌────┴─────┐  ┌────┴────┐   ┌────┴─────┐  ┌────┴─────┐
   │AI Engine│  │Robot Ctrl│  │  Edge   │   │ rbpodo   │  │ External │
   │PatchCore│  │RB5-850   │  │ Devices │   │ Bridge   │  │ Ollama   │
   │PaDiM    │  │rbpodo SDK│  │ MQTT    │   │  (WSL)   │  │ MuJoCo   │
   │SPADE    │  │Modbus TCP│  │ Sensors │   │ Physics  │  │Open-Meteo│
   │WinCLIP  │  │DataPort  │  └─────────┘   └──────────┘  └──────────┘
   │EfficientAD│ │ 5001     │
   │FastFlow  │  │Ctrl 5000 │
   │YOLO/VLM   │ └──────────┘
   └──────────┘
```

### Sidebar Menu Structure (13 sections — accordion)

```
📊 Dashboard      → Live Monitor · Quick Inspect · Recipes · Quality Gate · History
🧠 AI Studio      → AD Training · YOLO Training · Experiments · HPO
📁 Data           → Datasets · Labeling · ⚡Quick Training · Preprocessing · Data Collection
📦 Models         → Model Hub · Deployment · Evaluation · Monitoring
📐 3D Studio      → Viewer/Design · Format Converter · Measurement · Assembly · URDF Viewer · 2D Drawing
🤖 Robot          → Fleet · Robots · Telemetry(100Hz) · Auto/Autonomous Teaching · Digital Twin Rec · Tasks · Digital Twin · Line Scan Sim · 3D Simulator
🔥 Welding        → Multi-Robot HMI · 3D Modeling(SLAM) · Welding Digital Twin · Seam Tracking · LLM Robot Control
🍄 Agri-Farm      → Cube Farm Fleet · Farm Dashboard · Growth · Thinning · Harvest · Environment · AMR · GAP Reports
📈 Analytics      → Analytics · Production Analytics · Threshold Analysis · Reports · DOCX Report
🎓 Education      → Catalog · My Courses · Classroom · Lab · Assignments · Certificates · Q&A Board · Admin
🤝 Multi-Agent    → Harness Teams · 🧠Master Orchestrator · Agent Dashboard · 13 Welding Agents
📋 Ops Board      → Daily Reports
⚙️ System (admin) → Edge Devices · Alarms · Monitoring · Projects · Settings · Audit · Pricing · 🔑API Keys · Training Monitor
```

### Entry Points

| Entry Point | Command | Purpose |
|------------|---------|---------|
| Web Server | `python -m server.app --port 8000` | REST API + Web UI |
| Desktop UI | `python -m ui.main_window` | PySide6 standalone |
| CLI | `python main.py inspect <product_id>` | CLI inspection |

---

## 2. DASHBOARD & PRODUCTION

### 2.1 Dashboard (DASHBOARD)

시스템 전체 상태를 한눈에 보여주는 메인 화면.

- **System Status**: 서버 상태, 연결 수, 가동 시간, Fleet 로봇 연결 수
- **Today's Statistics**: 금일 검사 수량, OK/NG 비율, 평균 Cycle Time
- **Recent Results**: 최근 검사 결과 리스트 (날짜/시간 표시)
- **Quick Stats**: KPI 카드 (Total, OK, NG, OK Rate, Throughput items/hour)
- **Service Status Timeline**: 검사 결과 시계열 차트 (OK/NG/Cycle Time)

**API**: `GET /api/status`, `GET /api/statistics?days=1`

#### AI Daily Briefing 위젯 (NEW)

대시보드 상단에 표시되는 AI/ML 뉴스 일일 브리핑 카드.

- **자동 수집**: 매일 아침 `config/assistant_knowledge.yaml`의 소스 URL을 크롤링 → LLM 요약 → 브리핑 생성
- **표시**: 날짜, 생성 시각(KST), 기사 수, 요약(마크다운 렌더), 폰트 크기 조정(A-/A+)
- **Refresh**: 최신 브리핑 다시 로드 / **Run Agent**: 즉시 새 뉴스 수집 (백그라운드)
- **Web Push**: 구독 사용자에게 아침 푸시 알림 (VAPID)

**API**: `GET /api/ai-news/today`, `GET /api/ai-news/list?limit=7`, `GET /api/ai-news/date/{YYYY-MM-DD}`, `POST /api/ai-news/run`

### 2.2 Live Monitor (PRODUCTION)

실시간 검사 모니터링 화면.

- **Camera Feed**: 실시간 카메라 영상 (WebSocket 스트리밍)
- **Step Progress**: 검사 단계별 진행 상태 표시
- **Start/Stop Control**: 검사 시작/중지
- **Real-time Results**: 검사 완료 시 즉시 결과 표시

**API**: `POST /api/inspection/start`, `POST /api/inspection/stop`, `GET /api/inspection/status`
**WebSocket**: `WS /ws/results`

### 2.3 Quick Inspect (PRODUCTION)

빠른 단일 이미지 검사.

- **Model Selection**: PatchCore / PaDiM / YOLO 모델 선택
- **Threshold Tuning**: 실시간 임계값 조정
- **Image Upload**: 드래그 앤 드롭 이미지 업로드
- **Inference Result**: 이상 점수, 히트맵, 판정 결과
- **Remote/Local Mode**: 로컬 또는 원격 서버 추론 지원

**API**: `POST /api/quick-inspect` (multipart: image + model_id + threshold)
**Health**: `GET /api/quick-inspect/health`

### 2.4 History (PRODUCTION)

검사 이력 조회 및 상세 분석.

- **Date Range Filter**: 기간별 필터링
- **Product/Judgment Filter**: 제품별, 판정별 필터링
- **Pagination**: 페이지 단위 탐색 (최대 10,000건 로드)
- **Detail Modal**: 클릭 시 상세 정보 팝업
  - 이전/다음 네비게이션 (◀ ▶ 키보드 단축키)
  - 원본/히트맵 이미지 전체화면 보기
  - 단계별 결과 상세

**API**: `GET /api/results/history?date_from=&date_to=&page=&per_page=`
**Images**: `GET /api/results/image?path=`

### 2.5 Analytics (→ ANALYTICS section)

검사 결과 통계 분석.

- **Period Selection**: Today / 7 Days / 30 Days / Custom
- **KPI Cards**: Total Count, OK Rate, Avg Cycle Time, NG Count
- **Trend Charts**: 시간별/일별 검사 추이
- **Defect Distribution**: 결함 유형별 분포
- **Product Comparison**: 제품별 품질 비교

**API**: `GET /api/statistics?days=`, `GET /api/results/history`

---

## 3. AI STUDIO

### 3.1 Anomaly Detection Training

비지도 학습 기반 이상 탐지 모델 훈련. **6개 알고리즘**을 지원하며, 4개 탭(Train / Evaluate / History / Compare)으로 구성됩니다.

#### 지원 알고리즘 (6종)

| Algorithm | Type | Description |
|-----------|------|-------------|
| **PatchCore** | Memory Bank | Coreset 기반 KNN 이상 탐지. 가장 범용적, 기본 알고리즘 |
| **PaDiM** | Distribution | 위치별 가우시안 분포 (Mahalanobis Distance) |
| **SPADE** | Memory Bank | Sub-Image Anomaly Detection, PatchCore 유사 |
| **WinCLIP** | Zero/Few-shot | CLIP 기반, 텍스트 프롬프트로 이상 탐지 (학습 이미지 선택) |
| **EfficientAD** | Distillation | Teacher-Student 구조, 빠른 추론 속도 |
| **FastFlow** | Normalizing Flow | 2D Normalizing Flow 기반 이상 탐지 |

#### Train 탭

- **Algorithm Selection**: PatchCore (default) / PaDiM / SPADE / WinCLIP / EfficientAD / FastFlow
- **Backbone Selection**: ResNet18, ResNet50, Wide-ResNet50-2, EfficientNet-B4
- **Dataset Configuration**:
  - Train 폴더 (정상 이미지), Test 폴더 (정상+불량, good/ng 서브폴더 구조)
  - 인라인 폴더 브라우저로 경로 선택 (드라이브 탐색 지원)
  - 자동 데이터셋 분석 (이미지 수, OK/NG 수, 해상도)
- **Training Parameters**:
  - Input Size (224, 256, 320, 512)
  - Coreset Ratio (0.01 ~ 1.0) — PatchCore/SPADE용
  - K Neighbors (1 ~ 20) — PatchCore/SPADE용
  - Batch Size
  - Threshold (0.0 ~ 1.0)
- **Real-time Progress**: WebSocket 기반 실시간 진행 표시
  - 단계별 Phase 표시 (Loading → Training → Saving → Evaluation)
  - 경과 시간 표시
  - **Sample Training Images**: 학습 중 어떤 이미지로 학습하는지 2개 샘플 미리보기
  - 실시간 로그 출력
- **Train + Evaluate**: 학습 완료 후 자동으로 평가까지 연속 실행 (선택)
- **Auto Subsampling**: PatchCore/SPADE에서 이미지 300장 초과 시 자동 서브샘플링 (OOM 방지)
- **Model Metadata**: 학습 완료 시 모델 옆에 `.meta.json` 사이드카 파일 + 샘플 썸네일 자동 저장

#### Evaluate 탭

- **Model Selection**: 학습된 모델 파일 (.fpkl, .pth, .pt) 선택
- **Model Info**: 모델 메타데이터 표시 (알고리즘, 백본, 입력 크기, 학습 샘플 이미지)
- **Test Dataset**: OK/NG 이미지가 포함된 테스트 폴더 지정
- **Evaluation Metrics**: AUROC, F1 Score, Precision, Recall, Accuracy
- **Top NG Detections**: 이상 점수가 높은 NG 이미지 2개를 히트맵과 함께 인라인 표시, 클릭 시 전체화면 Heatmap Viewer
- **Confusion Matrix**: TP/FN/FP/TN 시각화 (Positive=OK, Negative=NG 규약)
- **Per-Image Results**: 각 이미지별 예측/실제 라벨, 점수, 히트맵 테이블
- **Heatmap Viewer**: 이미지 클릭 시 전체화면 히트맵 팝업
- **Threshold Simulation**: 임계값 변경 시 OK/NG 분포 및 F1/Precision/Recall 재계산
  - 최적 임계값 자동 탐색 (Best F1 기준)
  - 임계값 테이블 표시
  - Apply 버튼으로 최적 임계값 적용

#### History 탭

- **Training History**: 과거 학습/평가 이력 목록 (최신순)
- **Details Expand**: 각 이력 항목 클릭 시 상세 정보 표시
  - 알고리즘, 백본, 입력 크기, 학습 시간
  - **Training Sample Images**: 해당 모델의 학습 샘플 이미지 썸네일
  - Evaluation 결과 (AUROC, F1, Precision, Recall, Accuracy)
  - Confusion Matrix
  - 모델 파일 경로
- **History 삭제**: 개별 이력 삭제 가능

#### Compare 탭

여러 알고리즘을 동일 데이터셋으로 동시 학습/평가하여 성능 비교.

- **Algorithm Selection**: 6개 알고리즘 중 2개 이상 선택 (체크박스 그리드)
- **Common Parameters**: 공통 Backbone, Threshold, Input Size 설정
- **Dataset**: Train/Test 폴더 공유 (알고리즘 간 동일 조건 보장)
- **Save to History**: 비교 결과를 Training History에 저장 (선택)
- **Real-time Progress**:
  - Overall Progress Bar (전체 진행률)
  - 현재 학습 중인 알고리즘 표시 (Phase, Message, Elapsed, Model Path)
  - 알고리즘별 Status Chip (대기/학습중/평가중/완료/실패)
  - **Sample Training Images**: 학습 중인 이미지 미리보기
  - Compare Log: 알고리즘별 상세 로그
- **Ranking Table**: 완료된 알고리즘을 Composite Score (AUROC 40% + F1 30% + Accuracy 30%) 기준으로 자동 순위 정렬
  - 1위 모델 Gold 하이라이트
  - 각 알고리즘별 AUROC, F1, Precision, Recall, Accuracy, Time 표시
- **Session Persistence**: 비교 결과가 localStorage에 저장되어 페이지 이동 후 돌아와도 마지막 결과 유지

**API**: `POST /api/training/anomaly/start`, `GET /api/training/anomaly/status/{job_id}`
**WebSocket**: `WS /ws/training/anomaly` (학습/평가/비교 모두 동일 WebSocket 사용)

### 3.2 YOLO Training (Object Detection)

YOLOv8/v10 객체 탐지 모델 훈련.

- **Model Selection**: YOLOv8n/s/m/l/x, YOLOv10
- **Data YAML**: YOLO 형식 데이터셋 경로 지정
- **Training Parameters**: Epochs, Batch Size, Image Size, Learning Rate, Optimizer
- **Augmentation**: Mosaic, MixUp, Flip, HSV 등
- **Training Progress**: 실시간 Loss, mAP 그래프
- **Model Export**: 학습 완료 후 ONNX/TensorRT 내보내기
- **Evaluation**: mAP@50, mAP@50-95, Precision, Recall, Confusion Matrix

**API**: `POST /api/yolo/train`, `GET /api/yolo/train/status`

### 3.3 HPO (Hyperparameter Optimization)

Optuna 기반 하이퍼파라미터 자동 최적화.

- **Study Configuration**: Study name, direction (minimize/maximize), metric
- **Sampler Selection**: TPE, Random, Grid, CMA-ES
- **Pruner Selection**: Median, Hyperband, None
- **Search Space Definition**: 각 파라미터별 범위 지정
- **Trial Management**: N trials, timeout 설정
- **Real-time Trial Results**: WebSocket으로 실시간 시도 결과 전송
- **Best Parameters**: 최적 파라미터 자동 추출
- **Parameter Importance**: Optuna importance 분석

**API**: `POST /api/hyperopt/start`, `GET /api/hyperopt/status`
**WebSocket**: `WS /ws/training/hyperopt`

### 3.4 Experiments

학습 실험 추적 및 비교.

- **Experiment List**: 과거 학습 실험 목록
- **Metric Comparison**: 여러 실험의 성능 지표 비교
- **Parameter Diff**: 하이퍼파라미터 차이 분석
- **MLflow Integration**: (선택) MLflow 연동 실험 추적

---

## 4. DATA

### 4.1 Datasets

데이터셋 생성, 업로드, 관리.

- **Create Dataset**: 이름, 설명, 어노테이션 형식 (COCO/YOLO) 지정
- **Image Upload**: 이미지 파일 업로드 (다중 파일 지원)
- **Dataset Split**: Train/Val/Test 자동 분할 (비율 설정)
- **Statistics**: 이미지 수, 클래스 분포, 해상도 분석
- **Versioning**: 데이터셋 버전 관리
- **Auto-Annotate**: YOLO 모델 또는 OpenCV 기반 자동 라벨링

**API**: `GET /api/datasets`, `POST /api/datasets`, `POST /api/datasets/{id}/upload`

### 4.2 Labeling

COCO 형식 어노테이션 편집기.

- **Folder Browser**: 로컬 파일시스템 탐색
- **Image Browser**: 이미지 목록 + 썸네일
- **Annotation Editor**: COCO 형식 어노테이션 보기/편집
- **Format Conversion**: COCO → YOLO 형식 변환
- **Label Templates**: 사전 정의된 라벨 템플릿

**API**: `GET /api/labels/browse`, `POST /api/labels/convert-coco-to-yolo`

### 4.3 Preprocessing

이미지 전처리 파이프라인 관리.

- **Pipeline Creation**: 전처리 작업 순서 정의
- **Operations**: Resize, Normalize, Crop, Rotate, Blur, Threshold, CLAHE 등
- **Augmentation**: Flip, Color Jitter, Noise, Mosaic, MixUp
- **Pipeline Application**: 데이터셋에 파이프라인 일괄 적용
- **Preview**: 전처리 결과 미리보기

**API**: `GET /api/preprocessing/operations`, `POST /api/preprocessing/preview`

### 4.4 Quick Training (⚡ NEW) — Teachable Machine 방식

이미지 업로드 → 클래스 정의 → 바운딩 박스 라벨링 → YOLO 학습 → 모델 다운로드를 플랫폼 안에서 끝내는 노코드 학습 도구. 외부 API Key로도 호출 가능 (공개 문서 `/public-docs/quick-train-api`).

- **23종 베이스 모델 지원**:
  - YOLO11 (n/s/m/l/x — 최신, 권장), YOLOv10 (n/s/m/b/l/x — NMS-free)
  - YOLOv9 (t/s/m/c/e), YOLOv8 (n/s/m/l/x — 안정), RT-DETR (l/x — Transformer 기반)
- **워크플로우**:
  1. 세션 생성 (사용자별 격리)
  2. 이미지 배치 업로드 (JPEG/PNG/BMP, 파일당 20MB)
  3. 클래스 정의 (이름 + 색상)
  4. 이미지별 바운딩 박스 라벨링 (픽셀 좌표 → YOLO 정규화 자동 변환)
  5. 학습 시작 (백그라운드, 서버 전역 동시 학습 최대 2개)
  6. 진행 상태 폴링 (epoch, mAP50/50-95, Precision, Recall)
  7. 모델 다운로드 (pt/onnx/torchscript/engine/tflite)
  8. Edge 디바이스로 배포
- **학습 파라미터**: epochs(10~500), imgsz(320~1280), batch(1~64), patience(early stop), lr0, optimizer(auto/SGD/Adam/AdamW)
- **인증**: `X-API-Key` (scope: `quick-train`) 또는 세션 쿠키

**API**: `POST /api/quick-train/sessions`, `POST /api/quick-train/sessions/{sid}/images`, `POST /api/quick-train/sessions/{sid}/classes`, `POST /api/quick-train/sessions/{sid}/labels/{img_id}`, `POST /api/quick-train/sessions/{sid}/train`, `GET /api/quick-train/sessions/{sid}/status`, `GET /api/quick-train/sessions/{sid}/download/{fmt}`, `GET /api/quick-train/defaults`, `GET /api/quick-train/concurrency`

### 4.5 Data Collection (NEW)

검사 파이프라인에서 자동으로 이미지를 수집하는 잡(Job) 관리.

- **Capture Mode**: `all` / `ok_only` / `ng_only`
- **Sampling Rate**: 1~100% 샘플링
- **Max Images**: 잡당 최대 수집 수 제한
- **Product Filter**: 특정 제품 ID만 수집
- **Hook 연동**: 검사 완료(`on_inspection_result`) 시 활성 잡이 판정/제품을 필터링하여 대상 폴더로 복사
- **Real-time Status**: 진행률, 수집 수

**API**: `GET /api/data-collection/jobs`, `POST /api/data-collection/jobs`, `PUT /api/data-collection/jobs/{id}`, `POST /api/data-collection/jobs/{id}/start`, `POST /api/data-collection/jobs/{id}/stop`, `GET /api/data-collection/jobs/{id}/status`

---

## 5. MODELS

### 5.1 Model Hub

모델 레지스트리 및 버전 관리.

- **Model Registry**: 모든 학습된 모델 목록
- **Model Types**: PatchCore, PaDiM, SPADE, WinCLIP, EfficientAD, FastFlow, YOLO, Custom
- **Version Management**: 모델 버전별 관리
- **Performance Metrics**: 각 모델의 성능 지표 (AUROC, F1, mAP 등)
- **Model Comparison**: 두 모델의 성능 비교
- **Metadata**: 알고리즘, 백본, 입력 크기, 학습 설정, 데이터셋 정보, 생성 일시
- **Training Sample Images**: 모델이 학습된 샘플 이미지 썸네일 표시 (`.meta.json` 사이드카 파일 기반)

**API**: `GET /api/models`, `GET /api/models/{id}`, `GET /api/models/compare`

### 5.2 Deployment

모델 내보내기 및 배포.

- **ONNX Export**: PyTorch → ONNX 변환
- **TensorRT Export**: ONNX → TensorRT 최적화 (FP16/INT8)
- **Target Management**: 배포 대상 장치 관리
- **Deploy**: 모델을 대상 장치에 배포

**API**: `POST /api/deployment/export`, `POST /api/deployment/deploy`

### 5.3 Model Evaluation

모델 성능 평가. (Training 페이지의 Evaluate/Compare 탭에서도 동일 기능 사용 가능)

- **Test Dataset Selection**: 평가용 데이터셋 선택 (good/ng 서브폴더 구조)
- **Metrics**: AUROC, F1 Score, Precision, Recall, Accuracy
- **Top NG Detections**: 이상 점수가 높은 NG 이미지 히트맵 미리보기
- **Threshold Analysis**: 최적 임계값 탐색 (Best F1 기준)
- **Confusion Matrix**: 혼동 행렬 시각화 (Positive=OK, Negative=NG)
- **Per-Image Results**: 각 이미지별 결과 테이블 + 히트맵 뷰어
- **A/B Comparison**: Compare 탭에서 6개 알고리즘 동시 비교 및 Ranking

### 5.4 Model Monitoring (NEW)

운영 중인 모델의 추론 통계 및 데이터 드리프트 모니터링.

- **Summary**: 모델별 추론 횟수, 평균 점수, 평균 지연(ms), OK Rate, OK/NG 수
- **Time-series Metrics**: 일/시간 단위 버킷 (count, avg/p95 score, latency, OK/NG)
- **PSI Drift**: Population Stability Index 기반 드리프트 분석 (baseline vs recent 분포 비교) — PSI가 높을수록 분포 변화 큼
- **데이터 소스**: StepResultDB(step_name=model_id) + InspectionResultDB

**API**: `GET /api/models/monitoring/summary`, `GET /api/models/monitoring/{model_id}/metrics?date_from=&date_to=&bucket=day|hour`, `GET /api/models/monitoring/{model_id}/drift?baseline_days=30&recent_days=7`

---

## 6. SYSTEM

> **Note:** Robots와 Simulation(Digital Twin)은 Phase 1에서 ROBOT 섹션으로 이동했습니다. 하위 호환을 위해 여기에도 유지합니다.

### 6.1 Robots

로봇 등록, 제어, 스테이션 관리.

- **Robot Registration**: IP, Port, 로봇 타입 등록
- **Connection Control**: 연결/해제
- **Jog Control**: 조인트별 / 직교 좌표 조그 이동
- **Teach Points**: 교시점 저장/호출
- **Motion Sequences**: 동작 시퀀스 생성 (LINEAR/JOINT/ARC/BLEND)
- **3D Visualization**: Three.js 기반 3D 로봇 뷰어
- **Calibration**: TCP (3점), Hand-Eye (Tsai/Shah), Work Frame
- **Modbus TCP**: PLC 연동 (DIO, User Register, Speed 제어)
- **Activity Statistics**: 가동률, 작업 이력, 활동 통계
- **Station Management**: 검사 스테이션 등록/관리

**API**: `GET /api/robots`, `POST /api/robots/{id}/connect`, `POST /api/robots/{id}/jog`

### 6.2 Alarms

알람 규칙 관리 및 이벤트 이력.

- **Alarm Rules**: 조건 기반 알람 규칙 생성
  - 조건: NG Rate > threshold, Cycle Time >, Model Score <
  - 심각도: Critical, Warning, Info
  - 알림 채널: Sound, Email, Slack, PLC
- **Active Alarms**: 현재 활성 알람 목록
- **Alarm History**: 과거 알람 이력 (날짜 필터링)
- **Acknowledge**: 알람 확인 처리

**API**: `GET /api/alarms`, `POST /api/alarms/rules`, `POST /api/alarms/{id}/acknowledge`
**WebSocket**: `WS /ws/alarms`

### 6.2.1 Line Scan Cycle Simulator (NEW)

라인 스캔 카메라 + 회전 샤프트(ETC Shaft 등) 1 Cycle 촬영시간 시뮬레이션.

- **위치**: 사이드바 `Robot` → `🎥 Line Scan Sim` (URL: `/linescan-sim`)
- **설명 카드**: Area Scan vs Line Scan 차이, Line Rate / Frame Rate 의미를 화면 상단에 표시
- **입력 파라미터**:
  - 카메라: Line Rate(kHz), Pixels/line, Frame height, Bit depth, Channels
  - 모션: Motor RPM, Revolutions
  - 제품: Shaft Diameter, Length, Target μm/pixel
  - 보조 시간: Load / Align / AI Judge / Eject (sec)
- **산출**:
  - 1 Cycle Time (ms / s) — Scan/Aux 구간 분해 막대
  - Throughput (parts/h, /min, 8h shift, 24h)
  - 원주방향·축방향 Pixel Pitch (μm/pixel)
  - 카메라 Data Rate (MB/s, GB/min)
  - 회전당 이미지 크기 (W × H px, MB/rev)
  - 효과 fps (line_rate / frame_height)
- **판정**: OK / WARN / FAIL — 목표 해상도 충족 여부
- **권장값**: 현재 RPM 기준 권장 라인레이트, 현재 라인레이트 기준 권장 RPM
- **RPM Sweep**: 설정 RPM ±2배 구간을 자동 sweep하여 SVG 차트 + 표로 비교
- **Presets**: ETC Shaft / CV Joint Drive Shaft / Brake Rotor Hub / Ear-band

**핵심 식 (Line Scan + 회전축 표준 셋업)**:
```
period_sec       = 60 / RPM
lines_per_rev    = LineRate(Hz) × period_sec
required_lines   = π × Diameter / target_pixel_um (mm/μm 환산)
achieved_pixel   = π × Diameter / lines_per_rev
cycle_total      = load + align + (period × revolutions) + judge + eject
```

**API**:
- `POST /api/simulation/line-scan/cycle` — 1 Cycle 시뮬레이션
- `GET /api/simulation/line-scan/sweep?rpm_min=&rpm_max=&...` — RPM sweep
- `GET /api/simulation/line-scan/presets` — 제품 프리셋 목록

### 6.3 Simulation (Digital Twin 3D)

3D 디지털 트윈 기반 생산 라인 시뮬레이션.

- **3D Scene**: Three.js 기반 실시간 3D 렌더링
  - 컨베이어 벨트 (UV 애니메이션)
  - RB5-850 6-DOF 로봇팔 (관절 키프레임 보간)
  - 비전 카메라 스테이션 (검사 플래시 효과)
  - OK/NG 분류 박스
  - 제품 흐름 (생성 → 이송 → 검사 → 분류 → 완료)
- **Simulation Engine**: Client-side State Machine
  - Product States: SPAWN → CONVEYOR_MOVE → INSPECTING → WAIT_FOR_SORT → ROBOT_HOLD → DONE
  - Robot States: IDLE → MOVING_TO_PICK → PICKING → MOVING_TO_PLACE → PLACING → RETURNING
- **Controls**: Play/Pause/Reset/Step, Speed (1x/2x/4x)
- **View Presets**: Top, Front, Side, Isometric (OrbitControls)
- **Configuration Panel**: Cycle Time, Defect Rate, Conveyor Speed, Robot Speed, Inspection Time
- **Dashboard**: Real-time KPI (Throughput, OK Rate, Cycle Time, Utilization)
- **Charts**: Throughput Line Chart (60 datapoints), OK/NG Donut Chart
- **Event Log**: 최근 50개 이벤트 타임스탬프 로그

**API**: `GET /api/simulation/dt-config`, `POST /api/simulation/dt-config`, `GET /api/simulation/dt-stats`

### 6.4 Monitoring

시스템 리소스 모니터링.

- **CPU Usage**: 코어별 사용률
- **Memory**: RAM 사용량 / 전체
- **Disk**: 디스크 사용량 / 전체
- **GPU**: CUDA 메모리, GPU 사용률, 온도
- **Uptime**: 서버 가동 시간
- **Connections**: 활성 WebSocket 연결 수
- **PyTorch/CUDA**: 버전 정보

**API**: `GET /api/monitoring/status`, `GET /api/monitoring/gpu`, `GET /api/monitoring/resources`
**WebSocket**: `WS /ws/monitoring`

### 6.5 Recipes

검사 레시피 관리.

- **Recipe List**: 등록된 레시피 목록
- **Recipe Details**: 레시피 단계, 파라미터, 대상 제품
- **Product List**: 등록된 제품 목록

**API**: `GET /api/recipes`, `GET /api/products`

### 6.6 Reports

검사 보고서 생성 및 다운로드.

- **Templates**: Daily, Weekly, Monthly, Quality Analysis, Defect Analysis
- **Date Range**: 기간별 필터링 (Today, This Week, This Month, Quarter)
- **Product Filter**: 특정 제품만 포함
- **Output Format**: PDF (HTML), Excel (.xlsx), CSV
- **Sections**: Summary, Charts, Details, Images, Alarms
- **Report History**: 생성된 보고서 목록, 다운로드, 삭제
- **Auto Download**: 생성 완료 시 자동 다운로드

**API**: `POST /api/reports/generate`, `GET /api/reports/templates`, `GET /api/reports`, `GET /api/reports/{id}?download=true`

### 6.7 Projects

프로젝트 관리.

- **Create/List/Update/Delete**: 프로젝트 CRUD
- **Project Organization**: 데이터셋, 모델, 실험을 프로젝트 단위로 관리

**API**: `GET /api/projects`, `POST /api/projects`

### 6.8 Settings

시스템 설정.

- **Stream Settings**: 해상도 (480p/720p/1080p), 품질
- **Model Thresholds**: 기본 임계값
- **Path Settings**: 데이터셋/모델/결과 저장 경로
- **Feature Toggles**: 원격 추론, 클라우드 동기화, HPO 활성화

**API**: `GET /api/settings`, `PUT /api/settings`

### 6.9 Audit Log

사용자 활동 추적.

- **Action Logging**: 모든 사용자 작업 자동 기록
- **Filter**: 사용자, 액션 유형, 날짜 범위
- **CSV Export**: 감사 로그 CSV 내보내기
- **Notifications**: 시스템 알림 목록, 읽음 처리

**API**: `GET /api/audit/logs`, `GET /api/audit/logs/export`

### 6.10 추가 System 메뉴 (NEW)

SYSTEM 섹션(관리자 전용)에 추가된 항목 — 상세는 각 섹션 참조:

| 메뉴 | URL | 상세 |
|------|-----|------|
| **Edge Devices** | `/edge-devices` | [15.5 Edge Device Management](#15-edge-device-streaming) |
| **Pricing Policy / Simulator** | `/pricing-policy`, `/pricing-simulator` | [18.1 Pricing](#18-pricing--api-keys) |
| **🔑 API Keys** | `/api-keys` | [18.2 API Keys](#18-pricing--api-keys) |
| **⚡ Training Monitor** | `/training-monitor` | 전역 학습 작업 모니터 (Quick Train 동시 학습 슬롯 등) |

---

## 7. ROBOT

### 7.1 RB5-850 Robot Control

Rainbow Robotics RB5-850 협동 로봇 제어.

| Feature | Description |
|---------|-------------|
| **TCP Socket** | rbpodo SDK 기반 실시간 통신 (기본 IP: 10.0.2.7:5000) |
| **6-DOF Joint Control** | 6축 관절 개별 제어 |
| **Cartesian Control** | XYZ + RxRyRz 직교 좌표 제어 |
| **Jog Mode** | Step (증분) / Continuous (속도) 모드 |
| **Teach Points** | 교시점 저장/호출/삭제 |
| **Motion Sequences** | LINEAR, JOINT, ARC, BLEND 동작 시퀀스 |
| **Simulation Mode** | 실제 로봇 없이 시뮬레이션 동작 |

### 7.2 Calibration

| Method | Description |
|--------|-------------|
| **TCP Calibration** | 3점법으로 TCP(Tool Center Point) 보정 |
| **Hand-Eye Calibration** | Tsai/Shah 알고리즘 (Eye-in-Hand, Eye-to-Hand) |
| **Work Frame Calibration** | 작업 좌표계 정의 |

### 7.3 Modbus TCP (PLC Integration)

| Feature | Description |
|---------|-------------|
| **Connect/Disconnect** | Modbus TCP 서버 연결 |
| **DIO Read/Write** | 디지털 입출력 제어 |
| **User Registers** | 사용자 레지스터 읽기/쓰기 |
| **Speed Control** | 로봇 속도 조정 |
| **Jog via Modbus** | Modbus 경유 조그 명령 |

### 7.4 Coordinate Transform

| Feature | Description |
|---------|-------------|
| **4x4 Homogeneous Matrix** | 좌표 변환 행렬 |
| **TCP Offset** | 툴 오프셋 적용 |
| **Work Frame** | 작업 좌표계 변환 |
| **Hand-Eye** | 카메라-로봇 좌표 변환 |
| **Pose Conversions** | Euler ↔ Matrix 변환 |

### Fleet Dashboard

여러 로봇을 한 화면에서 모니터링.

- **Fleet Overview**: 총 로봇 수, 연결 수, 평균 가동률
- **Activity Timeline**: 로봇별 작업 이력 (시스템 이벤트 fallback)
- **Robot Cards**: TCP/Modbus 연결 배지, 상태, 마지막 활동

**API**: `GET /api/robots/fleet/summary`, `GET /api/robots/fleet/activity`

### Robot Telemetry (100Hz Streaming, NEW)

로봇 관절/TCP 포즈/힘 데이터를 실시간 스트리밍. 기본 10Hz 폴링(녹화 시 최대 50~100Hz).

- **3-tier 소스 우선순위**: RB Data Port(5001) → rbpodo Bridge → Control Script TCP → mock(사인파 시뮬레이션)
- **Ring Buffer**: 최근 1000 샘플 보관
- **Subscribe 콜백**: Auto Teaching / Digital Twin Recording이 구독하여 동시 녹화
- **Gripper 상태** 포함 (width_mm, closed, grip)
- **샘플 필드**: joint_positions, joint_velocities, tcp_pose, tcp_force, gripper, robot_state_code, moving, error

**API**: `GET /api/robot/telemetry/latest`, `GET /api/robot/telemetry/history?n=100`, `POST /api/robot/telemetry/start`, `POST /api/robot/telemetry/stop`
**WebSocket**: `WS /ws/robot/telemetry` (서버→클라: `telemetry`/`status`/`pong`, 클라→서버: `ping`/`pause`/`resume`)

### Auto Teaching (🔴 NEW)

로봇을 수동으로 교시(조그/펜던트)하며 동작을 녹화한 뒤, 녹화와 독립적인 속도/가속으로 재생.

- **실시간 캡처**: 텔레메트리 콜백 10Hz (rbpodo Bridge 연동 시 50Hz + blend 정확 녹화)
- **재생 모드**: `servo_stream`(rbpodo move_jb2 배치, 최고 충실도), `joint_rel`, `linear_rel`, blended 모드
- **이벤트 자동 감지**: Dwell(정지, <1°/s 0.3초), Gripper 위치 변화
- **재생 설정 분리**: 동일 궤적을 다른 속도로 재생 (speed, acceleration, speed_ratio, blend_deg)
- **Safe Start**: 재생 전 첫 웨이포인트로 자동 이동 (관절당 최대 45°)
- **Command Preview**: 정확한 RB Script 명령 시퀀스(move_j/move_jb/wait/gripper_macro) 생성

**API**: `POST /api/robot/auto-teaching/record/start|stop`, `GET /api/robot/auto-teaching/record/status`, `GET /api/robot/auto-teaching/recordings`, `GET /api/robot/auto-teaching/recordings/{id}/commands`, `PUT .../playback-config`, `POST .../recordings/{id}/play`, `POST /api/robot/auto-teaching/play/stop`, `GET /api/robot/auto-teaching/play/progress`
**저장**: `server/data/auto_teaching/recordings.json`

### Autonomous Teaching (✨ NEW)

사용자 지정 파라미터로 정형 동작 패턴(원, 직선, 용접 위빙, 댄스 등)을 자동 생성. Auto Teaching과 동일한 녹화 포맷으로 출력되어 통합 재생.

- **15+ 파라메트릭 패턴**: circle, rectangle, line_sweep, spiral, raster_scan, welding_weave, wave_dance, free_demo, joint_cycle 등
- **Workspace 검증**: 관절/TCP 경계 초과 시 reject/clip/warn
- **CCD IK**: 직교 패턴(원 → TCP → 관절) 역기구학
- **Workspace 유도**: Auto Teaching 녹화에서 경계 자동 산출 (margin 적용)
- **저장**: source=`autonomous:<pattern_id>` 로 영구 녹화 저장

**API**: `GET /api/robot/autonomous-teaching/patterns`, `POST /api/robot/autonomous-teaching/generate`, `POST /api/robot/autonomous-teaching/execute`, `POST /api/robot/autonomous-teaching/save`, `GET|PUT /api/robot/autonomous-teaching/workspace`, `POST /api/robot/autonomous-teaching/suggest-safe-params`

### Digital Twin Recording (📹 NEW, Phase I)

실제 로봇 동작만(mock 자동 제외) 타임라인 프레임으로 녹화하고, 각도/시간 임계값 기반으로 키프레임을 추출하여 실제 로봇으로 재생. `Digital_twin_pc`와 호환.

- **녹화**: 5~100Hz(기본 30Hz), mock 샘플 자동 스킵
- **키프레임 추출**: 최대 각도 스텝(기본 5°), 최대 시간 스텝(기본 2s), 정지 프레임 임계값
- **재생 모드**: `move_j`(절대), `move_jb`(blend), `move_j_rel`, `jointall`(정규화), `move_lb_batch`(선형 blend 배치)
- **모션 핸드셰이크**: Data Port 5001로 모션 시작/종료 확인(충돌 방지), KF 단위 안전 핸드셰이킹
- **Re-extract**: 임계값 조정 후 타임라인에서 키프레임 재계산

**API**: `GET /api/twin-rec/list`, `POST /api/twin-rec/start|stop`, `GET /api/twin-rec/status`, `GET /api/twin-rec/{name}`, `POST /api/twin-rec/{name}/re-extract-keyframes`, `POST /api/twin-rec/{name}/play`, `POST /api/twin-rec/play/abort`, `GET /api/twin-rec/play/status`
**저장**: `server/data/twin_recordings/`

### Unified Tasks (NEW)

도메인 무관 통합 Task 추상화 계층 — 로봇 잡/작업 관리.

- **상태 흐름**: pending → running → completed/failed/cancelled
- **Task Type**: domain + type 태그 (예: domain=robot, type=auto-teaching)
- **Robot Queue**: 로봇별 대기 작업을 우선순위 + scheduled_at 순으로 정렬
- **Filtering**: status, domain, robot_id, type, parent_task_id
- **Summary**: status/domain/type별 카운트

**API**: `GET /api/tasks`, `POST /api/tasks`, `GET /api/tasks/summary`, `GET /api/tasks/queue/{robot_id}`, `PUT /api/tasks/{id}`, `POST /api/tasks/{id}/start|complete|fail|cancel`

### Factory 3D Simulator (🏭 NEW)

드래그앤드롭 공장 레이아웃 에디터 + 시나리오 기반 시뮬레이션.

- **Layout CRUD**: 로봇/컨베이어/테이블/카메라/커스텀 GLB 장비 배치 (TransformControls Gizmo)
- **장비 카탈로그**: RB5-850(그리퍼 포함), 컨베이어, 카메라, 작업대, 제품 빈 등
- **Scenario**: 명명된 동작 시퀀스, Auto Teaching 녹화 임포트, 수동 스텝 추가
- **FK/IK**: 6축 정/역기구학 (CCD)
- **검증**: BBox 충돌 감지, Cycle Time 추정, 가동률 계산
- **Palletize 매크로**: N×M×L 적재 시퀀스 자동 생성
- **Snapshot**: 가상 카메라 캡처(PNG/JPG)
- **Vision Detect**: 카메라 FOV 대비 형상 검사
- **Synthetic Data**: 시뮬레이션 기반 합성 데이터셋 + COCO Export
- **Export**: RB Control Script · USD(Pixar) · SDF(Gazebo) · 리포트(MD/JSON)
- **Sim2Real Calibration**: 오프셋 분석

**API**: `GET /api/factory-sim/catalog`, `GET|POST|PUT|DELETE /api/factory-sim/layouts`, `.../scenarios`, `POST /api/factory-sim/fk|ik|validate`, `POST /api/factory-sim/palletize/generate`, `POST /api/factory-sim/program/export`, `POST /api/factory-sim/usd/export`, `POST /api/factory-sim/sdf/export`, `POST /api/factory-sim/synthetic/datasets/{id}/export-coco`
**저장**: `server/data/factory_layouts|factory_scenarios|factory_snapshots|factory_glb|factory_programs|factory_reports|factory_usd|factory_sdf/`

### rbpodo Bridge & Physics Bridge (백엔드 인프라)

| Bridge | 역할 |
|--------|------|
| **rbpodo Bridge** | WSL Linux 데몬(localhost:9000) 프록시 — 고속 관절 서보(`servo_j`) 및 batch `move_jb2` blend 재생(`replay_jb2_sync`). Phase G 연동. Auto-probe로 WSL IP 탐색, 4-method 진단 |
| **Physics Bridge** | MuJoCo 헤드리스 물리 엔진(kinematic fallback) — 레이아웃 30Hz 상태 스트리밍 |

**rbpodo API**: `GET /api/rbpodo/status|state|capabilities`, `POST /api/rbpodo/connect|disconnect|stop|move_j|servo_j|auto-probe|diagnose` · **WS** `/ws/rbpodo/stream`
**physics API**: `GET /api/physics/capabilities|state`, `POST /api/physics/start|stop|reset|control` · **WS** `/ws/physics`

---

## 7.5 ANALYTICS

### 7.5.1 Analytics
검사 결과 통계 분석. (2.5 Analytics와 동일 — ANALYTICS 메뉴에서 접근)

### 7.5.2 Production Analytics (NEW)
OEE (Overall Equipment Effectiveness) 기반 생산 효율 분석.
- **OEE Gauge**: Availability × Performance × Quality
- **Throughput Chart**: 시간대별 처리량 추이
- **Cycle Time Analysis**: 히스토그램 + 평균/최소/최대/표준편차

**API**: `GET /api/analytics/oee`, `GET /api/analytics/throughput`, `GET /api/analytics/cycle-time`

### 7.5.3 Threshold Analysis (NEW)

두 개의 `inspection_results.csv` 파일을 나란히 비교하여 최적 임계값을 제안.

- **자동 수치 필드 감지**: 메타데이터(Timestamp, Recipe_Name, Barcode, Status 등) 제외
- **필드별 통계**: min/max/mean/median/std/p5/p25/p75/p95
- **Histogram**: 5~100 bins (조정 가능)
- **임계값 제안**: midpoint, weighted, Otsu-style(클래스 간 분리 최대화), separation_z 점수
- **Overlap Range**: 두 분포의 중첩 구간 감지
- **정렬**: separation_z 내림차순으로 가장 잘 분리되는 필드 우선 표시

**API**: `POST /api/threshold-analysis/compare` (CSV 2개 업로드)

### 7.5.4 Reports
검사 보고서 생성 및 다운로드. (6.6 Reports와 동일 — ANALYTICS 메뉴에서 접근)

### 7.5.5 DOCX Report (NEW)

샘플 평가 워크플로우용 검증 보고서 DOCX 생성 (표지 + 섹션 + 도면).

- **Template Browser**: `reports/Template/*.docx` 템플릿 탐색
- **Dataset Analyzer**: train/test/model/score_images 구조 분석 (이미지 수, 결함 유형)
- **Figure 관리**: 도면 이미지 업로드 + 미리보기, 자동 번호 매김
- **Confusion Matrix**: `evaluation_results.csv`에서 계산
- **Cover Page**: 회사명, 버전, 고객, 제품, P/N, 제출일, 로고
- **Report History**: 생성 이력 (JSON 영속, 최대 20개)

**API**: `GET /api/reports/docx/templates`, `POST /api/reports/docx/figures`, `POST /api/reports/docx/analyze-dataset`, `POST /api/reports/docx/generate`, `GET /api/reports/docx/reports`, `GET /api/reports/docx/download/{report_id}`

---

## 7.6 WELDING — 조선용 협동로봇 중점과제

> **"조선용 협동로봇의 중소조선소 현장 운용 시스템 개발"** 과제 5개 개발 내용 통합 메뉴

### 7.6.1 Multi-Robot HMI (`/welding-hmi`)

다종 협동로봇 HMI 및 지능형 통합 플랫폼.

- **Multi-Vendor Integration**: 3개 제조사 이상 (Rainbow Robotics, Universal Robots, FANUC 등) 로봇 통합 운용
- **Unified Control Panel**: 제조사 무관 통합 제어 인터페이스
- **Connection Management**: 다종 로봇 연결 상태 모니터링
- **Robot Grid**: 등록된 로봇 목록, 상태, 페이로드, IP 정보

**API**: `GET /api/welding/hmi/robots`

### 7.6.2 3D Modeling (`/welding-modeling`)

센서 기반 용접 대상물 모델링 자동화 + **SLAM** 통합 (7탭).

- **3D Point Cloud**: 3D 스캔/포인트클라우드 기반 블록 형상 자동 인식 (Three.js 포인트클라우드 뷰어)
- **Modeling Jobs**: 모델링 작업 목록 (상태, 진행률, 포인트 수)
- **Auto Recognition**: 블록 내부 형상 자동 인식·모델링 파이프라인
- **SLAM 파이프라인**: 프레임 → 다운샘플 → ICP 정합 → 포즈 추정 → 맵 누적 (Open3D/kiss-icp, numpy fallback)
- **용접선 감지**: RANSAC + DBSCAN
- **경로 계획**: A* + RRT (점유 그리드 2D 캔버스)
- **7 탭**: Scan Jobs · Sensors · SLAM Map · Navigation · Weld Seams · Weld Paths · Settings

**API**: `GET /api/welding/modeling/jobs`, `/api/welding/slam/*` (18 endpoints: 세션4/스캔4/맵4/용접선2/경로4)
**WebSocket**: `WS /ws/slam` (실시간 프레임 처리, 포즈 업데이트)

### 7.6.3 Welding Digital Twin (`/welding-digital-twin`)

디지털 트윈 기반 로봇 운용 프로그램 검증 시스템.

- **3D Simulation Viewport**: Three.js 기반 용접 시뮬레이션 뷰어
- **Path Planning**: 용접 경로 계획 및 시각화
- **Collision Detection**: 가상 환경 사전 충돌 검사
- **Thermal Visualization**: 열 분포 시각화

**API**: `GET /api/welding/digital-twin/simulations`

### 7.6.4 Seam Tracking (`/welding-seam-tracking`)

용접선 인식/추적 및 자세별 용접품질 제어.

- **Vision-based Detection**: 비전 센서 기반 용접선 자동 인식
- **Real-time Tracking**: 실시간 용접선 추적
- **Quality Monitoring**: 자세별 용접 품질 모니터링
- **Statistics**: 일별 용접선 수, 평균 품질, 결함 수, 총 길이

**API**: `GET /api/welding/seam-tracking/status`

### 7.6.5 LLM Robot Control (`/welding-llm`)

AI 기반 언어모델을 활용한 용접 협동로봇 운용.

- **Natural Language Input**: 자연어 명령 입력 인터페이스
- **Program Generation**: 자연어 → 로봇 프로그램 자동 생성
- **Command History**: LLM 명령 이력 (입력, 생성 프로그램, 실행 상태)
- **Safety Verification**: 생성된 프로그램 안전 검증

**API**: `GET /api/welding/llm/history`

---

## 7.7 3D STUDIO — CAD Viewer, Modeling & Drawing

> **NEW** — STEP/IGES/STL 등 3D 파일 뷰어 + 파라메트릭 모델링 + 2D 도면 생성을 통합한 독립 대분류. 6개 하위 메뉴.

### 7.7.1 Viewer / Design (`/cad-viewer`)

3D CAD 파일 뷰어(View 모드) + 파라메트릭 모델링(Design 모드) 통합.

- **지원 포맷**: STEP, IGES, STL, OBJ, GLB, 3MF, PLY (업로드 최대 100MB)
- **View 모드**: GLB 변환(low/medium/high tessellation) 후 Three.js 렌더링
- **Design 모드**: 프리미티브 생성(Box/Cylinder/Sphere/Cone/Torus/Wedge), Boolean(Union/Cut/Intersect), Fillet/Chamfer, Transform(Translate/Rotate/Mirror)
- **Feature Tree**: Undo/Redo 히스토리
- **Export**: STEP 저장, GLB 미리보기
- **View↔Design 연동**: 열린 파일 자동 임포트 제안

**API**: `POST /api/cad-viewer/upload`, `GET /api/cad-viewer/files`, `POST /api/cad-viewer/convert/{id}`, `GET /api/cad-viewer/glb/{id}` · Design: `POST /api/cad-studio/sessions`, `.../primitives`, `.../boolean`, `.../fillet`, `.../chamfer`, `.../undo|redo`, `GET .../export/step`

### 7.7.2 Format Converter (`/3d-converter`)

CAD 포맷 간 변환 (드래그앤드롭).

- **입력**: STEP/STP, IGES/IGS, STL, OBJ, 3MF, PLY → **출력**: GLB, STL, OBJ, STEP
- **Quality**: low/medium/high
- **변환 이력**: JSON 로그 (최대 100개)

**API**: `POST /api/3d-studio/convert?target_format=&quality=`, `GET /api/3d-studio/convert/download/{filename}`, `GET /api/3d-studio/convert/history`, `GET /api/3d-studio/convert/formats`

### 7.7.3 Measurement (`/3d-measurement`)

3D 모델의 기하/물리 속성 추출.

- **부피(mm³) / 표면적(mm²) / Bounding Box / 무게중심**
- **Watertight 메시 판정**
- **재질별 무게 추정**: Steel, Aluminum, Copper, Titanium, ABS, PLA
- **Dual-engine**: OCP B-Rep 우선, trimesh fallback

**API**: `POST /api/3d-studio/measure`

### 7.7.4 Assembly (`/3d-assembly`)

다중 부품 어셈블리 구성.

- **부품 추가** + 위치/회전 변환 (position [x,y,z], rotation [rx,ry,rz])
- **부품별 GLB 변환** 시각화
- **Tree View**: 부품/구속조건

**API**: `GET /api/3d-studio/assembly/list`, `POST /api/3d-studio/assembly/create`, `POST /api/3d-studio/assembly/{id}/add-part`, `GET /api/3d-studio/assembly/{id}`

### 7.7.5 URDF Viewer (`/3d-urdf`)

로봇 URDF 모델 검사/관리.

- **업로드**: `.urdf`, `.xacro`, `.zip` 패키지
- **파싱**: 관절 계층(type, parent/child, DOF limit, axis), 링크 계층(visual/collision 메시)
- **모델 목록**: `robot_data/urdf/` 의 URDF 모델

**API**: `POST /api/3d-studio/urdf/upload`, `GET /api/3d-studio/urdf/list`, `GET /api/3d-studio/urdf/{id}/info`

### 7.7.6 2D Drawing (`/3d-drawing`)

3D 모델 → 제조용 2D 기술 도면 생성.

- **정투상**: Front/Top/Right/Left/Bottom/Back (HLR 은선 제거)
- **용지**: A4/A3/A2/A1
- **ISO 2768 공차**: Fine/Medium/Coarse
- **자동 치수**: 길이 + 원통형 피처(홀/축) 지름 주석
- **Title Block**: 모델명, 회사, 재질, 스케일, 투영법
- **Export**: SVG / DXF / PDF

**API**: `POST /api/3d-studio/drawing/generate`, `GET /api/3d-studio/drawing/export/{id}/{fmt}` (Design 세션: `POST /api/cad-studio/sessions/{id}/drawing/generate`, `.../drawing/svg|dxf|pdf`)

**저장**: `server/data/cad_viewer/`, `server/data/cad_studio/`, `server/data/3d_studio/`

---

## 7.8 AGRI-FARM — Mushroom Cube Farm Automation

> **NEW** — 표고버섯 큐브팜 AMR 자동화 도메인 (중소조선 외 신규 산업 적용). 8개 하위 메뉴. (Phase 1 skeleton — 일부 페이지는 Phase 3 예정)

### 7.8.1 Cube Farm Fleet (`/agri-fleet`)

다중 큐브팜 운영 개요 + 메타데이터 관리.

- **Fleet Summary**: 총 농장 수, 활성 수, 선반/배지 용량
- **Farm CRUD**: 농장 등록(이름, 위치 lat/lng, 선반/배지 구성, AMR/카메라 매핑)
- **상태 표시**: active / planning / maintenance

**API**: `GET|POST /api/agri/farms`, `GET|PUT|DELETE /api/agri/farms/{id}`, `GET /api/agri/fleet/summary`

### 7.8.2 Farm Dashboard (`/smart-farm`)

선택 농장의 생산 KPI / 환경 / 알림 통합 대시보드.

- **8-card KPI**: 생육 점검, 이상 감지, 수확 가능 수, 주간 수확량/kg, 온도/습도/CO2/조도 게이지
- **VPD 분석**: 생육 단계별 최적 범위 가이드
- **주간 수확 차트**(14일), **최근 알림 집계**

**API**: `GET /api/smart-farm/farms/{id}/dashboard`, `.../alerts`, `.../harvest-chart`, `.../env-analysis`

### 7.8.3 Growth Monitor (`/smart-farm-growth`)

PatchCore 기반 버섯 생육 단계/건강 이상 탐지.

- **이미지 업로드 분석**: 정상/오염/곰팡이/기형 분류
- **생육 단계 예측**: incubation → pinning → primordia → growing → mature → harvest_ready
- **Anomaly Score** 시각화, 농장별 기록 저장, 14일 이력
- 모델: `models/smart_farm_growth.fpkl` (미존재 시 mock fallback)

**API**: `POST /api/smart-farm/growth/analyze`, `POST /api/smart-farm/growth/record`, `GET /api/smart-farm/growth/{id}/history`

### 7.8.4 Thinning Control (`/agri-thinning`)

버섯 솎기(thinning) 의사결정 지원 — 배지당 "keep N" 핀 선별.

- **4-factor 가중 스코어링**: Size 30% / Position 15% / Spacing 25% / Health 30%
- **Keep / Remove 후보 리스트** + 개별 점수
- **Mission 기록**(감사 추적)

**API**: `POST /api/agri/thinning/simulate`, `GET /api/agri/thinning/missions`

### 7.8.5 Harvest & Quality (`/smart-farm-harvest`)

YOLO 기반 수확 후 품질 등급 판정 + 기록.

- **등급 분포**: premium / grade_a / grade_b / off_grade
- **갓 크기 추정**(px→mm), 수확 가능 비율
- **30일 통계** + 일별 수확 차트
- 모델: `models/smart_farm_quality.pt` (미존재 시 mock)

**API**: `POST /api/smart-farm/harvest/analyze`, `POST /api/smart-farm/harvest/record`, `GET /api/smart-farm/harvest/{id}/stats`

### 7.8.6 Environment (`/smart-farm-env`)

실시간 센서 모니터링 + VPD 분석 + 외부 기상 연동.

- **4-metric 게이지**: 온도/습도/CO2/조도 (단계별 최적 범위)
- **VPD / Delta-T / Environment Score(0~100)**
- **외부 기상**(Open-Meteo): 현재/시간별(24h)/일별(5일) + UV/ET₀ + 표고버섯 농업 힌트
- **위치**: 주소 검색(forward geocoding), GPS, 수동 lat/lng, 역지오코딩(OSM Nominatim)
- **MQTT 센서 수집**: `{base_topic}/{farm_id}/{metric}` (paho-mqtt, 미설치 시 graceful)

**API**: `POST /api/smart-farm/env/record`, `GET /api/smart-farm/env/{id}/current|history`, `POST /api/smart-farm/env/rules`, `GET /api/agri/weather`, `GET /api/agri/geocode`, `GET /api/agri/reverse-geocode`, `POST /api/smart-farm/mqtt/configure|start|stop`

### 7.8.7 AMR Navigation (`/agri-amr`)

자율주행 로봇(AMR) 통합 — Phase 3 예정 (LiDAR SLAM, A*/RRT 경로계획, ArUco 도킹, 장애물 회피). 현재는 로드맵 스텁 + Fleet Dashboard 링크.

### 7.8.8 GAP Reports (`/agri-gap`)

GAP(우수농산물관리) 준수 보고서 자동 생성.

- **자동 조립**: 농장 메타 + 생육 집계 + 솎기 이력 + 환경 로그 + 준수 체크리스트
- **JSON 미리보기 + 다운로드** (Phase 4: PDF + e-submission 예정)

**API**: `POST /api/agri/reports/gap`
**저장**: `server/data/agri_farm/` (cubefarms.json, thinning_missions.json), `server/data/smart_farm/` (farms/sensor/growth/harvest logs)

---

## 7.9 EDUCATION — Online Learning Platform

> **NEW** — 온라인 강의 제공/관리 시스템 (진도 추적, 과제, 토론, 실습, 수료증). 8개 하위 메뉴.

| 페이지 | URL | 기능 |
|--------|-----|------|
| **Course Catalog** | `/education` | 카테고리 필터 강의 카탈로그, 수강 신청 |
| **My Courses** | `/my-courses` | 수강 강의 + 진도(시청 시간) 추적 |
| **Classroom** | `/classroom` | 주차별 커리큘럼 + 레슨 학습 |
| **Lab** | `/lab` | 단계별 실습 가이드 + 결과 제출 |
| **Assignments** | `/assignments` | 과제 제출 (관리자 채점/피드백) |
| **Certificates** | `/certificates` | 수료증 발급 + PDF 다운로드 |
| **Q&A Board** | `/edu-board` | 토론 게시판 (답글, 고정) |
| **Education Admin** | `/education-admin` | 강의/주차/레슨/과제 생성, 수강생/채점 관리, 통계 (관리자) |

**주요 API** (prefix `/api/education`):
- 강의: `GET /courses`, `GET /courses/{id}`, `GET /courses/{id}/weeks`, `GET /lessons/{id}`
- 수강: `POST /enroll`, `GET /my-courses`, `POST /progress`, `GET /progress/{enrollment_id}`
- 과제: `GET /assignments`, `POST /submissions`, `GET /submissions/my`
- 토론: `GET /discussions/{course_id}`, `POST /discussions`, `PUT /discussions/{id}/pin`
- 실습: `GET /lab/guide`, `POST /lab/submit`, `POST /lab/complete-step`
- 수료증: `GET /certificates`, `GET /certificates/{id}/download`
- 관리자: `GET /admin/statistics`, `PUT /admin/submissions/{id}/grade`, `POST /admin/courses`, `POST /admin/certificates/issue`

**저장**: `server/data/education/` (courses, enrollments, progress, submissions, discussions, certificates, live_sessions JSON)

---

## 8. AI Engine

### 8.1 PatchCore (Anomaly Detection)

비지도 학습 기반 이상 탐지 — 정상 이미지만으로 학습. 가장 범용적인 기본 알고리즘.

| Parameter | Options |
|-----------|---------|
| **Backbone** | ResNet18, ResNet50, Wide-ResNet50-2 (default), EfficientNet-B4 |
| **Patch Extraction** | Unfold 기반, 설정 가능한 patch_size/stride |
| **Coreset Sampling** | Greedy, GPU 가속 |
| **KNN Search** | FAISS (설치 시) 또는 torch.cdist 폴백 |
| **Input** | RGB 이미지 (224~512px) |
| **Output** | Anomaly Score (0~1) + Heatmap |
| **Export** | ONNX, .fpkl (pickle) |
| **Auto Subsampling** | 300장 초과 시 자동 서브샘플링 (OOM 방지) |

### 8.2 PaDiM (Anomaly Detection)

가우시안 분포 모델링 기반 이상 탐지.

| Parameter | Options |
|-----------|---------|
| **Backbone** | ResNet18/50, Wide-ResNet50-2, EfficientNet-B4 |
| **Modeling** | 위치별 가우시안 (Mean + Covariance) |
| **Distance** | Mahalanobis Distance |
| **Multi-layer** | Embedding 연결 (1,2,3 레이어) |
| **d_reduced** | ResNet18: 100, ResNet50/WRN50-2: 550 |
| **Export** | ONNX |

### 8.3 SPADE (Anomaly Detection)

Sub-Image Anomaly Detection. PatchCore와 유사한 Memory Bank 방식.

| Parameter | Options |
|-----------|---------|
| **Backbone** | ResNet18/50, Wide-ResNet50-2, EfficientNet-B4 |
| **Method** | K-NN 기반 패치 레벨 이상 탐지 |
| **Input** | RGB 이미지 (224~512px) |
| **Output** | Anomaly Score (0~1) + Heatmap |
| **Auto Subsampling** | 300장 초과 시 자동 서브샘플링 (OOM 방지) |

### 8.4 WinCLIP (Anomaly Detection)

CLIP 기반 Zero/Few-shot 이상 탐지. 텍스트 프롬프트 활용.

| Parameter | Options |
|-----------|---------|
| **Method** | CLIP Vision-Language 모델 기반 |
| **Mode** | Zero-shot (프롬프트만) / Few-shot (소수 정상 이미지) |
| **Input** | RGB 이미지 |
| **Output** | Anomaly Score + Heatmap |

### 8.5 EfficientAD (Anomaly Detection)

Teacher-Student 구조 기반 빠른 이상 탐지.

| Parameter | Options |
|-----------|---------|
| **Method** | Knowledge Distillation (Teacher → Student) |
| **Speed** | 빠른 추론 속도 (경량 모델) |
| **Input** | RGB 이미지 |
| **Output** | Anomaly Score + Heatmap |

### 8.6 FastFlow (Anomaly Detection)

2D Normalizing Flow 기반 이상 탐지.

| Parameter | Options |
|-----------|---------|
| **Method** | 2D Normalizing Flow (likelihood 기반) |
| **Backbone** | ResNet18/50, Wide-ResNet50-2, EfficientNet-B4 |
| **Input** | RGB 이미지 |
| **Output** | Anomaly Score + Heatmap |

### 8.7 YOLO (Object Detection)

지도 학습 기반 객체 탐지.

| Feature | Description |
|---------|-------------|
| **Versions** | YOLOv8n/s/m/l/x, YOLOv10 |
| **Training** | Ultralytics 프레임워크 기반 |
| **Metrics** | mAP@50, mAP@50-95, Precision, Recall |
| **Augmentation** | Mosaic, MixUp, Flip, HSV, Copy-Paste |
| **Export** | ONNX, TensorRT, CoreML |

### 8.8 Inference Engine

| Feature | Description |
|---------|-------------|
| **Multi-Model** | 동시에 여러 모델 로드/관리 |
| **GPU/CPU Switch** | CUDA ↔ CPU 전환 |
| **Batch Inference** | 다중 이미지 일괄 추론 |
| **Memory Optimization** | 미사용 모델 자동 언로드 |
| **Caching** | 추론 결과 캐싱 |

---

## 9. Authentication & Security

### Email Code Verification

| Feature | Description |
|---------|-------------|
| **Login** | 이메일 주소로 인증 코드 발송 |
| **Verification** | 6자리 코드 검증 (5분 유효) |
| **Session** | JWT 토큰 기반 세션 관리 |
| **Brute Force Protection** | 로그인 시도 횟수 제한 |
| **Admin Panel** | 사용자 관리, 역할 지정, 로그인 이력 |
| **Domain ACL** | 허용 이메일 도메인 제한 |

**API**: `POST /api/auth/send-code`, `POST /api/auth/verify`, `POST /api/auth/logout`

---

## 10. WebSocket Real-time

| Endpoint | Purpose | Update Interval |
|----------|---------|----------------|
| `WS /ws` | 메인 연결 (ping/pong, 상태) | 30s heartbeat |
| `WS /ws/training/anomaly` | 이상 탐지 학습/평가/비교 진행 | 실시간 |
| `WS /ws/training/hyperopt` | HPO 시도 결과 | 1s polling |
| `WS /ws/alarms` | 알람 이벤트 | 실시간 |
| `WS /ws/monitoring` | 시스템 리소스 | 1~5s |
| `WS /ws/results` | 검사 결과 | 실시간 |
| `WS /ws/robots` | 로봇 상태/활동 | 실시간 |
| `WS /ws/robot/telemetry` | 로봇 텔레메트리 (관절/TCP/힘) | 10~100Hz |
| `WS /ws/rbpodo/stream` | rbpodo Bridge 상태 스트림 | 실시간 |
| `WS /ws/physics` | Physics Bridge 시뮬 상태 | 30Hz |
| `WS /ws/slam` | 용접 SLAM 프레임/포즈 | 실시간 |
| `WS /api/edge/ws/stream/{id}` | Edge Device 카메라 스트리밍 | 실시간 |

### WS /ws/training/anomaly 메시지 타입

| Direction | Message Type | Description |
|-----------|-------------|-------------|
| Client→Server | `start_training` | 학습 시작 요청 (config 포함) |
| Client→Server | `evaluate` | 평가 시작 요청 |
| Client→Server | `threshold_sim` | 임계값 시뮬레이션 요청 |
| Client→Server | `compare_algorithms` | 알고리즘 비교 시작 요청 |
| Client→Server | `stop_compare` | 비교 중지 요청 |
| Server→Client | `training_progress` | 학습 진행 (phase, percent, message, sample_image_paths) |
| Server→Client | `eval_progress` | 평가 진행 (per_image_results 포함) |
| Server→Client | `training_complete` | 학습 완료 (model_path) |
| Server→Client | `eval_complete` | 평가 완료 (metrics, confusion_matrix, per_image_results) |
| Server→Client | `compare_started` | 비교 시작 (algorithms, total) |
| Server→Client | `compare_algo_start` | 개별 알고리즘 학습 시작 |
| Server→Client | `compare_algo_complete` | 개별 알고리즘 완료 (result) |
| Server→Client | `compare_complete` | 전체 비교 완료 (results, ranking) |

---

## 11. Data Storage Paths

모든 경로는 프로젝트 루트(`rb_vision_platform/`) 기준 상대 경로입니다.

### Databases

| Path | Purpose | Engine |
|------|---------|--------|
| `server/data/platform.db` | 메인 DB (프로젝트, 데이터셋, 모델, 학습, 알람, 감사) | SQLite (aiosqlite) |
| `server/data/users.db` | 인증/사용자 DB | SQLite |

### Inspection Results

| Path | Purpose | Format |
|------|---------|--------|
| `results/` | 검사 결과 기본 디렉토리 | — |
| `results/{YYYY-MM-DD}/` | 일자별 결과 디렉토리 | — |
| `results/{YYYY-MM-DD}/{result_id}.json` | 개별 검사 결과 | JSON |
| `results/{YYYY-MM-DD}/{result_id}/` | 결과 이미지 폴더 | input.jpg, result.png |

### AI Models

| Path | Purpose | Format |
|------|---------|--------|
| `models/` | 학습된 모델 파일 | .fpkl, .pth, .pt, .onnx |
| `models/{name}.meta.json` | 모델 메타데이터 사이드카 (알고리즘, 백본, 샘플 이미지 등) | JSON |
| `models/{name}_sample_0.jpg` | 학습 샘플 썸네일 (120px JPEG, 모델당 최대 2개) | JPEG |
| `models/exports/` | 내보내기된 모델 (ONNX/TensorRT) | .onnx, .engine |
| `models/training_history.json` | 이상 탐지 학습 이력 (6개 알고리즘) | JSON |
| `models/yolo_history.json` | YOLO 학습/평가 이력 | JSON |

### Training Data

| Path | Purpose | Format |
|------|---------|--------|
| `LabelData/` | COCO 형식 어노테이션 데이터 | JSON + images |
| `datasets/` | 데이터셋 관리 기본 디렉토리 | — |
| `datasets/{dataset_id}/images/` | 데이터셋 이미지 | Image files |
| `datasets/{dataset_id}/labels/` | 데이터셋 라벨 | JSON |

### Robot Data

| Path | Purpose | Format |
|------|---------|--------|
| `robot_data/calibration/` | TCP/Hand-Eye/Work Frame 보정 데이터 | Files |
| `robot_data/motion_library/` | 교시점, 동작 시퀀스 | Files |
| `robot_data/coordinate_settings.yaml` | 좌표계 설정 | YAML |

### Configuration

| Path | Purpose | Format |
|------|---------|--------|
| `config/default_config.yaml` | 플랫폼 기본 설정 | YAML |
| `config/auth_config.yaml` | 인증 설정 (SMTP, 도메인) | YAML |
| `data/recipes/` | 검사 레시피 | JSON/YAML |
| `data/preprocessing/` | 전처리 파이프라인 설정 | JSON |
| `data/dt_config.json` | 디지털 트윈 3D 설정 | JSON |
| `data/dt_stats.json` | 디지털 트윈 통계 | JSON |

### Reports & Logs

| Path | Purpose | Format |
|------|---------|--------|
| `reports/` | 생성된 보고서 파일 | HTML, CSV, XLSX |
| `logs/` | 로그 파일 디렉토리 | — |
| `logs/rb_vision_{YYYYMMDD}.log` | 일별 로그 (30일 보관) | Text |

### Other

| Path | Purpose | Format |
|------|---------|--------|
| `server/quick_inspect_models.json` | Quick-Inspect 모델 레지스트리 | JSON |
| `server/data/robot_activity.json` | 로봇 활동 로그 (분단위) | JSON |
| `server/static/` | 정적 파일 (CSS, JS, Images) | — |
| `logo/` | 로고 이미지 | Image files |

### New Feature Data (v3.2)

| Path | Purpose | Format |
|------|---------|--------|
| `server/data/quick_train/{session_id}/` | Quick Training 세션 (이미지/라벨/dataset/runs) | mixed |
| `server/data/auto_teaching/recordings.json` | Auto/Autonomous Teaching 녹화 | JSON |
| `server/data/twin_recordings/` | Digital Twin Recording (타임라인+키프레임) | JSON |
| `server/data/factory_layouts\|scenarios\|snapshots\|glb\|programs\|reports\|usd\|sdf/` | Factory 3D Simulator | mixed |
| `server/data/cad_viewer/`, `cad_studio/`, `3d_studio/` | 3D Studio (업로드/세션/GLB/도면) | mixed |
| `server/data/agri_farm/`, `smart_farm/` | Agri-Farm (큐브팜/센서/생육/수확/솎기) | JSON |
| `server/data/education/` | Education (강의/수강/진도/과제/토론/수료증) | JSON |
| `server/data/ops_board/` | Ops Board (게시글/설정) | JSON |
| `server/data/pricing/pricing_policy.json` | Pricing 정책 | JSON |
| `server/data/api_keys/` | API Keys (keys.json, usage_log.json) | JSON |
| `server/data/ai_news/`, `knowledge_cache/` | AI Daily Briefing | JSON |
| `server/data/edge_devices.json`, `edge_update_history.json` | Edge Device 관리 | JSON |
| `server/data/slam/` | 용접 SLAM 세션/맵 | npy + JSON |

---

## 12. API Endpoint Reference

### INSPECTION

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/status` | 시스템 상태 |
| GET | `/api/statistics?days=` | 통계 (기간별) |
| GET | `/api/results?limit=&offset=` | 결과 목록 |
| GET | `/api/results/history?date_from=&date_to=&page=&per_page=` | 이력 조회 (최대 10,000건) |
| GET | `/api/results/image?path=` | 결과 이미지 |
| POST | `/api/inspection/start` | 검사 시작 |
| POST | `/api/inspection/stop` | 검사 중지 |
| GET | `/api/inspection/status` | 검사 상태 |
| POST | `/api/quick-inspect` | 빠른 추론 (multipart) |
| GET | `/api/quick-inspect/health` | QI 서버 상태 |
| GET | `/api/quick-inspect/models` | QI 모델 목록 |
| POST | `/api/quick-inspect/models/register` | QI 모델 등록 |
| DELETE | `/api/quick-inspect/models/{id}` | QI 모델 삭제 |

### TRAINING — Anomaly Detection

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/training/anomaly/start` | 이상 탐지 학습 시작 (6개 알고리즘) |
| GET | `/api/training/anomaly/status/{job_id}` | 학습 상태 |
| POST | `/api/training/anomaly/stop/{job_id}` | 학습 중지 |
| POST | `/api/training/anomaly/evaluate` | 모델 평가 |
| POST | `/api/training/anomaly/threshold-sim` | 임계값 시뮬레이션 |
| GET | `/api/training/anomaly/history` | 학습 이력 |
| GET | `/api/training/anomaly/image-count` | 폴더 내 이미지 수 조회 |
| GET | `/api/training/anomaly/sample-image` | 폴더 내 샘플 이미지 조회 (`dir_path`, `index`) |
| GET | `/api/training/anomaly/model-sample-image` | 모델 학습 샘플 썸네일 조회 (`model_path`, `index`) |
| GET | `/api/training/anomaly/model-info` | 모델 메타데이터 조회 |
| GET | `/api/training/anomaly/download-model` | 모델 파일 다운로드 |
| GET | `/api/training/anomaly/eval-image` | 평가 결과 이미지/히트맵 조회 |
| GET | `/api/training/anomaly/queue` | 학습 큐 상태 조회 |
| POST | `/api/training/anomaly/queue` | 학습 큐에 작업 추가 |

### TRAINING — YOLO / HPO

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/yolo/train` | YOLO 학습 시작 |
| GET | `/api/yolo/train/status` | YOLO 학습 상태 |
| POST | `/api/yolo/train/stop` | YOLO 학습 중지 |
| GET | `/api/yolo/models` | YOLO 모델 목록 |
| POST | `/api/hyperopt/start` | HPO 시작 |
| POST | `/api/hyperopt/stop` | HPO 중지 |
| GET | `/api/hyperopt/status` | HPO 상태 |
| GET | `/api/hyperopt/history` | HPO 이력 |

### DATA

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/datasets` | 데이터셋 목록 |
| POST | `/api/datasets` | 데이터셋 생성 |
| GET | `/api/datasets/{id}` | 데이터셋 상세 |
| POST | `/api/datasets/{id}/upload` | 이미지 업로드 |
| GET | `/api/labels/browse?path=` | 폴더 탐색 |
| POST | `/api/labels/convert-to-yolo` | COCO → YOLO 변환 |
| GET | `/api/preprocessing/operations` | 전처리 작업 목록 |
| POST | `/api/preprocessing/preview` | 전처리 미리보기 |

### MODELS

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/models` | 모델 목록 |
| POST | `/api/models` | 모델 등록 |
| GET | `/api/models/{id}` | 모델 상세 |
| DELETE | `/api/models/{id}` | 모델 삭제 |
| POST | `/api/deployment/export` | ONNX/TRT 내보내기 |
| POST | `/api/deployment/deploy` | 모델 배포 |

### SYSTEM

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/robots` | 로봇 목록 |
| POST | `/api/robots` | 로봇 등록 |
| POST | `/api/robots/{id}/connect` | 로봇 연결 |
| POST | `/api/robots/{id}/jog` | 조그 이동 |
| POST | `/api/robots/{id}/move` | 포즈 이동 |
| GET | `/api/alarms` | 알람 목록 |
| POST | `/api/alarms/rules` | 알람 규칙 생성 |
| GET | `/api/monitoring/status` | 시스템 상태 |
| GET | `/api/monitoring/gpu` | GPU 상태 |
| POST | `/api/reports/generate` | 보고서 생성 |
| GET | `/api/reports/templates` | 보고서 템플릿 |
| GET | `/api/reports` | 보고서 목록 |
| GET | `/api/reports/{id}?download=true` | 보고서 다운로드 |
| GET | `/api/simulation/dt-config` | DT 설정 |
| POST | `/api/simulation/dt-config` | DT 설정 저장 |
| POST | `/api/simulation/run` | 레시피 시뮬레이션 |
| GET | `/api/settings` | 시스템 설정 |
| PUT | `/api/settings` | 설정 변경 |
| GET | `/api/audit/logs` | 감사 로그 |
| GET | `/api/projects` | 프로젝트 목록 |

### WELDING

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/welding/hmi/robots` | 다종 로봇 목록 |
| GET | `/api/welding/modeling/jobs` | 모델링 작업 목록 |
| GET | `/api/welding/digital-twin/simulations` | 시뮬레이션 목록 |
| GET | `/api/welding/seam-tracking/status` | 용접선 추적 상태 |
| GET | `/api/welding/llm/history` | LLM 명령 이력 |
| * | `/api/welding/slam/*` | SLAM 18 endpoints (세션/스캔/맵/용접선/경로) |

### QUICK TRAINING

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/quick-train/sessions` | 학습 세션 생성 |
| POST | `/api/quick-train/sessions/{sid}/images` | 이미지 배치 업로드 |
| POST | `/api/quick-train/sessions/{sid}/classes` | 클래스 정의 |
| POST | `/api/quick-train/sessions/{sid}/labels/{img_id}` | 바운딩 박스 저장 |
| POST | `/api/quick-train/sessions/{sid}/train` | 학습 시작 |
| GET | `/api/quick-train/sessions/{sid}/status` | 학습 진행 상태 |
| GET | `/api/quick-train/sessions/{sid}/download/{fmt}` | 모델 다운로드 |
| GET | `/api/quick-train/defaults` | 23종 베이스 모델 + 파라미터 |

### ROBOT (Teaching / Telemetry / Tasks / Simulation)

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/robot/telemetry/latest` | 최신 텔레메트리 샘플 |
| POST | `/api/robot/telemetry/start` | 텔레메트리 폴링 시작 |
| POST | `/api/robot/auto-teaching/record/start` | Auto Teaching 녹화 시작 |
| POST | `/api/robot/auto-teaching/recordings/{id}/play` | 녹화 재생 |
| GET | `/api/robot/autonomous-teaching/patterns` | 자율 교시 패턴 목록 |
| POST | `/api/robot/autonomous-teaching/execute` | 패턴 즉시 실행 |
| POST | `/api/twin-rec/start` | Digital Twin 녹화 시작 |
| POST | `/api/twin-rec/{name}/play` | Digital Twin 재생 |
| GET | `/api/tasks` | 통합 Task 목록 |
| POST | `/api/tasks/{id}/start` | Task 실행 |
| GET | `/api/factory-sim/catalog` | 시뮬레이터 장비 카탈로그 |
| POST | `/api/factory-sim/program/export` | RB Script/USD/SDF Export |
| POST | `/api/rbpodo/move_j` | rbpodo Bridge 관절 이동 |
| POST | `/api/physics/start` | Physics 시뮬레이션 시작 |

### 3D STUDIO

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/cad-viewer/upload` | CAD 파일 업로드 |
| POST | `/api/cad-viewer/convert/{id}` | GLB 변환 |
| POST | `/api/cad-studio/sessions` | 모델링 세션 생성 |
| POST | `/api/3d-studio/convert` | 포맷 변환 |
| POST | `/api/3d-studio/measure` | 측정 (부피/표면적/무게) |
| POST | `/api/3d-studio/drawing/generate` | 2D 도면 생성 (SVG/DXF/PDF) |
| GET | `/api/3d-studio/urdf/list` | URDF 모델 목록 |

### AGRI-FARM

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/agri/farms` | 큐브팜 목록 |
| GET | `/api/agri/fleet/summary` | 플릿 요약 |
| POST | `/api/agri/thinning/simulate` | 솎기 시뮬레이션 |
| POST | `/api/agri/reports/gap` | GAP 보고서 생성 |
| GET | `/api/agri/weather` | 외부 기상 (Open-Meteo) |
| GET | `/api/smart-farm/farms/{id}/dashboard` | 농장 대시보드 |
| POST | `/api/smart-farm/growth/analyze` | 생육 이상 탐지 (PatchCore) |
| POST | `/api/smart-farm/harvest/analyze` | 수확 품질 (YOLO) |

### EDUCATION

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/education/courses` | 강의 목록 |
| POST | `/api/education/enroll` | 수강 신청 |
| POST | `/api/education/progress` | 진도 업데이트 |
| POST | `/api/education/submissions` | 과제 제출 |
| GET | `/api/education/certificates/{id}/download` | 수료증 PDF |
| GET | `/api/education/admin/statistics` | 관리자 통계 |

### MULTI-AGENT / OPS / PRICING / API KEYS / VLM / AI NEWS

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/agents/master/execute` | 자연어 명령 실행 (Orchestrator) |
| GET | `/api/harness/teams` | Harness 5팀 목록 |
| POST | `/api/harness/run` | 팀 실행 (자연어) |
| GET | `/api/ops-board/posts` | 운영 게시글 |
| POST | `/api/ops-board/agent/generate` | 일일 리포트 생성 |
| GET | `/api/models/monitoring/summary` | 모델 모니터링 요약 |
| GET | `/api/models/monitoring/{id}/drift` | PSI 드리프트 |
| POST | `/api/threshold-analysis/compare` | 임계값 비교 (CSV) |
| GET | `/api/pricing/policy` | 요금 정책 |
| POST | `/api/pricing/simulate` | 비용 시뮬레이션 |
| GET | `/api/api-keys` | 내 API 키 목록 |
| POST | `/api/api-keys` | 키 발급 |
| POST | `/api/vlm/analyze-heatmap` | VLM 히트맵 분석 (SSE) |
| GET | `/api/ai-news/today` | 오늘의 AI 브리핑 |
| POST | `/api/data-collection/jobs` | 데이터 수집 잡 생성 |
| POST | `/api/reports/docx/generate` | DOCX 보고서 생성 |
| POST | `/api/edge/register` | Edge 디바이스 등록 |

### AUTH

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/auth/send-code` | 인증 코드 발송 |
| POST | `/api/auth/verify` | 코드 검증 + 세션 생성 |
| POST | `/api/auth/logout` | 로그아웃 |

---

## 13. Configuration & Settings

### default_config.yaml

```yaml
# 주요 설정 항목
products:
  product_A:
    product_name: "제품A"
    product_type: "shaft"
    cycle_time_target: 5.0

robot:
  ip: "10.0.2.7"
  port: 5000
  simulation: true

camera:
  type: "simulation"  # gige, usb, simulation
  resolution: [1920, 1080]

ai_engine:
  default_backbone: "wide_resnet50_2"
  default_input_size: 224
  device: "cuda"  # cuda, cpu
```

### auth_config.yaml

```yaml
admin_email: "admin@example.com"
smtp:
  host: "smtp.gmail.com"
  port: 587
  use_tls: true
  username: "..."
  password: "..."
allowed_domains:
  - "example.com"
```

### Quick-Inspect Config (config_inferencer.ini)

```ini
[QUICK_INSPECT]
use_remote_server = true
server_url = http://localhost:8000
fallback_to_local = true
mode1_remote_model_id = patchcore_model_1
mode2_remote_model_id = yolo_model_1
```

---

## System Requirements

| Component | Requirement |
|-----------|------------|
| **Python** | 3.9, 3.10, 3.11 |
| **OS** | Windows 10/11, Linux |
| **GPU** | NVIDIA CUDA 11.8+ (선택) |
| **RAM** | 8GB+ (16GB 권장) |
| **Disk** | 10GB+ (모델 & 데이터) |
| **Browser** | Chrome, Edge, Firefox (최신) |

### Install

```bash
# CPU
pip install -e ".[full]"

# GPU (CUDA)
pip install -e ".[full-gpu]"

# GPU + MLflow/Optuna
pip install -e ".[full-mlops]"
```

---

---

## 14. MULTI-AGENT — Orchestration, Harness Teams & 용접 구조물 AI Agent

> **v3.0** — 35대 핵심 분류체계 기반 10개 AI Agent · **v3.2** — Master Orchestrator + Harness Teams 추가

LangGraph StateGraph 기반 멀티 에이전트 시스템. 용접 구조물 제조 공정의 인식·예측·자동화·소통·생성을 자동화합니다.

### 14.0 Master Orchestrator (🧠 `/agent-master`, NEW)

자연어 명령을 분해하여 하위 전문 에이전트에 위임하는 중앙 두뇌.

- **Bootstrap**: 14+ 도메인 에이전트 시작 시 자동 등록
- **LLM 분해**: Qwen3.5:9b가 자연어 → JSON Task 스텝(agent, capability, params, depends_on)
- **Task Graph**: 의존성 기반 병렬/순차 실행
- **Synthesis**: 에이전트 결과를 자연어로 종합
- **Session Memory**: 최근 100 세션(스텝 트레이스) in-memory
- **Fallback**: LLM 미가용 시 키워드 라우팅

**API**: `POST /api/agents/master/execute` (query, session_id, max_steps), `GET /api/agents/master/sessions`, `GET /api/agents/master/registry`, `POST /api/agents/master/register`, `DELETE /api/agents/master/registry/{name}`

### 14.0.1 Harness Teams (`/harness-teams`, NEW)

LangGraph 기반 5개 도메인 전문 팀 병렬 오케스트레이션.

| Team | 색상 | 워크플로우 | 에이전트 |
|------|------|-----------|----------|
| **Manufacturing** (제조 품질) | #3B82F6 | inspect→judge→analyze→learn | quality, bead_inspect, defect_predict, automation, tool_life |
| **Welding** (용접 전문) | #EF4444 | detect_seam→track→record→quality_check→report | weld_record, quality_alert, wps_report, communication, prediction |
| **Robot** (로봇 제어) | #8B5CF6 | monitor→predict_failure→schedule→execute | maintenance, scheduler, recognition |
| **SmartFarm** (스마트팜) | #10B981 | sensor→analyze→control→harvest_predict | smart_farm_service |
| **Ops** (운영관리) | #D4A574 | collect→analyze→generate_report→deliver | ops_agent, ai_news |

- **자연어 라우팅**: 키워드 기반 팀 선택 후 워크플로우 실행
- **Activity Monitor**: 에이전트별 timestamp/duration/success 로그 (최대 1000개)
- **LangGraph 시각화**: 노드/엣지 그래프

**API**: `GET /api/harness/teams`, `GET /api/harness/graph`, `GET /api/harness/monitor`, `GET /api/harness/logs`, `POST /api/harness/run`, `POST /api/harness/pipeline/manufacturing`, `POST /api/harness/pipeline/welding`, `GET /api/harness/pipeline/history`

### 14.1 Agent Dashboard (`/agent-dashboard`)
- 전체 에이전트 상태 카드 (idle/busy/error 실시간 표시)
- LangGraph Workflow SVG 시각화 (14개 노드 그래프, 클릭 → 해당 Agent 페이지 이동)
- 자연어 채팅 (SSE 스트리밍, Ollama LLM 연동)
- 알림 패널 (공구 교체, SPC 위반, 설비 보전 등)

### 14.2 인식 (Recognition)

| Agent | 페이지 | 핵심 기능 |
|-------|--------|----------|
| PPE 착용 감지 | `/agent-recognition` | YOLO 기반 PPE 4종 감지, 안전구역 침입, 작업자 준수율 |
| 비드 비전 검사 | `/agent-bead-inspect` | CNN/YOLO 불량 7종 픽셀 탐지, PASS/FAIL 판정, RCA 자동 트리거 |

### 14.3 예측 (Prediction)

| Agent | 페이지 | 핵심 기능 |
|-------|--------|----------|
| 설비 부품 수명 | `/agent-prediction` | 용접기 부품 8종 수명 예측, 건강도 0-100, 센서 5종 모니터링 |
| 불량 발생 예측 | `/agent-defect-predict` | 공정 파라미터 이탈 감지, 불량 유형별 확률(%) 예측, 예방 조치 |

### 14.4 자동화 (Automation)

| Agent | 페이지 | 핵심 기능 |
|-------|--------|----------|
| 용접 조건 기록 | `/agent-weld-record` | PLC/센서 기반 자동 기록, 입열량 자동 계산, 자동화율 추적 |
| 불량 RCA | `/agent-automation` | 불량 7종 자동 분류, 원인·시정조치 자동 생성, RAG 기반 유사 사례 검색 |

### 14.5 소통 (Communication)

| Agent | 페이지 | 핵심 기능 |
|-------|--------|----------|
| 디지털 트윈 협업 | `/agent-communication` | 용접 포인트 상태 관리, 워크플로우 4종, 3D 주석, 채널 메시지 |
| 품질 알림 소통 | `/agent-quality-alert` | 역할별 맞춤 알림, 에스컬레이션, 처리 현황 추적 |

### 14.6 생성 (Generation)

| Agent | 페이지 | 핵심 기능 |
|-------|--------|----------|
| 가상 품질 평가 | `/agent-generation` | 용접 파라미터 → 합격확률/등급 예측, 최적 파라미터 추천 |
| WPS 보고서 생성 | `/agent-wps-report` | WPS 준수 자동 검증, 배치 품질 보고서 자동 생성 |

### 14.7 기존 Agent (유지)

| Agent | 페이지 | 역할 |
|-------|--------|------|
| Tool Life | `/agent-tool-life` | CNC 공구 수명 예측 (Taylor 방정식) |
| Scheduler | `/agent-scheduler` | 생산 스케줄링 (EDD + 우선순위, Gantt) |
| Quality | `/agent-quality` | 품질 SPC (Western Electric 규칙) |
| Maintenance | `/agent-maintenance` | 설비 예방 보전 |

### 14.8 LangGraph Orchestrator

- **설치**: `pip install -e ".[agent]"` (langgraph + langchain-core)
- **Fallback**: LangGraph 미설치 시 키워드 라우팅 자동 폴백
- **API**: `GET /api/agents/graph` → 노드/엣지/라우팅 테이블 JSON

**API Endpoints (~95개)**:
```
/api/agents/dashboard               — 종합 대시보드
/api/agents/status                   — 에이전트 상태
/api/agents/graph                    — LangGraph 구조
/api/agents/chat                     — 자연어 채팅 (SSE)
/api/agents/recognition/*            — PPE 감지 (7 endpoints)
/api/agents/bead-inspect/*           — 비드 검사 (3 endpoints)
/api/agents/prediction/*             — 설비 예측 (6 endpoints)
/api/agents/defect-predict/*         — 불량 예측 (3 endpoints)
/api/agents/weld-record/*            — 용접 기록 (4 endpoints)
/api/agents/automation/*             — 불량 RCA (5 endpoints)
/api/agents/communication/*          — DT 협업 (11 endpoints)
/api/agents/quality-alert/*          — 품질 알림 (5 endpoints)
/api/agents/generation/*             — 가상 평가 (6 endpoints)
/api/agents/wps-report/*             — WPS 보고서 (5 endpoints)
/api/agents/tools/*                  — 공구 수명 (기존)
/api/agents/orders/*                 — 스케줄러 (기존)
/api/agents/quality/*                — 품질 SPC (기존)
/api/agents/maintenance/*            — 설비 보전 (기존)
```

---

## 15. Edge Device Streaming & Updates

> **v3.0** — Edge Device 카메라 프레임 WebSocket 전송 + YOLO 실시간 판정 · **v3.2** — Edge 디바이스 관리/모델 업데이트/지도

### 15.1 구조

```
[Edge Device]                    [Platform Server]              [Live Monitor]
 카메라(Basler)                   WebSocket 수신                  브라우저
   │                               │                              │
   ├─ 프레임 캡처                    │                              │
   │  └─ JPEG+base64               │                              │
   │     └─ WS 전송 ──────────────►├─ /ws/edge/stream/{id}       │
   │                               │  ├─ 이미지 → Live Monitor ──►│ liveImage
   │                               │  ├─ YOLO 추론                │
   │                               │  └─ 결과 → Live Monitor ────►│ liveResultImage
   │  ◄─ inference_result ─────────┤                              │
```

### 15.2 Edge Device Client

- **위치**: `Multi-Inspector_v2/Claude.code/EdgeDevice/`
- **모듈**: `edge_ws_client.py` (EdgeStreamClient)
- **설정**: `config/config_inferencer.ini` → `[EDGE_STREAM]` 섹션
- **UI**: Tkinter Statistics 패널 아래 Edge Stream 상태 표시 + Connect/Disconnect 버튼

### 15.3 Live Monitor 연동

- Edge 연결 시 상단에 **Edge Device Streaming 카드** 표시 (Frames, FPS, Result, Confidence, Inference)
- **YOLO Model 선택** 드롭다운으로 추론 모델 실시간 변경
- **Filter** 드롭다운으로 활성 모델 필터링 (정확 매칭)
- Edge 스트리밍 프레임은 파일 저장 없음 (메모리만)

### 15.4 API

```
GET  /api/edge/stream/sessions                    — 활성 스트리밍 세션
PUT  /api/edge/stream/sessions/{id}/model          — 추론 모델 변경
WS   /api/edge/ws/stream/{device_id}               — 스트리밍 WebSocket
```

### 15.5 Edge Device Management (System > Edge Devices, NEW)

엣지 디바이스 플릿 등록/하트비트/모델 버전 관리/지도.

- **Lifecycle**: 디바이스 자가 등록(`register`) → 주기적 하트비트(설치 모델/시스템 상태) → online/offline 자동 판정(5분 기준)
- **Model Update**: 클라이언트 vs 서버 최신 버전 비교, 승인 모델 다운로드(SHA256), 배포/확인/롤백
- **Map 탭**: Leaflet/OpenStreetMap — 로봇 얼굴 SVG 마커(Online 초록/Offline 회색), Set Location 다이얼로그(lat/lng/label), 클릭→상세 패널
- **Update History**: 디바이스별 업데이트 로그 (최대 1000개)

**API**: `POST /api/edge/register`, `PUT /api/edge/devices/{id}/heartbeat`, `GET /api/edge/devices`, `PUT /api/edge/devices/{id}/location`, `GET /api/edge/models/check`, `GET /api/edge/models/{name}/download`, `POST /api/edge/deploy`, `PUT /api/edge/confirm-update`, `PUT /api/edge/rollback`
**저장**: `server/data/edge_devices.json`, `edge_update_history.json`, `edge_deploy_requests.json`

---

## 16. UI Updates

### 16.1 사이드바 토글 메뉴

대분류 메뉴만 표시, 클릭 시 소분류가 펼쳐지는 **accordion 방식**:

```
📊 Dashboard             ← 클릭 → 바로 이동(+Production 소분류 펼침)
🧠 AI STUDIO         ▶    ← 클릭 → ▼ 펼침/접힘
📁 DATA              ▶
📦 MODELS            ▶
📐 3D STUDIO         ▶
🤖 ROBOT             ▶
🔥 WELDING           ▶
🍄 AGRI-FARM         ▶
📈 ANALYTICS         ▶
🎓 EDUCATION         ▶
🤝 MULTI-AGENT       ▶
📋 OPS BOARD         ▶
⚙️ SYSTEM            ▶   (관리자 전용)
```

- **대분류** 클릭 → 소분류 토글 (▶ ↔ ▼)
- **현재 페이지**가 속한 섹션은 **자동으로 펼침**
- **브라우저 뒤로/앞으로** 시에도 자동 펼침
- **SYSTEM** 섹션은 관리자(isAdmin)에게만 표시

### 16.2 Dashboard 날짜 표시

- 검사 결과 테이블: 시간 → **날짜/시간** (오늘이면 `오늘 14:32:15`, 과거면 `03-25 14:32:15`)
- 금일 데이터 없을 때: **최종 데이터 표시** 또는 "금일 검사 데이터 없음" 안내
- 수율 차트: 7일 데이터 없으면 "최근 7일간 검사 데이터가 없습니다" 표시

### 16.3 Modern Themes (v3.2)

- 다크/라이트 + 모던 테마 지원 (CSS 변수 기반 `--bg-sidebar`, `--primary` 등)
- 사이드바 접힘/펼침 (220px ↔ 42px)

---

## 17. OPS BOARD — Operations & Daily Reports

> **NEW** — AI 기반 일일 운영 인텔리전스. 플랫폼 활동 수집 → LLM 인사이트 리포트 생성 → 외부 채널 전송.

### 17.1 Daily Reports (`/ops-board`)

- **자동 리포트**: 일일/다중 시간 스케줄, 플랫폼 활동(git/API/모델/로봇/스마트팜) 수집
- **LLM 생성**: Ollama 기반 인사이트 + 팀 동기부여 메시지
- **게시판**: 카테고리(Daily Report/Incident/Update/Announcement), 상태(draft→published→archived), 이모지 반응
- **외부 전송**: Gmail, Google Space Webhook
- **Agent 설정**: 스케줄, 수신자, 언어, 기본 채널

**API**: `GET /api/ops-board/posts`, `POST /api/ops-board/posts`, `POST /api/ops-board/posts/{id}/react`, `POST /api/ops-board/agent/generate`, `GET /api/ops-board/agent/activity`, `POST /api/ops-board/deliver`, `GET|PUT /api/ops-board/agent/settings`, `GET /api/ops-board/stats`
**저장**: `server/data/ops_board/posts.json`, `settings.json`

---

## 18. Pricing & API Keys

> **NEW** — SaaS 요금 정책 관리 + 외부 API 인증 (System 섹션).

### 18.1 Pricing Policy / Simulator (`/pricing-policy`, `/pricing-simulator`)

- **4-tier 플랜**: Free / Starter / Professional / Enterprise
- **9종 사용량 단위**: devices, models, API calls, storage, users, robots, inspections, training hours, GPU hours
- **20+ 기능 플래그** per 플랜 (AD/YOLO, training, deployment, SSO 등)
- **할인 규칙**: 볼륨/기간/로열티 기반, 청구 주기(월/연, 연간 할인)
- **실시간 비용 시뮬레이션** + 플랜 비교, 다중 통화/세율

**API**: `GET /api/pricing/policy`, `GET /api/pricing/plans`, `POST /api/pricing/simulate`, `POST /api/pricing/compare`, `POST|PUT|DELETE /api/pricing/plans` (admin), `PUT /api/pricing/settings`
**저장**: `server/data/pricing/pricing_policy.json`

### 18.2 API Keys (🔑 `/api-keys`, NEW)

외부 API 호출용 셀프서비스 키 발급/관리/사용 분석.

- **인증 스킴**: `X-API-Key: ftai_live_<32자 랜덤>` 헤더
- **해시**: SHA-256만 DB 저장 (평문은 발급 시 1회만 표시)
- **Scope**: `quick-train`, `yolo-models`, `all`(와일드카드) 또는 커스텀
- **만료/활성화**: expires_days, active/inactive 토글
- **사용 분석**: 호출 로그(method/path/status/duration/IP), 일/월 통계, 성공률, top endpoints (ring buffer 10,000, 90일 보관)

**API**: `GET /api/api-keys`, `POST /api/api-keys` (발급, 평문 1회 반환), `POST /api/api-keys/{id}/deactivate|activate`, `DELETE /api/api-keys/{id}`, `GET /api/api-keys/{id}/usage`, `GET /api/api-keys/{id}/stats`, `GET /api/api-keys/stats/summary`
**저장**: `server/data/api_keys/keys.json`, `usage_log.json`

---

## 19. VLM — Vision-Language Inference

> **NEW** — Ollama 기반 Vision-Language 모델 추론 (히트맵/이미지 분석, SSE 스트리밍).

- **모델**: Ollama `qwen2.5vl:7b` (기본, 설정 가능) — AI Assistant 메인 모델(`qwen3.5:9b`)과 별개의 비전 전용 엔드포인트
- **Heatmap 분석**: 원본+히트맵+점수+임계값 → 결함 위치/유형/심각도/조치 권고 스트리밍
- **General 분석**: 이미지+프롬프트 → 토큰 스트리밍
- **응답 형식**: Server-Sent Events (`data: {"content": "..."}` ... `data: [DONE]`)
- **Graceful**: Ollama 미가용/모델 미설치 시 오류 + [DONE]

**API**: `GET /api/vlm/status`, `POST /api/vlm/analyze-heatmap` (SSE), `POST /api/vlm/analyze` (SSE)

---

*Generated: 2026-05-27 | finetheAi Physical AI Intelligent Platform v3.2 | finetheAi | Rainbow Robotics*
