95 lines
3.6 KiB
Python
95 lines
3.6 KiB
Python
"""Validated, source-backed observations for the compute comparison cards."""
|
|
|
|
from datetime import date
|
|
from typing import Annotated, Literal, Self
|
|
|
|
from app.services.compute_catalog import COUNTRY_PARTICIPANTS
|
|
from pydantic import BaseModel, ConfigDict, Field, HttpUrl, field_validator, model_validator
|
|
|
|
Year = Annotated[int, Field(strict=True, ge=2000, le=2100)]
|
|
Value = Annotated[float, Field(strict=True, allow_inf_nan=False, ge=0, le=1e12)]
|
|
Identifier = Annotated[str, Field(min_length=1, max_length=80, pattern=r"^[a-zA-Z0-9_-]+$")]
|
|
Text = Annotated[str, Field(min_length=1, max_length=500)]
|
|
|
|
|
|
class ConfigurationModel(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
|
|
class ComputeSource(ConfigurationModel):
|
|
id: Identifier
|
|
title: Text
|
|
url: HttpUrl
|
|
publisher: Text
|
|
report_year: Year
|
|
published_at: date | None = None
|
|
locator: Text
|
|
|
|
@field_validator("url")
|
|
@classmethod
|
|
def public_reference(cls, value: HttpUrl) -> HttpUrl:
|
|
if value.username or value.password or len(str(value)) > 2000:
|
|
raise ValueError("Use a report URL without credentials (maximum 2000 characters)")
|
|
return value
|
|
|
|
|
|
class ComputeObservation(ConfigurationModel):
|
|
year: Year
|
|
metric: Literal["global_share", "absolute"]
|
|
source_id: Identifier
|
|
values: dict[str, Value] = Field(min_length=1, max_length=250)
|
|
|
|
@model_validator(mode="after")
|
|
def comparable_values(self) -> Self:
|
|
if any(code not in COUNTRY_PARTICIPANTS for code in self.values):
|
|
raise ValueError(
|
|
"Use countries from the canonical compute catalog, not regional totals"
|
|
)
|
|
if self.metric == "global_share" and sum(self.values.values()) > 100.000001:
|
|
raise ValueError("Global shares for one year must total at most 100 percent")
|
|
return self
|
|
|
|
|
|
class InnovationObservation(ConfigurationModel):
|
|
year: Year
|
|
value: Annotated[float, Field(strict=True, allow_inf_nan=False, ge=-100, le=100)]
|
|
source_id: Identifier
|
|
|
|
|
|
class ComputeConfiguration(ConfigurationModel):
|
|
reviewed_at: date
|
|
sources: list[ComputeSource] = Field(max_length=200)
|
|
observations: list[ComputeObservation] = Field(max_length=202)
|
|
innovation: list[InnovationObservation] = Field(max_length=101)
|
|
|
|
@model_validator(mode="after")
|
|
def consistent_evidence(self) -> Self:
|
|
ids = [source.id for source in self.sources]
|
|
if len(ids) != len(set(ids)):
|
|
raise ValueError("Report source IDs must be unique")
|
|
keys = [(row.metric, row.year) for row in self.observations]
|
|
if len(keys) != len(set(keys)):
|
|
raise ValueError("Each metric/year may have only one observation")
|
|
years = [row.year for row in self.innovation]
|
|
if len(years) != len(set(years)):
|
|
raise ValueError("Innovation observation years must be unique")
|
|
sources = {source.id: source for source in self.sources}
|
|
for row in [*self.observations, *self.innovation]:
|
|
source = sources.get(row.source_id)
|
|
if source is None:
|
|
raise ValueError(f"Missing report source: {row.source_id}")
|
|
if row.year > source.report_year:
|
|
raise ValueError("Observation year must not be after its report year")
|
|
if self.reviewed_at > date.today():
|
|
raise ValueError("Review date must not be in the future")
|
|
return self
|
|
|
|
|
|
class ComputeConfigurationWrite(ConfigurationModel):
|
|
revision: str = Field(min_length=1, max_length=80)
|
|
config: ComputeConfiguration
|
|
|
|
|
|
class ComputeConfigurationReset(ConfigurationModel):
|
|
revision: str = Field(min_length=1, max_length=80)
|