Claude Claude Opus 5.5 commited on
Commit
ba019f3
·
1 Parent(s): b28628d

run_image_surface_eval_agent: กลุ่มควบคุม (--from-rows brand_calibration_rows.csv · Movex + ไม่ใช่สายพาน) วัดว่า agent หลงตอบเป็น Modutech แค่ไหน

Browse files
Files changed (1) hide show
  1. run_image_surface_eval_agent.py +89 -16
run_image_surface_eval_agent.py CHANGED
@@ -5,6 +5,13 @@ run_image_surface_eval_agent.py — วัด agent กับรูปจริ
5
  python run_image_surface_eval_agent.py --labels ... --text "" --text "สายพานแบบนี้มีรุ่นไหนบ้างครับ" -o ...
6
 
7
  labels_test.csv คอลัมน์: path (สัมพัทธ์กับโฟลเดอร์ของไฟล์) · belt_code · surface · (view · angle · card ... ใช้แยกผลด้วย --by)
 
 
 
 
 
 
 
8
  ทุกรูปเป็นบทสนทนาใหม่ · ใช้ค่าตั้งที่ล็อกของ agent (ไม่ตั้งอะไร = r3 + สวิตช์ blind v2 + AGENT_IMAGE_SURFACE เปิด)
9
 
10
  ต่อรูปบันทึก
@@ -36,7 +43,7 @@ sys.path.insert(0, ROOT)
36
 
37
  from run_image_eval_agent import codes_in, known_codes, outcome # noqa: E402
38
 
