|
| 1 | +from datetime import datetime, timezone |
| 2 | +import json |
| 3 | +import os |
| 4 | +import tempfile |
| 5 | +import shutil |
| 6 | +from typing import TYPE_CHECKING, List, Optional |
| 7 | +from eval_protocol.common_utils import load_jsonl |
| 8 | +from eval_protocol.dataset_logger.dataset_logger import DatasetLogger |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from eval_protocol.models import EvaluationRow |
| 12 | + |
| 13 | + |
| 14 | +class LocalFSDatasetLoggerAdapter(DatasetLogger): |
| 15 | + """ |
| 16 | + Logger that stores logs in the local filesystem. |
| 17 | + """ |
| 18 | + |
| 19 | + EVAL_PROTOCOL_DIR = ".eval_protocol" |
| 20 | + PYTHON_FILES = ["pyproject.toml", "requirements.txt"] |
| 21 | + DATASETS_DIR = "datasets" |
| 22 | + |
| 23 | + def __init__(self): |
| 24 | + # recursively look up for a .eval_protocol directory |
| 25 | + current_dir = os.path.dirname(os.path.abspath(__file__)) |
| 26 | + while current_dir != "/": |
| 27 | + if os.path.exists(os.path.join(current_dir, self.EVAL_PROTOCOL_DIR)): |
| 28 | + self.log_dir = os.path.join(current_dir, self.EVAL_PROTOCOL_DIR) |
| 29 | + break |
| 30 | + current_dir = os.path.dirname(current_dir) |
| 31 | + |
| 32 | + # if not found, recursively look up until a pyproject.toml or requirements.txt is found |
| 33 | + current_dir = os.path.dirname(os.path.abspath(__file__)) |
| 34 | + while current_dir != "/": |
| 35 | + if any(os.path.exists(os.path.join(current_dir, f)) for f in self.PYTHON_FILES): |
| 36 | + self.log_dir = os.path.join(current_dir, self.EVAL_PROTOCOL_DIR) |
| 37 | + break |
| 38 | + current_dir = os.path.dirname(current_dir) |
| 39 | + |
| 40 | + # get the PWD that this python process is running in |
| 41 | + self.log_dir = os.path.join(os.getcwd(), self.EVAL_PROTOCOL_DIR) |
| 42 | + |
| 43 | + # create the .eval_protocol directory if it doesn't exist |
| 44 | + os.makedirs(self.log_dir, exist_ok=True) |
| 45 | + |
| 46 | + # create the datasets subdirectory |
| 47 | + self.datasets_dir = os.path.join(self.log_dir, self.DATASETS_DIR) |
| 48 | + os.makedirs(self.datasets_dir, exist_ok=True) |
| 49 | + |
| 50 | + # ensure that log file exists |
| 51 | + if not os.path.exists(self.current_jsonl_path): |
| 52 | + with open(self.current_jsonl_path, "w") as f: |
| 53 | + f.write("") |
| 54 | + |
| 55 | + @property |
| 56 | + def current_date(self) -> str: |
| 57 | + # Use UTC timezone to be consistent across local device/locations/CI |
| 58 | + return datetime.now(timezone.utc).strftime("%Y-%m-%d") |
| 59 | + |
| 60 | + @property |
| 61 | + def current_jsonl_path(self) -> str: |
| 62 | + """ |
| 63 | + The current JSONL file path. Based on the current date. |
| 64 | + """ |
| 65 | + return os.path.join(self.datasets_dir, f"{self.current_date}.jsonl") |
| 66 | + |
| 67 | + def log(self, row: "EvaluationRow") -> None: |
| 68 | + """Log a row, updating existing row with same ID or appending new row.""" |
| 69 | + row_id = row.input_metadata.row_id |
| 70 | + |
| 71 | + # Check if row with this ID already exists |
| 72 | + if os.path.exists(self.current_jsonl_path): |
| 73 | + with open(self.current_jsonl_path, "r") as f: |
| 74 | + lines = f.readlines() |
| 75 | + |
| 76 | + # Find the line with matching ID |
| 77 | + for i, line in enumerate(lines): |
| 78 | + try: |
| 79 | + line_data = json.loads(line.strip()) |
| 80 | + if line_data["input_metadata"]["row_id"] == row_id: |
| 81 | + # Update existing row |
| 82 | + lines[i] = row.model_dump_json(exclude_none=True) + os.linesep |
| 83 | + with open(self.current_jsonl_path, "w") as f: |
| 84 | + f.writelines(lines) |
| 85 | + return |
| 86 | + except json.JSONDecodeError: |
| 87 | + continue |
| 88 | + |
| 89 | + # If no existing row found, append new row |
| 90 | + with open(self.current_jsonl_path, "a") as f: |
| 91 | + f.write(row.model_dump_json(exclude_none=True) + os.linesep) |
| 92 | + |
| 93 | + def read(self, row_id: Optional[str] = None) -> List["EvaluationRow"]: |
| 94 | + """Read rows from all JSONL files in the datasets directory.""" |
| 95 | + from eval_protocol.models import EvaluationRow |
| 96 | + |
| 97 | + if not os.path.exists(self.datasets_dir): |
| 98 | + return [] |
| 99 | + |
| 100 | + all_rows = [] |
| 101 | + for filename in os.listdir(self.datasets_dir): |
| 102 | + if filename.endswith(".jsonl"): |
| 103 | + file_path = os.path.join(self.datasets_dir, filename) |
| 104 | + try: |
| 105 | + data = load_jsonl(file_path) |
| 106 | + all_rows.extend([EvaluationRow(**r) for r in data]) |
| 107 | + except Exception: |
| 108 | + continue # skip files that can't be read/parsed |
| 109 | + |
| 110 | + if row_id: |
| 111 | + # Filter by row_id if specified |
| 112 | + return [row for row in all_rows if getattr(row.input_metadata, "row_id", None) == row_id] |
| 113 | + else: |
| 114 | + return all_rows |
0 commit comments