외부 데이터셋 검증기 — 엔진 입력 제약 9규칙 전수 검사 (xlsx/csv)

앵커 산식·9분면 clip·가격 관계·구간 라벨·상태-최종가 정합 검사,
위반 행을 사유 포함 CSV로 내보냄 (합성데이터 1만 건 QA에 사용)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UFZ7JWdwCaQAwNYJErL8pP
This commit is contained in:
민헌andClaude Fable 5 committed 2026-09-01 08:58:06 +09:00
1 parent 178f6daa17
commit c79fee74e7
1 file changed
+150
+150
View File
@@ -0,0 +1,150 @@
#!/usr/bin/env python3
"""외부 제공 협상 데이터셋(합성/운용) 검증기 — 엔진 입력 제약 전수 검사.
검사 규칙 (엔진·테스트셋 제약과 동일):
R1 품목가격 > 0
R2 0 < 목표가격 <= 품목가격
R3 목표앵커링가격 < 목표가격
R4 앵커 = floor(목표가격 × (1 − 앵커링값)) (오차 ±1)
R5 0.01 <= 앵커링값 <= 0.40 (9분면 매트릭스 clip 범위)
R6 앵커링가격범위/협력사유형에 'BASIC' 등 좌표 밖 값 없음 + 가격구간 라벨 일치
R7 인터넷최저가는 품목가격의 5%~500% 밴드 (결측 허용 — 엔진 fallback)
R8 협상완료면 최종협상가격 존재, 그 외 상태면 부재
R9 협상종료시간 >= 견적시작시간
(참고) 협상완료인데 최종가 > 품목가격은 결과 컬럼 경고로만 집계
사용:
python3 validate_dataset.py <파일.xlsx|파일.csv> [--sheet 원본] [--out 위반행.csv]
"""
import argparse
import csv
import math
import sys
from collections import Counter
from pathlib import Path
BANDS = {
"만원이하": lambda p: p <= 10000,
"만원초과 백만원미만": lambda p: 10000 < p < 1000000,
"백만원이상": lambda p: p >= 1000000,
}
def load_rows(path: Path, sheet: str):
if path.suffix.lower() == ".csv":
with open(path, newline="", encoding="utf-8-sig") as f:
reader = csv.reader(f)
header = next(reader)
yield header
for row in reader:
yield [c if c != "" else None for c in row]
return
import openpyxl
wb = openpyxl.load_workbook(path, read_only=True)
ws = wb[sheet] if sheet in wb.sheetnames else wb[wb.sheetnames[0]]
for row in ws.iter_rows(values_only=True):
yield list(row)
def num(v):
if v is None or v == "":
return None
try:
return float(v)
except (TypeError, ValueError):
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("file")
ap.add_argument("--sheet", default="원본")
ap.add_argument("--out", default=None, help="위반 행 CSV 경로 (사유 포함)")
args = ap.parse_args()
rows = load_rows(Path(args.file), args.sheet)
header = next(rows)
idx = {h: i for i, h in enumerate(header)}
def g(r, name):
i = idx.get(name)
return r[i] if i is not None and i < len(r) else None
counts = Counter()
warn = Counter()
violations = [] # (견적번호, 협력사코드, 견적차수, 사유들)
total = 0
for r in rows:
if g(r, "견적번호") is None:
continue
total += 1
price = num(g(r, "품목가격"))
target = num(g(r, "목표가격"))
anchor = num(g(r, "목표앵커링가격"))
av = num(g(r, "앵커링값"))
ilow = num(g(r, "인터넷최저가"))
final = num(g(r, "최종협상가격"))
state = g(r, "협상상태")
band = g(r, "앵커링가격범위")
reasons = []
if price is None or price <= 0:
reasons.append("R1 품목가격 0/결측")
if target is None or target <= 0:
reasons.append("R2 목표가격 결측")
elif price is not None and price > 0 and target > price:
reasons.append("R2 목표가>품목가격")
if anchor is not None and target is not None and anchor >= target:
reasons.append("R3 앵커>=목표가")
if av is not None:
if not (0.01 <= av <= 0.40):
reasons.append("R5 앵커링값 범위밖")
if target is not None and anchor is not None \
and abs(anchor - math.floor(target * (1 - av))) > 1:
reasons.append("R4 앵커 산식 불일치")
if band not in BANDS:
reasons.append(f"R6 가격범위 값 이상({band})")
elif price is not None and price > 0 and not BANDS[band](price):
reasons.append("R6 가격구간 라벨 불일치")
if ilow is not None and price is not None and price > 0 \
and not (price * 0.05 <= ilow <= price * 5):
reasons.append("R7 인터넷최저가 극단치")
if state == "협상완료" and final is None:
reasons.append("R8 완료인데 최종가 없음")
if state != "협상완료" and final is not None:
reasons.append("R8 미완료인데 최종가 존재")
s0, s1 = g(r, "견적시작시간"), g(r, "협상종료시간")
if s0 and s1 and str(s1) < str(s0):
reasons.append("R9 협상종료<견적시작")
# 결과 컬럼 경고 (입력 위반은 아님)
if state == "협상완료" and final is not None and price and final > price:
warn["경고: 완료 최종가>기존가"] += 1
if reasons:
for x in reasons:
counts[x] += 1
violations.append((g(r, "견적번호"), g(r, "협력사코드"),
g(r, "견적차수"), " | ".join(reasons)))
ok = total - len(violations)
print(f"총 {total}행 — 통과 {ok} ({ok/total*100:.1f}%) / 위반 {len(violations)}")
for k, v in sorted(counts.items(), key=lambda x: -x[1]):
print(f" {k}: {v}")
for k, v in warn.items():
print(f" {k}: {v}")
if args.out and violations:
with open(args.out, "w", newline="", encoding="utf-8-sig") as f:
w = csv.writer(f)
w.writerow(["견적번호", "협력사코드", "견적차수", "위반사유"])
w.writerows(violations)
print(f"위반 행 목록 저장: {args.out}")
sys.exit(0 if not violations else 1)
if __name__ == "__main__":
main()