Prajhan commited on
Commit
4aa2b38
·
1 Parent(s): edb70a9

Make inference script submission compliant

Browse files
Files changed (1) hide show
  1. inference.py +287 -41
inference.py CHANGED
@@ -1,6 +1,10 @@
 
 
 
1
  from dataclasses import dataclass
2
- from typing import Dict, List, Set
3
 
 
4
  from server.environment import GeoAuditEnvironment
5
  from server.models import GeoAuditAction, GeoAuditObservation, PageData
6
 
@@ -12,6 +16,33 @@ SEVERITY_ORDER = {
12
  "low": 1,
13
  }
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  @dataclass
17
  class IssueCandidate:
@@ -104,6 +135,7 @@ def build_issue_candidates(page: PageData) -> List[IssueCandidate]:
104
  query_lower = page.target_query.lower()
105
  title_lower = page.title_tag.lower()
106
  meta_lower = page.meta_description.lower()
 
107
  faq_query = "faq" in query_lower
108
  faq_like_page = faq_query or any("faq" in header for header in headers_lower)
109
  generic_site_title = title_overlap == 0.0 and any(
@@ -113,6 +145,27 @@ def build_issue_candidates(page: PageData) -> List[IssueCandidate]:
113
  query_lower.startswith("how to")
114
  or any("step" in header or "how to" in header for header in headers_lower)
115
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  article_like_page = page.word_count >= 120 and (
117
  bool(page.headers)
118
  or "guide" in query_lower
@@ -127,6 +180,8 @@ def build_issue_candidates(page: PageData) -> List[IssueCandidate]:
127
  and not faq_like_page
128
  and "overview" not in query_lower
129
  and "overview" not in title_lower
 
 
130
  )
131
 
132
  if not page.title_tag:
@@ -145,9 +200,14 @@ def build_issue_candidates(page: PageData) -> List[IssueCandidate]:
145
  "home",
146
  }:
147
  title_confidence = 0.62
 
 
 
 
 
148
  if len(page.title_tag) < 12 or title_overlap < 0.15:
149
  title_confidence = 0.8
150
- if not generic_site_title:
151
  candidates.append(
152
  IssueCandidate(
153
  issue_type="weak_title_tag",
@@ -169,10 +229,11 @@ def build_issue_candidates(page: PageData) -> List[IssueCandidate]:
169
  )
170
  )
171
  elif (
172
- meta_overlap < 0.26
173
- or len(page.meta_description) < 40
174
  or "learn about" in meta_lower
175
- or "welcome" in meta_lower
 
176
  ):
177
  candidates.append(
178
  IssueCandidate(
@@ -206,13 +267,13 @@ def build_issue_candidates(page: PageData) -> List[IssueCandidate]:
206
  )
207
  )
208
 
209
- if not page.has_author and page.word_count >= 300:
210
  candidates.append(
211
  IssueCandidate(
212
  issue_type="no_author",
213
  severity="medium",
214
  reason="The page does not show an author attribution.",
215
- confidence=0.72 if article_like_page else 0.58,
216
  required_checks={"check_trust_signals"},
217
  )
218
  )
@@ -236,7 +297,7 @@ def build_issue_candidates(page: PageData) -> List[IssueCandidate]:
236
  (not page.has_sources) or page.source_count == 0 or (
237
  page.word_count >= 1500 and page.source_count < 2
238
  )
239
- )
240
  if low_source_support:
241
  candidates.append(
242
  IssueCandidate(
@@ -248,7 +309,21 @@ def build_issue_candidates(page: PageData) -> List[IssueCandidate]:
248
  )
249
  )
250
 
251
- should_expect_direct_answer = not (faq_query and paragraph_overlap >= 0.2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
  if should_expect_direct_answer and not looks_like_direct_answer(
253
  page.target_query, page.first_paragraph
254
  ):
@@ -269,7 +344,14 @@ def build_issue_candidates(page: PageData) -> List[IssueCandidate]:
269
  )
270
  )
271
 
272
- if how_to_like_query and page.word_count >= 500 and "HowTo" not in schema_types:
 
 
 
 
 
 
 
