Spaces:
Running
Running
Sibam commited on
Commit Β·
5ee1380
1
Parent(s): 8fbc201
refactor: apply production readiness recommendations including dataset caching, XSS protection, pure schemas, and JSON decoding logic.
Browse filesFiles changed (4)
- inference.py+12-7
- models.py+1-1
- server/app.py+8-3
- server/environment.py+33-14
25 unmodified lines26272829303143 unmodified lines757677787980818283848586124 unmodified lines21121221321421521621721821925 unmodified linesclient = OpenAI(api_key=HF_TOKEN, base_url=API_BASE_URL)# ββ Mandatory log functions ββββββββββββββββββββββββββββββββββββ43 unmodified linesdef parse_json(text: str, fallback: dict) -> dict:"""Extract and parse the first JSON object found in text."""try:start = text.find("{")end = text.rfind("}") + 1if start >= 0 and end > start:return json.loads(text[start:end])except Exception:passreturn fallback124 unmodified lines# ββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββdef main():import syssys.path.insert(0, ".")from server.environment import PreferenceLabEnvironmentprint("=" * 60, flush=True)print("PreferenceLab Baseline Inference", flush=True)25 unmodified lines262728293031323343 unmodified lines77787980818283848586878889909192124 unmodified lines21721821922022122222322425 unmodified linesclient = OpenAI(api_key=HF_TOKEN, base_url=API_BASE_URL)from server.environment import PreferenceLabEnvironment# ββ Mandatory log functions ββββββββββββββββββββββββββββββββββββ43 unmodified linesdef parse_json(text: str, fallback: dict) -> dict:"""Extract and parse the first JSON object found in text using robust decoding."""try:decoder = json.JSONDecoder()# Find first '{' to start decoding directlystart = text.find("{")if start >= 0:obj, _ = decoder.raw_decode(text[start:])return objexcept json.JSONDecodeError:passexcept Exception:passreturn fallback124 unmodified lines# ββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββdef main():if not HF_TOKEN:raise SystemExit("HF_TOKEN is required to run baseline inference.")print("=" * 60, flush=True)print("PreferenceLab Baseline Inference", flush=True)
60 unmodified lines6162636465666760 unmodified linesclass ConsistencyAction(Action):"""Action for Task 3: rank 4 responses (A, B, C, D) from best to worst."""ranking: list[str] = Field(...,min_length=4,max_length=4,60 unmodified lines6162636465666760 unmodified linesclass ConsistencyAction(Action):"""Action for Task 3: rank 4 responses (A, B, C, D) from best to worst."""ranking: list[Literal["A", "B", "C", "D"]] = Field(...,min_length=4,max_length=4,
8 unmodified lines910111213141568 unmodified lines84858687888931 unmodified lines12112212312412512645 unmodified lines1721731741751761771781791801811821838 unmodified linesimport osfrom fastapi.responses import JSONResponsefrom openenv.core.env_server import create_appfrom models import (68 unmodified linesdef update_dashboard():import pandas as pdlogs = getattr(web_manager.episode_state, "action_logs", [])data = []31 unmodified linesinfo = last_log.observation.model_extra.get("info", {})dataset_str = info.get("dataset", "Synthetic / Unknown") if isinstance(info, dict) else "Unknown"# Session summary metricsinitial_reward = data[0]["Reward"]45 unmodified linesconf = last_log.action.confidenceelif isinstance(last_log.action, dict) and "confidence" in last_log.action:conf = last_log.action["confidence"]conf_str = f"{int(conf * 100)}%"return df, exp, tip, thinking, f"Dataset: <b>{dataset_str.upper()}</b>", summary, f"### Best Reward: {best_reward:.2f}", f"### Recent Delta: {delta_str}", f"### Confidence: {conf_str}"# Manual safe refresh mapping# Manual safe refresh mapping# Manual safe refresh mappingrefresh_btn.click(fn=update_dashboard,8 unmodified lines9101112131468 unmodified lines8384858687888931 unmodified lines12112212312412512612745 unmodified lines1731741751761771781791801811821831841851861871888 unmodified linesimport osfrom openenv.core.env_server import create_appfrom models import (68 unmodified linesdef update_dashboard():import pandas as pdimport htmllogs = getattr(web_manager.episode_state, "action_logs", [])data = []31 unmodified linesinfo = last_log.observation.model_extra.get("info", {})dataset_str = info.get("dataset", "Synthetic / Unknown") if isinstance(info, dict) else "Unknown"dataset_str = html.escape(str(dataset_str))# Session summary metricsinitial_reward = data[0]["Reward"]45 unmodified linesconf = last_log.action.confidenceelif isinstance(last_log.action, dict) and "confidence" in last_log.action:conf = last_log.action["confidence"]try:conf = float(conf)except (ValueError, TypeError):conf = 0.8conf_str = f"{int(conf * 100)}%"return df, exp, tip, thinking, f"Dataset: <b>{dataset_str.upper()}</b>", summary, f"### Best Reward: {best_reward:.2f}", f"### Recent Delta: {delta_str}", f"### Confidence: {conf_str}"# Manual safe refresh mappingrefresh_btn.click(fn=update_dashboard,
37 unmodified lines38394041424344157 unmodified lines2022032042052062072 unmodified lines21021121221321421521621721821922022122222322422522622710 unmodified lines23823924024124224324424524624724824925067 unmodified lines31831932032132232332437 unmodified linesdef _load_json(filename: str) -> list[dict]:path = DATA_DIR / filenameif path.exists():with open(path) as f:return json.load(f)return []157 unmodified lines# is fully isolated β concurrent use is safe.SUPPORTS_CONCURRENT_SESSIONS: bool = Truedef __init__(self):self._episode_id: str = ""self._step_count: int = 02 unmodified linesself._cumulative_reward: float = 0.0self._seed: int = 0# Load datasetsself._pairwise_data: list[dict] = _load_json("pairwise_data.json")self._likert_data: list[dict] = _load_json("likert_data.json")self._consistency_data: list[dict] = _load_json("consistency_data.json")# Fallback synthetic data if files not presentif not self._pairwise_data:self._pairwise_data = _synthetic_pairwise()if not self._likert_data:self._likert_data = _synthetic_likert()if not self._consistency_data:self._consistency_data = _synthetic_consistency()# ββ OpenEnv API βββββββββββββββββββββββββββββββββββββββββββ10 unmodified linesInitial observation for the episode."""task_type = kwargs.get("task_type", None)self._seed = seed if seed is not None else random.randint(0, 10_000)rng = random.Random(self._seed)self._episode_id = episode_id or str(uuid.uuid4())self._step_count = 0self._cumulative_reward = 0.0self._task_type = task_type if task_type in TASK_TYPES else rng.choice(TASK_TYPES)self._current_example = self._sample_example(rng)67 unmodified linesreturn grade_consistency(action, self._current_example)# Legacy fallback β dispatch by task_type string (e.g. dict-based actions)if self._task_type == "pairwise":return grade_pairwise(action, self._current_example)elif self._task_type == "likert":return grade_likert(action, self._current_example)37 unmodified lines38394041424344157 unmodified lines2022032042052062072082092102112122 unmodified lines21521621721821922022122222322422522622722822923023110 unmodified lines24224324424524624724824925025125225325425525625725867 unmodified lines32632732832933033133233333433533633733833934034134234337 unmodified linesdef _load_json(filename: str) -> list[dict]:path = DATA_DIR / filenameif path.exists():with open(path, encoding="utf-8") as f:return json.load(f)return []157 unmodified lines# is fully isolated β concurrent use is safe.SUPPORTS_CONCURRENT_SESSIONS: bool = True# Global cached dataset loading_CACHE_PAIRWISE_DATA: list[dict] | None = None_CACHE_LIKERT_DATA: list[dict] | None = None_CACHE_CONSISTENCY_DATA: list[dict] | None = Nonedef __init__(self):self._episode_id: str = ""self._step_count: int = 02 unmodified linesself._cumulative_reward: float = 0.0self._seed: int = 0# Load datasets globally on first initif PreferenceLabEnvironment._CACHE_PAIRWISE_DATA is None:PreferenceLabEnvironment._CACHE_PAIRWISE_DATA = _load_json("pairwise_data.json") or _synthetic_pairwise()if PreferenceLabEnvironment._CACHE_LIKERT_DATA is None:PreferenceLabEnvironment._CACHE_LIKERT_DATA = _load_json("likert_data.json") or _synthetic_likert()if PreferenceLabEnvironment._CACHE_CONSISTENCY_DATA is None:PreferenceLabEnvironment._CACHE_CONSISTENCY_DATA = _load_json("consistency_data.json") or _synthetic_consistency()self._pairwise_data = PreferenceLabEnvironment._CACHE_PAIRWISE_DATAself._likert_data = PreferenceLabEnvironment._CACHE_LIKERT_DATAself._consistency_data = PreferenceLabEnvironment._CACHE_CONSISTENCY_DATA# ββ OpenEnv API βββββββββββββββββββββββββββββββββββββββββββ10 unmodified linesInitial observation for the episode."""task_type = kwargs.get("task_type", None)if task_type is not None and task_type not in TASK_TYPES:raise ValueError(f"Unsupported task_type: '{task_type}'")self._seed = seed if seed is not None else random.randint(0, 10_000)rng = random.Random(self._seed)self._episode_id = episode_id or str(uuid.uuid4())self._step_count = 0self._cumulative_reward = 0.0self._task_type = task_type if task_type else rng.choice(TASK_TYPES)self._current_example = self._sample_example(rng)67 unmodified linesreturn grade_consistency(action, self._current_example)# Legacy fallback β dispatch by task_type string (e.g. dict-based actions)if isinstance(action, dict):if self._task_type == "pairwise":action = PairwiseAction(**action)return grade_pairwise(action, self._current_example)elif self._task_type == "likert":action = LikertAction(**action)return grade_likert(action, self._current_example)elif self._task_type == "consistency":action = ConsistencyAction(**action)return grade_consistency(action, self._current_example)elif self._task_type == "pairwise":return grade_pairwise(action, self._current_example)elif self._task_type == "likert":return grade_likert(action, self._current_example)
inference.py+12-7
models.py+1-1
server/app.py+8-3
server/environment.py+33-14