diff --git a/Homework/ML_FactoryAutomation/src/report_util.py b/Homework/ML_FactoryAutomation/src/report_util.py new file mode 100644 index 0000000..294048d --- /dev/null +++ b/Homework/ML_FactoryAutomation/src/report_util.py @@ -0,0 +1,50 @@ +"""회차별 예측 결과 CSV를 요약해 리포트 텍스트로 저장하는 유틸리티.""" +import os +import csv + + +def summarize_csv(path): + rows = [] + try: + with open(path) as f: + for row in csv.reader(f): + rows.append(row) + except Exception: + pass + + total = 0.0 + count = 0 + for row in rows[1:]: + if len(row) < 2: + continue + try: + total = total + float(row[1]) + count = count + 1 + except Exception: + pass + + if count == 0: + return {"mean": 0.0, "count": 0, "grade": "N/A"} + + mean = total / count + if mean > 0.75: + grade = "HIGH" + elif mean > 0.35: + grade = "MID" + else: + grade = "LOW" + + return {"mean": mean, "count": count, "grade": grade} + + +def save_summary(result, out_dir="C:/temp/pdm_reports"): + if not os.path.exists(out_dir): + os.makedirs(out_dir) + + out_path = out_dir + "/summary.txt" + with open(out_path, "w") as f: + f.write("count=" + str(result["count"]) + "\n") + f.write("mean=" + str(result["mean"]) + "\n") + f.write("grade=" + str(result["grade"]) + "\n") + + return out_path diff --git a/Homework/ML_FactoryAutomation/tests/test_report_util.py b/Homework/ML_FactoryAutomation/tests/test_report_util.py new file mode 100644 index 0000000..7388209 --- /dev/null +++ b/Homework/ML_FactoryAutomation/tests/test_report_util.py @@ -0,0 +1,32 @@ +import os + +from src.report_util import summarize_csv, save_summary + + +def test_summarize_csv_returns_na_for_header_only(tmp_path): + p = tmp_path / "empty.csv" + p.write_text("machine_id,risk\n", encoding="utf-8") + + result = summarize_csv(str(p)) + + assert result["count"] == 0 + assert result["grade"] == "N/A" + + +def test_summarize_csv_grades_high_when_mean_above_threshold(tmp_path): + p = tmp_path / "risk.csv" + p.write_text("machine_id,risk\nM-1,0.9\nM-2,0.8\n", encoding="utf-8") + + result = summarize_csv(str(p)) + + assert result["count"] == 2 + assert result["grade"] == "HIGH" + + +def test_save_summary_writes_expected_file(tmp_path): + out_dir = tmp_path / "reports" + + out_path = save_summary({"count": 2, "mean": 0.85, "grade": "HIGH"}, out_dir=str(out_dir)) + + assert os.path.exists(out_path) + assert "grade=HIGH" in open(out_path).read()