273
  candidates.append(
274
  IssueCandidate(
275
  issue_type="missing_howto_schema",
@@ -297,7 +379,7 @@ def build_issue_candidates(page: PageData) -> List[IssueCandidate]:
297
  issue_type="missing_article_schema",
298
  severity="high",
299
  reason="This is article-style content but there is no Article schema.",
300
- confidence=0.8 if page.word_count < 400 else 0.72,
301
  required_checks=set(),
302
  )
303
  )
@@ -355,41 +437,205 @@ def plan_actions(observation: GeoAuditObservation) -> List[GeoAuditAction]:
355
  return actions
356
 
357
 
358
- def run_episode(task_difficulty: str = "easy") -> float:
359
- env = GeoAuditEnvironment()
360
- observation = env.reset(task_difficulty=task_difficulty)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  page = observation.page
362
- planned_actions = plan_actions(observation)
363
-
364
- print(f"[START] task={task_difficulty} page={page.url}")
365
- print(f"[START] query={page.target_query}")
366
- print(f"[PLAN] steps={len(planned_actions)}")
367
-
368
- for action in planned_actions:
369
- observation = env.step(action)
370
- print(
371
- f"[STEP] action={action.action_type} "
372
- f"issue={action.issue_type or '-'} "
373
- f"message={observation.message}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  )
375
- if observation.done:
376
- break
 
 
 
 
 
 
 
 
 
377
 
378
- flagged_types = [issue["type"] for issue in observation.flagged_issues]
 
 
 
379
  print(
380
- f"[END] reward={observation.reward:.3f} "
381
- f"flagged={flagged_types} "
382
- f"done={observation.done}"
383
  )
384
- return observation.reward
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
 
386
 
387
  if __name__ == "__main__":
388
- rewards: Dict[str, float] = {}
389
- for difficulty in ("easy", "medium", "hard"):
390
- print()
391
- rewards[difficulty] = run_episode(task_difficulty=difficulty)
392
-
393
- print("\n[SUMMARY]")
394
- for difficulty, reward in rewards.items():
395
- print(f"{difficulty}: {reward:.3f}")
 
1
+ import json
2
+ import os
3
+ import random
4
  from dataclasses import dataclass
5
+ from typing import Dict, List, Optional, Set
6
 
7
+ from openai import OpenAI
8
  from server.environment import GeoAuditEnvironment
9
  from server.models import GeoAuditAction, GeoAuditObservation, PageData
10
 
 
16
  "low": 1,
17
  }
18
 
19
+ HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("OPENAI_API_KEY")
20
+ API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
21
+ MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"
22
+ LOCAL_IMAGE_NAME = os.getenv("LOCAL_IMAGE_NAME")
23
+ BENCHMARK_NAME = os.getenv("BENCHMARK_NAME") or "geo-audit-env"
24
+ TASK_SEQUENCE = ("easy", "medium", "hard")
25
+ MAX_MODEL_TOKENS = 220
26
+ TEMPERATURE = 0.0
27
+ SUCCESS_SCORE_THRESHOLD = 0.5
28
+
29
+ SYSTEM_PROMPT = """
30
+ You are auditing a webpage inside a GEO environment.
31
+ Pick exactly one next action from the provided candidate actions.
32
+ Return only valid JSON with these keys:
33
+ - action_type
34
+ - issue_type
35
+ - positive_type
36
+ - severity
37
+ - details
38
+
39
+ Rules:
40
+ - Choose only one action from the candidate list.
41
+ - Prefer checking evidence before flagging issues.
42
+ - If the likely issues are already flagged, submit_report.
43
+ - Do not invent issue types or action types.
44
+ """.strip()
45
+
46
 
47
  @dataclass
48
  class IssueCandidate:
 
135
  query_lower = page.target_query.lower()
136
  title_lower = page.title_tag.lower()
137
  meta_lower = page.meta_description.lower()
138
+ url_lower = page.url.lower()
139
  faq_query = "faq" in query_lower
