File size: 3,651 Bytes
a5f760c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()