cwl2citation 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,17 @@
1
+ # Copyright 2026 Transpiler-Mate
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Package metadata for CWL 2 Citation."""
16
+
17
+ __version__ = "0.1.0"
@@ -0,0 +1,19 @@
1
+ # Copyright 2026 Transpiler-Mate
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Generate software citations from CWL metadata."""
16
+
17
+ from cwl2citation.__about__ import __version__
18
+
19
+ __all__ = ["__version__"]
@@ -0,0 +1,220 @@
1
+ # Copyright 2026 Transpiler-Mate
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """CFF, BibTeX, RIS, CSL-JSON, and CSL-rendered text exporters."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from importlib.resources import files
21
+ from io import StringIO
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING, Any, cast
24
+
25
+ import rispy
26
+ from bibtexparser.entrypoint import write_string
27
+ from bibtexparser.library import Library
28
+ from bibtexparser.model import Entry, Field
29
+ from citeproc import (
30
+ Citation,
31
+ CitationItem,
32
+ CitationStylesBibliography,
33
+ CitationStylesStyle,
34
+ formatter,
35
+ )
36
+ from citeproc.frontend import CitationStylesLocale
37
+ from citeproc.source.json import CiteProcJSON
38
+ from citeproc_styles import get_style_filepath
39
+ from jsonschema import Draft7Validator, FormatChecker
40
+ from loguru import logger
41
+ from pylatexenc.latexencode import unicode_to_latex
42
+ from ruamel.yaml import YAML
43
+ from transpiler_mate.api import PluginFailureError
44
+
45
+ if TYPE_CHECKING:
46
+ from .model import CitationRecord
47
+
48
+
49
+ def schema(name: str) -> dict[str, Any]:
50
+ return cast(
51
+ "dict[str, Any]",
52
+ json.loads(
53
+ files("cwl2citation")
54
+ .joinpath("schemas")
55
+ .joinpath(name)
56
+ .read_text(encoding="utf-8")
57
+ ),
58
+ )
59
+
60
+
61
+ def validate(data: Any, name: str) -> None:
62
+ Draft7Validator(schema(name), format_checker=FormatChecker()).validate(data)
63
+
64
+
65
+ def cff(record: CitationRecord) -> str:
66
+ data: dict[str, Any] = {
67
+ "cff-version": "1.2.0",
68
+ "type": "software",
69
+ "message": "If you use this software, please cite it using these metadata.",
70
+ "title": record.title,
71
+ "abstract": record.abstract,
72
+ "version": record.version,
73
+ "authors": [],
74
+ }
75
+ for author in record.authors:
76
+ person = {"given-names": author.given, "family-names": author.family}
77
+ if author.orcid:
78
+ person["orcid"] = author.orcid
79
+ if author.affiliation:
80
+ person["affiliation"] = author.affiliation
81
+ data["authors"].append(person)
82
+ optional = {
83
+ "doi": record.doi,
84
+ "url": record.url,
85
+ "repository-code": record.repository,
86
+ "date-released": record.released.isoformat() if record.released else None,
87
+ "keywords": record.keywords or None,
88
+ }
89
+ data.update({key: value for key, value in optional.items() if value is not None})
90
+ supported = set(schema("cff-1.2.0.json")["definitions"]["license-enum"]["enum"])
91
+ licenses = [
92
+ value.removeprefix("https://spdx.org/licenses/").removesuffix(".html")
93
+ for value in record.licenses
94
+ ]
95
+ if licenses and all(value in supported for value in licenses):
96
+ data["license"] = licenses[0] if len(licenses) == 1 else licenses
97
+ elif licenses:
98
+ logger.warning(
99
+ "CFF omits license values that are not recognized SPDX identifiers: {}",
100
+ record.licenses,
101
+ )
102
+ validate(data, "cff-1.2.0.json")
103
+ stream = StringIO()
104
+ YAML().dump(data, stream)
105
+ return stream.getvalue()
106
+
107
+
108
+ def csl(record: CitationRecord) -> dict[str, Any]:
109
+ data: dict[str, Any] = {
110
+ "id": record.key,
111
+ "type": "software",
112
+ "title": record.title,
113
+ "abstract": record.abstract,
114
+ "version": record.version,
115
+ "author": [
116
+ {"given": author.given, "family": author.family}
117
+ for author in record.authors
118
+ ],
119
+ "publisher": record.publisher,
120
+ }
121
+ for key, value in {
122
+ "DOI": record.doi,
123
+ "URL": record.url,
124
+ "keyword": "; ".join(record.keywords) or None,
125
+ }.items():
126
+ if value:
127
+ data[key] = value
128
+ if record.released:
129
+ data["issued"] = {
130
+ "date-parts": [
131
+ [record.released.year, record.released.month, record.released.day]
132
+ ]
133
+ }
134
+ validate([data], "csl-data.json")
135
+ return data
136
+
137
+
138
+ def bibtex(record: CitationRecord) -> str:
139
+ def latex(value: str) -> str:
140
+ return str(unicode_to_latex(value))
141
+
142
+ fields = {
143
+ "title": "{" + latex(record.title) + "}",
144
+ "author": " and ".join(
145
+ "{" + latex(author.family) + "}, {" + latex(author.given) + "}"
146
+ for author in record.authors
147
+ ),
148
+ "publisher": latex(record.publisher),
149
+ "note": latex(f"Computer software, version {record.version}"),
150
+ }
151
+ if record.released:
152
+ fields["year"] = str(record.released.year)
153
+ for key, value in {"doi": record.doi, "url": record.url}.items():
154
+ if value:
155
+ fields[key] = latex(value)
156
+ return str(
157
+ write_string(
158
+ Library(
159
+ [
160
+ Entry(
161
+ "misc",
162
+ record.key,
163
+ [Field(key, value) for key, value in fields.items()],
164
+ )
165
+ ]
166
+ )
167
+ )
168
+ )
169
+
170
+
171
+ class CitationRisWriter(rispy.RisWriter): # type: ignore[misc]
172
+ def set_header(self, count: int) -> str:
173
+ return ""
174
+
175
+
176
+ def ris(record: CitationRecord) -> str:
177
+ entry: dict[str, Any] = {
178
+ "type_of_reference": "COMP",
179
+ "title": record.title,
180
+ "authors": [f"{author.family}, {author.given}" for author in record.authors],
181
+ "abstract": record.abstract,
182
+ "publisher": record.publisher,
183
+ "edition": record.version,
184
+ }
185
+ if record.keywords:
186
+ entry["keywords"] = record.keywords
187
+ if record.doi:
188
+ entry["doi"] = record.doi
189
+ if record.url:
190
+ entry["urls"] = [record.url]
191
+ if record.released:
192
+ entry.update(
193
+ year=str(record.released.year), date=record.released.strftime("%Y/%m/%d")
194
+ )
195
+ return str(rispy.dumps([entry], implementation=CitationRisWriter))
196
+
197
+
198
+ def text(record: CitationRecord, style: str, locale: str) -> str:
199
+ candidate = Path(style)
200
+ if candidate.is_file():
201
+ style_path = str(candidate)
202
+ else:
203
+ if "/" in style or "\\" in style or style.endswith(".csl"):
204
+ raise PluginFailureError(f"CSL style file does not exist: {style}")
205
+ style_path = str(get_style_filepath(style))
206
+ CitationStylesLocale(locale)
207
+ processor = CitationStylesStyle(style_path, locale=locale, validate=True)
208
+ processor.schema.assertValid(processor.xml)
209
+ if not processor.has_bibliography():
210
+ raise PluginFailureError(
211
+ f"CSL style {style} has no bibliography; use an independent bibliography style"
212
+ )
213
+ bibliography = CitationStylesBibliography(
214
+ processor, CiteProcJSON([csl(record)]), formatter.plain
215
+ )
216
+ bibliography.register(Citation([CitationItem(record.key)]))
217
+ result = "\n".join(str(item) for item in bibliography.bibliography())
218
+ if not result.strip():
219
+ raise PluginFailureError(f"CSL style {style} produced no bibliography entry")
220
+ return result + "\n"
cwl2citation/model.py ADDED
@@ -0,0 +1,186 @@
1
+ # Copyright 2026 Transpiler-Mate
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Normalize software metadata once for all citation exporters."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from datetime import date
21
+ from typing import TYPE_CHECKING
22
+ from urllib.parse import urlsplit
23
+
24
+ from loguru import logger
25
+ from pydantic import BaseModel, Field
26
+ from transpiler_mate.api import AuthorRole, DefinedTerm, PluginFailureError
27
+
28
+ if TYPE_CHECKING:
29
+ from transpiler_mate.api import SoftwareApplication
30
+
31
+
32
+ class Author(BaseModel):
33
+ given: str = Field(min_length=1)
34
+ family: str = Field(min_length=1)
35
+ orcid: str | None = None
36
+ affiliation: str | None = None
37
+
38
+
39
+ class CitationRecord(BaseModel):
40
+ key: str
41
+ title: str = Field(min_length=1)
42
+ abstract: str
43
+ version: str = Field(min_length=1)
44
+ authors: list[Author] = Field(min_length=1)
45
+ publisher: str
46
+ released: date | None = None
47
+ doi: str | None = None
48
+ url: str | None = None
49
+ repository: str | None = None
50
+ licenses: list[str] = Field(default_factory=list)
51
+ keywords: list[str] = Field(default_factory=list)
52
+
53
+
54
+ def clean(value: str) -> str:
55
+ """Collapse line breaks to prevent line-oriented export injection."""
56
+ return " ".join(value.split())
57
+
58
+
59
+ def normalize_doi(value: str | None, *, explicit: bool = False) -> str | None:
60
+ if value is None:
61
+ return None
62
+ candidate = re.sub(
63
+ r"^(?:https?://(?:dx\.)?doi\.org/|doi:\s*)", "", value.strip(), flags=re.I
64
+ )
65
+ if re.fullmatch(r"10\.\d{4,9}/[^\s]+", candidate):
66
+ return candidate
67
+ if explicit or value.lower().startswith(
68
+ ("doi:", "https://doi.org/", "http://doi.org/", "10.")
69
+ ):
70
+ raise PluginFailureError(f"Invalid DOI: {value}")
71
+ return None
72
+
73
+
74
+ def http_url(value: str | None) -> str | None:
75
+ if value is None:
76
+ return None
77
+ parts = urlsplit(value)
78
+ if (
79
+ parts.scheme not in {"http", "https"}
80
+ or not parts.netloc
81
+ or any(c.isspace() for c in value)
82
+ ):
83
+ raise PluginFailureError(f"Expected an HTTP(S) URL: {value}")
84
+ return value
85
+
86
+
87
+ def author_orcid(value: object) -> str | None:
88
+ text = str(value or "")
89
+ identifier = re.sub(r"^https?://orcid\.org/", "", text, flags=re.I)
90
+ if not re.fullmatch(r"\d{4}-\d{4}-\d{4}-\d{3}[\dX]", identifier):
91
+ if "orcid.org" in text:
92
+ raise PluginFailureError(f"Invalid ORCID: {text}")
93
+ return None
94
+ digits = identifier.replace("-", "")
95
+ total = 0
96
+ for digit in digits[:-1]:
97
+ total = (total + int(digit)) * 2
98
+ check = (12 - total % 11) % 11
99
+ if digits[-1] != ("X" if check == 10 else str(check)):
100
+ raise PluginFailureError(f"Invalid ORCID checksum: {text}")
101
+ return f"https://orcid.org/{identifier}"
102
+
103
+
104
+ def from_metadata(
105
+ metadata: SoftwareApplication,
106
+ *,
107
+ doi: str | None,
108
+ released: str | None,
109
+ url: str | None,
110
+ repository: str | None,
111
+ ) -> CitationRecord:
112
+ people = metadata.author if isinstance(metadata.author, list) else [metadata.author]
113
+ authors = []
114
+ for entry in people:
115
+ person = entry.author if isinstance(entry, AuthorRole) else entry
116
+ affiliations = (
117
+ person.affiliation
118
+ if isinstance(person.affiliation, list)
119
+ else [person.affiliation]
120
+ )
121
+ authors.append(
122
+ Author(
123
+ given=clean(person.given_name),
124
+ family=clean(person.family_name),
125
+ orcid=author_orcid(person.identifier),
126
+ affiliation="; ".join(clean(org.name) for org in affiliations),
127
+ )
128
+ )
129
+ identifier = str(metadata.identifier) if metadata.identifier is not None else None
130
+ resolved_doi = (
131
+ normalize_doi(doi, explicit=True)
132
+ if doi is not None
133
+ else normalize_doi(identifier)
134
+ )
135
+ release = date.fromisoformat(released) if released else None
136
+ if released and (not re.fullmatch(r"\d{4}-\d{2}-\d{2}", released)):
137
+ raise PluginFailureError("--released must use YYYY-MM-DD")
138
+ repository = http_url(repository)
139
+ landing = (
140
+ http_url(url)
141
+ if url
142
+ else (f"https://doi.org/{resolved_doi}" if resolved_doi else repository)
143
+ )
144
+ raw_keywords = (
145
+ metadata.keywords
146
+ if isinstance(metadata.keywords, list)
147
+ else [metadata.keywords]
148
+ )
149
+ keywords = [
150
+ clean(str(item.name or item.term_code or ""))
151
+ if isinstance(item, DefinedTerm)
152
+ else clean(str(item))
153
+ for item in raw_keywords
154
+ if item is not None
155
+ ]
156
+ licenses = (
157
+ metadata.license if isinstance(metadata.license, list) else [metadata.license]
158
+ )
159
+ license_values = [
160
+ str(getattr(item, "identifier", None) or getattr(item, "url", None) or item)
161
+ for item in licenses
162
+ ]
163
+ if metadata.contributor:
164
+ logger.info(
165
+ "Citation authors come from author metadata; contributors are not promoted to authors."
166
+ )
167
+ key = (
168
+ re.sub(
169
+ r"[^a-zA-Z0-9_-]+", "-", f"{metadata.name}-{metadata.software_version}"
170
+ ).strip("-")
171
+ or "workflow"
172
+ )
173
+ return CitationRecord(
174
+ key=key,
175
+ title=clean(metadata.name),
176
+ abstract=clean(metadata.description),
177
+ version=clean(metadata.software_version),
178
+ authors=authors,
179
+ publisher=clean(metadata.publisher.name),
180
+ released=release,
181
+ doi=resolved_doi,
182
+ url=landing,
183
+ repository=repository,
184
+ licenses=license_values,
185
+ keywords=[item for item in keywords if item],
186
+ )
cwl2citation/plugin.py ADDED
@@ -0,0 +1,128 @@
1
+ # Copyright 2026 Transpiler-Mate
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Generate selected citation formats through Transpiler-Mate."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from pathlib import Path
21
+ from typing import TYPE_CHECKING, Literal
22
+
23
+ from pydantic import BaseModel, ConfigDict, Field
24
+ from transpiler_mate.api import (
25
+ PluginError,
26
+ PluginExecutionError,
27
+ PluginFailureError,
28
+ transpiler_plugin,
29
+ )
30
+
31
+ from . import exporters
32
+ from .model import from_metadata
33
+
34
+ if TYPE_CHECKING:
35
+ from transpiler_mate.api import TranspilerContext
36
+
37
+
38
+ CitationFormat = Literal["cff", "bibtex", "ris", "csl-json", "text"]
39
+ ALL_FORMATS: list[CitationFormat] = ["cff", "bibtex", "ris", "csl-json", "text"]
40
+
41
+
42
+ class CWL2CitationOptions(BaseModel):
43
+ model_config = ConfigDict(extra="forbid")
44
+ output: Path = Field(default=Path("citations"), description="Output directory")
45
+ format: list[CitationFormat] = Field(
46
+ default_factory=lambda: ALL_FORMATS.copy(),
47
+ description="Output format (repeatable; default: all five)",
48
+ )
49
+ style: str = Field(
50
+ default="apa",
51
+ description="Packaged CSL style name or local .csl file; text only",
52
+ )
53
+ locale: str = Field(default="en-US", description="CSL locale; text only")
54
+ doi: str | None = Field(
55
+ default=None, description="Explicit software DOI, overriding metadata"
56
+ )
57
+ released: str | None = Field(
58
+ default=None,
59
+ description="Release/publication date YYYY-MM-DD; never inferred from dateCreated",
60
+ )
61
+ code_repository: str | None = Field(
62
+ default=None, description="Source repository HTTP(S) URL"
63
+ )
64
+ url: str | None = Field(
65
+ default=None, description="Software landing-page HTTP(S) URL"
66
+ )
67
+
68
+
69
+ FILENAMES = {
70
+ "cff": "CITATION.cff",
71
+ "bibtex": "citation.bib",
72
+ "ris": "citation.ris",
73
+ "csl-json": "citation.csl.json",
74
+ "text": "citation.txt",
75
+ }
76
+
77
+
78
+ @transpiler_plugin(
79
+ name="cwl2citation",
80
+ description="Export CFF, BibTeX, RIS, CSL-JSON, and styled software citations.",
81
+ options_model=CWL2CitationOptions,
82
+ )
83
+ def cwl2citation(context: TranspilerContext, options: CWL2CitationOptions) -> None:
84
+ try:
85
+ if context.process_id:
86
+ _ = (
87
+ context.resolved_process
88
+ ) # Validate the requested fragment; metadata is document-level.
89
+ if not options.format:
90
+ raise PluginFailureError("Select at least one citation format")
91
+ formats = list(dict.fromkeys(options.format))
92
+ for kind in formats:
93
+ target = options.output / FILENAMES[kind]
94
+ if target.exists() or target.is_symlink():
95
+ raise PluginFailureError(f"Output already exists: {target}")
96
+ record = from_metadata(
97
+ context.metadata,
98
+ doi=options.doi,
99
+ released=options.released,
100
+ url=options.url,
101
+ repository=options.code_repository,
102
+ )
103
+ renderers = {
104
+ "cff": lambda: exporters.cff(record),
105
+ "bibtex": lambda: exporters.bibtex(record),
106
+ "ris": lambda: exporters.ris(record),
107
+ "csl-json": lambda: (
108
+ json.dumps([exporters.csl(record)], ensure_ascii=False, indent=2) + "\n"
109
+ ),
110
+ "text": lambda: exporters.text(record, options.style, options.locale),
111
+ }
112
+ rendered = {FILENAMES[kind]: renderers[kind]() for kind in formats}
113
+ options.output.mkdir(parents=True, exist_ok=True)
114
+ written: list[Path] = []
115
+ try:
116
+ for name, content in rendered.items():
117
+ target = options.output / name
118
+ with target.open("x", encoding="utf-8") as stream:
119
+ written.append(target)
120
+ stream.write(content)
121
+ except Exception:
122
+ for target in written:
123
+ target.unlink()
124
+ raise
125
+ except PluginError:
126
+ raise
127
+ except Exception as exc:
128
+ raise PluginExecutionError(f"Unable to generate citations: {exc}") from exc
cwl2citation/py.typed ADDED
File without changes
@@ -0,0 +1,16 @@
1
+ # Third-party materials
2
+
3
+ Project code is Apache-2.0. The following schemas are bundled unchanged in `src/cwl2citation/schemas`:
4
+
5
+ | File | Upstream | License |
6
+ | --- | --- | --- |
7
+ | `cff-1.2.0.json` | [Citation File Format contributors, tag 1.2.0](https://github.com/citation-file-format/citation-file-format/tree/1.2.0) (`schema.json`) | CC BY 4.0; see `cff-LICENSE` |
8
+ | `csl-data.json` | [Citation Style Language contributors, tag v1.0.2](https://github.com/citation-style-language/schema/tree/v1.0.2) (`schemas/input/csl-data.json`) | MIT; see `csl-LICENSE` |
9
+
10
+ No endorsement by the upstream authors is implied. Schema licenses and source attribution are also included in the installed package. CSL styles are supplied by the separately installed `citeproc-py-styles` dependency; their upstream licenses apply.
11
+
12
+ ## SHA-256
13
+
14
+ `0b8d22140da702d766df318dcff3a91af2f39521298dcf36d76315fd99cc169b` cff-1.2.0.json
15
+
16
+ `257f86d4c3f19e15c7208657512ad4c9559a3b0d83b03360ed006c5f02d2977c` csl-data.json