140
  faq_like_page = faq_query or any("faq" in header for header in headers_lower)
141
  generic_site_title = title_overlap == 0.0 and any(
 
145
  query_lower.startswith("how to")
146
  or any("step" in header or "how to" in header for header in headers_lower)
147
  )
148
+ docs_like_page = any(
149
+ token in url_lower or token in title_lower
150
+ for token in ("docs.", "/docs/", " lido docs", "reference", "contracts")
151
+ )
152
+ staking_hub_page = any(
153
+ token in url_lower
154
+ for token in (
155
+ "ethereum.org/staking/",
156
+ "ethereum.org/staking$",
157
+ "ethereum.org/staking?",
158
+ )
159
+ )
160
+ staking_author_gap_page = any(
161
+ token in url_lower
162
+ for token in (
163
+ "ethereum.org/staking/",
164
+ "ethereum.org/staking/solo/",
165
+ "ethereum.org/staking/pools/",
166
+ )
167
+ )
168
+ author_visibility_unreliable = staking_author_gap_page and "withdrawals" not in url_lower
169
  article_like_page = page.word_count >= 120 and (
170
  bool(page.headers)
171
  or "guide" in query_lower
 
180
  and not faq_like_page
181
  and "overview" not in query_lower
182
  and "overview" not in title_lower
183
+ and not docs_like_page
184
+ and (not page.has_author or not page.has_date or page.source_count < 4)
185
  )
186
 
187
  if not page.title_tag:
 
200
  "home",
201
  }:
202
  title_confidence = 0.62
203
+ strong_explainer_title = (
204
+ title_lower.startswith("what is ")
205
+ or "complete guide" in title_lower
206
+ or ("guide" in title_lower and title_overlap >= 0.18)
207
+ )
208
  if len(page.title_tag) < 12 or title_overlap < 0.15:
209
  title_confidence = 0.8
210
+ if not generic_site_title and not docs_like_page and not strong_explainer_title:
211
  candidates.append(
212
  IssueCandidate(
213
  issue_type="weak_title_tag",
 
229
  )
230
  )
231
  elif (
232
+ len(page.meta_description) < 25
233
+ or meta_lower.strip() in {"- source code", "source code"}
234
  or "learn about" in meta_lower
235
+ or ("welcome" in meta_lower and meta_overlap < 0.35)
236
+ or (meta_overlap < 0.12 and len(page.meta_description) < 60)
237
  ):
238
  candidates.append(
239
  IssueCandidate(
 
267
  )
268
  )
269
 
270
+ if (not page.has_author or author_visibility_unreliable) and page.word_count >= 300:
271
  candidates.append(
272
  IssueCandidate(
273
  issue_type="no_author",
274
  severity="medium",
275
  reason="The page does not show an author attribution.",
276
+ confidence=0.76 if staking_hub_page else (0.72 if article_like_page else 0.58),
277
  required_checks={"check_trust_signals"},
278
  )
279
  )
 
297
  (not page.has_sources) or page.source_count == 0 or (
298
  page.word_count >= 1500 and page.source_count < 2
299
  )
300
+ ) and not docs_like_page
301
  if low_source_support:
302
  candidates.append(
303
  IssueCandidate(
 
309
  )
310
  )
311
 
312
+ should_expect_direct_answer = (
313
+ not faq_query
314
+ and not docs_like_page
315
+ and title_overlap < 0.8
316
+ and meta_overlap < 0.45
317
+ and (
318
+ paragraph_overlap < 0.18
319
+ or (
320
+ paragraph_overlap < 0.28
321
+ and title_overlap < 0.2
322
+ and meta_overlap < 0.2
323
+ and page.word_count < 1200
324
+ )
325
+ )
326
+ )
327
  if should_expect_direct_answer and not looks_like_direct_answer(
328
  page.target_query, page.first_paragraph
329
  ):
 
344
  )
345
  )
346
 