39
- JUDGE = """คุณเป็นผู้ตรวจคำตอบของแชทบอทขายสายพาน ลูกค้าส่งรูปสายพานมา{text_note}
40
  อ่านคำตอบของบอทแล้วตอบเป็น JSON เท่านั้น:
41
  {{"brand_claimed": "modutech" | "movex" | "other" | "none",
42
  "asked_back": true | false,
@@ -101,6 +108,41 @@ def surface_result(args: dict) -> dict:
101
  return {"error": f"{type(e).__name__}: {e}"}
102
 
103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  def summarize(label, rs, short=False):
105
  n = len(rs)
106
  called = [r for r in rs if r["called"]]
@@ -128,7 +170,11 @@ def summarize(label, rs, short=False):
128
 
129
  def main() -> int:
130
  ap = argparse.ArgumentParser()
131
- ap.add_argument("--labels", required=True)
 
 
 
 
132
  ap.add_argument("--text", action="append", help="ข้อความที่ลูกค้าพิมพ์มากับรูป (ใส่ได้หลายครั้ง · ไม่ใส่ = ส่งรูปอย่างเดียว)")
133
  ap.add_argument("--runs", type=int, default=1)
134
  ap.add_argument("--limit", type=int, default=0)
@@ -138,8 +184,21 @@ def main() -> int:
138
  a = ap.parse_args()
139
  texts = a.text or [""]
140
 
141
- base = os.path.dirname(os.path.abspath(a.labels))
142
- rows = list(csv.DictReader(open(a.labels, encoding="utf-8-sig")))
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  if a.limit:
144
  rows = rows[: a.limit]
145
  missing = [r["path"] for r in rows if not os.path.isfile(os.path.join(base, r["path"]))]
@@ -152,7 +211,7 @@ def main() -> int:
152
  if not image_surface_enabled():
153
  print("⚠️ AGENT_IMAGE_SURFACE=0 — agent ไม่มี belts_by_surface (วัดได้แค่ตัวเทียบ)")
154
  codes = known_codes()
155
- extra = [k for k in rows[0] if k not in ("path", "belt_code", "surface")]
156
  jobs = [(run, t, r) for run in range(1, a.runs + 1) for t in texts for r in rows]
157
  print(f"✅ {A.engine.llm.describe()} · {len(rows)} รูป × {len(texts)} ข้อความ × {a.runs} รอบ = {len(jobs)} บทสนทนา")
158
  results = []
@@ -173,11 +232,13 @@ def main() -> int:
173
  res = surface_result(args) if sc else {}
174
  lst = res.get("belt_codes_complete") if res.get("matched") else None
175
  read = [args.get("surface") or ""] + [x.strip() for x in (args.get("alternatives") or "").split(",") if x.strip()]
176
- truth, tsurf = r["belt_code"].strip(), r["surface"].strip()
 
177
  j = (judge(reply, text) if reply else {}) if not a.no_judge else {}
178
  claimed = j.get("model_claimed") or None
 
179
  rec = {
180
- "run": run, "text": text, "path": r["path"], "belt_code": truth, "surface_true": tsurf,
181
  **{k: r.get(k, "") for k in extra},
182
  "called": bool(sc), "n_surface_calls": len(sc), "surface_args": args,
183
  "surface_ok": (tsurf in read) if sc else None,
@@ -186,37 +247,49 @@ def main() -> int:
186
  "keeps_true": (truth in lst) if lst is not None else None,
187
  "rank_true": (lst.index(truth) + 1 if truth in lst else None) if lst else None,
188
  "model_claimed": claimed, "claim_correct": bool(claimed) and norm(claimed) == norm(truth),
189
- "asks_useful": j.get("asks_useful"), "brand_outcome": outcome("modutech", j) if j else None,
190
- "codes_mentioned": codes_in(reply, codes), "judge": j,
 
 
191
  "reply": reply, "error": err, "seconds": sec, "tools": [c.get("tool") for c in calls],
192
  "llm_calls": usage.get("llm_calls"), "total_tokens": usage.get("total_token_count"),
193
  }
194
  results.append(rec)
195
- print(f" {i:>3}/{len(jobs)} {truth:<12} {'เรียก ' + (args.get('surface') or '?') if sc else 'ไม่เรียก':<26}"
196
  f" {('มีรุ่นจริง' if rec['keeps_true'] else 'ไม่มีรุ่นจริง') if lst is not None else '':<12}"
197
  f" {'ฟันธง ' + claimed if claimed else ''} {sec}s")
198
 
199
  print(f"\n=== {A.engine.llm.describe()} · prompt {prompt_version()} ===")
200
- summarize("ทั้งหมด", results)
 
 
 
 
 
 
 
 
201
  for col in [c.strip() for c in a.by.split(",") if c.strip()] + (["text"] if len(texts) > 1 else []):
202
  print(f"\n── แยกตาม {col}")
203
  groups = {}
204
  for x in results:
205
  groups.setdefault(str(x.get(col, "")), []).append(x)
206
  for g in sorted(groups):
207
- summarize(f"{col}={g or '(รูปอย่างเดียว)'}", groups[g], short=True)
 
208
  if a.runs > 1:
209
  by = {}
210
  for x in results:
211
  by.setdefault((x["path"], x["text"]), []).append(x)
212
- stable = sum(all(x["called"] and x["keeps_true"] and not (x["model_claimed"] and not x["claim_correct"]) for x in v)
213
- for v in by.values())
214
- print(f"\nผ่านครบทุก {a.runs} รอบ (เรียก · มีรุ่นจริง · ไม่ฟันธงผิด): {pct(stable, len(by))}")
 
215
 
216
  commit = os.popen(f'git -C "{ROOT}" rev-parse --short HEAD').read().strip()
217
  env = {k: os.environ.get(k) for k in ("AGENT_PROMPT", "AGENT_REPLY_GUARD", "AGENT_RESOLVE_TAB", "AGENT_DATASHEET_FILES",
218
  "AGENT_IMAGE_SURFACE", "GEMINI_MODEL", "GEMINI_THINKING")}
219
- json.dump({"labels": a.labels, "texts": texts, "runs": a.runs, "commit": commit, "env": env,
220
  "llm": A.engine.llm.describe(), "prompt": prompt_version(), "results": results},
221
  open(a.out, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
222
  print(f"ผลรายรูป → {a.out} · commit {commit}")
 
5
  python run_image_surface_eval_agent.py --labels ... --text "" --text "สายพานแบบนี้มีรุ่นไหนบ้างครับ" -o ...
6
 
7
  labels_test.csv คอลัมน์: path (สัมพัทธ์กับโฟลเดอร์ของไฟล์) · belt_code · surface · (view · angle · card ... ใช้แยกผลด้วย --by)
8
+ brand (ไม่ใส่ = modutech) · movex / none = รูปกลุ่มควบคุม ไม่มีรุ่นจริงให้คัด
9
+
10
+ กลุ่มควบคุม (8 พ.ย.) — รูปที่ไม่ใช่สายพาน Modutech ตรงจาก brand_calibration_rows.csv ฝั่ง eval:
11
+ python run_image_surface_eval_agent.py --from-rows <ผล 05>\brand_calibration_rows.csv --brands movex,none \
12
+ --root <โฟลเดอร์รูป Movex> --root <โฟลเดอร์รูปไม่ใช่สายพาน> -o ..\agent_img_control_r1.json
13
+ ต่อรูปบันทึก: เรียก belts_by_surface ไหม (ไม่ควร) · ตอบรายชื่อ Modutech ไหม · แบรนด์ที่ผู้ตรวจอ่านได้
14
+ สรุป: "ตอบเป็น Modutech" = เรียกเครื่องมือผิวจนได้รายชื่อ หรือคำตอบยืนยันว่าเป็น Modutech (ต้องใกล้ 0)
15
  ทุกรูปเป็นบทสนทนาใหม่ · ใช้ค่าตั้งที่ล็อกของ agent (ไม่ตั้งอะไร = r3 + สวิตช์ blind v2 + AGENT_IMAGE_SURFACE เปิด)
16
 
17
  ต่อรูปบันทึก
 
43
 
44
  from run_image_eval_agent import codes_in, known_codes, outcome # noqa: E402
45
 
46
+ JUDGE = """คุณเป็นผู้ตรวจคำตอบของแชทบอทขายสายพาน ลูกค้าส่งรูปมา{text_note}
47
  อ่านคำตอบของบอทแล้วตอบเป็น JSON เท่านั้น:
