destiny_sdk 0.6.0__tar.gz → 0.7.1__tar.gz

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.
Files changed (42) hide show
  1. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/.gitignore +2 -0
  2. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/PKG-INFO +1 -1
  3. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/pyproject.toml +1 -1
  4. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/client.py +34 -2
  5. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/enhancements.py +58 -19
  6. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/identifiers.py +75 -5
  7. destiny_sdk-0.7.1/src/destiny_sdk/parsers/eppi_parser.py +284 -0
  8. destiny_sdk-0.7.1/src/destiny_sdk/parsers/exceptions.py +17 -0
  9. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/search.py +2 -1
  10. destiny_sdk-0.7.1/tests/unit/parsers/test_eppi_parser.py +228 -0
  11. destiny_sdk-0.7.1/tests/unit/test_data/eppi_import.jsonl +4 -0
  12. destiny_sdk-0.7.1/tests/unit/test_data/eppi_import_with_annotations.jsonl +4 -0
  13. destiny_sdk-0.7.1/tests/unit/test_data/eppi_import_with_raw.jsonl +4 -0
  14. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/test_data/eppi_report.json +6 -1
  15. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/test_enhancements.py +48 -0
  16. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/test_identifiers.py +27 -0
  17. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/test_references.py +2 -1
  18. destiny_sdk-0.6.0/src/destiny_sdk/parsers/eppi_parser.py +0 -172
  19. destiny_sdk-0.6.0/tests/unit/parsers/test_eppi_parser.py +0 -47
  20. destiny_sdk-0.6.0/tests/unit/test_data/eppi_import.jsonl +0 -4
  21. destiny_sdk-0.6.0/tests/unit/test_data/eppi_import_with_annotations.jsonl +0 -4
  22. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/LICENSE +0 -0
  23. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/README.md +0 -0
  24. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/__init__.py +0 -0
  25. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/auth.py +0 -0
  26. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/core.py +0 -0
  27. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/imports.py +0 -0
  28. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/labs/__init__.py +0 -0
  29. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/labs/references.py +0 -0
  30. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/parsers/__init__.py +0 -0
  31. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/py.typed +0 -0
  32. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/references.py +0 -0
  33. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/robots.py +0 -0
  34. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/src/destiny_sdk/visibility.py +0 -0
  35. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/__init__.py +0 -0
  36. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/conftest.py +0 -0
  37. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/labs/test_references.py +0 -0
  38. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/test_auth.py +0 -0
  39. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/test_client.py +0 -0
  40. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/test_data/destiny_references.jsonl +0 -0
  41. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/tests/unit/test_robots.py +0 -0
  42. {destiny_sdk-0.6.0 → destiny_sdk-0.7.1}/uv.lock +0 -0