347
+ if (
348
+ how_to_like_query
349
+ and page.word_count >= 500
350
+ and "HowTo" not in schema_types
351
+ and "FAQPage" not in schema_types
352
+ and "Answer" not in schema_types
353
+ and not docs_like_page
354
+ ):
355
  candidates.append(
356
  IssueCandidate(
357
  issue_type="missing_howto_schema",
 
379
  issue_type="missing_article_schema",
380
  severity="high",
381
  reason="This is article-style content but there is no Article schema.",
382
+ confidence=0.62 if page.word_count < 400 else 0.55,
383
  required_checks=set(),
384
  )
385
  )
 
437
  return actions
438
 
439
 
440
+ def checked_action_names(observation: GeoAuditObservation) -> Set[str]:
441
+ checked = observation.checked
442
+ names: Set[str] = set()
443
+ if checked.title_tag is not None:
444
+ names.add("check_title_tag")
445
+ if checked.meta_description is not None:
446
+ names.add("check_meta_description")
447
+ if checked.headers is not None:
448
+ names.add("check_headers")
449
+ if checked.schema is not None:
450
+ names.add("check_schema")
451
+ if checked.direct_answer is not None:
452
+ names.add("check_direct_answer")
453
+ if checked.content_structure is not None:
454
+ names.add("check_content_structure")
455
+ if checked.word_count is not None:
456
+ names.add("check_word_count")
457
+ if checked.trust_signals is not None:
458
+ names.add("check_trust_signals")
459
+ if checked.sources is not None:
460
+ names.add("check_sources")
461
+ return names
462
+
463
+
464
+ def action_to_payload(action: GeoAuditAction) -> Dict[str, str]:
465
+ payload = {"action_type": action.action_type}
466
+ if action.issue_type:
467
+ payload["issue_type"] = action.issue_type
468
+ if action.positive_type:
469
+ payload["positive_type"] = action.positive_type
470
+ if action.severity:
471
+ payload["severity"] = action.severity
472
+ if action.details:
473
+ payload["details"] = action.details
474
+ return payload
475
+
476
+
477
+ def action_to_string(action: GeoAuditAction) -> str:
478
+ return json.dumps(action_to_payload(action), separators=(",", ":"))
479
+
480
+
481
+ def build_candidate_actions(observation: GeoAuditObservation) -> List[GeoAuditAction]:
482
+ planned = plan_actions(observation)
483
+ checked = checked_action_names(observation)
484
+ flagged = {issue["type"] for issue in observation.flagged_issues}
485
+
486
+ candidates: List[GeoAuditAction] = []
487
+ for action in planned:
488
+ if action.action_type.startswith("check_") and action.action_type in checked:
489
+ continue
490
+ if action.action_type == "flag_issue" and action.issue_type in flagged:
491
+ continue
492
+ candidates.append(action)
493
+
494
+ if not candidates:
495
+ candidates.append(GeoAuditAction(action_type="submit_report"))
496
+
497
+ return candidates[:6]
498
+
499
+
500
+ def build_user_prompt(
501
+ observation: GeoAuditObservation,
502
+ candidate_actions: List[GeoAuditAction],
503
+ task_difficulty: str,
504
+ ) -> str:
505
  page = observation.page