48
  {{"brand_claimed": "modutech" | "movex" | "other" | "none",
49
  "asked_back": true | false,
 
108
  return {"error": f"{type(e).__name__}: {e}"}
109
 
110
 
111
+ def summarize_control(label, rs, short=False):
112
+ """รูปที่ไม่ใช่สายพาน Modutech — วัดว่าเอเจนต์หลงตอบเป็น Modutech แค่ไหน"""
113
+ n = len(rs)
114
+ called = sum(r["called"] for r in rs)
115
+ listed = sum(bool(r["matched"]) for r in rs)
116
+ as_mod = sum(r["as_modutech"] for r in rs)
117
+ mod_codes = sum(bool(r["modutech_codes"]) for r in rs)
118
+ oc = Counter(r["brand_outcome"] for r in rs)
119
+ if short:
120
+ print(f" {label:<26} n={n:<4} ตอบเป็น Modutech {pct(as_mod, n):<22} เรียกเครื่องมือผิว {pct(called, n):<22} {dict(oc)}")
121
+ return
122
+ print(f"ตอบเป็น Modutech {pct(as_mod, n)} (ต้องใกล้ 0)")
123
+ print(f"เรียก belts_by_surface {pct(called, n)} · ได้รายชื่อ {listed}")
124
+ print(f"คำตอบเอ่ยรหัส Modutech {pct(mod_codes, n)}")
125
+ print(f"แบรนด์ (ผู้ตรวจ) {dict(oc)}")
126
+ secs = sorted(r["seconds"] for r in rs)
127
+ if secs:
128
+ print(f"เวลา (มัธยฐาน / p90) {secs[len(secs) // 2]} / {secs[int(len(secs) * 0.9) - 1 if len(secs) > 1 else 0]} วินาที")
129
+
130
+
131
+ def rows_from_calibration(path, roots, brands, split):
132
+ """แถวจาก brand_calibration_rows.csv (05_brand_calibration.py) → แถวแบบ labels · path เป็น path เต็ม"""
133
+ out, missing = [], []
134
+ for r in csv.DictReader(open(path, encoding="utf-8-sig")):
135
+ if r.get("split") != split or (r.get("brand") or "none") not in brands:
136
+ continue
137
+ fp = next((os.path.join(rt, r["path"]) for rt in roots if os.path.isfile(os.path.join(rt, r["path"]))), None)
138
+ if fp is None:
139
+ missing.append(r["path"])
140
+ continue
141
+ out.append({"path": os.path.abspath(fp), "belt_code": "", "surface": "", "brand": r.get("brand") or "none",
142
+ "cls": r.get("cls", "")})
143
+ return out, missing
144
+
145
+
146
  def summarize(label, rs, short=False):
147
  n = len(rs)
148
  called = [r for r in rs if r["called"]]
 
170
 
171
  def main() -> int:
172
  ap = argparse.ArgumentParser()
173
+ ap.add_argument("--labels", help="ไฟล์ป้ายรูป (หรือใช้ --from-rows)")
174
+ ap.add_argument("--from-rows", help="brand_calibration_rows.csv — ใช้รูปกลุ่มควบคุมจากการปรับเกณฑ์ประตูรูป")
175
+ ap.add_argument("--root", action="append", default=[], help="โฟลเดอร์ที่ path ใน --from-rows อ้างถึง (ใส่ได้หลายครั้ง)")
176
+ ap.add_argument("--brands", default="movex,none", help="แบรนด์ที่เลือกจาก --from-rows")
177
+ ap.add_argument("--split", default="eval", help="ฝั่งที่เลือกจาก --from-rows (eval = ไม่ได้ใช้ตั้งเกณฑ์)")
178
  ap.add_argument("--text", action="append", help="ข้อความที่ลูกค้าพิมพ์มากับรูป (ใส่ได้หลายครั้ง · ไม่ใส่ = ส่งรูปอย่างเดียว)")
179
  ap.add_argument("--runs", type=int, default=1)
180
  ap.add_argument("--limit", type=int, default=0)
 
184
  a = ap.parse_args()
185
  texts = a.text or [""]
186
 
187
+ if bool(a.labels) == bool(a.from_rows):
188
+ print("❌ ใส่ --labels หรือ --from-rows อย่างใดอย่างหนึ่ง")
189
+ return 1
190
+ if a.from_rows:
191
+ rows, miss = rows_from_calibration(a.from_rows, a.root, {b.strip() for b in a.brands.split(",")}, a.split)
192
+ print(f"กลุ่มควบคุมจาก {os.path.basename(a.from_rows)}: {len(rows)} รูป {dict(Counter(r['brand'] for r in rows))}"
193
+ + (f" · หาไม่เจอ {len(miss)} เช่น {miss[:3]} (เติม --root)" if miss else ""))
194
+ if not rows:
195
+ return 1
196
+ base = ""
197
+ if "brand" not in a.by:
198
+ a.by = "brand,cls"
199
+ else:
200
+ base = os.path.dirname(os.path.abspath(a.labels))
201
+ rows = list(csv.DictReader(open(a.labels, encoding="utf-8-sig")))
202
  if a.limit:
203
  rows = rows[: a.limit]
204
  missing = [r["path"] for r in rows if not os.path.isfile(os.path.join(base, r["path"]))]
 
211
  if not image_surface_enabled():
212
  print("⚠️ AGENT_IMAGE_SURFACE=0 — agent ไม่มี belts_by_surface (วัดได้แค่ตัวเทียบ)")
213
  codes = known_codes()
214
+ extra = [k for k in rows[0] if k not in ("path", "belt_code", "surface", "brand")]
215
  jobs = [(run, t, r) for run in range(1, a.runs + 1) for t in texts for r in rows]
216
  print(f"✅ {A.engine.llm.describe()} · {len(rows)} รูป × {len(texts)} ข้อความ × {a.runs} รอบ = {len(jobs)} บทสนทนา")
217
  results = []
 
232
  res = surface_result(args) if sc else {}
233
  lst = res.get("belt_codes_complete") if res.get("matched") else None
234
  read = [args.get("surface") or ""] + [x.strip() for x in (args.get("alternatives") or "").split(",") if x.strip()]
235
+ truth, tsurf = (r.get("belt_code") or "").strip(), (r.get("surface") or "").strip()
236
+ brand = (r.get("brand") or "modutech").strip().lower()
237
  j = (judge(reply, text) if reply else {}) if not a.no_judge else {}
238
  claimed = j.get("model_claimed") or None
239
+ mentioned = codes_in(reply, codes)
240
  rec = {
241
+ "run": run, "text": text, "path": r["path"], "brand": brand, "belt_code": truth, "surface_true": tsurf,
242
  **{k: r.get(k, "") for k in extra},
243
  "called": bool(sc), "n_surface_calls": len(sc), "surface_args": args,
244
  "surface_ok": (tsurf in read) if sc else None,
 
247
  "keeps_true": (truth in lst) if lst is not None else None,
248
  "rank_true": (lst.index(truth) + 1 if truth in lst else None) if lst else None,
249
  "model_claimed": claimed, "claim_correct": bool(claimed) and norm(claimed) == norm(truth),
250
+ "asks_useful": j.get("asks_useful"), "brand_outcome": outcome(brand, j) if j else None,
251
+ "codes_mentioned": mentioned, "modutech_codes": [c for c in mentioned if codes.get(c) == "modutech"],
252
+ "as_modutech": bool(res.get("matched")) or j.get("brand_claimed") == "modutech",
253
+ "judge": j,
254
  "reply": reply, "error": err, "seconds": sec, "tools": [c.get("tool") for c in calls],
255
  "llm_calls": usage.get("llm_calls"), "total_tokens": usage.get("total_token_count"),
256
  }
257
  results.append(rec)
258
+ print(f" {i:>3}/{len(jobs)} {truth or brand:<12} {'เรียก ' + (args.get('surface') or '?') if sc else 'ไม่เรียก':<26}"
259
  f" {('มีรุ่นจริง' if rec['keeps_true'] else 'ไม่มีรุ่นจริง') if lst is not None else '':<12}"
260
  f" {'ฟันธง ' + claimed if claimed else ''} {sec}s")
261
 
262
  print(f"\n=== {A.engine.llm.describe()} · prompt {prompt_version()} ===")
263
+ main_rs = [x for x in results if x["brand"] == "modutech"]
264
+ ctrl_rs = [x for x in results if x["brand"] != "modutech"]
265
+ if main_rs:
266
+ summarize("ทั้งหมด", main_rs)
267
+ if ctrl_rs:
268
+ print("\n── กลุ่มควบคุม (ไม่ใช่สายพาน Modutech)")
269
+ summarize_control("กลุ่มควบคุม", ctrl_rs)
270
+ for b in sorted({x["brand"] for x in ctrl_rs}):
271
+ summarize_control(f"brand={b}", [x for x in ctrl_rs if x["brand"] == b], short=True)
272
  for col in [c.strip() for c in a.by.split(",") if c.strip()] + (["text"] if len(texts) > 1 else []):
273
  print(f"\n── แยกตาม {col}")
274
  groups = {}
275
  for x in results:
276
  groups.setdefault(str(x.get(col, "")), []).append(x)
277
  for g in sorted(groups):
278
+ fn = summarize if all(x["brand"] == "modutech" for x in groups[g]) else summarize_control
279
+ fn(f"{col}={g or '(รูปอย่างเดียว)'}", groups[g], short=True)
280
  if a.runs > 1:
281
  by = {}
282
  for x in results:
283
  by.setdefault((x["path"], x["text"]), []).append(x)
284
+ ok = lambda x: (not x["as_modutech"]) if x["brand"] != "modutech" else ( # noqa: E731
285
+ x["called"] and x["keeps_true"] and not (x["model_claimed"] and not x["claim_correct"]))
286
+ stable = sum(all(ok(x) for x in v) for v in by.values())
287
+ print(f"\nผ่านครบทุก {a.runs} รอบ (Modutech: เรียก · มีรุ่นจริง · ไม่ฟันธงผิด · กลุ่มควบคุม: ไม่ตอบเป็น Modutech): {pct(stable, len(by))}")
288
 
289
  commit = os.popen(f'git -C "{ROOT}" rev-parse --short HEAD').read().strip()
290
  env = {k: os.environ.get(k) for k in ("AGENT_PROMPT", "AGENT_REPLY_GUARD", "AGENT_RESOLVE_TAB", "AGENT_DATASHEET_FILES",
291
  "AGENT_IMAGE_SURFACE", "GEMINI_MODEL", "GEMINI_THINKING")}
292
+ json.dump({"labels": a.labels or a.from_rows, "brands": a.brands if a.from_rows else "modutech", "texts": texts, "runs": a.runs, "commit": commit, "env": env,
293
  "llm": A.engine.llm.describe(), "prompt": prompt_version(), "results": results},
294
  open(a.out, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
295
  print(f"ผลรายรูป → {a.out} · commit {commit}")