Spaces:
Sleeping
Sleeping
File size: 12,551 Bytes
cd2e1b8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | """
validate.py β Pre-submission OpenEnv compliance validator.
Run this before submitting to catch any issues.
Usage:
python validate.py
"""
from __future__ import annotations
import json
import sys
import traceback
from typing import Any, Dict, List, Tuple
PASS = "β"
FAIL = "β"
WARN = "β "
results: List[Tuple[str, str, str]] = [] # (status, check, detail)
def check(label: str, condition: bool, detail: str = "", warn_only: bool = False) -> bool:
status = PASS if condition else (WARN if warn_only else FAIL)
results.append((status, label, detail))
return condition
# ---------------------------------------------------------------------------
# 1. File presence
# ---------------------------------------------------------------------------
import os
REQUIRED_FILES = [
"inference.py",
"openenv.yaml",
"Dockerfile",
"README.md",
"requirements.txt",
"env/environment.py",
"env/models.py",
"env/tasks.py",
"env/grader.py",
"env/__init__.py",
"app.py",
"LICENSE",
]
print("\nββ File presence ββββββββββββββββββββββββββββββββββββββ")
for f in REQUIRED_FILES:
check(f"File exists: {f}", os.path.isfile(f))
# ---------------------------------------------------------------------------
# 2. openenv.yaml
# ---------------------------------------------------------------------------
print("\nββ openenv.yaml βββββββββββββββββββββββββββββββββββββββ")
try:
import yaml
with open("openenv.yaml") as fh:
spec = yaml.safe_load(fh)
check("Has 'name' field", "name" in spec, spec.get("name", ""))
check("Has 'version' field", "version" in spec, spec.get("version", ""))
check("Has 'tasks' list", "tasks" in spec and len(spec["tasks"]) >= 3,
f"{len(spec.get('tasks', []))} task(s)")
check("Has 'openenv' tag", "openenv" in spec.get("tags", []))
check("Has 'reward' section", "reward" in spec)
check("Has 'endpoints' section", "endpoints" in spec)
tasks = spec.get("tasks", [])
difficulties = [t.get("difficulty") for t in tasks]
check("Has easy task", "easy" in difficulties)
check("Has medium task", "medium" in difficulties)
check("Has hard task", "hard" in difficulties)
except Exception as e:
check("openenv.yaml parseable", False, str(e))
# ---------------------------------------------------------------------------
# 3. Pydantic models
# ---------------------------------------------------------------------------
print("\nββ Pydantic models ββββββββββββββββββββββββββββββββββββ")
try:
from env.models import (
ModerationAction, ModerationObservation, ModerationReward,
ModerationDecision, ViolationCategory, Severity,
ContentItem, UserContext, PolicyRule,
)
check("ModerationObservation importable", True)
check("ModerationAction importable", True)
check("ModerationReward importable", True)
# Instantiation test
from env.models import ContentType, UserReputation
content = ContentItem(
content_id="v001", content_type=ContentType.TEXT,
text="test", reported_count=0, view_count=100, engagement_rate=0.1, has_links=False,
)
user = UserContext(user_id="u001", reputation=UserReputation.TRUSTED, account_age_days=100)
obs = ModerationObservation(
content=content, user_context=user, applicable_rules=[],
queue_position=1, queue_total=5, items_processed=0,
correct_so_far=0, step_number=0, task_id="test", task_difficulty="easy",
)
check("ModerationObservation instantiates", True)
action = ModerationAction(
content_id="v001",
decision=ModerationDecision.APPROVE,
violation_category=ViolationCategory.NONE,
severity_assessment=Severity.LOW,
confidence=0.9,
)
check("ModerationAction instantiates", True)
reward = ModerationReward(
decision_score=0.6, category_score=0.25, severity_score=0.15,
efficiency_bonus=0.0, consistency_bonus=0.0, penalty=0.0,
total=1.0, explanation="test",
)
check("ModerationReward instantiates", True)
except Exception as e:
check("Models import/instantiate", False, traceback.format_exc(limit=3))
# ---------------------------------------------------------------------------
# 4. Environment API β reset / step / state
# ---------------------------------------------------------------------------
print("\nββ Environment API ββββββββββββββββββββββββββββββββββββ")
try:
from env.environment import ContentModerationEnv
env = ContentModerationEnv()
check("ContentModerationEnv instantiates", True)
for task_name in ["easy", "medium", "hard"]:
obs = env.reset(task=task_name)
check(f"reset('{task_name}') returns ModerationObservation",
isinstance(obs, ModerationObservation),
f"type={type(obs).__name__}")
# Step with a valid action
action = ModerationAction(
content_id=obs.content.content_id,
decision=ModerationDecision.ESCALATE,
violation_category=ViolationCategory.NONE,
severity_assessment=Severity.LOW,
confidence=0.5,
)
result = env.step(action)
check(f"step() returns 4-tuple for '{task_name}'", len(result) == 4)
_obs, reward, done, info = result
check(f"reward is float for '{task_name}'", isinstance(reward, float))
check(f"done is bool for '{task_name}'", isinstance(done, bool))
check(f"info is dict for '{task_name}'", isinstance(info, dict))
check(f"reward in [-1, 1] for '{task_name}'", -1.0 <= reward <= 1.0,
f"reward={reward:.4f}")
state = env.state()
check(f"state() returns dict for '{task_name}'", isinstance(state, dict))
check(f"state() has 'task_id' for '{task_name}'", "task_id" in state)
except Exception as e:
check("Environment API", False, traceback.format_exc(limit=5))
# ---------------------------------------------------------------------------
# 5. Graders
# ---------------------------------------------------------------------------
print("\nββ Graders ββββββββββββββββββββββββββββββββββββββββββββ")
try:
from env.grader import GRADERS, grade_single_action
from env.tasks import ALL_TASKS
for difficulty, grader_fn in GRADERS.items():
task_def = ALL_TASKS[difficulty]
items = task_def["items"]
# Build a set of decisions using ground-truth answers
decisions = [
{
"action": ModerationAction(
content_id=item["content"].content_id,
decision=item["gt_decision"],
violation_category=item["gt_category"],
severity_assessment=item["gt_severity"],
confidence=0.95,
),
"gt_decision": item["gt_decision"],
"gt_category": item["gt_category"],
"gt_severity": item["gt_severity"],
}
for item in items
]
result = grader_fn(decisions)
check(f"grade_{difficulty}() returns EpisodeResult", hasattr(result, "final_score"))
check(f"grade_{difficulty}() score in [0,1]",
0.0 <= result.final_score <= 1.0, f"score={result.final_score:.4f}")
check(f"grade_{difficulty}() score is deterministic",
grader_fn(decisions).final_score == result.final_score)
# Perfect run should score > 0.9
check(f"grade_{difficulty}() perfect run scores >0.90",
result.final_score >= 0.90, f"got {result.final_score:.4f}", warn_only=True)
# Random (bad) decisions should score lower than perfect
bad_decisions = [
{
"action": ModerationAction(
content_id=item["content"].content_id,
decision=ModerationDecision.APPROVE,
violation_category=ViolationCategory.NONE,
severity_assessment=Severity.LOW,
confidence=0.1,
),
"gt_decision": item["gt_decision"],
"gt_category": item["gt_category"],
"gt_severity": item["gt_severity"],
}
for item in items
]
bad_result = grader_fn(bad_decisions)
check(f"grade_{difficulty}() bad run scores lower than perfect",
bad_result.final_score < result.final_score,
f"bad={bad_result.final_score:.4f} vs perfect={result.final_score:.4f}")
except Exception as e:
check("Graders", False, traceback.format_exc(limit=5))
# ---------------------------------------------------------------------------
# 6. Task dataset integrity
# ---------------------------------------------------------------------------
print("\nββ Task dataset βββββββββββββββββββββββββββββββββββββββ")
try:
from env.tasks import ALL_TASKS
for difficulty, task_def in ALL_TASKS.items():
items = task_def["items"]
check(f"Task '{difficulty}' has β₯3 items", len(items) >= 3, f"{len(items)} items")
ids = [item["content"].content_id for item in items]
check(f"Task '{difficulty}' all content_ids unique",
len(ids) == len(set(ids)), f"ids={ids}")
for item in items:
assert "gt_decision" in item, f"Missing gt_decision in {item}"
assert "gt_category" in item, f"Missing gt_category in {item}"
assert "gt_severity" in item, f"Missing gt_severity in {item}"
check(f"Task '{difficulty}' all items have ground truth", True)
except Exception as e:
check("Task dataset integrity", False, traceback.format_exc(limit=3))
# ---------------------------------------------------------------------------
# 7. Dockerfile basics
# ---------------------------------------------------------------------------
print("\nββ Dockerfile βββββββββββββββββββββββββββββββββββββββββ")
with open("Dockerfile") as fh:
df = fh.read()
check("Dockerfile EXPOSE 7860", "EXPOSE 7860" in df)
check("Dockerfile HEALTHCHECK", "HEALTHCHECK" in df)
check("Dockerfile non-root user", "useradd" in df or "USER" in df)
check("Dockerfile copies requirements", "COPY" in df and "requirements" in df)
# ---------------------------------------------------------------------------
# 8. inference.py compliance
# ---------------------------------------------------------------------------
print("\nββ inference.py βββββββββββββββββββββββββββββββββββββββ")
with open("inference.py") as fh:
inf = fh.read()
check("Uses 'from openai import OpenAI'", "from openai import OpenAI" in inf)
check("Reads API_BASE_URL env var", "API_BASE_URL" in inf and "os.getenv" in inf)
check("Reads MODEL_NAME env var", "MODEL_NAME" in inf)
check("Reads HF_TOKEN env var", "HF_TOKEN" in inf)
check("Has TEMPERATURE constant", "TEMPERATURE" in inf)
check("Covers all 3 tasks",
all(t in inf for t in ['"easy"', '"medium"', '"hard"']))
# ---------------------------------------------------------------------------
# Summary
# ---------------------------------------------------------------------------
print("\n" + "="*56)
print(" VALIDATION SUMMARY")
print("="*56)
passed = sum(1 for s, _, _ in results if s == PASS)
warned = sum(1 for s, _, _ in results if s == WARN)
failed = sum(1 for s, _, _ in results if s == FAIL)
for status, label, detail in results:
suffix = f" [{detail}]" if detail else ""
print(f" {status} {label}{suffix}")
print(f"\n Passed: {passed} | Warnings: {warned} | Failed: {failed}")
if failed == 0:
print("\n π ALL CHECKS PASSED β submission is ready!")
sys.exit(0)
else:
print(f"\n β {failed} check(s) failed β fix before submitting.")
sys.exit(1)
|