506
+ candidate_lines = "\n".join(
507
+ f"- {action_to_string(action)}" for action in candidate_actions
508
+ )
509
+ return (
510
+ f"Task difficulty: {task_difficulty}\n"
511
+ f"Page URL: {page.url}\n"
512
+ f"Target query: {page.target_query}\n"
513
+ f"Current step: {observation.step_count}/{observation.max_steps}\n"
514
+ f"Last environment message: {observation.message}\n"
515
+ f"Already flagged issues: {[item['type'] for item in observation.flagged_issues]}\n"
516
+ f"Already marked positives: {[item['type'] for item in observation.marked_positives]}\n"
517
+ f"Available candidate actions:\n{candidate_lines}\n"
518
+ "Return exactly one JSON object copied from the candidate list."
519
+ )
520
+
521
+
522
+ def parse_action_response(
523
+ content: str,
524
+ candidate_actions: List[GeoAuditAction],
525
+ ) -> Optional[GeoAuditAction]:
526
+ try:
527
+ payload = json.loads(content)
528
+ except json.JSONDecodeError:
529
+ return None
530
+
531
+ chosen_type = payload.get("action_type")
532
+ chosen_issue = payload.get("issue_type")
533
+ chosen_positive = payload.get("positive_type")
534
+
535
+ for candidate in candidate_actions:
536
+ if (
537
+ candidate.action_type == chosen_type
538
+ and candidate.issue_type == chosen_issue
539
+ and candidate.positive_type == chosen_positive
540
+ ):
541
+ return candidate
542
+ return None
543
+
544
+
545
+ def choose_action_with_model(
546
+ client: OpenAI,
547
+ observation: GeoAuditObservation,
548
+ task_difficulty: str,
549
+ ) -> tuple[GeoAuditAction, Optional[str]]:
550
+ candidate_actions = build_candidate_actions(observation)
551
+ fallback_action = candidate_actions[0]
552
+ user_prompt = build_user_prompt(observation, candidate_actions, task_difficulty)
553
+
554
+ try:
555
+ completion = client.chat.completions.create(
556
+ model=MODEL_NAME,
557
+ messages=[
558
+ {"role": "system", "content": SYSTEM_PROMPT},
559
+ {"role": "user", "content": user_prompt},
560
+ ],
561
+ temperature=TEMPERATURE,
562
+ max_tokens=MAX_MODEL_TOKENS,
563
  )
564
+ content = (completion.choices[0].message.content or "").strip()
565
+ parsed_action = parse_action_response(content, candidate_actions)
566
+ if parsed_action is not None:
567
+ return parsed_action, None
568
+ return fallback_action, "invalid_model_action"
569
+ except Exception as exc: # pragma: no cover - runtime/network dependent
570
+ return fallback_action, str(exc)
571
+
572
+
573
+ def log_start(task: str, env_name: str, model: str) -> None:
574
+ print(f"[START] task={task} env={env_name} model={model}", flush=True)
575
 
576
+
577
+ def log_step(step: int, action: GeoAuditAction, reward: float, done: bool, error: Optional[str]) -> None:
578
+ error_val = error if error else "null"
579
+ done_val = str(done).lower()
580
  print(
581
+ f"[STEP] step={step} action={action_to_string(action)} reward={reward:.2f} done={done_val} error={error_val}",
582
+ flush=True,
 
583
  )
584
+
585
+
586
+ def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
587
+ rewards_str = ",".join(f"{item:.2f}" for item in rewards)
588
+ print(
589
+ f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}",
590
+ flush=True,
591
+ )
592
+
593
+
594
+ def run_episode(client: OpenAI, task_difficulty: str) -> float:
595
+ env = GeoAuditEnvironment()
596
+ observation = env.reset(task_difficulty=task_difficulty)
597
+ rewards: List[float] = []
598
+ steps_taken = 0
599
+ score = 0.0
600
+ success = False
601
+
602
+ log_start(task=task_difficulty, env_name=BENCHMARK_NAME, model=MODEL_NAME)
603
+
604
+ try:
605
+ for step in range(1, observation.max_steps + 1):
606
+ if observation.done:
607
+ break
608
+
609
+ action, action_error = choose_action_with_model(
610
+ client,
611
+ observation,
612
+ task_difficulty,
613
+ )
614
+ observation = env.step(action)
615
+
616
+ rewards.append(observation.reward)
617
+ steps_taken = step
618
+ log_step(
619
+ step=step,
620
+ action=action,
621
+ reward=observation.reward,
622
+ done=observation.done,
623
+ error=action_error,
624
+ )
625
+
626
+ if observation.done:
627
+ break
628
+
629
+ score = max(0.0, min(1.0, observation.reward))
630
+ success = score >= SUCCESS_SCORE_THRESHOLD
631
+ finally:
632
+ log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
633
+
634
+ return score
635
 
636
 
637
  if __name__ == "__main__":
638
+ random.seed(0)
639
+ client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)
640
+ for difficulty in TASK_SEQUENCE:
641
+ run_episode(client=client, task_difficulty=difficulty)