@@ -203,3 +203,5 @@ libs/fake_data/*.jsonl
203
203
  .env.*
204
204
  !.env.example
205
205
  .idea/
206
+
207
+ .test.tmp
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: destiny_sdk
3
- Version: 0.6.0
3
+ Version: 0.7.1
4
4
  Summary: A software development kit (sdk) to support interaction with the DESTINY repository
5
5
  Author-email: Adam Hamilton <adam@futureevidence.org>, Andrew Harvey <andrew@futureevidence.org>, Daniel Breves <daniel@futureevidence.org>, Jack Walmisley <jack@futureevidence.org>, Tim Repke <tim.repke@pik-potsdam.de>
6
6
  License-Expression: Apache-2.0
@@ -34,7 +34,7 @@ license = "Apache-2.0"
34
34
  name = "destiny_sdk"
35
35
  readme = "README.md"
36
36
  requires-python = "~=3.12"
37
- version = "0.6.0"
37
+ version = "0.7.1"
38
38
 
39
39
  [project.optional-dependencies]
40
40
  labs = []
@@ -114,7 +114,11 @@ class Client:
114
114
  return RobotEnhancementBatchRead.model_validate(response.json())
115
115
 
116
116
  def poll_robot_enhancement_batch(
117
- self, robot_id: UUID4, limit: int = 10, timeout: int = 60
117
+ self,
118
+ robot_id: UUID4,
119
+ limit: int = 10,
120
+ lease: str | None = None,
121
+ timeout: int = 60,
118
122
  ) -> RobotEnhancementBatch | None:
119
123
  """
120
124
  Poll for a robot enhancement batch.
@@ -125,13 +129,20 @@ class Client:
125
129
  :type robot_id: UUID4
126
130
  :param limit: The maximum number of pending enhancements to return
127
131
  :type limit: int
132
+ :param lease: The duration to lease the pending enhancements for,
133
+ in ISO 8601 duration format eg PT10M. If not provided the repository will
134
+ use a default lease duration.
135
+ :type lease: str | None
128
136
  :return: The RobotEnhancementBatch object from the response, or None if no
129
137
  batches available
130
138
  :rtype: destiny_sdk.robots.RobotEnhancementBatch | None
131
139
  """
140
+ params = {"robot_id": str(robot_id), "limit": limit}
141
+ if lease:
142
+ params["lease"] = lease
132
143
  response = self.session.post(
133
144
  "/robot-enhancement-batches/",
134
- params={"robot_id": str(robot_id), "limit": limit},
145
+ params=params,
135
146
  timeout=timeout,
136
147
  )
137
148
  # HTTP 204 No Content indicates no batches available
@@ -140,3 +151,24 @@ class Client:
140
151
 
141
152
  response.raise_for_status()
142
153
  return RobotEnhancementBatch.model_validate(response.json())
154
+
155
+ def renew_robot_enhancement_batch_lease(
156
+ self, robot_enhancement_batch_id: UUID4, lease_duration: str | None = None
157
+ ) -> None:
158
+ """
159
+ Renew the lease for a robot enhancement batch.
160
+
161
+ Signs the request with the client's secret key.
162
+
163
+ :param robot_enhancement_batch_id: The ID of the robot enhancement batch
164
+ :type robot_enhancement_batch_id: UUID4
165
+ :param lease_duration: The duration to lease the pending enhancements for,
166
+ in ISO 8601 duration format eg PT10M. If not provided the repository will
167
+ use a default lease duration.
168
+ :type lease_duration: str | None
169
+ """
170
+ response = self.session.post(
171
+ f"/robot-enhancement-batches/{robot_enhancement_batch_id}/renew-lease/",
172
+ params={"lease": lease_duration} if lease_duration else None,
173
+ )
174
+ response.raise_for_status()
@@ -2,9 +2,9 @@
2
2
 
3
3
  import datetime
4
4
  from enum import StrEnum, auto
5
- from typing import Annotated, Literal
5
+ from typing import Annotated, Any, Literal, Self
6
6
 
7
- from pydantic import UUID4, BaseModel, Field, HttpUrl
7
+ from pydantic import UUID4, BaseModel, Field, HttpUrl, model_validator
8
8
 
9
9
  from destiny_sdk.core import _JsonlFileInputMixIn
10
10
  from destiny_sdk.visibility import Visibility
@@ -25,6 +25,8 @@ class EnhancementType(StrEnum):
25
25
  """A free-form enhancement for tagging with labels."""
26
26
  LOCATION = auto()
27
27
  """Locations where the reference can be found."""
28
+ RAW = auto()
29
+ """A free form enhancement for arbitrary/unstructured data."""
28
30
  FULL_TEXT = auto()
29
31
  """The full text of the reference. (To be implemented)"""
30
32
 
@@ -145,22 +147,33 @@ class AnnotationType(StrEnum):
145
147
  """
146
148
 
147
149
 
148
- class ScoreAnnotation(BaseModel):
149
- """
150
- An annotation which represents the score for a label.
150
+ class BaseAnnotation(BaseModel):
151
+ """Base class for annotations, defining the minimal required fields."""
151
152
 
152
- This is similar to a BooleanAnnotation, but lacks a boolean determination
153
- as to the application of the label.
154
- """
155
-
156
- annotation_type: Literal[AnnotationType.SCORE] = AnnotationType.SCORE
157
153
  scheme: str = Field(
158
154
  description="An identifier for the scheme of annotation",
159
155
  examples=["openalex:topic", "pubmed:mesh"],
156
+ pattern=r"^[^/]+$", # No slashes allowed
160
157
  )
161
158
  label: str = Field(
162
159
  description="A high level label for this annotation like the name of the topic",
163
160
  )
161
+
162
+ @property
163
+ def qualified_label(self) -> str:
164
+ """The qualified label for this annotation."""
165
+ return f"{self.scheme}/{self.label}"
166
+
167
+
168
+ class ScoreAnnotation(BaseAnnotation):
169
+ """
170
+ An annotation which represents the score for a label.
171
+
172
+ This is similar to a BooleanAnnotation, but lacks a boolean determination
173
+ as to the application of the label.
174
+ """
175
+
176
+ annotation_type: Literal[AnnotationType.SCORE] = AnnotationType.SCORE
164
177
  score: float = Field(description="""Score for this annotation""")
165
178
  data: dict = Field(
166
179
  default_factory=dict,
@@ -171,7 +184,7 @@ class ScoreAnnotation(BaseModel):
171
184
  )
172
185
 
173
186
 
174
- class BooleanAnnotation(BaseModel):
187
+ class BooleanAnnotation(BaseAnnotation):
175
188
  """
176
189
  An annotation is a way of tagging the content with a label of some kind.
177
190
 
@@ -180,13 +193,6 @@ class BooleanAnnotation(BaseModel):
180
193
  """
181
194
 
182
195
  annotation_type: Literal[AnnotationType.BOOLEAN] = AnnotationType.BOOLEAN
183
- scheme: str = Field(
184
- description="An identifier for the scheme of the annotation",
185
- examples=["openalex:topic", "pubmed:mesh"],
186
- )
187
- label: str = Field(
188
- description="A high level label for this annotation like the name of the topic",
189
- )
190
196
  value: bool = Field(description="""Boolean flag for this annotation""")
191
197
  score: float | None = Field(
192
198
  None, description="A confidence score for this annotation"
@@ -295,12 +301,45 @@ class LocationEnhancement(BaseModel):
295
301
  )
296
302
 
297
303
 
304
+ class RawEnhancement(BaseModel):
305
+ """
306
+ An enhancement for storing raw/arbitrary/unstructured data.
307
+
308
+ Data in these enhancements is intended for future conversion into structured form.
309
+
310
+ This enhancement accepts any fields passed in to `data`. These enhancements cannot
311
+ be created by robots.
312
+ """
313
+
314
+ enhancement_type: Literal[EnhancementType.RAW] = EnhancementType.RAW
315
+ source_export_date: datetime.datetime = Field(
316
+ description="Date the enhancement data was retrieved."
317
+ )
318
+ description: str = Field(
319
+ description="Description of the data to aid in future refinement."
320
+ )
321
+ metadata: dict[str, Any] = Field(
322
+ default_factory=dict,
323
+ description="Additional metadata to aid in future structuring of raw data",
324
+ )
325
+ data: Any = Field(description="Unstructured data for later processing.")
326
+
327
+ @model_validator(mode="after")
328
+ def forbid_no_data(self) -> Self:
329
+ """Prevent a raw enhancement from being created with no data."""
330
+ if not self.data:
331
+ msg = "data must be populated on a raw enhancement."
332
+ raise ValueError(msg)
333
+ return self
334
+
335
+
298
336
  #: Union type for all enhancement content types.
299
337
  EnhancementContent = Annotated[
300
338
  BibliographicMetadataEnhancement
301
339
  | AbstractContentEnhancement
302
340
  | AnnotationEnhancement
303
- | LocationEnhancement,
341
+ | LocationEnhancement
342
+ | RawEnhancement,
304
343
  Field(discriminator="enhancement_type"),
305
344
  ]
306
345
 
@@ -17,8 +17,14 @@ class ExternalIdentifierType(StrEnum):
17
17
 
18
18
  DOI = auto()
19
19
  """A DOI (Digital Object Identifier) which is a unique identifier for a document."""
20
+ ERIC = auto()
21
+ """An ERIC (Education Resources Information Identifier) ID which is a unique
22
+ identifier for a document in ERIC.
23
+ """
20
24
  PM_ID = auto()
21
25
  """A PubMed ID which is a unique identifier for a document in PubMed."""
26
+ PRO_QUEST = auto()
27
+ """A ProQuest ID which is a unqiue identifier for a document in ProQuest."""
22
28
  OPEN_ALEX = auto()
23
29
  """An OpenAlex ID which is a unique identifier for a document in OpenAlex."""
24
30
  OTHER = auto()
@@ -41,8 +47,64 @@ class DOIIdentifier(BaseModel):
41
47
  def remove_doi_url(cls, value: str) -> str:
42
48
  """Remove the URL part of the DOI if it exists."""
43
49
  return (
44
- value.removeprefix("http://doi.org/")
45
- .removeprefix("https://doi.org/")
50
+ value.removeprefix("http://")
51
+ .removeprefix("https://")
52
+ .removeprefix("doi.org/")
53
+ .removeprefix("dx.doi.org/")
54
+ .removeprefix("doi:")
55
+ .strip()
56
+ )
57
+
58
+
59
+ class ProQuestIdentifier(BaseModel):
60
+ """An external identifier representing a ProQuest ID."""
61
+
62
+ identifier: str = Field(
63
+ description="The ProQuest id of the reference", pattern=r"[0-9]+$"
64
+ )
65
+ identifier_type: Literal[ExternalIdentifierType.PRO_QUEST] = Field(
66
+ ExternalIdentifierType.PRO_QUEST, description="The type of identifier used."
67
+ )
68
+
69
+ @field_validator("identifier", mode="before")
70
+ @classmethod
71
+ def remove_proquest_url(cls, value: str) -> str:
72
+ """Remove the URL part of the ProQuest id if it exists."""
73
+ return (
74
+ value.removeprefix("http://")
75
+ .removeprefix("https://")
76
+ .removeprefix("search.proquest.com/")
77
+ .removeprefix("www.proquest.com/")
78
+ .removeprefix("docview/")
79
+ .strip()
80
+ )
81
+
82
+
83
+ class ERICIdentifier(BaseModel):
84
+ """
85
+ An external identifier representing an ERIC Number.
86
+
87
+ An ERIC Number is defined as a unqiue identifiying number preceeded by
88
+ EJ (for a journal article) or ED (for a non-journal document).
89
+ """
90
+
91
+ identifier: str = Field(
92
+ description="The ERIC Number of the reference.", pattern=r"E[D|J][0-9]+$"
93
+ )
94
+ identifier_type: Literal[ExternalIdentifierType.ERIC] = Field(
95
+ ExternalIdentifierType.ERIC, description="The type of identifier used."
96
+ )
97
+
98
+ @field_validator("identifier", mode="before")
99
+ @classmethod
100
+ def remove_eric_url(cls, value: str) -> str:
101
+ """Remove the URL part of the ERIC ID if it exists."""
102
+ return (
103
+ value.removeprefix("http://")
104
+ .removeprefix("https://")
105
+ .removeprefix("eric.ed.gov/?id=")
106
+ .removeprefix("files.eric.ed.gov/fulltext/")
107
+ .removesuffix(".pdf")
46
108
  .strip()
47
109
  )
48
110
 
@@ -71,8 +133,11 @@ class OpenAlexIdentifier(BaseModel):
71
133
  def remove_open_alex_url(cls, value: str) -> str:
72
134
  """Remove the OpenAlex URL if it exists."""
73
135
  return (
74
- value.removeprefix("http://openalex.org/")
75
- .removeprefix("https://openalex.org/")
136
+ value.removeprefix("http://")
137
+ .removeprefix("https://")
138
+ .removeprefix("openalex.org/")
139
+ .removeprefix("explore.openalex.org/")
140
+ .removeprefix("works/")
76
141
  .strip()
77
142
  )
78
143
 
@@ -91,7 +156,12 @@ class OtherIdentifier(BaseModel):
91
156
 
92
157
  #: Union type for all external identifiers.
93
158
  ExternalIdentifier = Annotated[
94
- DOIIdentifier | PubMedIdentifier | OpenAlexIdentifier | OtherIdentifier,
159
+ DOIIdentifier
160
+ | ERICIdentifier
161
+ | PubMedIdentifier
162
+ | ProQuestIdentifier
163
+ | OpenAlexIdentifier
164
+ | OtherIdentifier,
95
165
  Field(discriminator="identifier_type"),
96
166
  ]
97
167
 
@@ -0,0 +1,284 @@
1
+ """Parser for a EPPI JSON export file."""
2
+
3
+ from datetime import datetime
4
+ from typing import Any
5
+
6
+ from pydantic import ValidationError
7
+
8
+ from destiny_sdk.enhancements import (
9
+ AbstractContentEnhancement,
10
+ AbstractProcessType,
11
+ AnnotationEnhancement,
12
+ AnnotationType,
13
+ AuthorPosition,
14
+ Authorship,
15
+ BibliographicMetadataEnhancement,
16
+ BooleanAnnotation,
17
+ EnhancementContent,
18
+ EnhancementFileInput,
19
+ RawEnhancement,
20
+ )
21
+ from destiny_sdk.identifiers import (
22
+ DOIIdentifier,
23
+ ERICIdentifier,
24
+ ExternalIdentifier,
25
+ OpenAlexIdentifier,
26
+ ProQuestIdentifier,
27
+ )
28
+ from destiny_sdk.parsers.exceptions import ExternalIdentifierNotFoundError
29
+ from destiny_sdk.references import ReferenceFileInput
30
+ from destiny_sdk.visibility import Visibility
31
+
32
+
33
+ class EPPIParser:
34
+ """
35
+ Parser for an EPPI JSON export file.
36
+
37
+ See example here: https://eppi.ioe.ac.uk/cms/Portals/35/Maps/Examples/example_orignal.json
38
+ """
39
+
40
+ version = "2.0"
41
+
42
+ def __init__(
43
+ self,
44
+ *,
45
+ tags: list[str] | None = None,
46
+ include_raw_data: bool = False,
47
+ source_export_date: datetime | None = None,
48
+ data_description: str | None = None,
49
+ raw_enhancement_excludes: list[str] | None = None,
50
+ ) -> None:
51
+ """
52
+ Initialize the EPPIParser with optional tags.
53
+
54
+ Args:
55
+ tags (list[str] | None): Optional list of tags to annotate references.
56
+
57
+ """
58
+ self.tags = tags or []
59
+ self.parser_source = f"destiny_sdk.eppi_parser@{self.version}"
60
+ self.include_raw_data = include_raw_data
61
+ self.source_export_date = source_export_date
62
+ self.data_description = data_description
63
+ self.raw_enhancement_excludes = (
64
+ raw_enhancement_excludes if raw_enhancement_excludes else []
65
+ )
66
+
67
+ if self.include_raw_data and not all(
68
+ (
69
+ self.source_export_date,
70
+ self.data_description,
71
+ )
72
+ ):
73
+ msg = (
74
+ "Cannot include raw data enhancements without "
75
+ "source_export_date, data_description, and raw_enhancement_metadata"
76
+ )
77
+ raise RuntimeError(msg)
78
+
79
+ def _parse_identifiers(
80
+ self, ref_to_import: dict[str, Any]
81
+ ) -> list[ExternalIdentifier]:
82
+ identifiers = []
83
+ if doi := ref_to_import.get("DOI"):
84
+ doi_identifier = self._parse_doi(doi=doi)
85
+ if doi_identifier:
86
+ identifiers.append(doi_identifier)
87
+
88
+ if url := ref_to_import.get("URL"):
89
+ identifier = self._parse_url_to_identifier(url=url)
90
+ if identifier:
91
+ identifiers.append(identifier)
92
+
93
+ if not identifiers:
94
+ msg = (
95
+ "No known external identifiers found for Reference data "
96
+ f"with DOI: '{doi if doi else None}' "
97
+ f"and URL: '{url if url else None}'."
98
+ )
99
+ raise ExternalIdentifierNotFoundError(detail=msg)
100
+
101
+ return identifiers
102
+
103
+ def _parse_doi(self, doi: str) -> DOIIdentifier | None:
104
+ """Attempt to parse a DOI from a string."""
105
+ try:
106
+ doi = doi.strip()
107
+ return DOIIdentifier(identifier=doi)
108
+ except ValidationError:
109
+ return None
110
+
111
+ def _parse_url_to_identifier(self, url: str) -> ExternalIdentifier | None:
112
+ """Attempt to parse an external identifier from a url string."""
113
+ url = url.strip()
114
+ identifier_cls = None
115
+ if "eric" in url:
116
+ identifier_cls = ERICIdentifier
117
+ elif "proquest" in url:
118
+ identifier_cls = ProQuestIdentifier
119
+ elif "openalex" in url:
120
+ identifier_cls = OpenAlexIdentifier
121
+ else:
122
+ return None
123
+
124
+ try:
125
+ return identifier_cls(identifier=url)
126
+ except ValidationError:
127
+ return None
128
+
129
+ def _parse_abstract_enhancement(
130
+ self, ref_to_import: dict[str, Any]
131
+ ) -> EnhancementContent | None:
132
+ if abstract := ref_to_import.get("Abstract"):
133
+ return AbstractContentEnhancement(
134
+ process=AbstractProcessType.OTHER,
135
+ abstract=abstract,
136
+ )
137
+ return None
138
+
139
+ def _parse_bibliographic_enhancement(
140
+ self, ref_to_import: dict[str, Any]
141
+ ) -> EnhancementContent | None:
142
+ title = ref_to_import.get("Title")
143
+ publication_year = (
144
+ int(year)
145
+ if (year := ref_to_import.get("Year")) and year.isdigit()
146
+ else None
147
+ )
148
+ publisher = ref_to_import.get("Publisher")
149
+ authors_string = ref_to_import.get("Authors")
150
+
151
+ authorships = []
152
+ if authors_string:
153
+ authors = [
154
+ author.strip() for author in authors_string.split(";") if author.strip()
155
+ ]
156
+ for i, author_name in enumerate(authors):
157
+ position = AuthorPosition.MIDDLE
158
+ if i == 0:
159
+ position = AuthorPosition.FIRST
160
+ if i == len(authors) - 1 and i > 0:
161
+ position = AuthorPosition.LAST
162
+
163
+ authorships.append(
164
+ Authorship(
165
+ display_name=author_name,
166
+ position=position,
167
+ )
168
+ )
169
+
170
+ if not title and not publication_year and not publisher and not authorships:
171
+ return None
172
+
173
+ return BibliographicMetadataEnhancement(
174
+ title=title,
175
+ publication_year=publication_year,
176
+ publisher=publisher,
177
+ authorship=authorships if authorships else None,
178
+ )
179
+
180
+ def _parse_raw_enhancement(
181
+ self, ref_to_import: dict[str, Any], raw_enhancement_metadata: dict[str, Any]
182
+ ) -> EnhancementContent | None:
183
+ """Add Reference data as a raw enhancement."""
184
+ raw_enhancement_data = ref_to_import.copy()
185
+
186
+ # Remove any keys that should be excluded
187
+ for exclude in self.raw_enhancement_excludes:
188
+ raw_enhancement_data.pop(exclude, None)
189
+
190
+ return RawEnhancement(
191
+ source_export_date=self.source_export_date,
192
+ description=self.data_description,
193
+ metadata=raw_enhancement_metadata,
194
+ data=raw_enhancement_data,
195
+ )
196
+
197
+ def _create_annotation_enhancement(self) -> EnhancementContent | None:
198
+ if not self.tags:
199
+ return None
200
+ annotations = [
201
+ BooleanAnnotation(
202
+ annotation_type=AnnotationType.BOOLEAN,
203
+ scheme=self.parser_source,
204
+ label=tag,
205
+ value=True,
206
+ )
207
+ for tag in self.tags
208
+ ]
209
+ return AnnotationEnhancement(
210
+ annotations=annotations,
211
+ )
212
+
213
+ def parse_data(
214
+ self,
215
+ data: dict,
216
+ source: str | None = None,
217
+ robot_version: str | None = None,
218
+ ) -> tuple[list[ReferenceFileInput], list[dict]]:
219
+ """
220
+ Parse an EPPI JSON export dict and return a list of ReferenceFileInput objects.
221
+
222
+ Args:
223
+ data (dict): Parsed EPPI JSON export data.
224
+ source (str | None): Optional source string for deduplication/provenance.
225
+ robot_version (str | None): Optional robot version string for provenance.
226
+ Defaults to parser version.
227
+
228
+ Returns:
229
+ list[ReferenceFileInput]: List of parsed references from the data.
230
+
231
+ """
232
+ parser_source = source if source is not None else self.parser_source
233
+
234
+ if self.include_raw_data:
235
+ codesets = [codeset.get("SetId") for codeset in data.get("CodeSets", [])]
236
+ raw_enhancement_metadata = {"codeset_ids": codesets}
237
+
238
+ references = []
239
+ failed_refs = []
240
+ for ref_to_import in data.get("References", []):
241
+ try:
242
+ enhancement_contents = [
243
+ content
244
+ for content in [
245
+ self._parse_abstract_enhancement(ref_to_import),
246
+ self._parse_bibliographic_enhancement(ref_to_import),
247
+ self._create_annotation_enhancement(),
248
+ ]
249
+ if content
250
+ ]
251
+
252
+ if self.include_raw_data:
253
+ raw_enhancement = self._parse_raw_enhancement(
254
+ ref_to_import=ref_to_import,
255
+ raw_enhancement_metadata=raw_enhancement_metadata,
256
+ )
257
+
258
+ if raw_enhancement:
259
+ enhancement_contents.append(raw_enhancement)
260
+
261
+ enhancements = [
262
+ EnhancementFileInput(
263
+ source=parser_source,
264
+ visibility=Visibility.PUBLIC,
265
+ content=content,
266
+ robot_version=robot_version,
267
+ )
268
+ for content in enhancement_contents
269
+ ]
270
+
271
+ references.append(
272
+ ReferenceFileInput(
273
+ visibility=Visibility.PUBLIC,
274
+ identifiers=self._parse_identifiers(
275
+ ref_to_import=ref_to_import
276
+ ),
277
+ enhancements=enhancements,
278
+ )
279
+ )
280
+
281
+ except ExternalIdentifierNotFoundError:
282
+ failed_refs.append(ref_to_import)
283
+
284
+ return references, failed_refs
@@ -0,0 +1,17 @@
1
+ """Custom exceptions for destiny sdk parsers."""
2
+
3
+
4
+ class ExternalIdentifierNotFoundError(Exception):
5
+ """Raised when an reference has no identifiable external identifiers."""
6
+
7
+ def __init__(self, detail: str | None = None, *args: object) -> None:
8
+ """
9
+ Initialize the ExternalIdentifiersNotFoundError.
10
+
11
+ Args:
12
+ *args: Additional arguments for the exception.
13
+ **kwargs: Additional keyword arguments for the exception.
14
+
15
+ """
16
+ self.detail = detail or "No detail provided."
17
+ super().__init__(detail, *args)
@@ -30,6 +30,7 @@ class AnnotationFilter(BaseModel):
30
30
 
31
31
  scheme: str = Field(
32
32
  description="The annotation scheme to filter by.",
33
+ pattern=r"^[^/]+$",
33
34
  )
34
35
  label: str | None = Field(
35
36
  None,
@@ -42,7 +43,7 @@ class AnnotationFilter(BaseModel):
42
43
  le=1.0,
43
44
  )
44
45
 
45
- def serialize(self) -> str:
46
+ def __repr__(self) -> str:
46
47
  """Serialize the annotation filter to a string."""
47
48
  annotation = self.scheme
48
49
  if self.label: