Spaces:
Sleeping
Sleeping
Download data_confidence.py from Assefore/forest-suitability: direct link, hf CLI and curl.
- Browser
- Download file 27.4 kB
-
https://huggingface.co/spaces/Assefore/forest-suitability/resolve/main/data_confidence.py
- Command line
-
hf download hf://spaces/Assefore/forest-suitability/data_confidence.py
-
curl -L -o data_confidence.py https://huggingface.co/spaces/Assefore/forest-suitability/resolve/main/data_confidence.py
27.4 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| data_confidence.py — AsseFore 데이터 신뢰도 시스템 (3분리) | |
| ──────────────────────────────────────────────────────────── | |
| 문제: 신뢰도가 평균 35점으로 과소평가됨. | |
| ① 있는 데이터도 key mismatch로 missing 처리 (예: ph → soil_ph) | |
| ② 전략과 무관한 missing도 일괄 벌점 (예: 임산물에 grid_distance) | |
| ③ 입력/전략/수익 신뢰도를 하나로 합쳐 표시 | |
| ④ revenue를 전부 Tier E 기본값처럼 처리(income_source 미활용) | |
| 해결: 신뢰도를 input/strategy/revenue(+owner_fit) 로 분리하고, | |
| 전략별 필요 필드만 평가하며, missing penalty에 상한을 둔다. | |
| 없는 데이터를 있는 척하지 않되, 있는 공공데이터는 제대로 인정한다. | |
| 기존 구조 비파괴: app/results/opt/portfolio 를 읽기만 하고, | |
| build_confidence_result() 가 단일 confidence_result 객체를 돌려준다. | |
| """ | |
| from __future__ import annotations | |
| # ── §3 source_quality_score ───────────────────────────────────────── | |
| SOURCE_QUALITY = { | |
| "measured_field_data": 95, "official_api": 90, "official_vector_layer": 85, | |
| "public_gis_layer": 75, "official_statistics": 65, "remote_sensing_proxy": 60, | |
| "osm_proxy": 55, "user_self_report": 50, "expert_label": 75, | |
| "interview_estimate": 45, "model_default": 30, "simulation": 25, "missing": 0, | |
| } | |
| def lookup_source_quality(source_type): | |
| return SOURCE_QUALITY.get(source_type, 0) | |
| # ── §2 등급 체계 ──────────────────────────────────────────────────── | |
| def grade_from_score(score): | |
| if score >= 85: return "A" | |
| if score >= 70: return "B" | |
| if score >= 55: return "C" | |
| if score >= 40: return "D" | |
| return "E" | |
| def level_from_score(score): | |
| if score >= 85: return "높음" | |
| if score >= 70: return "양호" | |
| if score >= 55: return "중간" | |
| if score >= 40: return "낮음" | |
| return "매우 낮음" | |
| def _clip(x, lo=0, hi=100): | |
| return max(lo, min(hi, x)) | |
| # ── §12 값 정상범위 검사 ──────────────────────────────────────────── | |
| _VALID_RANGES = { | |
| "slope": (0, 60), "soil_ph": (3.5, 8.0), "age_class": (1, 7), | |
| "altitude": (0, 1950), "canopy_density": (0, 100), "annual_rain": (600, 2500), | |
| "mean_temp": (-5, 20), "area_ha": (0.01, 100000), | |
| } | |
| def value_validity_score(field, value): | |
| if value is None or value == "" or value == "unknown": | |
| return 0 | |
| rng = _VALID_RANGES.get(field) | |
| if rng: | |
| try: | |
| v = float(value) | |
| if rng[0] <= v <= rng[1]: | |
| return 100 | |
| # 범위 약간 벗어남 → 의심값 | |
| if rng[0] * 0.8 <= v <= rng[1] * 1.2: | |
| return 60 | |
| return 30 | |
| except Exception: | |
| return 60 | |
| if field == "ecological_grade": | |
| return 100 if value in (1, 2, 3, 8, 9, 10) else 60 | |
| return 100 # 범주형/일반값은 존재하면 정상으로 간주 | |
| # ── §4 field_quality 생성 + §12 field_confidence ──────────────────── | |
| _VALIDATION_METHOD = { | |
| "soil_ph": "토양정밀검사", "slope": "현장 경사 측정", "drainage": "현장 배수 확인", | |
| "forest_type": "현장 임상 확인", "legal_zone": "지자체 산지구분 확인", | |
| "area_ha": "지적측량", "road_distance": "임도/진입로 현장확인", | |
| } | |
| _IMPACT = { | |
| "soil_ph": "작물 적합도·수익 추정", "slope": "생산가능면적·작업성·리스크", | |
| "forest_type": "재배 적지·전략 판정", "legal_zone": "법적 실현가능성·전략", | |
| "drainage": "작물 적합도", "ecological_grade": "보존 필요도·가용면적", | |
| "landslide_grade": "리스크·생산가능면적", "area_ha": "전체 규모·투자·수익", | |
| } | |
| def build_field_quality(field, value, source, source_type, | |
| spatial="public_layer_intersect", validated=False): | |
| is_missing = value is None or value == "" or value == "unknown" | |
| sqs = 0 if is_missing else lookup_source_quality(source_type) | |
| vvs = value_validity_score(field, value) | |
| srs = {"field_clip": 90, "public_layer_intersect": 75, "buffer_estimate": 55, | |
| "point_estimate": 45, "simulation": 20}.get(spatial, 60) | |
| vs = (80 if validated else (40 if source_type in ( | |
| "public_gis_layer", "official_api", "official_vector_layer", | |
| "official_statistics") else 30)) | |
| if is_missing: | |
| srs = vs = 0 | |
| field_conf = _clip(0.50 * sqs + 0.25 * vvs + 0.15 * srs + 0.10 * vs) | |
| is_proxy = source_type in ("osm_proxy", "remote_sensing_proxy") | |
| return { | |
| "field": field, "value": value, "source": source, "source_type": source_type, | |
| "source_quality_score": sqs, "confidence_score": round(field_conf), | |
| "confidence_level": "missing" if is_missing else level_from_score(field_conf), | |
| "is_missing": is_missing, "is_proxy": is_proxy, | |
| "is_measured": source_type == "measured_field_data", | |
| "needs_field_validation": is_missing or (not validated and field in _VALIDATION_METHOD), | |
| "validation_method": _VALIDATION_METHOD.get(field, "현장확인"), | |
| "impact_on_model": _IMPACT.get(field, "보조 지표"), | |
| "warning": (f"{field} 누락 — {_VALIDATION_METHOD.get(field, '현장확인')} 필요" | |
| if is_missing else ("추정값(현장확인 권장)" if is_proxy else "")), | |
| } | |
| # ── §5 soil_ph mapping (핵심 버그 수정) ───────────────────────────── | |
| def map_soil_ph(data): | |
| """data['ph'] 등 다양한 key를 soil_ph로 흡수. (value, source, source_type, validated)""" | |
| d = data or {} | |
| if d.get("soil_ph") is not None: | |
| meas = d.get("soil_ph_is_measured") | |
| return (d["soil_ph"], "실측/명시 soil_ph", | |
| "measured_field_data" if meas else "public_gis_layer", bool(meas)) | |
| for k in ("ph", "soil_pH", "pH"): | |
| if d.get(k) is not None: | |
| src_sim = (d.get("source") == "시뮬레이션") | |
| return (d[k], "산림입지토양도 기반 pH 추정", | |
| "simulation" if src_sim else "public_gis_layer", False) | |
| return (None, "missing", "missing", False) | |
| # ── 입력 필드 메타 (값 추출 + 출처 판정) ──────────────────────────── | |
| INPUT_FIELD_WEIGHTS = { | |
| "area_ha": 10, "parcel_geometry": 10, "slope": 8, "altitude": 4, | |
| "forest_type": 10, "species_composition": 8, "age_class": 8, | |
| "canopy_density": 6, "density": 4, "drainage": 6, "soil_ph": 6, | |
| "landslide_grade": 5, "ecological_grade": 6, "legal_zone": 7, | |
| "protection_area": 4, "annual_rain": 4, "mean_temp": 4, | |
| } | |
| _INPUT_CRITICAL = {"area_ha", "parcel_geometry", "forest_type", "slope", "legal_zone"} | |
| def _src_type_for(data, field): | |
| """현장데이터 출처(실측 SHP vs 시뮬레이션)에 따라 source_type 결정.""" | |
| sim = (data or {}).get("source") == "시뮬레이션" | |
| api_fields = {"legal_zone", "protection_area", "area_ha", "parcel_geometry"} | |
| gis_fields = {"forest_type", "species_composition", "age_class", "canopy_density", | |
| "density", "drainage", "slope", "altitude", "soil_ph"} | |
| weather = {"annual_rain", "mean_temp"} | |
| eco = {"ecological_grade", "landslide_grade"} | |
| if field in api_fields: | |
| return "simulation" if sim else "official_api" | |
| if field in gis_fields: | |
| return "simulation" if sim else "public_gis_layer" | |
| if field in eco: | |
| return "simulation" if sim else "public_gis_layer" | |
| if field in weather: | |
| return "simulation" if sim else "official_api" | |
| return "simulation" if sim else "public_gis_layer" | |
| def _build_input_fq(data, land_info=None): | |
| """입력 필드별 field_quality dict 생성.""" | |
| d = data or {} | |
| li = land_info or {} | |
| fq = {} | |
| def put(field, value, source): | |
| fq[field] = build_field_quality(field, value, source, _src_type_for(d, field)) | |
| put("area_ha", d.get("area_ha"), "VWorld 필지/선택 면적") | |
| put("parcel_geometry", d.get("parcel_polygon"), "VWorld 연속지적") | |
| put("slope", d.get("slope"), "토양도/지형") | |
| put("altitude", d.get("elevation"), "토양도/산정보") | |
| put("forest_type", d.get("forest_type"), "임상도") | |
| put("species_composition", (d.get("species_mix") or {}).get("by_area"), "임상도 집계") | |
| put("age_class", d.get("age_class") or d.get("age_years"), "임상도 영급") | |
| put("canopy_density", d.get("canopy_density"), "임상도 수관밀도") | |
| put("density", d.get("density") or d.get("canopy_density"), "임상도 밀도") | |
| put("drainage", d.get("drainage"), "산림입지토양도") | |
| # soil_ph 특수 처리 | |
| _v, _s, _st, _val = map_soil_ph(d) | |
| fq["soil_ph"] = build_field_quality("soil_ph", _v, _s, _st, validated=_val) | |
| put("landslide_grade", d.get("landslide_grade"), "산사태위험지도") | |
| put("ecological_grade", d.get("eco_grade"), "생태자연도(EcoBank)") | |
| put("legal_zone", li.get("legal_zone") or li.get("jimok") or | |
| (li.get("zones") or [None])[0], "VWorld 토지이용/산지구분") | |
| put("protection_area", li.get("is_conservation") if li else None, "VWorld 보호구역") | |
| put("annual_rain", d.get("annual_rain"), "기상청 ASOS") | |
| put("mean_temp", d.get("mean_temp"), "기상청 ASOS") | |
| return fq | |
| # ── §9 missing penalty cap + critical cap ─────────────────────────── | |
| def apply_critical_caps(score, missing_critical_count): | |
| if missing_critical_count == 0: | |
| cap = 100 | |
| elif missing_critical_count == 1: | |
| cap = 65 | |
| elif missing_critical_count == 2: | |
| cap = 50 | |
| else: | |
| cap = 40 | |
| return min(score, cap) | |
| # ── §6-1 input_data_confidence ────────────────────────────────────── | |
| def calculate_input_data_confidence(data, land_info=None): | |
| fq = _build_input_fq(data, land_info) | |
| tot_w = sum(INPUT_FIELD_WEIGHTS.values()) | |
| cov_w = sum(w for f, w in INPUT_FIELD_WEIGHTS.items() if not fq[f]["is_missing"]) | |
| coverage = cov_w / tot_w * 100 | |
| # source quality / field confidence 가중평균(존재 필드 기준) | |
| present = [(INPUT_FIELD_WEIGHTS[f], fq[f]) for f in INPUT_FIELD_WEIGHTS if not fq[f]["is_missing"]] | |
| if present: | |
| src_q = sum(w * q["source_quality_score"] for w, q in present) / sum(w for w, _ in present) | |
| fld_c = sum(w * q["confidence_score"] for w, q in present) / sum(w for w, _ in present) | |
| else: | |
| src_q = fld_c = 0 | |
| missing_crit = [f for f in _INPUT_CRITICAL if fq.get(f, {}).get("is_missing", True)] | |
| crit_score = 100 - 25 * len(missing_crit) | |
| val_score = 30 # 검증자료 기본값(없음) | |
| if any(q["is_measured"] for q in fq.values()): | |
| val_score = 70 | |
| raw = 0.45 * coverage + 0.30 * src_q + 0.15 * _clip(crit_score) + 0.10 * val_score | |
| # 가중평균 field confidence 도 반영(품질 보정) | |
| raw = 0.7 * raw + 0.3 * fld_c | |
| score = apply_critical_caps(raw, len(missing_crit)) | |
| # area 특수 cap | |
| if fq["area_ha"]["is_missing"]: | |
| score = min(score, 45) | |
| elif fq["parcel_geometry"]["is_missing"]: | |
| score = min(score, 75) | |
| score = round(_clip(score)) | |
| return { | |
| "score": score, "grade": grade_from_score(score), "level": level_from_score(score), | |
| "summary": f"임상도·토양도·생태·기상·VWorld 기반 입력 {round(coverage)}% 확보", | |
| "components": {"coverage": round(coverage), "source_quality": round(src_q), | |
| "field_confidence": round(fld_c), "missing_critical": missing_crit}, | |
| "field_quality": fq, | |
| } | |
| # ── §6-2 전략별 required fields ───────────────────────────────────── | |
| REQUIRED_FIELDS_BY_STRATEGY = { | |
| # 사유림 위주: 접근성은 전국 커버 road_distance 를 주력으로, | |
| # forest_road_distance(임도망도=국유림 한정)는 보너스라 optional 로만 둔다. | |
| "임산물": {"critical": ["area_ha", "slope", "forest_type", "drainage", "soil_ph"], | |
| "important": ["road_distance", "ecological_grade", "legal_zone"], | |
| "optional": ["forest_road_distance", "stream_distance", "trail_distance", "village_distance"]}, | |
| "산양삼": {"critical": ["slope", "forest_type", "canopy_density", "drainage", "soil_ph"], | |
| "important": ["trail_distance", "legal_zone"], | |
| "optional": ["road_distance", "forest_road_distance", "village_distance"]}, | |
| "버섯": {"critical": ["forest_type", "oak_ratio", "canopy_density", "drainage"], | |
| "important": ["road_distance", "stream_distance"], | |
| "optional": ["forest_road_distance", "soil_ph"]}, | |
| "더덕": {"critical": ["soil_ph", "drainage", "slope"], | |
| "important": ["road_distance", "legal_zone"], | |
| "optional": ["trail_distance", "village_distance"]}, | |
| "벌채": {"critical": ["forest_type", "age_class", "slope", "legal_zone"], | |
| "important": ["road_distance", "landslide_grade"], | |
| "optional": ["forest_road_distance"]}, | |
| "조경수": {"critical": ["slope", "road_distance", "legal_zone"], | |
| "important": ["species_composition"], | |
| "optional": ["forest_road_distance", "village_distance"]}, | |
| "탄소": {"critical": ["area_ha", "forest_type", "age_class", "legal_zone"], | |
| "important": ["ecological_grade"], | |
| "optional": ["ownership_complexity"]}, | |
| "태양광": {"critical": ["slope", "grid_distance", "legal_zone"], | |
| "important": ["road_distance", "protection_area", "ecological_grade"], | |
| "optional": []}, | |
| "위탁경영": {"critical": ["owner_direct_management_intent", "legal_zone"], | |
| "important": ["road_distance"], | |
| "optional": ["forest_road_distance", "owner_age", "ownership_complexity"]}, | |
| "보존": {"critical": ["ecological_grade", "legal_zone", "forest_type"], | |
| "important": ["landslide_grade", "protection_area"], | |
| "optional": []}, | |
| "복원": {"critical": ["forest_type", "age_class", "legal_zone"], | |
| "important": ["ecological_grade", "slope"], | |
| "optional": []}, | |
| "저강도": {"critical": ["forest_type", "slope", "legal_zone"], | |
| "important": ["drainage", "ecological_grade"], | |
| "optional": []}, | |
| } | |
| _W = {"critical": 3, "important": 2, "optional": 1} | |
| _LEGAL_SENSITIVE = {"벌채", "조경수", "태양광", "탄소"} | |
| def _strategy_key(name): | |
| """전략명 → REQUIRED 키 매핑(부분일치).""" | |
| n = name or "" | |
| for k in REQUIRED_FIELDS_BY_STRATEGY: | |
| if k in n: | |
| return k | |
| if "버섯" in n or "표고" in n or "목이" in n: | |
| return "버섯" | |
| if "도라지" in n: | |
| return "더덕" | |
| if "임산물" in n or "복합" in n: | |
| return "임산물" | |
| if "보전" in n: | |
| return "보존" | |
| return "임산물" | |
| def _field_present(field, fq): | |
| """입력 field_quality 또는 거리/소유 필드 존재 여부.""" | |
| if field in fq: | |
| return not fq[field]["is_missing"], fq[field].get("confidence_score", 0) | |
| # 아직 미구현 필드(거리·소유 등)는 결측으로 처리 | |
| return False, 0 | |
| def calculate_strategy_confidence(strategy_name, fq, parcel_extra=None): | |
| key = _strategy_key(strategy_name) | |
| spec = REQUIRED_FIELDS_BY_STRATEGY[key] | |
| extra = parcel_extra or {} | |
| def present(field): | |
| if field in fq: | |
| return not fq[field]["is_missing"], fq[field].get("confidence_score", 0) | |
| v = extra.get(field) | |
| return (v is not None), (60 if v is not None else 0) | |
| tot_w = avail_w = 0 | |
| conf_sum = 0 | |
| missing_crit = 0 | |
| for level, fields in (("critical", spec["critical"]), ("important", spec["important"]), | |
| ("optional", spec["optional"])): | |
| for f in fields: | |
| w = _W[level] | |
| tot_w += w | |
| ok, c = present(f) | |
| if ok: | |
| avail_w += w | |
| conf_sum += w * c | |
| elif level == "critical": | |
| missing_crit += 1 | |
| coverage = (avail_w / tot_w * 100) if tot_w else 0 | |
| src_q = (conf_sum / avail_w) if avail_w else 0 | |
| relevance = 100 # 전략별 필요필드만 봤으므로 관련성 만점 | |
| validation = 30 | |
| execution = 50 | |
| raw = (0.40 * coverage + 0.25 * src_q + 0.20 * relevance | |
| + 0.10 * validation + 0.05 * execution) | |
| # hard caps | |
| score = raw | |
| if missing_crit >= 1: | |
| score = min(score, 65) | |
| if missing_crit >= 2: | |
| score = min(score, 50) | |
| if key in _LEGAL_SENSITIVE and (fq.get("legal_zone", {}).get("is_missing", True)): | |
| score = min(score, 55) | |
| if key == "태양광" and not extra.get("grid_distance"): | |
| score = min(score, 45) | |
| score = round(_clip(score)) | |
| return {"score": score, "grade": grade_from_score(score), "level": level_from_score(score), | |
| "coverage": round(coverage), "missing_critical": missing_crit} | |
| def calculate_all_strategy_confidences(fq, strategy_result, parcel_extra=None): | |
| """포트폴리오 상위 전략의 가중평균으로 strategy_confidence 산출.""" | |
| by_strategy = {} | |
| sr = strategy_result or {} | |
| tops = sr.get("top_strategies") or [] | |
| for t in tops: | |
| by_strategy[t["name"]] = calculate_strategy_confidence(t["name"], fq, parcel_extra) | |
| # 포트폴리오 비중으로 가중(없으면 top 단순평균) | |
| pf = sr.get("portfolio") or {} | |
| score = None | |
| if pf and by_strategy: | |
| num = den = 0 | |
| for name, conf in by_strategy.items(): | |
| # 전략명→유형 매칭이 어려우면 동일가중 | |
| w = 1 | |
| num += w * conf["score"]; den += w | |
| score = num / den if den else None | |
| if score is None and by_strategy: | |
| score = sum(c["score"] for c in by_strategy.values()) / len(by_strategy) | |
| if score is None: | |
| score = 50 | |
| score = round(_clip(score)) | |
| return {"score": score, "grade": grade_from_score(score), "level": level_from_score(score), | |
| "summary": "포트폴리오 상위 전략 기준, 전략별 필요 데이터만 반영", | |
| "by_strategy": by_strategy} | |
| # ── §6-3 revenue_confidence (source tier 반영) ────────────────────── | |
| def calculate_revenue_confidence(results, crop_name=None, parcel_data=None): | |
| r = (results or {}).get(crop_name, {}) if crop_name else {} | |
| income_source = (r.get("income_source") or "") | |
| pd = parcel_data or {} | |
| # 기본 점수(모델 기본값 가정) | |
| yield_s = price_s = 30 | |
| cost_s = 30 | |
| if "임산물소득조사" in income_source: | |
| yield_s = max(yield_s, 65); price_s = max(price_s, 60); tier = "C" | |
| elif "추정치" in income_source: | |
| yield_s = max(yield_s, 45); price_s = max(price_s, 45); tier = "D" | |
| else: | |
| tier = "E" | |
| # 실제 견적이 있으면(운영자/피드백 연동 시) cost_s 상승 — 현재는 추정 | |
| if r.get("quote_cost"): | |
| cost_s = max(cost_s, 80) | |
| local_market = 50 # 일반 시장 존재 가정 | |
| field_validation = 30 # 현장검증 없음 | |
| legal_execution = 60 if pd.get("legal_zone") else 40 | |
| weighted = (0.25 * yield_s + 0.20 * price_s + 0.20 * cost_s | |
| + 0.15 * local_market + 0.10 * field_validation + 0.10 * legal_execution) | |
| # capped penalties | |
| pen = 0 | |
| pen += 10 # 현장검증 없음 | |
| if not pd.get("legal_zone"): | |
| pen += 8 | |
| if (pd.get("slope") or 0) >= 30: | |
| pen += 5 | |
| pen = min(pen, 25) | |
| score = weighted - pen | |
| if yield_s == 30 and price_s == 30 and cost_s == 30: | |
| score = min(score, 45) | |
| if yield_s == 0 and price_s == 0: | |
| score = min(score, 50) | |
| score = round(_clip(score)) | |
| return {"score": score, "grade": grade_from_score(score), "level": level_from_score(score), | |
| "summary": f"수익 출처 등급 {tier} · 수확량/단가/비용 {'통계' if tier=='C' else '추정·모델'} 기반", | |
| "components": {"yield": yield_s, "price": price_s, "cost": cost_s, | |
| "local_market": local_market, "tier": tier}} | |
| # ── owner_fit_confidence ──────────────────────────────────────────── | |
| def calculate_owner_fit_confidence(user_inputs=None): | |
| u = user_inputs or {} | |
| have = [k for k in ("ownership_complexity", "owner_direct_management_intent", | |
| "owner_goal", "long_term_lease_possible") if u.get(k)] | |
| score = round(_clip(25 + len(have) * 18)) | |
| return {"score": score, "grade": grade_from_score(score), "level": level_from_score(score), | |
| "summary": ("산주 의향 정보 미입력 — 위탁/직접경영 추천 신뢰도 낮음" if not have | |
| else f"산주 의향 {len(have)}/4 항목 입력됨")} | |
| # ── §8 개선 플랜 ──────────────────────────────────────────────────── | |
| def build_improvement_plan(input_c, strategy_c, revenue_c, fq): | |
| plan = [] | |
| if fq.get("soil_ph", {}).get("is_missing") or fq.get("soil_ph", {}).get("is_proxy") \ | |
| or fq.get("soil_ph", {}).get("source_type") == "public_gis_layer": | |
| plan.append({"action": "토양정밀검사(soil_ph 실측)", | |
| "expected_impact": {"input_data_confidence": +5, "strategy_confidence": +8, | |
| "revenue_confidence": +4}}) | |
| plan.append({"action": "도로/임도/수계 거리 데이터 추가", | |
| "expected_impact": {"input_data_confidence": +5, "strategy_confidence": +15, | |
| "revenue_confidence": +3}}) | |
| plan.append({"action": "산림조합/업체 초기투자비 견적 입력", | |
| "expected_impact": {"input_data_confidence": 0, "strategy_confidence": +5, | |
| "revenue_confidence": +15}}) | |
| plan.append({"action": "산주 경영의향 입력", | |
| "expected_impact": {"input_data_confidence": 0, "strategy_confidence": +8, | |
| "revenue_confidence": 0, "owner_fit_confidence": +25}}) | |
| plan.append({"action": "전문가(교수/산림조합) 라벨링", | |
| "expected_impact": {"input_data_confidence": +3, "strategy_confidence": +10, | |
| "revenue_confidence": +5}}) | |
| return plan | |
| def _after(cur, plan, keys): | |
| """선택 플랜들의 기대 효과를 더해 보완 후 점수 산출.""" | |
| out = dict(cur) | |
| for p in plan: | |
| for k, v in p["expected_impact"].items(): | |
| short = {"input_data_confidence": "input", "strategy_confidence": "strategy", | |
| "revenue_confidence": "revenue"}.get(k) | |
| if short in out: | |
| out[short] = min(100, out[short] + v) | |
| return out | |
| # ── §1 메인: 단일 confidence_result ───────────────────────────────── | |
| def build_confidence_result(data, results, opt=None, portfolio=None, | |
| user_inputs=None, strategy_result=None, | |
| land_info=None, crop_name=None): | |
| input_c = calculate_input_data_confidence(data, land_info) | |
| fq = input_c["field_quality"] | |
| # 거리·소유 등 미구현 필드(있으면 사용) | |
| extra = {} | |
| for k in ("road_distance", "forest_road_distance", "stream_distance", | |
| "trail_distance", "village_distance", "grid_distance", | |
| "oak_ratio", "owner_direct_management_intent"): | |
| if (data or {}).get(k) is not None: | |
| extra[k] = data[k] | |
| if (data or {}).get("species_mix"): | |
| extra.setdefault("oak_ratio", ((data["species_mix"].get("by_area") or {}))) | |
| strat_c = calculate_all_strategy_confidences(fq, strategy_result, extra) | |
| if crop_name is None and results: | |
| crop_name = max(results, key=lambda n: results[n].get("score", 0)) | |
| pd_min = {"legal_zone": fq.get("legal_zone", {}).get("value"), | |
| "slope": (data or {}).get("slope")} | |
| rev_c = calculate_revenue_confidence(results, crop_name, pd_min) | |
| owner_c = calculate_owner_fit_confidence(user_inputs) | |
| plan = build_improvement_plan(input_c, strat_c, rev_c, fq) | |
| cur = {"input": input_c["score"], "strategy": strat_c["score"], "revenue": rev_c["score"]} | |
| after_basic = _after(cur, plan[:3], cur) | |
| after_full = _after(cur, plan, cur) | |
| crit_missing = input_c["components"]["missing_critical"] | |
| noncrit = [f for f, q in fq.items() if q["is_missing"] and f not in _INPUT_CRITICAL] | |
| checks = [] | |
| if fq.get("area_ha", {}).get("is_missing") is False: | |
| checks.append("실제 지적경계 확인") | |
| checks += ["토양정밀검사(pH)", "도로/임도 진입 가능성", "수계/계곡부 확인", | |
| "산림조합/업체 초기투자비 견적", "산주 경영의향/장기계약 가능성"] | |
| result = { | |
| "input_data_confidence": {k: input_c[k] for k in | |
| ("score", "grade", "level", "summary", "components")}, | |
| "strategy_confidence": strat_c, | |
| "revenue_confidence": rev_c, | |
| "owner_fit_confidence": owner_c, | |
| "field_quality": fq, | |
| "critical_missing_fields": crit_missing, | |
| "noncritical_missing_fields": noncrit, | |
| "field_checks_required": checks, | |
| "improvement_plan": plan, | |
| "current_vs_after_improvement": { | |
| "current": cur, "after_basic_improvement": after_basic, | |
| "after_field_validation": after_full}, | |
| "display_text": "", | |
| } | |
| result["display_text"] = generate_confidence_display_text(result) | |
| return result | |
| # ── §14 표시 문구 ─────────────────────────────────────────────────── | |
| def generate_confidence_display_text(cr): | |
| i = cr["input_data_confidence"]; s = cr["strategy_confidence"]; r = cr["revenue_confidence"] | |
| return ( | |
| f"입력데이터 신뢰도 {i['grade']}({i['score']}점) · " | |
| f"전략추천 신뢰도 {s['grade']}({s['score']}점) · " | |
| f"수익예측 정밀도 {r['grade']}({r['score']}점). " | |
| "수익예측은 현장견적·실제 수확량 자료가 없어 보수적으로 낮게 표시됩니다. " | |
| "다만 산지 기본정보는 임상도·토양도·생태자연도·산사태위험·기상·VWorld 기반으로 분석되었으며, " | |
| "도로/임도/수계 거리, 토양정밀검사, 산림조합 견적이 추가되면 신뢰도가 상승합니다." | |
| ) | |