Coverage for src/bioimageio/spec/conda_env.py: 81%
69 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 16:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 16:20 +0000
1"""Representation of conda environment.yaml files for bioimageio specifications."""
3from __future__ import annotations
5import warnings
6from collections.abc import Callable
7from typing import Any, cast
9from pydantic import BaseModel, Field, field_validator, model_validator
12class PipDeps(BaseModel):
13 """Pip dependencies to include in conda dependecies"""
15 pip: list[str] = Field(default_factory=list)
17 @field_validator("pip", mode="after")
18 @classmethod
19 def _remove_empty_and_sort(cls, value: list[str]) -> list[str]:
20 return sorted(vs for v in value if (vs := v.strip()))
22 def __lt__(self, other: Any):
23 if isinstance(other, PipDeps):
24 return len(self.pip) < len(other.pip)
25 else:
26 return False
28 def __gt__(self, other: Any):
29 if isinstance(other, PipDeps):
30 return len(self.pip) > len(other.pip)
31 else:
32 return False
35class CondaEnv(BaseModel):
36 """Represenation of the content of a conda environment.yaml file"""
38 name: str | None = None
39 channels: list[str] = Field(default_factory=list)
40 dependencies: list[str | PipDeps] = Field(
41 default_factory=cast(Callable[[], list[str | PipDeps]], list)
42 )
44 @field_validator("name", mode="after")
45 def _ensure_valid_conda_env_name(cls, value: str | None) -> str | None:
46 if value is None:
47 return None
49 for illegal in ("/", " ", ":", "#"):
50 value = value.replace(illegal, "")
52 return value or "empty"
54 @property
55 def wo_name(self):
56 return self.model_construct(**{k: v for k, v in self if k != "name"})
58 def _get_version_pin(self, package: str):
59 """Helper to return any version pin for **package**
61 TODO: improve: interprete version pin and return structured information.
62 """
63 for d in self.dependencies:
64 if isinstance(d, PipDeps):
65 for p in d.pip:
66 if p.startswith(package):
67 return p[len(package) :]
68 elif d.startswith(package):
69 return d[len(package) :]
70 elif "::" in d and (d_wo_channel := d.split("::", 1)[-1]).startswith(
71 package
72 ):
73 return d_wo_channel[len(package) :]
75 def get_pip_deps(self) -> list[str]:
76 """Get the pip dependencies of this conda env."""
77 for dep in self.dependencies:
78 if isinstance(dep, PipDeps):
79 return dep.pip
81 return []
84class BioimageioCondaEnv(CondaEnv):
85 """A special `CondaEnv` that
86 - automatically adds bioimageio specific dependencies
87 - sorts dependencies
88 """
90 @model_validator(mode="after")
91 def _normalize_bioimageio_conda_env(self):
92 """update a conda env such that we have bioimageio.core and sorted dependencies"""
93 for req_channel in ("conda-forge", "nodefaults"):
94 if req_channel not in self.channels:
95 self.channels.append(req_channel)
97 if "defaults" in self.channels:
98 warnings.warn("removing 'defaults' from conda-channels")
99 self.channels.remove("defaults")
101 if "pip" not in self.dependencies:
102 self.dependencies.append("pip")
104 for dep in self.dependencies:
105 if isinstance(dep, PipDeps):
106 pip_section = dep
107 pip_section.pip.sort()
108 break
109 else:
110 pip_section = None
112 if (
113 pip_section is None
114 or not any(pd.startswith("bioimageio.core") for pd in pip_section.pip)
115 ) and not any(
116 d.startswith(("bioimageio.core", "conda-forge::bioimageio.core"))
117 for d in self.dependencies
118 if not isinstance(d, PipDeps)
119 ):
120 self.dependencies.append("conda-forge::bioimageio.core>=0.9.4")
122 self.dependencies.sort()
123 return self