pydantic-codemeta 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,53 @@
1
+ """Minimal schema.org models used for CodeMeta metadata."""
2
+
3
+ from .base import JsonLdContext, PropertyValue, SchemaOrgBase, Thing
4
+ from .codemeta import (
5
+ CODEMETA_V3_CONTEXT,
6
+ CodeMeta,
7
+ CodeMetaV3,
8
+ codemeta_to_codemeta_v3,
9
+ codemeta_v3_to_codemeta,
10
+ )
11
+ from .normalization import migrate_legacy_codemeta, normalize_jsonld_context
12
+ from .types import (
13
+ ComputerLanguage,
14
+ ContactPoint,
15
+ CreativeWork,
16
+ DataFeed,
17
+ MediaObject,
18
+ Organization,
19
+ Person,
20
+ PostalAddress,
21
+ Review,
22
+ Role,
23
+ ScholarlyArticle,
24
+ SoftwareApplication,
25
+ SoftwareSourceCode,
26
+ )
27
+
28
+ __all__ = [
29
+ "CodeMeta",
30
+ "CodeMetaV3",
31
+ "CODEMETA_V3_CONTEXT",
32
+ "codemeta_v3_to_codemeta",
33
+ "codemeta_to_codemeta_v3",
34
+ "normalize_jsonld_context",
35
+ "migrate_legacy_codemeta",
36
+ "JsonLdContext",
37
+ "ComputerLanguage",
38
+ "ContactPoint",
39
+ "CreativeWork",
40
+ "DataFeed",
41
+ "MediaObject",
42
+ "Organization",
43
+ "Person",
44
+ "PostalAddress",
45
+ "PropertyValue",
46
+ "Review",
47
+ "Role",
48
+ "SchemaOrgBase",
49
+ "ScholarlyArticle",
50
+ "SoftwareApplication",
51
+ "SoftwareSourceCode",
52
+ "Thing",
53
+ ]
@@ -0,0 +1,179 @@
1
+ """Shared JSON-LD behavior and base schema.org models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from math import isfinite
7
+ from typing import Annotated, Literal, Self, TypeAlias, cast
8
+
9
+ from pydantic import (
10
+ BaseModel,
11
+ BeforeValidator,
12
+ ConfigDict,
13
+ Field,
14
+ JsonValue,
15
+ StrictBool,
16
+ StrictFloat,
17
+ StrictInt,
18
+ model_validator,
19
+ )
20
+
21
+
22
+ def _check_raw_json_value(value: object, path: str) -> None:
23
+ """Reject Python-only values before Pydantic can coerce them."""
24
+
25
+ value_type = type(value)
26
+ if value is None or value_type in (bool, int, str):
27
+ return
28
+ if value_type is float:
29
+ if not isfinite(value):
30
+ raise ValueError(f"{path} must contain only finite JSON numbers")
31
+ return
32
+ if value_type is list:
33
+ for index, item in enumerate(value):
34
+ _check_raw_json_value(item, f"{path}[{index}]")
35
+ return
36
+ if value_type is dict:
37
+ for key, item in value.items():
38
+ if type(key) is not str:
39
+ raise ValueError(f"{path} must contain only string object keys")
40
+ _check_raw_json_value(item, f"{path}.{key}")
41
+ return
42
+ raise ValueError(f"{path} must be a raw JSON value")
43
+
44
+
45
+ def _validate_raw_json_value(value: object) -> object:
46
+ _check_raw_json_value(value, "$")
47
+ return value
48
+
49
+
50
+ def _declared_input_keys(model: type[BaseModel]) -> set[str]:
51
+ """Return field names and string aliases accepted as declared input."""
52
+
53
+ return {
54
+ key
55
+ for name, field in model.model_fields.items()
56
+ for key in (name, field.alias)
57
+ if isinstance(key, str)
58
+ }
59
+
60
+
61
+ RawJsonValue: TypeAlias = Annotated[
62
+ JsonValue, BeforeValidator(_validate_raw_json_value)
63
+ ]
64
+ RawJsonObject: TypeAlias = Annotated[
65
+ dict[str, JsonValue], BeforeValidator(_validate_raw_json_value)
66
+ ]
67
+ JsonLdContextObject: TypeAlias = RawJsonObject
68
+ JsonLdContextEntry: TypeAlias = str | JsonLdContextObject | None
69
+ JsonLdContext: TypeAlias = JsonLdContextEntry | list[JsonLdContextEntry]
70
+
71
+
72
+ class SchemaOrgBase(BaseModel):
73
+ """Common JSON-LD behavior for the package's typed resources.
74
+
75
+ Declared fields are typed vocabulary terms. Extra fields are retained as
76
+ raw JSON-compatible values so future terms and extensions can round-trip.
77
+ """
78
+
79
+ model_config = ConfigDict(
80
+ allow_inf_nan=False,
81
+ populate_by_name=True,
82
+ extra="allow",
83
+ use_enum_values=True,
84
+ )
85
+
86
+ __pydantic_extra__: dict[str, object] = Field(init=False)
87
+
88
+ id: str | None = Field(None, alias="@id")
89
+ type: str = Field(..., alias="@type")
90
+
91
+ @model_validator(mode="before")
92
+ @classmethod
93
+ def reject_alias_name_collisions(cls, data: object) -> object:
94
+ """Reject ambiguous aliases and Python-only extra values."""
95
+
96
+ if not isinstance(data, Mapping):
97
+ return data
98
+
99
+ field_keys = _declared_input_keys(cls)
100
+ collisions = [
101
+ (name, field.alias)
102
+ for name, field in cls.model_fields.items()
103
+ if isinstance(field.alias, str)
104
+ and field.alias != name
105
+ and name in data
106
+ and field.alias in data
107
+ ]
108
+ if collisions:
109
+ rendered = ", ".join(
110
+ f"{name!r} and {alias!r}" for name, alias in collisions
111
+ )
112
+ raise ValueError(f"Conflicting field name and JSON-LD alias: {rendered}")
113
+
114
+ for key, value in data.items():
115
+ if key not in field_keys:
116
+ _check_raw_json_value(value, key)
117
+ return data
118
+
119
+ def to_jsonld(self) -> dict[str, object]:
120
+ """Serialize the model using JSON-LD aliases."""
121
+
122
+ payload = cast(
123
+ dict[str, object],
124
+ self.model_dump(
125
+ by_alias=True,
126
+ mode="json",
127
+ ),
128
+ )
129
+ return cast(dict[str, object], _prune_declared_none(self, payload))
130
+
131
+ @classmethod
132
+ def from_jsonld(cls, data: dict[str, object]) -> Self:
133
+ """Validate a JSON-LD dictionary without normalization or migration."""
134
+
135
+ return cls.model_validate(data)
136
+
137
+
138
+ def _prune_declared_none(value: object, serialized: object) -> object:
139
+ """Omit null typed fields while retaining nulls inside raw JSON extras."""
140
+
141
+ if isinstance(value, SchemaOrgBase) and isinstance(serialized, dict):
142
+ for name, field in type(value).model_fields.items():
143
+ alias = field.serialization_alias or field.alias or name
144
+ field_value = getattr(value, name)
145
+ if field_value is None:
146
+ preserve_null_context = (
147
+ name == "context" and name in value.model_fields_set
148
+ )
149
+ if not preserve_null_context:
150
+ serialized.pop(alias, None)
151
+ elif alias in serialized:
152
+ serialized[alias] = _prune_declared_none(field_value, serialized[alias])
153
+ return serialized
154
+ if isinstance(value, list) and isinstance(serialized, list):
155
+ return [
156
+ _prune_declared_none(item, dumped)
157
+ for item, dumped in zip(value, serialized, strict=True)
158
+ ]
159
+ return serialized
160
+
161
+
162
+ class Thing(SchemaOrgBase):
163
+ """Base schema.org Thing model."""
164
+
165
+ type: Literal["Thing"] = Field("Thing", alias="@type")
166
+ name: str | None = None
167
+ description: str | None = None
168
+ url: str | list[str] | None = None
169
+ identifier: str | PropertyValue | list[str | PropertyValue] | None = None
170
+ related_link: str | list[str] | None = Field(None, alias="relatedLink")
171
+ same_as: str | list[str] | None = Field(None, alias="sameAs")
172
+
173
+
174
+ class PropertyValue(Thing):
175
+ """A schema.org structured property value."""
176
+
177
+ type: Literal["PropertyValue"] = Field("PropertyValue", alias="@type")
178
+ value: StrictBool | str | StrictInt | StrictFloat | RawJsonObject | None = None
179
+ property_id: str | None = Field(None, alias="propertyID")
@@ -0,0 +1,89 @@
1
+ """CodeMeta v3 models and explicit compatibility adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from pydantic import Field
8
+
9
+ from .base import JsonLdContext
10
+ from .normalization import migrate_legacy_codemeta, normalize_jsonld_context
11
+ from .types import SoftwareSourceCode
12
+
13
+ CODEMETA_V3_CONTEXT = "https://w3id.org/codemeta/3.0"
14
+
15
+
16
+ class CodeMeta(SoftwareSourceCode):
17
+ """Canonical open CodeMeta model preserving any declared context.
18
+
19
+ ``from_jsonld`` is a pure parse (``model_validate``) identical to every
20
+ other model. It preserves the declared ``@context`` structure and performs
21
+ no migration or normalization.
22
+
23
+ For legacy input that uses prefix-qualified keys (``schema:name``) or
24
+ pre-v3 property names (``creator``, ``embargoDate``,
25
+ ``contIntegration``), use :meth:`from_legacy_jsonld`.
26
+ """
27
+
28
+ context: JsonLdContext = Field(CODEMETA_V3_CONTEXT, alias="@context")
29
+ type: Literal["SoftwareSourceCode"] = Field("SoftwareSourceCode", alias="@type")
30
+
31
+ @classmethod
32
+ def from_legacy_jsonld(cls, data: dict[str, object]) -> CodeMeta:
33
+ """Parse legacy JSON-LD with prefix flattening and property migration.
34
+
35
+ Applies :func:`normalize_jsonld_context` (flattens dict ``@context``
36
+ prefixes, removes the dict context) and :func:`migrate_legacy_codemeta`
37
+ (renames ``creator``→``author``, ``embargoDate``→``embargoEndDate``,
38
+ ``contIntegration``→``continuousIntegration``), then parses the result
39
+ as CodeMeta v3 and adapts to the canonical open :class:`CodeMeta`.
40
+
41
+ This is intentionally lossy: the dict ``@context`` is removed after
42
+ prefix flattening, and the v3 context is backfilled. Use
43
+ :meth:`from_jsonld` when the input is already canonical and no
44
+ migration is needed.
45
+ """
46
+
47
+ return codemeta_v3_to_codemeta(CodeMetaV3.from_legacy_jsonld(data))
48
+
49
+
50
+ class CodeMetaV3(CodeMeta):
51
+ """Version-specific CodeMeta v3 binding.
52
+
53
+ The context and root type are fixed while inherited vocabulary terms and
54
+ raw JSON extras remain open. Direct validation performs no transforms.
55
+ """
56
+
57
+ context: Literal[CODEMETA_V3_CONTEXT] = Field(CODEMETA_V3_CONTEXT, alias="@context")
58
+
59
+ @classmethod
60
+ def from_legacy_jsonld(cls, data: dict[str, object]) -> CodeMetaV3:
61
+ """Normalize and migrate legacy input into the v3 binding."""
62
+
63
+ normalized = normalize_jsonld_context(data)
64
+ migrated = migrate_legacy_codemeta(normalized)
65
+ return cls.model_validate(migrated)
66
+
67
+
68
+ def codemeta_v3_to_codemeta(model: CodeMetaV3) -> CodeMeta:
69
+ """Adapt a v3 model to the canonical open CodeMeta model."""
70
+
71
+ return CodeMeta.model_validate(model.model_dump(by_alias=True, mode="python"))
72
+
73
+
74
+ def codemeta_to_codemeta_v3(model: CodeMeta) -> CodeMetaV3:
75
+ """Adapt canonical CodeMeta to v3, rejecting non-v3 declared contexts.
76
+
77
+ A structured ``@context`` or any string other than the v3 context is
78
+ rejected, since :class:`CodeMetaV3` requires a literal v3 context.
79
+ """
80
+
81
+ payload = model.model_dump(by_alias=True, mode="python")
82
+ context = payload.get("@context")
83
+ if context is None:
84
+ payload["@context"] = CODEMETA_V3_CONTEXT
85
+ elif context != CODEMETA_V3_CONTEXT:
86
+ raise ValueError(
87
+ f"CodeMeta context must be {CODEMETA_V3_CONTEXT!r} for v3 adaptation"
88
+ )
89
+ return CodeMetaV3.model_validate(payload)
@@ -0,0 +1,59 @@
1
+ """Explicit, root-only compatibility transforms for JSON-LD input."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ def normalize_jsonld_context(data: dict[str, Any]) -> dict[str, Any]:
9
+ """Flatten configured dict-context prefixes at the document root.
10
+
11
+ This is intentionally lossy: a dict ``@context`` is removed after known
12
+ prefixed root keys are flattened. String, list, malformed, and unknown
13
+ contexts are retained. Nested dictionaries are never inspected.
14
+ """
15
+
16
+ context = data.get("@context")
17
+ if not isinstance(context, dict):
18
+ return dict(data)
19
+
20
+ result = dict(data)
21
+ configured_prefixes = tuple(
22
+ key for key in context if isinstance(key, str) and not key.startswith("@")
23
+ )
24
+ for key in tuple(data):
25
+ if not isinstance(key, str):
26
+ continue
27
+ for prefix in configured_prefixes:
28
+ marker = f"{prefix}:"
29
+ if key.startswith(marker):
30
+ target = key[len(marker) :]
31
+ if target in data or target in result:
32
+ raise ValueError(
33
+ f"JSON-LD context normalization collision for {target!r}"
34
+ )
35
+ result[target] = result.pop(key)
36
+ break
37
+ result.pop("@context", None)
38
+ return result
39
+
40
+
41
+ def migrate_legacy_codemeta(data: dict[str, Any]) -> dict[str, Any]:
42
+ """Migrate the three legacy root-level CodeMeta property names.
43
+
44
+ Migration is shallow and checks key presence rather than truthiness, so
45
+ falsey values are migrated and simultaneous old/new keys are rejected.
46
+ """
47
+
48
+ result = dict(data)
49
+ migrations = (
50
+ ("embargoDate", "embargoEndDate"),
51
+ ("contIntegration", "continuousIntegration"),
52
+ ("creator", "author"),
53
+ )
54
+ for old, new in migrations:
55
+ if old in data and new in data:
56
+ raise ValueError(f"Cannot migrate {old!r}: {new!r} is also present")
57
+ if old in data:
58
+ result[new] = result.pop(old)
59
+ return result
@@ -0,0 +1,318 @@
1
+ """Typed schema.org and CodeMeta vocabulary terms used by the package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, datetime
6
+ from typing import Literal, TypeAlias
7
+
8
+ from pydantic import Field, StrictBool, StrictFloat, StrictInt, field_validator
9
+
10
+ from .base import JsonLdContext, PropertyValue, RawJsonObject, Thing
11
+
12
+
13
+ def _parse_iso_date(value: object) -> date | str | None:
14
+ """Parse ISO dates while preserving other strings verbatim."""
15
+
16
+ if value is None:
17
+ return None
18
+ if isinstance(value, datetime):
19
+ raise ValueError("datetime values are not accepted for date fields")
20
+ if isinstance(value, date):
21
+ return value
22
+ if not isinstance(value, str):
23
+ raise ValueError("date fields accept only date objects or strings")
24
+ try:
25
+ return date.fromisoformat(value)
26
+ except ValueError:
27
+ return value
28
+
29
+
30
+ _NON_CREATIVE_WORK_TYPES = {
31
+ "Thing",
32
+ "Person",
33
+ "Organization",
34
+ "Role",
35
+ "ContactPoint",
36
+ "PostalAddress",
37
+ "ComputerLanguage",
38
+ "PropertyValue",
39
+ }
40
+
41
+
42
+ class ContactPoint(Thing):
43
+ """A schema.org contact point."""
44
+
45
+ type: Literal["ContactPoint"] = Field("ContactPoint", alias="@type")
46
+ contact_type: str | None = Field(None, alias="contactType")
47
+ email: str | None = None
48
+
49
+
50
+ class PostalAddress(Thing):
51
+ """A schema.org postal address."""
52
+
53
+ type: Literal["PostalAddress"] = Field("PostalAddress", alias="@type")
54
+ street_address: str | None = Field(None, alias="streetAddress")
55
+ address_locality: str | None = Field(None, alias="addressLocality")
56
+ address_region: str | None = Field(None, alias="addressRegion")
57
+ postal_code: str | None = Field(None, alias="postalCode")
58
+ address_country: str | None = Field(None, alias="addressCountry")
59
+
60
+
61
+ class Organization(Thing):
62
+ """A schema.org organization."""
63
+
64
+ type: Literal["Organization"] = Field("Organization", alias="@type")
65
+ email: str | None = None
66
+ contact_point: ContactPoint | list[ContactPoint] | None = Field(
67
+ None, alias="contactPoint"
68
+ )
69
+ address: PostalAddress | str | None = None
70
+
71
+
72
+ class Person(Thing):
73
+ """A schema.org person."""
74
+
75
+ type: Literal["Person"] = Field("Person", alias="@type")
76
+ email: str | None = None
77
+ given_name: str | None = Field(None, alias="givenName")
78
+ family_name: str | None = Field(None, alias="familyName")
79
+ affiliation: Organization | str | None = None
80
+ contact_point: ContactPoint | list[ContactPoint] | None = Field(
81
+ None, alias="contactPoint"
82
+ )
83
+ address: PostalAddress | str | None = None
84
+
85
+
86
+ class Role(Thing):
87
+ """A schema.org role associating an agent with a contribution."""
88
+
89
+ type: Literal["Role"] = Field("Role", alias="@type")
90
+ role_name: str | None = Field(None, alias="roleName")
91
+ start_date: date | str | None = Field(None, alias="startDate")
92
+ end_date: date | str | None = Field(None, alias="endDate")
93
+ author: Person | Organization | str | None = None
94
+
95
+ @field_validator("start_date", "end_date", mode="before")
96
+ @classmethod
97
+ def parse_role_dates(cls, value: object) -> date | str | None:
98
+ return _parse_iso_date(value)
99
+
100
+
101
+ class ComputerLanguage(Thing):
102
+ """A schema.org computer programming language."""
103
+
104
+ type: Literal["ComputerLanguage"] = Field("ComputerLanguage", alias="@type")
105
+
106
+
107
+ Agent: TypeAlias = Person | Organization | Role | str
108
+ AgentField: TypeAlias = Agent | list[Agent]
109
+ Party: TypeAlias = Person | Organization | str
110
+ PartyField: TypeAlias = Party | list[Party]
111
+
112
+
113
+ class CreativeWork(Thing):
114
+ """Open CreativeWork relation model and base for known concrete subtypes.
115
+
116
+ The type remains open so an unfamiliar CreativeWork subtype can retain its
117
+ declared ``@type`` when it appears in a typed relationship field.
118
+ """
119
+
120
+ type: str = Field("CreativeWork", alias="@type")
121
+ author: AgentField | None = None
122
+ contributor: AgentField | None = None
123
+ editor: Person | list[Person] | None = None
124
+ publisher: PartyField | None = None
125
+ copyright_holder: PartyField | None = Field(None, alias="copyrightHolder")
126
+ copyright_year: StrictInt | None = Field(None, alias="copyrightYear")
127
+ funder: PartyField | None = None
128
+ sponsor: PartyField | None = None
129
+ provider: PartyField | None = None
130
+ producer: PartyField | None = None
131
+ license: CreativeWork | str | list[CreativeWork | str] | None = None
132
+ citation: (
133
+ ScholarlyArticle
134
+ | CreativeWork
135
+ | str
136
+ | list[ScholarlyArticle | CreativeWork | str]
137
+ | None
138
+ ) = None
139
+ review: Review | str | None = None
140
+ is_part_of: CreativeWork | str | list[CreativeWork | str] | None = Field(
141
+ None, alias="isPartOf"
142
+ )
143
+ has_part: CreativeWork | str | list[CreativeWork | str] | None = Field(
144
+ None, alias="hasPart"
145
+ )
146
+ encoding: MediaObject | list[MediaObject] | None = None
147
+ keywords: str | list[str] | None = None
148
+ position: StrictInt | str | None = None
149
+ date_created: date | str | None = Field(None, alias="dateCreated")
150
+ date_modified: date | str | None = Field(None, alias="dateModified")
151
+ date_published: date | str | None = Field(None, alias="datePublished")
152
+
153
+ @field_validator("date_created", "date_modified", "date_published", mode="before")
154
+ @classmethod
155
+ def parse_dates(cls, value: object) -> date | str | None:
156
+ return _parse_iso_date(value)
157
+
158
+ @field_validator("type")
159
+ @classmethod
160
+ def reject_known_non_creative_work_type(cls, value: str) -> str:
161
+ if value in _NON_CREATIVE_WORK_TYPES:
162
+ raise ValueError(f"{value} is not a CreativeWork type")
163
+ return value
164
+
165
+
166
+ class MediaObject(CreativeWork):
167
+ """A schema.org media object used by ``encoding``."""
168
+
169
+ type: Literal["MediaObject"] = Field("MediaObject", alias="@type")
170
+ content_url: str | None = Field(None, alias="contentUrl")
171
+ encoding_format: str | None = Field(None, alias="encodingFormat")
172
+ content_size: str | None = Field(None, alias="contentSize")
173
+
174
+
175
+ class DataFeed(CreativeWork):
176
+ """A schema.org data feed used by ``supportingData``."""
177
+
178
+ type: Literal["DataFeed"] = Field("DataFeed", alias="@type")
179
+ data_feed_element: str | RawJsonObject | list[str | RawJsonObject] | None = Field(
180
+ None, alias="dataFeedElement"
181
+ )
182
+
183
+
184
+ class Review(CreativeWork):
185
+ """A schema.org review."""
186
+
187
+ type: Literal["Review"] = Field("Review", alias="@type")
188
+ review_body: str | None = Field(None, alias="reviewBody")
189
+ review_aspect: str | None = Field(None, alias="reviewAspect")
190
+
191
+
192
+ class ScholarlyArticle(CreativeWork):
193
+ """A schema.org scholarly article."""
194
+
195
+ type: Literal["ScholarlyArticle"] = Field("ScholarlyArticle", alias="@type")
196
+
197
+
198
+ class SoftwareSourceCode(CreativeWork):
199
+ """Stable, version-neutral SoftwareSourceCode information model."""
200
+
201
+ context: JsonLdContext = Field(None, alias="@context")
202
+ type: Literal["SoftwareSourceCode"] = Field("SoftwareSourceCode", alias="@type")
203
+ code_repository: str | None = Field(None, alias="codeRepository")
204
+ programming_language: (
205
+ ComputerLanguage | str | list[ComputerLanguage | str] | None
206
+ ) = Field(None, alias="programmingLanguage")
207
+ runtime_platform: str | list[str] | None = Field(None, alias="runtimePlatform")
208
+ target_product: (
209
+ SoftwareApplication | str | list[SoftwareApplication | str] | None
210
+ ) = Field(None, alias="targetProduct")
211
+ application_category: str | list[str] | None = Field(
212
+ None, alias="applicationCategory"
213
+ )
214
+ application_sub_category: str | list[str] | None = Field(
215
+ None, alias="applicationSubCategory"
216
+ )
217
+ download_url: str | list[str] | None = Field(None, alias="downloadUrl")
218
+ file_size: str | None = Field(None, alias="fileSize")
219
+ install_url: str | list[str] | None = Field(None, alias="installUrl")
220
+ memory_requirements: str | list[str] | None = Field(
221
+ None, alias="memoryRequirements"
222
+ )
223
+ operating_system: str | list[str] | None = Field(None, alias="operatingSystem")
224
+ permissions: str | list[str] | None = None
225
+ processor_requirements: str | list[str] | None = Field(
226
+ None, alias="processorRequirements"
227
+ )
228
+ release_notes: str | list[str] | None = Field(None, alias="releaseNotes")
229
+ software_help: CreativeWork | str | list[CreativeWork | str] | None = Field(
230
+ None, alias="softwareHelp"
231
+ )
232
+ software_requirements: (
233
+ SoftwareSourceCode | str | list[SoftwareSourceCode | str] | None
234
+ ) = Field(None, alias="softwareRequirements")
235
+ software_version: str | None = Field(None, alias="softwareVersion")
236
+ storage_requirements: str | list[str] | None = Field(
237
+ None, alias="storageRequirements"
238
+ )
239
+ file_format: str | list[str] | None = Field(None, alias="fileFormat")
240
+ is_accessible_for_free: StrictBool | None = Field(None, alias="isAccessibleForFree")
241
+ version: (
242
+ StrictInt | StrictFloat | str | list[StrictInt | StrictFloat | str] | None
243
+ ) = None
244
+ supporting_data: DataFeed | list[DataFeed] | None = Field(
245
+ None, alias="supportingData"
246
+ )
247
+
248
+ # CodeMeta-specific vocabulary terms.
249
+ maintainer: AgentField | None = None
250
+ build_instructions: str | list[str] | None = Field(None, alias="buildInstructions")
251
+ continuous_integration: str | list[str] | None = Field(
252
+ None, alias="continuousIntegration"
253
+ )
254
+ development_status: str | None = Field(None, alias="developmentStatus")
255
+ embargo_end_date: date | str | None = Field(None, alias="embargoEndDate")
256
+ funding: str | list[str] | None = None
257
+ has_source_code: (
258
+ SoftwareSourceCode | str | list[SoftwareSourceCode | str] | None
259
+ ) = Field(None, alias="hasSourceCode")
260
+ is_source_code_of: (
261
+ SoftwareApplication | str | list[SoftwareApplication | str] | None
262
+ ) = Field(None, alias="isSourceCodeOf")
263
+ issue_tracker: str | list[str] | None = Field(None, alias="issueTracker")
264
+ readme: str | list[str] | None = None
265
+ reference_publication: (
266
+ ScholarlyArticle | str | list[ScholarlyArticle | str] | None
267
+ ) = Field(None, alias="referencePublication")
268
+ software_suggestions: (
269
+ SoftwareSourceCode | str | list[SoftwareSourceCode | str] | None
270
+ ) = Field(None, alias="softwareSuggestions")
271
+
272
+ @field_validator("embargo_end_date", mode="before")
273
+ @classmethod
274
+ def parse_embargo_date(cls, value: object) -> date | str | None:
275
+ return _parse_iso_date(value)
276
+
277
+
278
+ class SoftwareApplication(CreativeWork):
279
+ """A schema.org SoftwareApplication model."""
280
+
281
+ type: Literal["SoftwareApplication"] = Field("SoftwareApplication", alias="@type")
282
+ application_category: str | list[str] | None = Field(
283
+ None, alias="applicationCategory"
284
+ )
285
+ application_sub_category: str | list[str] | None = Field(
286
+ None, alias="applicationSubCategory"
287
+ )
288
+ operating_system: str | list[str] | None = Field(None, alias="operatingSystem")
289
+ software_version: str | None = Field(None, alias="softwareVersion")
290
+ download_url: str | list[str] | None = Field(None, alias="downloadUrl")
291
+ install_url: str | list[str] | None = Field(None, alias="installUrl")
292
+ memory_requirements: str | list[str] | None = Field(
293
+ None, alias="memoryRequirements"
294
+ )
295
+ processor_requirements: str | list[str] | None = Field(
296
+ None, alias="processorRequirements"
297
+ )
298
+ storage_requirements: str | list[str] | None = Field(
299
+ None, alias="storageRequirements"
300
+ )
301
+ permissions: str | list[str] | None = None
302
+ supporting_data: DataFeed | list[DataFeed] | None = Field(
303
+ None, alias="supportingData"
304
+ )
305
+
306
+
307
+ _MODEL_TYPES_NAMESPACE = {"PropertyValue": PropertyValue}
308
+
309
+ CreativeWork.model_rebuild(_types_namespace=_MODEL_TYPES_NAMESPACE)
310
+ MediaObject.model_rebuild(_types_namespace=_MODEL_TYPES_NAMESPACE)
311
+ DataFeed.model_rebuild(_types_namespace=_MODEL_TYPES_NAMESPACE)
312
+ Review.model_rebuild(_types_namespace=_MODEL_TYPES_NAMESPACE)
313
+ ScholarlyArticle.model_rebuild(_types_namespace=_MODEL_TYPES_NAMESPACE)
314
+ SoftwareSourceCode.model_rebuild(_types_namespace=_MODEL_TYPES_NAMESPACE)
315
+ SoftwareApplication.model_rebuild(_types_namespace=_MODEL_TYPES_NAMESPACE)
316
+ Role.model_rebuild(_types_namespace=_MODEL_TYPES_NAMESPACE)
317
+ Person.model_rebuild(_types_namespace=_MODEL_TYPES_NAMESPACE)
318
+ Organization.model_rebuild(_types_namespace=_MODEL_TYPES_NAMESPACE)
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: pydantic-codemeta
3
+ Version: 0.1.0
4
+ Summary: CodeMeta-focused schema.org models built with Pydantic v2
5
+ Author-email: Allen Lee <allen.lee@asu.edu>
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: pydantic<3,>=2
11
+ Requires-Dist: typing-extensions>=4.7
12
+ Dynamic: license-file
13
+
14
+ # pydantic-codemeta
15
+
16
+ Pydantic v2 models for parsing, validating, and serializing [CodeMeta](https://codemeta.github.io/) JSON-LD metadata, with typed Python APIs and round-trip preservation of unknown properties.
17
+
18
+ The package provides a typed representation of common CodeMeta and schema.org terms while preserving unknown JSON-LD properties during round trips.
19
+
20
+ ## Features
21
+
22
+ - Typed CodeMeta and schema.org models built on Pydantic v2
23
+ - JSON-LD aliases such as `@context`, `@type`, and `codeRepository`
24
+ - Preservation of unknown JSON-compatible properties
25
+ - Explicit legacy CodeMeta migration without implicit document rewriting
26
+ - Typed CodeMeta 3.0 models with strict @context validation
27
+
28
+ ## Requirements
29
+
30
+ - Python 3.11 or newer
31
+ - Pydantic 2.x
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ python -m pip install pydantic-codemeta
37
+ ```
38
+
39
+ ## Usage
40
+
41
+ Parse a CodeMeta document into a validated model and serialize it back to
42
+ JSON-LD:
43
+
44
+ ```python
45
+ from pydantic_codemeta import CodeMeta
46
+
47
+ document = {
48
+ "@context": "https://w3id.org/codemeta/3.0",
49
+ "@type": "SoftwareSourceCode",
50
+ "name": "Example",
51
+ "codeRepository": "https://example.org/repository",
52
+ }
53
+
54
+ metadata = CodeMeta.from_jsonld(document)
55
+
56
+ assert metadata.code_repository == "https://example.org/repository"
57
+ assert metadata.to_jsonld()["codeRepository"] == document["codeRepository"]
58
+ ```
59
+
60
+ Python attributes use snake_case names. `to_jsonld()` emits the corresponding
61
+ CodeMeta and schema.org aliases.
62
+
63
+ ### Parsing Behavior
64
+
65
+ - `CodeMeta.from_jsonld()` validates canonical CodeMeta 3.0 without rewriting it.
66
+ - `CodeMeta.from_legacy_jsonld()` explicitly migrates supported legacy forms.
67
+ - Unknown JSON-compatible properties survive parse and serialization round trips.
68
+
69
+ See the
70
+ [model specification](https://github.com/SciCodes/pydantic-codemeta/blob/main/docs/specs/codemeta-pydantic-v2.md)
71
+ for the complete field, context, migration, date, collision, and round-trip
72
+ contracts.
73
+
74
+ ## Development
75
+
76
+ Install [uv](https://docs.astral.sh/uv/), then create the development
77
+ environment and run the test suite:
78
+
79
+ ```bash
80
+ uv sync
81
+ uv run python -m pytest -q -s
82
+ ```
83
+
84
+ Build and validate the distribution artifacts:
85
+
86
+ ```bash
87
+ uv build
88
+ uv run twine check dist/*
89
+ ```
90
+
91
+ Docker-based checks are also available:
92
+
93
+ ```bash
94
+ make docker-test
95
+ make docker-package
96
+ ```
97
+
98
+ ## TestPyPI rehearsal
99
+
100
+ A full TestPyPI rehearsal builds, validates, and uploads the package without
101
+ touching production PyPI. Configure `~/.pypirc` with TestPyPI credentials:
102
+
103
+ ```ini
104
+ [testpypi]
105
+ username = __token__
106
+ password = pypi-<your-testpypi-token>
107
+ ```
108
+
109
+ Then run:
110
+
111
+ ```bash
112
+ make release-test
113
+ ```
114
+
115
+ This runs `clean`, `test`, `package`, `check`, and `publish-test` (uploads to
116
+ TestPyPI). After uploading, verify the package installs from TestPyPI:
117
+
118
+ ```bash
119
+ make smoke-test
120
+ ```
121
+
122
+ Production PyPI releases are published by the GitHub Actions release workflow
123
+ using PyPI Trusted Publishing. Do not use `make publish` for production
124
+ releases.
125
+
126
+ ## Contributing
127
+
128
+ Contributions are welcome. See
129
+ [CONTRIBUTING.md](https://github.com/SciCodes/pydantic-codemeta/blob/main/CONTRIBUTING.md)
130
+ for development setup, testing, formatting, pull request guidelines, and the
131
+ release process.
132
+
133
+ ## License
134
+
135
+ `pydantic-codemeta` is distributed under the
136
+ [MIT License](https://github.com/SciCodes/pydantic-codemeta/blob/main/LICENSE).
@@ -0,0 +1,10 @@
1
+ pydantic_codemeta/__init__.py,sha256=IhCAgMqf3Iy2aCOOhn9ZO3W4NVdVuvdonyEsQC225KI,1134
2
+ pydantic_codemeta/base.py,sha256=My-WEZ6A7B1FDHIhWVC_fs6LhGVK_vHpx9aVMhyQa-Y,5904
3
+ pydantic_codemeta/codemeta.py,sha256=32QHAxVQLocj4Muy9kItQM8DakUmvZAr93tGde4c3s0,3425
4
+ pydantic_codemeta/normalization.py,sha256=dRI-90uByuHAuUduBVRLbv8evDtwKFtxzV-St4Aas7s,2026
5
+ pydantic_codemeta/types.py,sha256=1O5y2Y5SEXS2qtoMTDt-QV_C0e8QcEMnFIvxRKxQ6HI,12343
6
+ pydantic_codemeta-0.1.0.dist-info/licenses/LICENSE,sha256=REUo6CgPpMGXDeIeYM7C2L3B_p_7guxmAM62T6FPbPo,1118
7
+ pydantic_codemeta-0.1.0.dist-info/METADATA,sha256=QiHJqYgGXM0ehHQklzj3383m-44y2WloSa4FatD95Qk,3664
8
+ pydantic_codemeta-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
+ pydantic_codemeta-0.1.0.dist-info/top_level.txt,sha256=wsFzWBFAabOqsNXUviUFjRZmAV7RMdIZ6faA2m5sNz8,18
10
+ pydantic_codemeta-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Consortium of Scientific Software Registries and Repositories
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pydantic_codemeta