ssslm 0.0.1__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.
ssslm/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """A simple standard for sharing literal mappings."""
2
+
3
+ from .model import (
4
+ LiteralMapping,
5
+ LiteralMappingTuple,
6
+ append_literal_mapping,
7
+ df_to_literal_mappings,
8
+ group_literal_mappings,
9
+ lint_literal_mappings,
10
+ literal_mappings_to_df,
11
+ read_literal_mappings,
12
+ remap_literal_mappings,
13
+ write_literal_mappings,
14
+ )
15
+ from .ner import Annotation, Annotator, Grounder, Match, Matcher, make_grounder
16
+
17
+ __all__ = [
18
+ "Annotation",
19
+ "Annotator",
20
+ "Grounder",
21
+ "LiteralMapping",
22
+ "LiteralMappingTuple",
23
+ "Match",
24
+ "Matcher",
25
+ "append_literal_mapping",
26
+ "df_to_literal_mappings",
27
+ "group_literal_mappings",
28
+ "lint_literal_mappings",
29
+ "literal_mappings_to_df",
30
+ "make_grounder",
31
+ "read_literal_mappings",
32
+ "remap_literal_mappings",
33
+ "write_literal_mappings",
34
+ ]
ssslm/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Entrypoint module, in case you use `python -m ssslm`."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
ssslm/cli.py ADDED
@@ -0,0 +1,16 @@
1
+ """Command line interface for :mod:`ssslm`."""
2
+
3
+ import click
4
+
5
+ __all__ = [
6
+ "main",
7
+ ]
8
+
9
+
10
+ @click.command()
11
+ def main() -> None:
12
+ """CLI for SSSLM."""
13
+
14
+
15
+ if __name__ == "__main__":
16
+ main()
ssslm/model.py ADDED
@@ -0,0 +1,522 @@
1
+ """A data model for synonyms."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import datetime
7
+ import importlib.util
8
+ import itertools as itt
9
+ from collections import defaultdict
10
+ from collections.abc import Iterable, Mapping
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING, Any, Literal, NamedTuple, TypeAlias
13
+
14
+ from curies import NamableReference, NamedReference, Reference
15
+ from curies import vocabulary as v
16
+ from pydantic import BaseModel, Field
17
+ from pydantic_extra_types.language_code import LanguageAlpha2
18
+ from tqdm import tqdm
19
+
20
+ if TYPE_CHECKING:
21
+ import gilda
22
+ import pandas
23
+
24
+ __all__ = [
25
+ "LiteralMapping",
26
+ "LiteralMappingTuple",
27
+ "append_literal_mapping",
28
+ "df_to_literal_mappings",
29
+ "group_literal_mappings",
30
+ "lint_literal_mappings",
31
+ "literal_mappings_to_df",
32
+ "read_literal_mappings",
33
+ "remap_literal_mappings",
34
+ "write_literal_mappings",
35
+ ]
36
+
37
+
38
+ class LiteralMappingTuple(NamedTuple):
39
+ """Represents rows in a spreadsheet."""
40
+
41
+ text: str
42
+ curie: str
43
+ name: str | None
44
+ predicate: str
45
+ type: str | None
46
+ provenance: str | None
47
+ contributor: str | None
48
+ date: str | None
49
+ language: str | None
50
+ comment: str | None
51
+ source: str | None
52
+ taxon: str | None
53
+
54
+
55
+ SynonymTuple = LiteralMappingTuple
56
+ NamableReferenceType: TypeAlias = type[NamableReference]
57
+
58
+ #: The header for the spreadsheet
59
+ HEADER = list(LiteralMappingTuple._fields)
60
+
61
+ #: A set of permissible predicates
62
+ PREDICATES = [v.has_label, *v.synonym_scopes.values()]
63
+
64
+ #: The default synonym type predicate was chosen based on the OBO
65
+ #: standard - when you don't specify a scope, this is what it infers
66
+ DEFAULT_PREDICATE = v.has_related_synonym
67
+
68
+
69
+ class LiteralMapping(BaseModel):
70
+ """A data model for literal mappings."""
71
+
72
+ # the first four fields are the core of the literal mapping
73
+ reference: NamableReference = Field(..., description="The subject of the literal mapping")
74
+ predicate: Reference = Field(
75
+ default=DEFAULT_PREDICATE,
76
+ description="The predicate that connects the term (as subject) "
77
+ "to the textual synonym (as object)",
78
+ examples=PREDICATES,
79
+ )
80
+ text: str = Field(..., description="The object of the literal mapping")
81
+ language: LanguageAlpha2 | None = Field(
82
+ None,
83
+ description="The language of the synonym. If not given, typically "
84
+ "assumed to be american english.",
85
+ )
86
+
87
+ type: Reference | None = Field(
88
+ default=None,
89
+ title="Synonym type",
90
+ description="A qualification for the type of mapping",
91
+ examples=list(v.synonym_types),
92
+ )
93
+ provenance: list[Reference] = Field(
94
+ default_factory=list,
95
+ description="A list of articles (e.g., from PubMed, PMC, arXiv) where this synonym appears",
96
+ )
97
+ contributor: Reference | None = Field(
98
+ None,
99
+ description="The contributor, usually given as a reference to ORCID",
100
+ examples=[v.charlie],
101
+ )
102
+ comment: str | None = Field(
103
+ None, description="An optional comment on the synonym curation or status"
104
+ )
105
+ source: str | None = Field(
106
+ None, description="The name of the resource where the synonym was curated"
107
+ )
108
+ date: datetime.date | None = Field(None, description="The date of initial curation")
109
+ taxon: Reference | None = Field(
110
+ None,
111
+ description="If taxon-specific, annotate it here. "
112
+ "Only use `NCBITaxon` or `ncbitaxon` as the prefix.",
113
+ )
114
+
115
+ def __lt__(self, other: LiteralMapping) -> bool:
116
+ return _lm_sort_key(self) < _lm_sort_key(other)
117
+
118
+ def get_all_references(self) -> set[Reference]:
119
+ """Get all references made by this object."""
120
+ rv: set[Reference] = {self.reference, self.predicate, *self.provenance}
121
+ if self.type:
122
+ rv.add(self.type)
123
+ if self.contributor:
124
+ rv.add(self.contributor)
125
+ return rv
126
+
127
+ @property
128
+ def name(self) -> str | None:
129
+ """Get the reference's (optional) name."""
130
+ return self.reference.name
131
+
132
+ @property
133
+ def curie(self) -> str:
134
+ """Get the reference's CURIE."""
135
+ return self.reference.curie
136
+
137
+ @property
138
+ def date_str(self) -> str:
139
+ """Get the date as a string."""
140
+ if self.date is None:
141
+ raise ValueError("date is not set")
142
+ return self.date.strftime("%Y-%m-%d")
143
+
144
+ @classmethod
145
+ def from_row(
146
+ cls,
147
+ row: dict[str, Any],
148
+ *,
149
+ names: Mapping[Reference, str] | None = None,
150
+ reference_cls: NamableReferenceType = NamableReference,
151
+ ) -> LiteralMapping:
152
+ """Parse a dictionary representing a row in a TSV."""
153
+ reference = reference_cls.from_curie(row["curie"])
154
+ name = (names or {}).get(reference) or row.get("name")
155
+ data = {
156
+ "text": row["text"],
157
+ "reference": reference_cls(
158
+ prefix=reference.prefix, identifier=reference.identifier, name=name
159
+ ),
160
+ "predicate": (
161
+ reference_cls.from_curie(predicate_curie.strip())
162
+ if (predicate_curie := row.get("predicate"))
163
+ else DEFAULT_PREDICATE
164
+ ),
165
+ "provenance": [
166
+ reference_cls.from_curie(provenance_curie.strip())
167
+ for provenance_curie in (row.get("provenance") or "").split(",")
168
+ if provenance_curie.strip()
169
+ ],
170
+ # get("X") or None protects against empty strings
171
+ "type": row.get("type") or None,
172
+ "language": row.get("language") or None,
173
+ "comment": row.get("comment") or None,
174
+ "source": row.get("source") or None,
175
+ "date": row.get("date") or None,
176
+ }
177
+ if contributor_curie := (row.get("contributor") or "").strip():
178
+ data["contributor"] = reference_cls.from_curie(contributor_curie)
179
+
180
+ return cls.model_validate(data)
181
+
182
+ def _as_row(self) -> LiteralMappingTuple:
183
+ """Get the synonym as a row for writing."""
184
+ return LiteralMappingTuple(
185
+ text=self.text,
186
+ curie=self.curie,
187
+ name=self.name,
188
+ predicate=self.predicate.curie,
189
+ type=self.type.curie if self.type else None,
190
+ provenance=",".join(p.curie for p in self.provenance) if self.provenance else None,
191
+ contributor=self.contributor.curie if self.contributor is not None else None,
192
+ date=self.date_str if self.date is not None else None,
193
+ language=self.language or None,
194
+ comment=self.comment or None,
195
+ source=self.source or None,
196
+ taxon=self.taxon.curie if self.taxon else None,
197
+ )
198
+
199
+ @staticmethod
200
+ def _predicate_type_from_gilda(status: GildaStatus) -> tuple[Reference, Reference | None]:
201
+ if status == "name":
202
+ return v.has_label, None
203
+ elif status == "former_name":
204
+ return DEFAULT_PREDICATE, v.previous_name
205
+ elif status == "synonym":
206
+ return DEFAULT_PREDICATE, None
207
+ elif status == "curated":
208
+ # assume higher confidence in exact synonym
209
+ return v.has_exact_synonym, None
210
+ raise ValueError(f"unhandled gilda status: {status}")
211
+
212
+ @classmethod
213
+ def from_gilda(cls, term: gilda.Term) -> LiteralMapping:
214
+ """Construct a synonym from a :mod:`gilda` term.
215
+
216
+ :param term: A Gilda term
217
+
218
+ :returns: A synonym object
219
+
220
+ .. warning::
221
+
222
+ Gilda's data model is less detailed, so resulting synonym objects will not
223
+ have detailed curation provenance
224
+
225
+ """
226
+ predicate, synonym_type = cls._predicate_type_from_gilda(term.status)
227
+ data = {
228
+ "reference": NamedReference(prefix=term.db, identifier=term.id, name=term.entry_name),
229
+ "predicate": predicate,
230
+ "text": term.text,
231
+ "type": synonym_type,
232
+ "source": term.source,
233
+ }
234
+ if term.organism:
235
+ data["taxon"] = Reference(prefix="NCBITaxon", identifier=term.organism)
236
+ return cls.model_validate(data)
237
+
238
+ def _get_gilda_status(self) -> GildaStatus:
239
+ """Get the Gilda status for a synonym."""
240
+ if self.predicate and self.predicate.pair == v.has_label.pair:
241
+ return "name"
242
+ if self.type and self.type.pair == v.previous_name.pair:
243
+ return "former_name"
244
+ return "synonym"
245
+
246
+ def to_gilda(self) -> gilda.Term:
247
+ """Get this synonym as a :mod:`gilda` term.
248
+
249
+ :returns: An object that can be indexed by Gilda for NER and grounding
250
+
251
+ """
252
+ if not self.name:
253
+ raise ValueError("can't make a Gilda term without a label")
254
+ if self.taxon and self.taxon.prefix.lower() != "ncbitaxon":
255
+ raise ValueError("NCBITaxon reference is required to convert to gilda.")
256
+ return _gilda_term(
257
+ text=self.text,
258
+ reference=self.reference,
259
+ status=self._get_gilda_status(),
260
+ source=self.source,
261
+ ncbitaxon_id=self.taxon.identifier if self.taxon else None,
262
+ )
263
+
264
+
265
+ #: See https://github.com/gyorilab/gilda/blob/ea328734f26c91189438e6d3408562f990f38644/gilda/term.py#L167C1-L167C69
266
+ GildaStatus: TypeAlias = Literal["name", "synonym", "curated", "former_name"]
267
+
268
+
269
+ def _gilda_term(
270
+ *,
271
+ text: str,
272
+ reference: NamableReference,
273
+ status: GildaStatus,
274
+ source: str | None,
275
+ ncbitaxon_id: str | None = None,
276
+ ) -> gilda.Term:
277
+ import gilda
278
+ from gilda.process import normalize
279
+
280
+ return gilda.Term(
281
+ normalize(text),
282
+ text=text,
283
+ db=reference.prefix,
284
+ id=reference.identifier,
285
+ entry_name=reference.name or text,
286
+ status=status,
287
+ source=source,
288
+ organism=ncbitaxon_id,
289
+ )
290
+
291
+
292
+ def literal_mappings_to_df(literal_mappings: Iterable[LiteralMapping]) -> pandas.DataFrame:
293
+ """Get a pandas dataframe from the literal mappings."""
294
+ import pandas as pd
295
+
296
+ df = pd.DataFrame(
297
+ (literal_mapping._as_row() for literal_mapping in literal_mappings), columns=HEADER
298
+ )
299
+
300
+ # remove any columns that are fully blank
301
+ for col in df.columns:
302
+ if df[col].isna().all():
303
+ del df[col]
304
+
305
+ return df
306
+
307
+
308
+ def df_to_literal_mappings(
309
+ df: pandas.DataFrame,
310
+ *,
311
+ names: Mapping[Reference, str] | None = None,
312
+ ) -> list[LiteralMapping]:
313
+ """Get mapping objects from a dataframe."""
314
+ return _from_dicts((row for _, row in df.iterrows()), names=names)
315
+
316
+
317
+ Writer = Literal["pandas", "csv"]
318
+
319
+
320
+ def _resolve_writer(writer: Writer | None = None) -> Writer:
321
+ if writer is None:
322
+ writer = "pandas"
323
+ if writer == "pandas" and not importlib.util.find_spec("pandas"):
324
+ writer = "csv"
325
+ return writer
326
+
327
+
328
+ def write_literal_mappings(
329
+ literal_mappings: Iterable[LiteralMapping],
330
+ path: str | Path,
331
+ *,
332
+ writer: Literal["pandas", "csv"] | None = None,
333
+ ) -> None:
334
+ """Write literal mappings to a path."""
335
+ path = Path(path).expanduser().resolve()
336
+ writer = _resolve_writer(writer)
337
+ if writer == "pandas":
338
+ _write_pandas(literal_mappings=literal_mappings, path=path)
339
+ elif writer == "csv":
340
+ _write_builtin(literal_mappings=literal_mappings, path=path)
341
+ else:
342
+ raise ValueError(f"invalid writer: {writer}. Choose one of {Writer}")
343
+
344
+
345
+ def _write_builtin(*, path: Path, literal_mappings: Iterable[LiteralMapping]) -> None:
346
+ with path.open("w") as file:
347
+ writer = csv.writer(file, delimiter="\t")
348
+ writer.writerow(HEADER)
349
+ writer.writerows(literal_mapping._as_row() for literal_mapping in literal_mappings)
350
+
351
+
352
+ def _write_pandas(*, path: Path, literal_mappings: Iterable[LiteralMapping]) -> None:
353
+ df = literal_mappings_to_df(literal_mappings)
354
+ df.to_csv(path, index=False, sep="\t")
355
+
356
+
357
+ def append_literal_mapping(path: str | Path, literal_mapping: LiteralMapping) -> None:
358
+ """Append a literal mapping to an existing file."""
359
+ raise NotImplementedError
360
+
361
+
362
+ def read_literal_mappings(
363
+ path: str | Path,
364
+ *,
365
+ delimiter: str | None = None,
366
+ names: Mapping[Reference, str] | None = None,
367
+ reference_cls: NamableReferenceType = NamableReference,
368
+ ) -> list[LiteralMapping]:
369
+ """Load literal mappings from a file.
370
+
371
+ :param path: A local file path or URL for a biosynonyms-flavored CSV/TSV file
372
+ :param delimiter: The delimiter for the CSV/TSV file. Defaults to tab
373
+ :param names: A pre-parsed dictionary from references (i.e., prefix-luid pairs) to
374
+ default labels
375
+ :param reference_cls: The class used to parse references. E.g., swap out for
376
+ :class:`pyobo.Reference` to automatically do Bioregistry validation on
377
+ references.
378
+
379
+ :returns: A list of literal mappings parsed from the table
380
+
381
+ """
382
+ if isinstance(path, str) and any(path.startswith(schema) for schema in ("https://", "http://")):
383
+ import requests
384
+
385
+ res = requests.get(path, timeout=15)
386
+ res.raise_for_status()
387
+ return _from_lines(
388
+ res.iter_lines(decode_unicode=True),
389
+ delimiter=delimiter,
390
+ names=names,
391
+ reference_cls=reference_cls,
392
+ )
393
+
394
+ path = Path(path).expanduser().resolve()
395
+
396
+ if path.suffix == ".numbers":
397
+ return _parse_numbers(path, names=names)
398
+
399
+ with path.open() as file:
400
+ return _from_lines(file, delimiter=delimiter, names=names, reference_cls=reference_cls)
401
+
402
+
403
+ def _parse_numbers(
404
+ path: str | Path,
405
+ *,
406
+ names: Mapping[Reference, str] | None = None,
407
+ reference_cls: NamableReferenceType = NamableReference,
408
+ ) -> list[LiteralMapping]:
409
+ # code example from https://pypi.org/project/numbers-parser
410
+ import numbers_parser
411
+
412
+ doc = numbers_parser.Document(path)
413
+ sheets = doc.sheets
414
+ tables = sheets[0].tables
415
+ header, *rows = tables[0].rows(values_only=True)
416
+ return _from_dicts(
417
+ (dict(zip(header, row, strict=False)) for row in rows),
418
+ names=names,
419
+ reference_cls=reference_cls,
420
+ )
421
+
422
+
423
+ def _from_lines(
424
+ lines: Iterable[str],
425
+ *,
426
+ delimiter: str | None = None,
427
+ names: Mapping[Reference, str] | None = None,
428
+ reference_cls: NamableReferenceType = NamableReference,
429
+ ) -> list[LiteralMapping]:
430
+ return _from_dicts(
431
+ csv.DictReader(lines, delimiter=delimiter or "\t"),
432
+ names=names,
433
+ reference_cls=reference_cls,
434
+ )
435
+
436
+
437
+ def _from_dicts(
438
+ dicts: Iterable[dict[str, Any]],
439
+ *,
440
+ names: Mapping[Reference, str] | None = None,
441
+ reference_cls: NamableReferenceType = NamableReference,
442
+ ) -> list[LiteralMapping]:
443
+ rv = []
444
+ for i, record in enumerate(dicts, start=2):
445
+ record = {k: v for k, v in record.items() if k and v and k.strip() and v.strip()}
446
+ if record:
447
+ try:
448
+ literal_mapping = LiteralMapping.from_row(
449
+ record, names=names, reference_cls=reference_cls
450
+ )
451
+ except ValueError as e:
452
+ raise ValueError(f"failed on row {i}: {record}") from e
453
+ rv.append(literal_mapping)
454
+ return rv
455
+
456
+
457
+ def group_literal_mappings(
458
+ literal_mappings: Iterable[LiteralMapping],
459
+ ) -> dict[NamableReference, list[LiteralMapping]]:
460
+ """Aggregate literal mappings by reference."""
461
+ dd: defaultdict[NamableReference, list[LiteralMapping]] = defaultdict(list)
462
+ for literal_mapping in tqdm(
463
+ literal_mappings, unit="literal mapping", unit_scale=True, leave=False
464
+ ):
465
+ dd[literal_mapping.reference].append(literal_mapping)
466
+ return dict(dd)
467
+
468
+
469
+ def lint_literal_mappings(path: Path, *, delimiter: str | None = None) -> None:
470
+ """Lint a literal mappings file."""
471
+ literal_mappings = read_literal_mappings(path, delimiter=delimiter)
472
+ literal_mappings = sorted(literal_mappings)
473
+ write_literal_mappings(literal_mappings, path)
474
+
475
+
476
+ def _lm_sort_key(lm: LiteralMapping) -> tuple[str, str, str, str]:
477
+ return lm.text.casefold(), lm.text, lm.reference.curie.casefold(), lm.reference.curie
478
+
479
+
480
+ def remap_literal_mappings(
481
+ literal_mappings: list[LiteralMapping],
482
+ mappings: list[tuple[Reference, Reference]],
483
+ *,
484
+ progress: bool = False,
485
+ ) -> list[LiteralMapping]:
486
+ """Use a priority mapping to re-write terms with priority groundings.
487
+
488
+ :param literal_mappings: A list of literal mappings
489
+ :param mappings: A list of pairs that constitute mappings, e.g. from SeMRA
490
+ :param progress: Should a progress bar be shown?
491
+
492
+ :returns: A new list of literal mapping objects that have been remapped
493
+
494
+ """
495
+ index = group_literal_mappings(literal_mappings)
496
+
497
+ for source, target in tqdm(
498
+ mappings, unit="mapping", unit_scale=True, desc="applying mappings", disable=not progress
499
+ ):
500
+ source_literal_mappings: list[LiteralMapping] | None = index.pop(source, None)
501
+ if source_literal_mappings:
502
+ index.setdefault(target, []).extend(
503
+ _make_new_lm(literal_mapping, target) for literal_mapping in source_literal_mappings
504
+ )
505
+
506
+ # Unwind the terms index
507
+ new_terms = list(itt.chain.from_iterable(index.values()))
508
+ # TODO filter out duplicates?
509
+ return new_terms
510
+
511
+
512
+ def _make_new_lm(
513
+ term: LiteralMapping,
514
+ ref: Reference,
515
+ ) -> LiteralMapping:
516
+ """Make a new literal term object by replacing the database, identifier, and name."""
517
+ new_ref = NamableReference(
518
+ prefix=ref.prefix,
519
+ identifier=ref.identifier,
520
+ name=getattr(ref, "name", None),
521
+ )
522
+ return term.model_copy(update={"reference": new_ref})
ssslm/ner.py ADDED
@@ -0,0 +1,218 @@
1
+ """NER utilities build on literal mappings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from collections.abc import Iterable
7
+ from typing import TYPE_CHECKING, Any, Literal, TypeAlias
8
+
9
+ from curies import NamableReference, NamedReference
10
+ from pydantic import BaseModel
11
+
12
+ from .model import LiteralMapping
13
+
14
+ if TYPE_CHECKING:
15
+ import gilda
16
+
17
+ __all__ = [
18
+ "Annotation",
19
+ "Annotator",
20
+ "GildaGrounder",
21
+ "Grounder",
22
+ "Match",
23
+ "Matcher",
24
+ "make_grounder",
25
+ ]
26
+
27
+ Implementation: TypeAlias = Literal["gilda"]
28
+
29
+
30
+ def make_grounder(
31
+ literal_mappings: Iterable[LiteralMapping],
32
+ *,
33
+ implementation: Implementation | None = None,
34
+ **kwargs: Any,
35
+ ) -> Grounder:
36
+ """Get a Gilda grounder from literal mappings."""
37
+ if implementation is None or implementation == "gilda":
38
+ return GildaGrounder(literal_mappings, **kwargs)
39
+ raise ValueError(f"Unsupported implementation: {implementation}")
40
+
41
+
42
+ class Match(BaseModel):
43
+ """A match from NER."""
44
+
45
+ reference: NamableReference
46
+ score: float
47
+
48
+ @property
49
+ def prefix(self) -> str:
50
+ """Get the scored match's term's prefix."""
51
+ return self.reference.prefix
52
+
53
+ @property
54
+ def identifier(self) -> str:
55
+ """Get the scored match's term's identifier."""
56
+ return self.reference.identifier
57
+
58
+ @property
59
+ def curie(self) -> str:
60
+ """Get the scored match's CURIE."""
61
+ return self.reference.curie
62
+
63
+ @property
64
+ def name(self) -> str | None:
65
+ """Get the scored match's term's name."""
66
+ return self.reference.name
67
+
68
+
69
+ class Annotation(BaseModel):
70
+ """Data about an annotation."""
71
+
72
+ text: str
73
+ start: int
74
+ end: int
75
+ match: Match
76
+
77
+ @property
78
+ def reference(self) -> NamableReference:
79
+ """Get the scored match's reference."""
80
+ return self.match.reference
81
+
82
+ @property
83
+ def prefix(self) -> str:
84
+ """Get the scored match's term's prefix."""
85
+ return self.reference.prefix
86
+
87
+ @property
88
+ def identifier(self) -> str:
89
+ """Get the scored match's term's identifier."""
90
+ return self.reference.identifier
91
+
92
+ @property
93
+ def curie(self) -> str:
94
+ """Get the scored match's CURIE."""
95
+ return self.reference.curie
96
+
97
+ @property
98
+ def name(self) -> str | None:
99
+ """Get the scored match's term's name."""
100
+ return self.reference.name
101
+
102
+ @property
103
+ def score(self) -> float:
104
+ """Get the match's score."""
105
+ return self.match.score
106
+
107
+ @property
108
+ def substr(self) -> str:
109
+ """Get the substring that was matched."""
110
+ return self.text[self.start : self.end]
111
+
112
+
113
+ class Matcher(ABC):
114
+ """An interface for a grounder."""
115
+
116
+ @abstractmethod
117
+ def get_matches(self, text: str, **kwargs: Any) -> list[Match]:
118
+ """Get matches in the SSSLM format."""
119
+
120
+ def get_best_match(self, text: str, **kwargs: Any) -> Match | None:
121
+ """Get matches in the SSSLM format."""
122
+ matches = self.get_matches(text, **kwargs)
123
+ return matches[0] if matches else None
124
+
125
+
126
+ class Annotator(ABC):
127
+ """An interface for something that can annotate."""
128
+
129
+ @abstractmethod
130
+ def annotate(self, text: str, **kwargs: Any) -> list[Annotation]:
131
+ """Annotate the text."""
132
+
133
+
134
+ class Grounder(Matcher, Annotator, ABC):
135
+ """A combine matcher and annotator."""
136
+
137
+
138
+ def _ensure_nltk() -> None:
139
+ """Ensure NLTK data is downloaded properly."""
140
+ import nltk.data
141
+ import pystow
142
+
143
+ directory = pystow.join("nltk")
144
+ nltk.download("stopwords", download_dir=directory)
145
+ nltk.data.path.append(directory)
146
+
147
+
148
+ class GildaGrounder(Grounder):
149
+ """A grounder and annotator that uses gilda as a backend."""
150
+
151
+ def __init__(
152
+ self,
153
+ literal_mappings: Iterable[LiteralMapping],
154
+ *,
155
+ prefix_priority: list[str] | None = None,
156
+ grounder_cls: type[gilda.Grounder] | None = None,
157
+ ) -> None:
158
+ """Initialize a grounder wrapping a :class:`gilda.Grounder`.
159
+
160
+ :param literal_mappings: The literal mappings to populate the grounder
161
+ :param prefix_priority: The priority list of prefixes to break ties. Maps to
162
+ ``namespace_priority`` in :meth:`gilda.Grounder.__init__`
163
+ :param grounder_cls: A custom subclass of :class:`gilda.Grounder`, if given.
164
+
165
+ """
166
+ _ensure_nltk() # very important - do this before importing gilda.ner
167
+
168
+ import gilda.ner
169
+
170
+ if grounder_cls is None:
171
+ import gilda
172
+
173
+ grounder_cls = gilda.Grounder
174
+
175
+ self._grounder = grounder_cls(
176
+ [m.to_gilda() for m in literal_mappings], namespace_priority=prefix_priority
177
+ )
178
+ self._annotate = gilda.ner.annotate
179
+
180
+ @staticmethod
181
+ def _convert_gilda_match(scored_match: gilda.ScoredMatch) -> Match:
182
+ """Wrap a Gilda scored match."""
183
+ return Match(
184
+ reference=NamedReference(
185
+ prefix=scored_match.term.db,
186
+ identifier=scored_match.term.id,
187
+ name=scored_match.term.entry_name,
188
+ ),
189
+ score=scored_match.score,
190
+ )
191
+
192
+ def get_matches( # type:ignore[override]
193
+ self,
194
+ text: str,
195
+ context: str | None = None,
196
+ organisms: list[str] | None = None,
197
+ namespaces: list[str] | None = None,
198
+ ) -> list[Match]:
199
+ """Get matches in the SSSLM format using :meth:`gilda.Grounder.ground`."""
200
+ return [
201
+ self._convert_gilda_match(scored_match)
202
+ for scored_match in self._grounder.ground(
203
+ text, context=context, organisms=organisms, namespaces=namespaces
204
+ )
205
+ ]
206
+
207
+ def annotate(self, text: str, **kwargs: Any) -> list[Annotation]:
208
+ """Annotate the text."""
209
+ return [
210
+ Annotation(
211
+ text=text,
212
+ match=self._convert_gilda_match(match),
213
+ start=annotation.start,
214
+ end=annotation.end,
215
+ )
216
+ for annotation in self._annotate(text, grounder=self._grounder, **kwargs)
217
+ for match in annotation.matches
218
+ ]
ssslm/py.typed ADDED
@@ -0,0 +1 @@
1
+
ssslm/version.py ADDED
@@ -0,0 +1,40 @@
1
+ """Version information for :mod:`ssslm`.
2
+
3
+ Run with ``python -m ssslm.version``
4
+
5
+ """
6
+
7
+ import os
8
+ from subprocess import CalledProcessError, check_output
9
+
10
+ __all__ = [
11
+ "VERSION",
12
+ "get_git_hash",
13
+ "get_version",
14
+ ]
15
+
16
+ VERSION = "0.0.1"
17
+
18
+
19
+ def get_git_hash() -> str:
20
+ """Get the :mod:`ssslm` git hash."""
21
+ with open(os.devnull, "w") as devnull:
22
+ try:
23
+ ret = check_output(
24
+ ["git", "rev-parse", "HEAD"],
25
+ cwd=os.path.dirname(__file__),
26
+ stderr=devnull,
27
+ )
28
+ except CalledProcessError:
29
+ return "UNHASHED"
30
+ else:
31
+ return ret.strip().decode("utf-8")[:8]
32
+
33
+
34
+ def get_version(with_git_hash: bool = False) -> str:
35
+ """Get the :mod:`ssslm` version string, including a git hash."""
36
+ return f"{VERSION}-{get_git_hash()}" if with_git_hash else VERSION
37
+
38
+
39
+ if __name__ == "__main__":
40
+ print(get_version(with_git_hash=True)) # noqa:T201
@@ -0,0 +1,440 @@
1
+ Metadata-Version: 2.4
2
+ Name: ssslm
3
+ Version: 0.0.1
4
+ Summary: A simple standard for sharing literal mappings
5
+ Keywords: snekpack,cookiecutter
6
+ Author: Charles Tapley Hoyt
7
+ Author-email: Charles Tapley Hoyt <cthoyt@gmail.com>
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 1 - Planning
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Framework :: Pytest
15
+ Classifier: Framework :: tox
16
+ Classifier: Framework :: Sphinx
17
+ Classifier: Natural Language :: English
18
+ Classifier: Programming Language :: Python
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3 :: Only
24
+ Classifier: Typing :: Typed
25
+ Requires-Dist: curies
26
+ Requires-Dist: pydantic
27
+ Requires-Dist: pydantic-extra-types[pycountry]
28
+ Requires-Dist: tqdm
29
+ Requires-Dist: click
30
+ Requires-Dist: sphinx>=8 ; extra == 'docs'
31
+ Requires-Dist: sphinx-rtd-theme>=3.0 ; extra == 'docs'
32
+ Requires-Dist: sphinx-click ; extra == 'docs'
33
+ Requires-Dist: sphinx-automodapi ; extra == 'docs'
34
+ Requires-Dist: gilda ; extra == 'gilda'
35
+ Requires-Dist: nltk ; extra == 'gilda'
36
+ Requires-Dist: pystow ; extra == 'gilda'
37
+ Requires-Dist: gilda-slim ; extra == 'gilda-slim'
38
+ Requires-Dist: nltk ; extra == 'gilda-slim'
39
+ Requires-Dist: pystow ; extra == 'gilda-slim'
40
+ Requires-Dist: pytest ; extra == 'tests'
41
+ Requires-Dist: coverage[toml] ; extra == 'tests'
42
+ Requires-Dist: responses ; extra == 'tests'
43
+ Requires-Dist: pandas ; extra == 'tests'
44
+ Maintainer: Charles Tapley Hoyt
45
+ Maintainer-email: Charles Tapley Hoyt <cthoyt@gmail.com>
46
+ Requires-Python: >=3.10
47
+ Project-URL: Bug Tracker, https://github.com/cthoyt/ssslm/issues
48
+ Project-URL: Documentation, https://ssslm.readthedocs.io
49
+ Project-URL: Funding, https://github.com/sponsors/cthoyt
50
+ Project-URL: Homepage, https://github.com/cthoyt/ssslm
51
+ Project-URL: Repository, https://github.com/cthoyt/ssslm.git
52
+ Provides-Extra: docs
53
+ Provides-Extra: gilda
54
+ Provides-Extra: gilda-slim
55
+ Provides-Extra: tests
56
+ Description-Content-Type: text/markdown
57
+
58
+ <!--
59
+ <p align="center">
60
+ <img src="https://github.com/cthoyt/ssslm/raw/main/docs/source/logo.png" height="150">
61
+ </p>
62
+ -->
63
+
64
+ <h1 align="center">
65
+ Simple Standard for Sharing Literal Mappings
66
+ </h1>
67
+
68
+ <p align="center">
69
+ <a href="https://github.com/cthoyt/ssslm/actions/workflows/tests.yml">
70
+ <img alt="Tests" src="https://github.com/cthoyt/ssslm/actions/workflows/tests.yml/badge.svg" /></a>
71
+ <a href="https://pypi.org/project/ssslm">
72
+ <img alt="PyPI" src="https://img.shields.io/pypi/v/ssslm" /></a>
73
+ <a href="https://pypi.org/project/ssslm">
74
+ <img alt="PyPI - Python Version" src="https://img.shields.io/pypi/pyversions/ssslm" /></a>
75
+ <a href="https://github.com/cthoyt/ssslm/blob/main/LICENSE">
76
+ <img alt="PyPI - License" src="https://img.shields.io/pypi/l/ssslm" /></a>
77
+ <a href='https://ssslm.readthedocs.io/en/latest/?badge=latest'>
78
+ <img src='https://readthedocs.org/projects/ssslm/badge/?version=latest' alt='Documentation Status' /></a>
79
+ <a href="https://codecov.io/gh/cthoyt/ssslm/branch/main">
80
+ <img src="https://codecov.io/gh/cthoyt/ssslm/branch/main/graph/badge.svg" alt="Codecov status" /></a>
81
+ <a href="https://github.com/cthoyt/cookiecutter-python-package">
82
+ <img alt="Cookiecutter template from @cthoyt" src="https://img.shields.io/badge/Cookiecutter-snekpack-blue" /></a>
83
+ <a href="https://github.com/astral-sh/ruff">
84
+ <img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json" alt="Ruff" style="max-width:100%;"></a>
85
+ <a href="https://github.com/cthoyt/ssslm/blob/main/.github/CODE_OF_CONDUCT.md">
86
+ <img src="https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg" alt="Contributor Covenant"/></a>
87
+ <!-- uncomment if you archive on zenodo
88
+ <a href="https://zenodo.org/badge/latestdoi/XXXXXX">
89
+ <img src="https://zenodo.org/badge/XXXXXX.svg" alt="DOI"></a>
90
+ -->
91
+ </p>
92
+
93
+ A simple standard for sharing literal mappings (SSSLM).
94
+
95
+ This repository implements a data model for literal mappings that supports
96
+ encoding labels, synonyms, synonym types, internationalization, and other
97
+ important information for curation, construction of lexica, and population of
98
+ NER/NEN tools.
99
+
100
+ ## 💪 Getting Started
101
+
102
+ ```python
103
+ import ssslm
104
+ from ssslm import LiteralMapping
105
+ from curies import NamedReference
106
+
107
+ # Construct a mapping using Pydantic objects
108
+ m1 = LiteralMapping(
109
+ reference=NamedReference(prefix="NCBITaxon", identifier="9606", name="Homo sapiens"),
110
+ text="human",
111
+ )
112
+
113
+ # get a pandas dataframe
114
+ df = ssslm.literal_mappings_to_df([m1])
115
+
116
+ # Write mappings to TSV
117
+ ssslm.write_literal_mappings([m1], "literal_mappings.tsv")
118
+
119
+ # Read mappings from TSV
120
+ mappings = ssslm.read_literal_mappings("literal_mappings.tsv")
121
+ ```
122
+
123
+ Note that references are standardized using the
124
+ [`curies`](https://github.com/biopragmatics/curies) package. It's up to you to
125
+ use a meaningful set of prefixes, so consider adopting
126
+ [the Bioregistry](https://github.com/biopragmatics/bioregistry) as a standard.
127
+
128
+ ## Data Model
129
+
130
+ The SSSLM data model is defined using Pydantic, and corresponds to the following
131
+ columns in a TSV file:
132
+
133
+ 1. `text` the label/synonym text itself
134
+ 2. `curie` the compact uniform resource identifier (CURIE) for a biomedical
135
+ entity or concept
136
+ 3. `name` the standard name for the concept
137
+ 4. `predicate` the predicate which encodes the synonym scope, written as a CURIE
138
+ from the [OBO in OWL (`oboInOWL`)](https://bioregistry.io/oio) or RDFS
139
+ controlled vocabularies, e.g., one of:
140
+ - `rdfs:label`
141
+ - `oboInOwl:hasExactSynonym`
142
+ - `oboInOwl:hasNarrowSynonym` (i.e., the synonym represents a narrower term)
143
+ - `oboInOwl:hasBroadSynonym` (i.e., the synonym represents a broader term)
144
+ - `oboInOwl:hasRelatedSynonym` (use this if the scope is unknown)
145
+ 5. `type` the (optional) synonym property type, written as a CURIE from the
146
+ [OBO Metadata Ontology (`omo`)](https://bioregistry.io/omo) controlled
147
+ vocabulary, e.g., one of:
148
+ - `OMO:0003000` (abbreviation)
149
+ - `OMO:0003001` (ambiguous synonym)
150
+ - `OMO:0003002` (dubious synonym)
151
+ - `OMO:0003003` (layperson synonym)
152
+ - `OMO:0003004` (plural form)
153
+ - ...
154
+ 6. `provenance` a comma-delimited list of CURIEs corresponding to publications
155
+ that use the given synonym (ideally using highly actionable identifiers from
156
+ semantic spaces like [`pubmed`](https://bioregistry.io/pubmed),
157
+ [`pmc`](https://bioregistry.io/pmc), [`doi`](https://bioregistry.io/doi))
158
+ 7. `contributor` a CURIE with the ORCID identifier of the contributor
159
+ 8. `date` the optional date when the row was curated in YYYY-MM-DD format
160
+ 9. `language` the (optional) ISO 2-letter language code. If missing, assumed to
161
+ be American English.
162
+ 10. `comment` an optional comment
163
+ 11. `source` the source of the synonyms, usually `biosynonyms` unless imported
164
+ from elsewhere
165
+ 12. `taxon` the optional NCBITaxon CURIE, if the term is taxon-specific, like
166
+ `NCBITaxon:9606` for humans
167
+
168
+ Here's an example of some rows in the synonyms table (with linkified CURIEs):
169
+
170
+ | text | curie | predicate | provenance | contributor | language |
171
+ | --------------- | --------------------------------------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -------- |
172
+ | alsterpaullone | [CHEBI:138488](https://bioregistry.io/CHEBI:138488) | [rdfs:label](https://bioregistry.io/rdfs:label) | [pubmed:30655881](https://bioregistry.io/pubmed:30655881) | [orcid:0000-0003-4423-4370](https://bioregistry.io/orcid:0000-0003-4423-4370) | en |
173
+ | 9-nitropaullone | [CHEBI:138488](https://bioregistry.io/CHEBI:138488) | [oboInOwl:hasExactSynonym](https://bioregistry.io/oboInOwl:hasExactSynonym) | [pubmed:11597333](https://bioregistry.io/pubmed:11597333), [pubmed:10911915](https://bioregistry.io/pubmed:10911915) | [orcid:0000-0003-4423-4370](https://bioregistry.io/orcid:0000-0003-4423-4370) | en |
174
+
175
+ **Limitations**
176
+
177
+ - It's hard to know which exact matches between different vocabularies could be
178
+ used to deduplicate synonyms. Right now, this isn't covered but some partial
179
+ solutions already exist that could be adopted.
180
+ - This doesn't keep track of NER annotations, such as when you want to keep
181
+ track of the start and end position in a full sentence or paragraph
182
+ - This doesn't keep track of transformations done to make mappings. It's more
183
+ oriented towards curation.
184
+
185
+ ## 🚀 Installation
186
+
187
+ <!-- Uncomment this section after your first ``tox -e finish``
188
+ The most recent release can be installed from
189
+ [PyPI](https://pypi.org/project/ssslm/) with uv:
190
+
191
+ ```console
192
+ $ uv pip install ssslm
193
+ ```
194
+
195
+ or with pip:
196
+
197
+ ```console
198
+ $ python3 -m pip install ssslm
199
+ ```
200
+ -->
201
+
202
+ The most recent code and data can be installed directly from GitHub with uv:
203
+
204
+ ```console
205
+ $ uv --preview pip install git+https://github.com/cthoyt/ssslm.git
206
+ ```
207
+
208
+ or with pip:
209
+
210
+ ```console
211
+ $ UV_PREVIEW=1 python3 -m pip install git+https://github.com/cthoyt/ssslm.git
212
+ ```
213
+
214
+ Note that this requires setting `UV_PREVIEW` mode enabled until the uv build
215
+ backend becomes a stable feature.
216
+
217
+ ## 👐 Contributing
218
+
219
+ Contributions, whether filing an issue, making a pull request, or forking, are
220
+ appreciated. See
221
+ [CONTRIBUTING.md](https://github.com/cthoyt/ssslm/blob/master/.github/CONTRIBUTING.md)
222
+ for more information on getting involved.
223
+
224
+ ## 👋 Attribution
225
+
226
+ ### ⚖️ License
227
+
228
+ The code in this package is licensed under the MIT License.
229
+
230
+ <!--
231
+ ### 📖 Citation
232
+
233
+ Citation goes here!
234
+ -->
235
+
236
+ <!--
237
+ ### 🎁 Support
238
+
239
+ This project has been supported by the following organizations (in alphabetical order):
240
+
241
+ - [Biopragmatics Lab](https://biopragmatics.github.io)
242
+
243
+ -->
244
+
245
+ <!--
246
+ ### 💰 Funding
247
+
248
+ This project has been supported by the following grants:
249
+
250
+ | Funding Body | Program | Grant Number |
251
+ |---------------|--------------------------------------------------------------|--------------|
252
+ | Funder | [Grant Name (GRANT-ACRONYM)](https://example.com/grant-link) | ABCXYZ |
253
+ -->
254
+
255
+ ### 🍪 Cookiecutter
256
+
257
+ This package was created with
258
+ [@audreyfeldroy](https://github.com/audreyfeldroy)'s
259
+ [cookiecutter](https://github.com/cookiecutter/cookiecutter) package using
260
+ [@cthoyt](https://github.com/cthoyt)'s
261
+ [cookiecutter-snekpack](https://github.com/cthoyt/cookiecutter-snekpack)
262
+ template.
263
+
264
+ ## 🛠️ For Developers
265
+
266
+ <details>
267
+ <summary>See developer instructions</summary>
268
+
269
+ The final section of the README is for if you want to get involved by making a
270
+ code contribution.
271
+
272
+ ### Development Installation
273
+
274
+ To install in development mode, use the following:
275
+
276
+ ```console
277
+ $ git clone git+https://github.com/cthoyt/ssslm.git
278
+ $ cd ssslm
279
+ $ uv --preview pip install -e .
280
+ ```
281
+
282
+ Alternatively, install using pip:
283
+
284
+ ```console
285
+ $ UV_PREVIEW=1 python3 -m pip install -e .
286
+ ```
287
+
288
+ Note that this requires setting `UV_PREVIEW` mode enabled until the uv build
289
+ backend becomes a stable feature.
290
+
291
+ ### Updating Package Boilerplate
292
+
293
+ This project uses `cruft` to keep boilerplate (i.e., configuration, contribution
294
+ guidelines, documentation configuration) up-to-date with the upstream
295
+ cookiecutter package. Install cruft with either `uv tool install cruft` or
296
+ `python3 -m pip install cruft` then run:
297
+
298
+ ```console
299
+ $ cruft update
300
+ ```
301
+
302
+ More info on Cruft's update command is available
303
+ [here](https://github.com/cruft/cruft?tab=readme-ov-file#updating-a-project).
304
+
305
+ ### 🥼 Testing
306
+
307
+ After cloning the repository and installing `tox` with
308
+ `uv tool install tox --with tox-uv` or `python3 -m pip install tox tox-uv`, the
309
+ unit tests in the `tests/` folder can be run reproducibly with:
310
+
311
+ ```console
312
+ $ tox -e py
313
+ ```
314
+
315
+ Additionally, these tests are automatically re-run with each commit in a
316
+ [GitHub Action](https://github.com/cthoyt/ssslm/actions?query=workflow%3ATests).
317
+
318
+ ### 📖 Building the Documentation
319
+
320
+ The documentation can be built locally using the following:
321
+
322
+ ```console
323
+ $ git clone git+https://github.com/cthoyt/ssslm.git
324
+ $ cd ssslm
325
+ $ tox -e docs
326
+ $ open docs/build/html/index.html
327
+ ```
328
+
329
+ The documentation automatically installs the package as well as the `docs` extra
330
+ specified in the [`pyproject.toml`](pyproject.toml). `sphinx` plugins like
331
+ `texext` can be added there. Additionally, they need to be added to the
332
+ `extensions` list in [`docs/source/conf.py`](docs/source/conf.py).
333
+
334
+ The documentation can be deployed to [ReadTheDocs](https://readthedocs.io) using
335
+ [this guide](https://docs.readthedocs.io/en/stable/intro/import-guide.html). The
336
+ [`.readthedocs.yml`](.readthedocs.yml) YAML file contains all the configuration
337
+ you'll need. You can also set up continuous integration on GitHub to check not
338
+ only that Sphinx can build the documentation in an isolated environment (i.e.,
339
+ with `tox -e docs-test`) but also that
340
+ [ReadTheDocs can build it too](https://docs.readthedocs.io/en/stable/pull-requests.html).
341
+
342
+ #### Configuring ReadTheDocs
343
+
344
+ 1. Log in to ReadTheDocs with your GitHub account to install the integration at
345
+ https://readthedocs.org/accounts/login/?next=/dashboard/
346
+ 2. Import your project by navigating to https://readthedocs.org/dashboard/import
347
+ then clicking the plus icon next to your repository
348
+ 3. You can rename the repository on the next screen using a more stylized name
349
+ (i.e., with spaces and capital letters)
350
+ 4. Click next, and you're good to go!
351
+
352
+ ### 📦 Making a Release
353
+
354
+ #### Configuring Zenodo
355
+
356
+ [Zenodo](https://zenodo.org) is a long-term archival system that assigns a DOI
357
+ to each release of your package.
358
+
359
+ 1. Log in to Zenodo via GitHub with this link:
360
+ https://zenodo.org/oauth/login/github/?next=%2F. This brings you to a page
361
+ that lists all of your organizations and asks you to approve installing the
362
+ Zenodo app on GitHub. Click "grant" next to any organizations you want to
363
+ enable the integration for, then click the big green "approve" button. This
364
+ step only needs to be done once.
365
+ 2. Navigate to https://zenodo.org/account/settings/github/, which lists all of
366
+ your GitHub repositories (both in your username and any organizations you
367
+ enabled). Click the on/off toggle for any relevant repositories. When you
368
+ make a new repository, you'll have to come back to this
369
+
370
+ After these steps, you're ready to go! After you make "release" on GitHub (steps
371
+ for this are below), you can navigate to
372
+ https://zenodo.org/account/settings/github/repository/cthoyt/ssslm to see the
373
+ DOI for the release and link to the Zenodo record for it.
374
+
375
+ #### Registering with the Python Package Index (PyPI)
376
+
377
+ You only have to do the following steps once.
378
+
379
+ 1. Register for an account on the
380
+ [Python Package Index (PyPI)](https://pypi.org/account/register)
381
+ 2. Navigate to https://pypi.org/manage/account and make sure you have verified
382
+ your email address. A verification email might not have been sent by default,
383
+ so you might have to click the "options" dropdown next to your address to get
384
+ to the "re-send verification email" button
385
+ 3. 2-Factor authentication is required for PyPI since the end of 2023 (see this
386
+ [blog post from PyPI](https://blog.pypi.org/posts/2023-05-25-securing-pypi-with-2fa/)).
387
+ This means you have to first issue account recovery codes, then set up
388
+ 2-factor authentication
389
+ 4. Issue an API token from https://pypi.org/manage/account/token
390
+
391
+ #### Configuring your machine's connection to PyPI
392
+
393
+ You have to do the following steps once per machine.
394
+
395
+ ```console
396
+ $ uv tool install keyring
397
+ $ keyring set https://upload.pypi.org/legacy/ __token__
398
+ $ keyring set https://test.pypi.org/legacy/ __token__
399
+ ```
400
+
401
+ Note that this deprecates previous workflows using `.pypirc`.
402
+
403
+ #### Uploading to PyPI
404
+
405
+ After installing the package in development mode and installing `tox` with
406
+ `uv tool install tox --with tox-uv` or `python3 -m pip install tox tox-uv`, run
407
+ the following from the console:
408
+
409
+ ```console
410
+ $ tox -e finish
411
+ ```
412
+
413
+ This script does the following:
414
+
415
+ 1. Uses [bump-my-version](https://github.com/callowayproject/bump-my-version) to
416
+ switch the version number in the `pyproject.toml`, `CITATION.cff`,
417
+ `src/ssslm/version.py`, and [`docs/source/conf.py`](docs/source/conf.py) to
418
+ not have the `-dev` suffix
419
+ 2. Packages the code in both a tar archive and a wheel using
420
+ [`uv build`](https://docs.astral.sh/uv/guides/publish/#building-your-package)
421
+ 3. Uploads to PyPI using
422
+ [`uv publish`](https://docs.astral.sh/uv/guides/publish/#publishing-your-package).
423
+ 4. Push to GitHub. You'll need to make a release going with the commit where the
424
+ version was bumped.
425
+ 5. Bump the version to the next patch. If you made big changes and want to bump
426
+ the version by minor, you can use `tox -e bumpversion -- minor` after.
427
+
428
+ #### Releasing on GitHub
429
+
430
+ 1. Navigate to https://github.com/cthoyt/ssslm/releases/new to draft a new
431
+ release
432
+ 2. Click the "Choose a Tag" dropdown and select the tag corresponding to the
433
+ release you just made
434
+ 3. Click the "Generate Release Notes" button to get a quick outline of recent
435
+ changes. Modify the title and description as you see fit
436
+ 4. Click the big green "Publish Release" button
437
+
438
+ This will trigger Zenodo to assign a DOI to your release as well.
439
+
440
+ </details>
@@ -0,0 +1,12 @@
1
+ ssslm/version.py,sha256=aab0a8152987e203c5e2a7a5edd9495ed3fcd34ff89af29129377c2661732f31,946
2
+ ssslm/__init__.py,sha256=b26c7eee7bd1e8016afa3b2c88c9495009bf7ccd37c02c991e873d2f9ea697d6,827
3
+ ssslm/model.py,sha256=6c052a910d154d3ad032867f66edf97421e4be487b02ee96f3e9655ee8e8d1a3,17508
4
+ ssslm/cli.py,sha256=0c1f66599606624319a8dfb5f6f11fa48b0822dadd834059e39cb59a63cf8efc,192
5
+ ssslm/ner.py,sha256=4248f024efd6f9bdae85b56d54b902e2d046de51f79852c8d8f8a40b0fa674f6,6114
6
+ ssslm/py.typed,sha256=01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b,1
7
+ ssslm/__main__.py,sha256=8d5a7f138a7bb9ebfb01d8cf338557a8d2d5d9b8f392f0c90f47cdb605d46b08,122
8
+ ssslm-0.0.1.dist-info/licenses/LICENSE,sha256=4be0ec343e3bf11fd54321a6b576d5616ebb7d18898f741f63c517209e33bcb2,1076
9
+ ssslm-0.0.1.dist-info/WHEEL,sha256=6feffb24f1396d560c24d781d487dbd48d12d39bfeb3acb4928d5e11f32fb262,79
10
+ ssslm-0.0.1.dist-info/entry_points.txt,sha256=a331c55416577ee269318ab66d1afc204f10627a88125eecd447b42d07e1751c,42
11
+ ssslm-0.0.1.dist-info/METADATA,sha256=3653e6f27bc859a0cd2846da3a837d1ae8298325aa19013c0d25c984d7ffed66,17912
12
+ ssslm-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.5.29
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ ssslm = ssslm.cli:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Charles Tapley Hoyt
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.