Spaces:
Sleeping
Sleeping
Download inference.py from gauravnetes/datacleaning-env: direct link, hf CLI and curl.
- Browser
- Download file 4.16 kB
-
https://huggingface.co/spaces/gauravnetes/datacleaning-env/resolve/main/inference.py
- Command line
-
hf download hf://spaces/gauravnetes/datacleaning-env/inference.py
-
curl -L -o inference.py https://huggingface.co/spaces/gauravnetes/datacleaning-env/resolve/main/inference.py
4.16 kB
| import os | |
| import json | |
| from openai import OpenAI | |
| from env import DataCleaningEnv, Action | |
| API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1") | |
| MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct") | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| BENCHMARK = "datacleaning-env" | |
| client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN or "dummy_key") | |
| TASKS = [ | |
| "fix_missing_values", | |
| "normalize_and_deduplicate", | |
| "schema_repair", | |
| ] | |
| SYSTEM_PROMPT = """You are a data cleaning agent. You will receive observations about a dirty dataset. | |
| Your job is to clean it by emitting JSON actions. | |
| Available operations: | |
| - fill_nulls: {"operation": "fill_nulls", "column": "<col>", "strategy": "mean|median|mode|constant", "value": <optional>} | |
| - normalize_dates: {"operation": "normalize_dates", "column": "<col>"} | |
| - normalize_phones: {"operation": "normalize_phones", "column": "<col>"} | |
| - drop_duplicates: {"operation": "drop_duplicates", "subset": ["<col>"], "keep": "first"} | |
| - cast_column: {"operation": "cast_column", "column": "<col>", "dtype": "<dtype>"} | |
| - rename_column: {"operation": "rename_column", "column": "<old_name>", "value": "<new_name>"} | |
| - remove_outliers: {"operation": "remove_outliers", "column": "<col>"} | |
| - submit: {"operation": "submit"} | |
| Rules: | |
| - Respond with ONLY a valid JSON object. No explanation, no markdown, no extra text. | |
| - One action per response. | |
| - When you think the dataset is clean, emit {"operation": "submit"}. | |
| """ | |
| def build_user_prompt(obs_dict: dict) -> str: | |
| return f"""Current dataset state: | |
| - Task: {obs_dict['task']} | |
| - Shape: {obs_dict['shape']} | |
| - Columns: {obs_dict['columns']} | |
| - Dtypes: {obs_dict['dtypes']} | |
| - Null counts: {obs_dict['null_counts']} | |
| - Sample rows: {json.dumps(obs_dict['sample_rows'], indent=2)} | |
| - Message: {obs_dict['message']} | |
| Emit the next cleaning action as JSON. | |
| """ | |
| def get_action_from_llm(messages: list) -> Action: | |
| response = client.chat.completions.create( | |
| model=MODEL_NAME, | |
| messages=messages, | |
| max_tokens=256, | |
| temperature=0.2, | |
| ) | |
| raw = response.choices[0].message.content.strip() | |
| # Strip markdown fences if present | |
| if raw.startswith("```"): | |
| raw = raw.split("```")[1] | |
| if raw.startswith("json"): | |
| raw = raw[4:] | |
| raw = raw.strip() | |
| data = json.loads(raw) | |
| return Action(**data) | |
| def run_task(task_name: str): | |
| env = DataCleaningEnv(task_name=task_name) | |
| obs = env.reset() | |
| print(f"[START] task={task_name} env={BENCHMARK} model={MODEL_NAME}") | |
| messages = [{"role": "system", "content": SYSTEM_PROMPT}] | |
| rewards = [] | |
| step = 0 | |
| score = 0.0 | |
| max_steps = 10 if task_name != "schema_repair" else 15 | |
| while True: | |
| step += 1 | |
| # Build conversation history | |
| user_msg = build_user_prompt(obs.model_dump()) | |
| messages.append({"role": "user", "content": user_msg}) | |
| # Get action from LLM | |
| error_str = "null" | |
| try: | |
| action = get_action_from_llm(messages) | |
| action_str = json.dumps(action.model_dump(exclude_none=True)) | |
| except Exception as e: | |
| error_str = str(e).replace("\n", " ") | |
| action = Action(operation="submit") | |
| action_str = '{"operation": "submit"}' | |
| # Step environment | |
| obs, reward = env.step(action) | |
| rewards.append(reward.score) | |
| score = reward.score | |
| # Add assistant reply to history | |
| messages.append({"role": "assistant", "content": action_str}) | |
| done_str = "true" if reward.done else "false" | |
| print(f"[STEP] step={step} action={action_str} reward={reward.score:.2f} done={done_str} error={error_str}") | |
| if reward.done or step >= max_steps: | |
| break | |
| success = score >= 0.5 | |
| rewards_str = ",".join(f"{r:.2f}" for r in rewards) | |
| print(f"[END] success={'true' if success else 'false'} steps={step} score={score:.2f} rewards={rewards_str}") | |
| return score | |
| def main(): | |
| for task in TASKS: | |
| run_task(task) | |
| print() # blank line between tasks | |
| if __name__ == "__main__": | |
| main() |