diff --git a/B03_FileInput/B03_FileInput_Service_WF1.py b/B03_FileInput/B03_FileInput_Service_WF1.py index e5091a92..125be8fd 100644 --- a/B03_FileInput/B03_FileInput_Service_WF1.py +++ b/B03_FileInput/B03_FileInput_Service_WF1.py @@ -21,9 +21,8 @@ from config.config_system import ( AUTO_DESIGN_CHAIN_ENABLED, SEND_ANALYSIS_COMPLETION_EMAIL, SHEET_SURFACE_DEFAULT_METHOD, + SURFACE_AUTO_METHODS, SURFACE_CONTOUR_INTERVAL_M, - SURFACE_MODEL_PRECOMPUTE, - SURFACE_MODEL_SOURCE_FILTERS, ) logger = logging.getLogger(__name__) @@ -62,11 +61,13 @@ async def trigger_wf1_analysis_and_email( pool = get_db_pool() project_info: dict[str, Any] | None = None try: - source_filters = list(SURFACE_MODEL_SOURCE_FILTERS) - methods = list(SURFACE_MODEL_PRECOMPUTE) + # 자동 전처리는 기본 조합만 만든다 — 필터는 엔진이 입력 LAS를 보고 정하고 + # (분류 있으면 classification, 없으면 csf), 표현은 SURFACE_AUTO_METHODS. + # 다른 조합은 관리자가 B04 드롭다운에서 요청할 때 만든다 (2026-09-01 사용자 확정). + methods = list(SURFACE_AUTO_METHODS) params = { "input_file_id": str(input_file_id), - "source_filters": source_filters, + "source_filters": None, "methods": methods, "force": False, } @@ -116,12 +117,17 @@ async def trigger_wf1_analysis_and_email( run_surface_analysis, project_root, source_path, - source_filters=source_filters, + source_filters=None, methods=methods, force=False, on_progress=_on_progress, ) + # 엔진이 정한 기본 필터 — LAS 없는 설계(도엽 서피스)는 이 키가 없다. + resolved_filters = list(analysis_result.get("source_filters") or []) + if not resolved_filters and las_free: + resolved_filters = [f"sheet_{SHEET_SURFACE_DEFAULT_METHOD}"] + auto_confirmation_error: str | None = None auto_confirmed = False confirmed_model_id: int | None = None @@ -133,7 +139,7 @@ async def trigger_wf1_analysis_and_email( project_id=project_id, input_file_id=input_file_id, analysis_result=analysis_result, - source_filters=source_filters, + source_filters=resolved_filters, ) # 역할 무관 자동 확정(2026-08-04 사용자 확정) — 시스템 관리자도 같은 # 사용자다. 모두 기본값으로 자동 확정하고 B05·B06 자동 계산 체인까지 탄다. @@ -147,16 +153,20 @@ async def trigger_wf1_analysis_and_email( # LAS 없는 설계는 도엽 서피스 모델(sheet/dtm)로 확정한다. # 스무딩은 LAS 경로와 같이 적용한다(2026-08-30 사용자 확정) — 방식마다 # `dtm_sheet_*_smooth.npz`를 같이 만들어 두므로 종·횡단이 그걸 샘플링한다. - selection = ( - { + if las_free: + selection = { "source_filter": f"sheet_{SHEET_SURFACE_DEFAULT_METHOD}", "method": "dtm", "smooth": True, "contour_interval_m": SURFACE_CONTOUR_INTERVAL_M, } - if las_free - else surface_confirmation_defaults() - ) + else: + # 자동 확정은 엔진이 정한 기본 필터를 그대로 따른다 — 이제 그 필터 + # 하나만 만들어 두므로 config 기본값과 어긋나면 확정할 모델이 없다. + selection = surface_confirmation_defaults() + if resolved_filters: + selection["source_filter"] = resolved_filters[0] + selection["method"] = methods[0] try: model_id = await find_surface_model_for_selection( connection, project_id, selection diff --git a/B04_PreProcess/B04_PreProcess_Api_Fetch.ts b/B04_PreProcess/B04_PreProcess_Api_Fetch.ts index 651a46e2..0845ae71 100644 --- a/B04_PreProcess/B04_PreProcess_Api_Fetch.ts +++ b/B04_PreProcess/B04_PreProcess_Api_Fetch.ts @@ -178,10 +178,12 @@ export async function analyzeSurface( projectId: string, request: SurfaceAnalyzeRequest, ): Promise { - return requestJson(`/projects/${projectId}/surface/analyze`, { - method: "POST", - body: JSON.stringify(request), - }); + // 조합 하나를 새로 만드는 요청이라 기본 30초로는 못 끝난다. + return requestJson( + `/projects/${projectId}/surface/analyze`, + { method: "POST", body: JSON.stringify(request) }, + API_ANALYSIS_TIMEOUT_MS, + ); } /** 프로젝트의 지표면 모델 목록을 조회한다. */ diff --git a/B04_PreProcess/B04_PreProcess_Engine.py b/B04_PreProcess/B04_PreProcess_Engine.py index 3f470d98..fe7e2bcc 100644 --- a/B04_PreProcess/B04_PreProcess_Engine.py +++ b/B04_PreProcess/B04_PreProcess_Engine.py @@ -15,7 +15,7 @@ import numpy as np from B04_PreProcess.B04_PreProcess_Engine_Ground import ( build_ground_masks, - detect_extra_filters, + resolve_auto_source_filters, run_ground_filter, summarize_masks, ) @@ -106,15 +106,18 @@ def run_surface_analysis( project_root: Path, las_path: Path, *, - source_filters: list[str], + source_filters: list[str] | None, methods: list[str], force: bool = False, on_progress: ProgressCallback | None = None, ) -> dict[str, Any]: """구조화→필터→모델 빌드를 수행하고 산출 메타데이터를 반환한다. + `source_filters`가 비면 입력 LAS를 보고 기본 필터를 정한다(자동 전처리 경로). + 반환 dict: - processed: {processed_file_path, converted_file_path, point_count, bounds, statistics} + - source_filters: 실제로 계산한 필터 목록 (자동 판정 결과 포함) - ground_summary: 필터별 지면 포인트 요약 - manifest: 지표면 모델 파이프라인 manifest - models: [{model_type, model_file_path, resolution_m, generation_params, layers}] @@ -174,11 +177,10 @@ def run_surface_analysis( # 2. 지면 필터 실행 — mask_{filter}.npy 영구 캐시 우선 재사용 (PLAN A-1) _report(40, "ground_filter", "지면 필터 적용 중") - # LAS가 지면분류를 싣고 왔으면 필터 하나로 더 쓴다 — 미분류 LAS면 조용히 빠진다. - extra_filters = detect_extra_filters(data, source_filters) - if extra_filters: - source_filters = list(source_filters) + extra_filters - logger.info("B04 LAS 자체 지면분류 감지 — 필터 추가: %s", ", ".join(extra_filters)) + # 자동 전처리는 목록을 넘기지 않는다 — 기본 필터는 입력 LAS를 보고 여기서 정한다. + if not source_filters: + source_filters = resolve_auto_source_filters(data) + logger.info("B04 자동 전처리 기본 필터: %s", ", ".join(source_filters)) masks: dict[str, np.ndarray] = {} for filter_key in source_filters: mask_path = processed_dir / f"mask_{filter_key}.npy" @@ -266,7 +268,7 @@ def run_surface_analysis( _report(95, "saving", "결과 저장 중") - return _collect_analysis_result( + result = _collect_analysis_result( project_root, models_dir, structured_path, @@ -278,6 +280,9 @@ def run_surface_analysis( sheet_models, total_started, ) + # 자동 경로는 필터를 넘기지 않으므로, 무엇으로 계산했는지 호출부에 돌려준다. + result["source_filters"] = list(source_filters) + return result def download_geodata( diff --git a/B04_PreProcess/B04_PreProcess_Engine_Ground.py b/B04_PreProcess/B04_PreProcess_Engine_Ground.py index 8500b8b4..b9d7e899 100644 --- a/B04_PreProcess/B04_PreProcess_Engine_Ground.py +++ b/B04_PreProcess/B04_PreProcess_Engine_Ground.py @@ -17,6 +17,7 @@ from B04_PreProcess.B04_PreProcess_Engine_Filter_CSF import filter_csf from B04_PreProcess.B04_PreProcess_Engine_Filter_Grid import filter_grid_min_z from B04_PreProcess.B04_PreProcess_Engine_Filter_PMF import filter_pmf from B04_PreProcess.B04_PreProcess_Engine_Filter_RANSAC import filter_ransac +from config.config_system import SURFACE_AUTO_FALLBACK_FILTER # 필터 키 → 함수 매핑 _FILTERS = { @@ -35,16 +36,24 @@ def available_filters() -> tuple[str, ...]: return tuple(_FILTERS.keys()) -def detect_extra_filters( +def usable_conditional_filters( structured_data: dict[str, Any] | np.lib.npyio.NpzFile, - filter_keys: tuple[str, ...] | list[str], ) -> list[str]: - """이 LAS에서만 쓸 수 있는 조건부 필터 중 아직 목록에 없는 것을 고른다.""" - return [ - key - for key, is_usable in _CONDITIONAL_FILTERS.items() - if key not in filter_keys and is_usable(structured_data) - ] + """이 LAS에서 실제로 쓸 수 있는 조건부 필터를 고른다 (드롭다운 노출용).""" + return [key for key, is_usable in _CONDITIONAL_FILTERS.items() if is_usable(structured_data)] + + +def resolve_auto_source_filters( + structured_data: dict[str, Any] | np.lib.npyio.NpzFile, +) -> list[str]: + """자동 전처리가 만들 기본 필터를 입력 LAS를 보고 정한다. + + 업체가 이미 지면을 분류해 놨으면 그것을 쓴다 — 계산이 없고 품질도 가장 안정적이다. + csf는 분류가 없는 LAS의 지면을 추려내기 위한 수단이므로 그때만 쓴다 + (2026-09-01 사용자 확정). + """ + usable = usable_conditional_filters(structured_data) + return usable[:1] if usable else [SURFACE_AUTO_FALLBACK_FILTER] def run_ground_filter( diff --git a/B04_PreProcess/B04_PreProcess_Engine_ModelContext.py b/B04_PreProcess/B04_PreProcess_Engine_ModelContext.py index e58fe9e4..13300da3 100644 --- a/B04_PreProcess/B04_PreProcess_Engine_ModelContext.py +++ b/B04_PreProcess/B04_PreProcess_Engine_ModelContext.py @@ -87,12 +87,20 @@ def evaluate_nurbs_spline( return np.clip(z_values, low, high) +# 서명에서 빼는 키 — 지오메트리를 만드는 방법이 아니라 "무엇을 만들지"를 고르는 값들. +# source_filters·precompute를 넣으면 조합을 바꿀 때마다 manifest가 통째로 폐기돼 +# 이전에 만들어 둔 조합이 사라진다. manifest는 이미 필터·방식별로 키가 갈린다. +_SIGNATURE_EXCLUDED_KEYS = {"source_filters", "precompute"} + + def config_signature(config: dict[str, Any]) -> str: - """지오메트리 원본과 무관한 등고선·스무딩 설정을 제외한 캐시 서명.""" + """지오메트리 생성 방법만 남긴 캐시 서명 (선택 목록·등고선·스무딩 제외).""" sig_config = { k: v for k, v in config.items() - if not k.startswith("contour_") and not k.startswith("smoothing_") + if not k.startswith("contour_") + and not k.startswith("smoothing_") + and k not in _SIGNATURE_EXCLUDED_KEYS } encoded = json.dumps(sig_config, sort_keys=True, default=list).encode("utf-8") return hashlib.sha256(encoded).hexdigest()[:16] diff --git a/B04_PreProcess/B04_PreProcess_UI_Page.ts b/B04_PreProcess/B04_PreProcess_UI_Page.ts index ae01a030..9b730325 100644 --- a/B04_PreProcess/B04_PreProcess_UI_Page.ts +++ b/B04_PreProcess/B04_PreProcess_UI_Page.ts @@ -4,6 +4,7 @@ import { createButton, createTag, hideLoadingOverlay, + showConfirmDialog, showLoadingOverlay, showToast, } from "@ui/ui_template_elements"; @@ -22,6 +23,7 @@ import { type WorkflowState, } from "../A00_Common/b_workflow_nav"; import { + analyzeSurface, confirmSurfaceModel, fetchConfirmedSurface, fetchSurfacePointCloud, @@ -38,7 +40,9 @@ import { createSurfaceTerrainViewer } from "./B04_PreProcess_UI_TerrainViewer"; import { createSurfacePointCloudViewer } from "./B04_PreProcess_UI_Viewer"; import "./B04_PreProcess_UI_Style.css"; -const SOURCE_FILTERS = ["grid_min_z", "csf", "pmf"] as const; +// 고를 수 있는 필터. 자동 전처리는 이 중 기본 하나만 만들고, 나머지는 관리자가 +// 드롭다운에서 고를 때 그 조합만 계산한다 (2026-09-01 사용자 확정). +const SOURCE_FILTERS = ["classification", "grid_min_z", "csf", "pmf"] as const; const MODEL_METHODS = ["tin", "dtm", "nurbs", "implicit", "meshfree"] as const; const DEFAULT_FILTER = "csf"; const DEFAULT_METHOD = "dtm"; @@ -155,6 +159,9 @@ export async function renderB04Surface(root: HTMLElement): Promise { MODEL_METHODS, DEFAULT_METHOD, ); + // 되돌릴 값을 기억해 둔다 — 모달에서 취소하면 드롭다운을 원래 자리로 돌린다. + let appliedFilter = DEFAULT_FILTER; + let appliedMethod = DEFAULT_METHOD; const viewer = createSurfacePointCloudViewer(); const terrainViewer = createSurfaceTerrainViewer(); const mapViewer = createSurfaceMapViewer(); @@ -411,6 +418,57 @@ export async function renderB04Surface(root: HTMLElement): Promise { ); } + /** 고른 조합이 영구 저장돼 있으면 그대로 쓰고, 없으면 물어본 뒤 그 조합만 만든다. */ + async function ensureCombinationBuilt( + previousFilter: string, + previousMethod: string, + ): Promise { + const projectId = getProjectId(); + const filter = filterGroup.select.value; + const method = methodGroup.select.value; + if (!projectId || findSelectedModel()) return true; + if (!selectedInputFile) { + showToast(L("B04_Surface_Load_Failed"), "error"); + return false; + } + + const message = L("B04_Surface_Build_Confirm") + .replace("{filter}", filter) + .replace("{method}", method); + if (!(await showConfirmDialog(message, L("B04_Surface_Build_Action")))) { + filterGroup.select.value = previousFilter; + methodGroup.select.value = previousMethod; + return false; + } + + showLoadingOverlay(); + showToast(L("B04_Surface_Build_Running"), "info"); + try { + await analyzeSurface(projectId, { + input_file_id: selectedInputFile.id, + source_filters: [filter], + methods: [method], + force: false, + }); + models = (await listSurfaceModels(projectId)).models; + showToast( + L("B04_Surface_Build_Done") + .replace("{filter}", filter) + .replace("{method}", method), + "success", + ); + return true; + } catch (error) { + const detail = error instanceof Error ? error.message : ""; + showToast(`${L("B04_Surface_Build_Failed")} ${detail}`, "error"); + filterGroup.select.value = previousFilter; + methodGroup.select.value = previousMethod; + return false; + } finally { + hideLoadingOverlay(); + } + } + function updateSelectedModel(): void { const projectId = getProjectId(); if (!projectId) return; @@ -591,6 +649,9 @@ export async function renderB04Surface(root: HTMLElement): Promise { } catch { showToast(L("B04_Surface_Load_Failed"), "error"); } finally { + // 확정값이 드롭다운에 반영된 뒤이므로, 되돌릴 기준도 여기서 다시 맞춘다. + appliedFilter = filterGroup.select.value; + appliedMethod = methodGroup.select.value; hideLoadingOverlay(); } } @@ -601,10 +662,24 @@ export async function renderB04Surface(root: HTMLElement): Promise { renderInputInfo(); }); filterGroup.select.addEventListener("change", () => { - updateSelectedModel(); - void updatePointCloudForFilter(); + void (async () => { + if (!(await ensureCombinationBuilt(appliedFilter, appliedMethod))) { + updateSelectedModel(); + return; + } + appliedFilter = filterGroup.select.value; + updateSelectedModel(); + await updatePointCloudForFilter(); + })(); + }); + methodGroup.select.addEventListener("change", () => { + void (async () => { + if (await ensureCombinationBuilt(appliedFilter, appliedMethod)) { + appliedMethod = methodGroup.select.value; + } + updateSelectedModel(); + })(); }); - methodGroup.select.addEventListener("change", updateSelectedModel); root.replaceChildren(layout.root); const projectId = getProjectId(); diff --git a/config/config_system.py b/config/config_system.py index 8bc08a47..a0673e08 100644 --- a/config/config_system.py +++ b/config/config_system.py @@ -140,10 +140,15 @@ SURFACE_GROUND_RATIO_WARN = float(os.getenv("SURFACE_GROUND_RATIO_WARN", "0.01") # ───────────────────────────────────────────────────────────────────────── # 5-2. 지표면 모델 생성 파라미터 (TIN/DTM/NURBS/implicit/meshfree) # ───────────────────────────────────────────────────────────────────────── -# 빌드 대상 지면 필터·표현 방식 +# 고를 수 있는 지면 필터 전체 — 관리자가 B04 드롭다운에서 요청할 때 쓰인다. +# 자동 전처리가 미리 만드는 조합이 아니다(그건 SURFACE_AUTO_* 가 정한다). SURFACE_MODEL_SOURCE_FILTERS = tuple( - os.getenv("SURFACE_MODEL_SOURCE_FILTERS", "grid_min_z,csf,pmf").split(",") + os.getenv("SURFACE_MODEL_SOURCE_FILTERS", "classification,grid_min_z,csf,pmf").split(",") ) +# 자동 전처리가 만드는 조합 — 기본 필터 1종 × 아래 표현. 나머지는 관리자 요청 시 만든다. +SURFACE_AUTO_METHODS = tuple(os.getenv("SURFACE_AUTO_METHODS", "dtm").split(",")) +# 기본 필터는 입력 LAS를 보고 정한다 — 지면분류(class 2)가 있으면 그것을, 없으면 아래 값. +SURFACE_AUTO_FALLBACK_FILTER = os.getenv("SURFACE_AUTO_FALLBACK_FILTER", "csf") # dtm을 먼저 빌드해야 TIN 등고선 사전 캐시가 dtm footprint를 참조할 수 있다 (PLAN D-6) SURFACE_MODEL_PRECOMPUTE = tuple( os.getenv("SURFACE_MODEL_PRECOMPUTE", "dtm,tin,nurbs,implicit,meshfree").split(",") diff --git a/ui_template/ui_template_locale_b1.ts b/ui_template/ui_template_locale_b1.ts index 44277d3f..c61d1168 100644 --- a/ui_template/ui_template_locale_b1.ts +++ b/ui_template/ui_template_locale_b1.ts @@ -501,6 +501,23 @@ export const ui_locales_b1 = { "모델 확정에 실패했습니다.", "Failed to confirm model.", ], + B04_Surface_Build_Confirm: [ + "이 조합({filter} · {method})은 아직 만들어지지 않았습니다.\n지금 계산해 영구 저장할까요? 자료량에 따라 수 분이 걸립니다.", + "This combination ({filter} · {method}) has not been built yet.\nBuild and store it now? This can take several minutes depending on data size.", + ], + B04_Surface_Build_Action: ["계산하기", "Build"], + B04_Surface_Build_Running: [ + "지표면 모델 계산 중… 창을 닫지 마세요.", + "Building surface model… keep this window open.", + ], + B04_Surface_Build_Done: [ + "계산 완료 — {filter} · {method} 모델을 저장했습니다.", + "Build complete — stored the {filter} · {method} model.", + ], + B04_Surface_Build_Failed: [ + "지표면 모델 계산에 실패했습니다.", + "Failed to build the surface model.", + ], B04_Surface_Map_Title: [ "2D 배경 지도 및 GIS 레이어", "2D Basemap and GIS Layers",