elcc / util /validate.py
bboldt's picture
Initial public commit
a5f760c
raw
history blame
3.65 kB
from pathlib import Path
import logging
from typing import Any, Literal, TypeVar
import pydantic
import yaml # type: ignore
T = TypeVar("T")
logging.basicConfig(level=logging.INFO)
Url = str
class BaseModel(pydantic.BaseModel):
model_config = pydantic.ConfigDict(extra="forbid")
class OriginMetadata(BaseModel):
source: Url
"""Where the code is from."""
upstream_source: Url | None = None
"""The original implementation."""
paper: Url | None = None
"""The paper which introduces the system."""
class SystemMetadata(BaseModel):
game_type: Literal["signalling", "conversation", "navigation"]
observation_type: Literal["vector", "image"]
observation_continuous: bool
data_source: None | Literal["natural", "synthetic"]
variants: dict[str, Any]
"""Different variants of the environment.
Each dict should be populated with the distinguishing characteristics of
that environment.
"""
game_subtype: None | str
seeding_available: bool
"""System implements settable random seeds."""
multi_step: bool
"""Environment has multiple timesteps per episode."""
symmetric_agents: bool
"""Agents can send and receive messages."""
multi_utterance: bool
"""Multiple utterances are present per line."""
more_than_2_agents: bool
"""More than two agents present in the environment."""
@pydantic.field_validator("variants")
@classmethod
def check_variants(cls, v: T, info: pydantic.ValidationInfo) -> T:
if not isinstance(v, dict):
raise ValueError(f'Field "variants" must be a dict.')
if info.context and (path := info.context.get("path", None)):
# Check that all listed variants are present on the filesystem.
for k in v.keys():
validate_variant(f"{path}/data/{k}")
# Check that all variants on the filesystem are listed in the metadata.
for var in Path(path).glob("data/*"):
if var.name not in v.keys():
logging.warning(
f'Directory "{path}/data/{var}" found but not listed in metadata.'
)
return v # type: ignore
def validate_variant(_path: str) -> None:
path = Path(_path)
if not path.exists():
logging.warning(
f"Variant {path.name} in metadata but not {path} does not exist."
)
return
corpus_path = path / "corpus.jsonl"
if not corpus_path.exists():
logging.warning(f"Corpus file {corpus_path} does not exist.")
metadata_path = path / "metadata.json"
if not metadata_path.exists():
logging.warning(f"Metadata file {metadata_path} does not exist.")
class SystemLevelMetadata(BaseModel):
origin: OriginMetadata
system: SystemMetadata
notes: str | None = None
def main() -> None:
paths = list(Path(".").glob("data/*"))
for path in paths:
try:
md_path = path / "metadata.yml"
if not md_path.exists():
logging.warning(f'Missing metadata file at "{md_path}".')
continue
with md_path.open() as fo:
raw = yaml.load(fo.read(), Loader=yaml.Loader)
if raw is None:
logging.warning(f'"{md_path}" is empty.')
continue
SystemLevelMetadata.model_validate(raw, context={"path": path})
except (yaml.parser.ParserError, pydantic.ValidationError) as e:
logging.warning(f'Path "{md_path}" failed validation with:\n{e}')
logging.info("Validation completed.")
if __name__ == "__main__":
main()