Reference

Every name the package sdb_reader exports, with its signature, its fields and its description: the interface the library promises (What is promised), and nothing beside it. What is reached only through a submodule is not listed here and can change without notice.

The descriptions are the ones in the code. The pages under Using the library explain how the names work together; the sections below follow them.

Reading a file

What read_sheet and its relatives give back is described in A reading and its parts.

read_sheet(path: Path, *, max_pages: int | None = None) → SheetReading

Read the PDF at path, judge what kind of document it is, and parse a sheet.

The file is judged by its content alone; its name says nothing. max_pages bounds how many pages are read, by default all. A file that cannot be read gives a reading with extraction None and the reason in errors.

extract_pdf_text(path: Path, *, max_pages: int | None = None, ocr: bool = True) → ExtractionResult

Extract text from path using PyMuPDF, in the order the pages print it.

A text layer is read by the position of its words (layout.page_text, SDB-42 to SDB-45); a file without a readable one goes to OCR (SDB-46).

All pages are read, as read_sheet reads them; max_pages bounds how many. With ocr off, a PDF without a text layer is not handed to text recognition: the call fails with no-text-layer instead.

read_extraction(extraction: ExtractionResult) → SheetReading

Judge and parse a text that was read from a PDF before (BIB-3).

Gives what read_sheet gives for the file the text came from. Reading a PDF’s text takes nearly all the time of a reading; a caller that keeps the text (extraction_to_dict) reads a sheet again in milliseconds.

>>> from sdb_reader import extraction_from_dict
>>> text = (
...     "Sicherheitsdatenblatt\n"
...     "ABSCHNITT 1: Bezeichnung des Stoffs bzw. des Gemischs\n"
...     "Produktname: Musterfarbe\n"
...     "ABSCHNITT 2: Mögliche Gefahren\n"
...     "Verordnung (EG) Nr. 1907/2006\n"
...     "Signalwort: Achtung\n"
...     "H315: Verursacht Hautreizungen.\n"
... )
>>> reading = read_extraction(
...     extraction_from_dict(
...         {"text": text, "extractor": "pymupdf", "pages_sampled": 1, "warnings": []}
...     )
... )
>>> reading.verification.kind.value
'safety-data-sheet'
>>> label = reading.parser_result.sheet.hazard_statements
>>> label.hazard_codes, label.signal_word
(['H315'], 'Achtung')
class SheetReading(verification: Verification, extraction: ExtractionResult | None = None, parser_result: ParsedSheet | None = None, warnings: list[Message] = <factory>, errors: list[Message] = <factory>)

What reading one file found.

verification: Verification
extraction: ExtractionResult | None
parser_result: ParsedSheet | None
warnings: list[Message]
errors: list[Message]
class Verification(errors: list[Message], warnings: list[Message], kind: DocumentKind = DocumentKind.DOCUMENT, prints_statement_codes: bool | None = None)

What kind of document a text is, and why.

kind is the verdict; only a SAFETY_DATA_SHEET is parsed. errors say why a file is none, warnings what else stood out.

errors: list[Message]
warnings: list[Message]
kind: DocumentKind
prints_statement_codes: bool | None
class DocumentKind

What a file filed as a safety data sheet is (SDB-66, SDB-68).

SAFETY_DATA_SHEET = 'safety-data-sheet'
SAFETY_INFORMATION = 'safety-information'
FOREIGN_SAFETY_DATA_SHEET = 'safety-data-sheet-other-language'
DOCUMENT = 'document'
class ParsedSheet(sheet: ~sdb_reader.schema.SafetyDataSheet, warnings: list[~sdb_reader.messages.Message], parts: list[~sdb_reader.parser.SheetPart] = <factory>, cover_page: bool = False, display_term: str | None = None)

A parsed sheet, and what the parser noticed while reading it.

sheet: SafetyDataSheet
warnings: list[Message]
parts: list[SheetPart]
cover_page: bool
display_term: str | None
class SheetPart(sheet: SafetyDataSheet, warnings: list[Message], text: str)

One sheet of a file that holds several, read on its own (SDB-118).

sheet: SafetyDataSheet
warnings: list[Message]
text: str
class ExtractionResult(text: str, raw_text: str, extractor: str, pages_sampled: int, warnings: list[Message], metadata: dict[str, object])

Details about a text extraction attempt.

text: str
raw_text: str
extractor: str
pages_sampled: int
warnings: list[Message]
metadata: dict[str, object]
exception ExtractionError(message: Message)

Raised when text cannot be extracted from an SDS PDF.

message says why, as a code and its values; str() of the error is that message in English, for a traceback.

A sheet

The parts of a parsed sheet.

class SafetyDataSheet(product_identifier: str | None, issue_date: date | None, revision_date: date | None, version: str | None, language: str, hazard_statements: HazardStatements = <factory>, contact_info: ContactInfo = <factory>, section_text: dict[~sdb_reader.schema.Section, str]=<factory>, countries: list[str] = <factory>, stated_classification: StatedClassification = StatedClassification.NOT_STATED, stated_voluntary: bool = False, stated_article: bool = False)

What the parser read from one German safety data sheet.

product_identifier: str | None
issue_date: date | None
revision_date: date | None
version: str | None
language: str
hazard_statements: HazardStatements
contact_info: ContactInfo
section_text: dict[Section, str]
countries: list[str]
stated_classification: StatedClassification
stated_voluntary: bool
stated_article: bool
class HazardStatements(hazard_codes: list[str] = <factory>, precautionary_codes: list[str] = <factory>, supplemental_codes: list[str] = <factory>, signal_word: str | None = None, pictograms: list[str] = <factory>, hazard_text: str | None = None, precautionary_text: str | None = None, supplemental_text: str | None = None)

The label of a sheet (section 2.2): codes, their texts as printed, the signal word and the pictograms.

hazard_codes: list[str]
precautionary_codes: list[str]
supplemental_codes: list[str]
signal_word: str | None
pictograms: list[str]
hazard_text: str | None
precautionary_text: str | None
supplemental_text: str | None
class ContactInfo(supplier_name: str | None = None, supplier_address: str | None = None, supplier_phone: str | None = None, emergency_phone: str | None = None, supplier_email: str | None = None, supplier_website: str | None = None, information_email: str | None = None)

The supplier named in section 1.3, and the emergency telephone of 1.4.

supplier_name: str | None
supplier_address: str | None
supplier_phone: str | None
emergency_phone: str | None
supplier_email: str | None
supplier_website: str | None
information_email: str | None
class StatedClassification

What section 2 of a sheet says about the product’s classification (SDB-75).

CLASSIFIED = 'classified'
OLD_SYSTEM = 'classified-old-system'
NOT_CLASSIFIED = 'not-classified'
NOT_STATED = 'not-stated'
class Section

The sixteen sections of a safety data sheet, as keys of its section texts.

IDENTIFICATION = 'section_1'
HAZARDS = 'section_2'
COMPOSITION = 'section_3'
FIRST_AID = 'section_4'
FIRE_FIGHTING = 'section_5'
ACCIDENTAL_RELEASE = 'section_6'
HANDLING_STORAGE = 'section_7'
EXPOSURE_PPE = 'section_8'
PHYSICAL_CHEMICAL = 'section_9'
STABILITY_REACTIVITY = 'section_10'
TOXICOLOGY = 'section_11'
ECOLOGY = 'section_12'
DISPOSAL = 'section_13'
TRANSPORT = 'section_14'
REGULATORY = 'section_15'
OTHER = 'section_16'

Keeping readings and texts

See Keeping texts and The JSON schema.

reading_to_dict(reading: SheetReading, *, include_raw_text: bool = False, embedded: EmbeddedData | None = None, catalog: Catalog | None = None, today: date | None = None) → dict[str, Any]

What reading one file found, as sdb-reader read prints it.

today is the day the findings take as the present (sheet_findings); the command passes the machine’s date. Without it no date is questioned, and the record is the same on any day.

Without the file itself: the command puts its path, name and size in front. embedded is what read_embedded found in the PDF; with it the record lists where the embedded data and the sheet as read differ (SDW-11). Every message stands as its code, its values and a sentence from catalog: the shipped German one unless another is given (SDW-17).

sheet_to_dict(sheet: SafetyDataSheet, extraction: ExtractionResult) → dict[str, Any]

The parsed sheet as JSON: the sheet part of what the command prints.

extraction is the text the sheet was parsed from; its fingerprint goes into the record. Every value stands once (SDW-18).

sheet_from_dict(stored: Mapping[str, Any]) → SafetyDataSheet

The sheet sheet_to_dict stored, to judge it again (BIB-21).

Reads what this version writes: the sheet part of a record of read, or of one of its parts. content_hash and sheet_required are not part of a sheet and are left out; requires_sheet gives the second again. A key this version does not know is ignored.

A record that lacks a key, or holds a value of another kind, was stored by another version and is refused with ValueError: make the reading again from the stored text (read_extraction) instead. Whether a record still holds is the caller’s to compare with PARSER_VERSION.

>>> stored = {
...     "version": "2.0", "product_identifier": "Musterfarbe",
...     "issue_date": None, "revision_date": "2024-03-01", "language": "de",
...     "countries": ["DE"], "stated_classification": "classified",
...     "stated_voluntary": False, "stated_article": False,
...     "hazard_statements": {
...         "hazard_codes": ["H315"], "precautionary_codes": [],
...         "supplemental_codes": [], "signal_word": "Achtung",
...         "pictograms": ["GHS07"], "hazard_text": None,
...         "precautionary_text": None, "supplemental_text": None,
...     },
...     "contact_info": {
...         "supplier_name": "Nordwerk GmbH", "supplier_address": None,
...         "supplier_phone": None, "emergency_phone": None,
...         "supplier_email": None, "supplier_website": None,
...         "information_email": None,
...     },
...     "section_text": {"section_2": "Signalwort: Achtung"},
... }
>>> sheet = sheet_from_dict(stored)
>>> sheet.revision_date, sheet.hazard_statements.signal_word
(datetime.date(2024, 3, 1), 'Achtung')
>>> requires_sheet(sheet)
True
verification_to_dict(verification: Verification, *, catalog: Catalog | None = None) → dict[str, Any]

The verdict as a record stores it; catalog words its messages.

extraction_to_dict(extraction: ExtractionResult) → dict[str, Any]

The text read from a PDF, in a form to store as JSON (BIB-3).

Holds what a reading needs and names the stage it comes from. The text before tidying and the single pages are not kept.

>>> text = "Sicherheitsdatenblatt\nABSCHNITT 1: Bezeichnung des Stoffs\n"
>>> stored = extraction_to_dict(
...     extraction_from_dict(
...         {"text": text, "extractor": "pymupdf", "pages_sampled": 1, "warnings": []}
...     )
... )
>>> sorted(stored)
['extractor', 'pages_sampled', 'stage', 'text', 'warnings']
>>> stored["stage"] == extraction_stage()
True
extraction_from_dict(stored: Mapping[str, Any]) → ExtractionResult

The text extraction_to_dict stored, for read_extraction (BIB-3).

Whether the stored stage still holds is the caller’s to compare with extraction_stage(); a text of another stage is read all the same. A warning stored as a sentence, before warnings had codes, gets the code of that sentence, or “unknown” with the sentence as its value; so does a warning with a code this version does not know.

>>> extraction = extraction_from_dict(
...     {"text": "Sicherheitsdatenblatt", "extractor": "pymupdf",
...      "pages_sampled": 1, "warnings": []}
... )
>>> extraction.text, extraction.pages_sampled
('Sicherheitsdatenblatt', 1)
extraction_stage() → str

The reading stage a text comes from: its version and the PDF library’s.

The text of a PDF depends on both, so a stored text holds for one value of this and no other.

Judging a sheet

See Judging a sheet.

sheet_findings(sheet: SafetyDataSheet, parser_warnings: Sequence[Message], *, today: date | None = None, parts: Sequence[SheetPart] = ()) → list[Message]

What is wrong with sheet as a document (SDW-6, SDW-7, SDW-9).

parts are the sheets of a file that holds several (ParsedSheet.parts); with them, what they say about each other is among the findings (several_sheets_findings).

today is the day the caller takes as the present; the library has no clock of its own. With it, a revision date (or, where the sheet names none, an issue date) after that day is reported and does not count for the sheet’s age: the sheet is judged by its issue date where that is no later than today, else like a sheet without a date (SDB-137). Without today no date is questioned.

parser_warnings are the warnings of the parser’s result for the sheet. Each finding is a message; where it concerns one statement, its values name it as statement.

>>> from sdb_reader import extraction_from_dict, read_extraction
>>> text = (
...     "Sicherheitsdatenblatt\n"
...     "ABSCHNITT 1: Bezeichnung des Stoffs bzw. des Gemischs\n"
...     "Produktname: Musterfarbe\n"
...     "ABSCHNITT 2: Mögliche Gefahren\n"
...     "Verordnung (EG) Nr. 1907/2006\n"
...     "Signalwort: Achtung\n"
...     "H315: Verursacht Hautreizungen.\n"
... )
>>> result = read_extraction(
...     extraction_from_dict(
...         {"text": text, "extractor": "pymupdf", "pages_sampled": 1, "warnings": []}
...     )
... ).parser_result
>>> [finding.code for finding in sheet_findings(result.sheet, result.warnings)]
['undated']
classification(hazard_codes: Collection[str], signal_word: str | None, parser_warnings: Iterable[Message]) → Classification

What the label states, from the parser’s codes, signal word and warnings.

A label that says nobody determined the classification counts as that even where the parser found codes elsewhere in section 2.

>>> classification(["H315"], "Achtung", []).value
'classified'
>>> classification([], None, []).value
'not-classified'
class Classification

What a sheet’s label states about the product’s classification.

UNDETERMINED = 'undetermined'
CLASSIFIED = 'classified'
OLD_SYSTEM = 'classified-old-system'
NOT_CLASSIFIED = 'not-classified'
requires_sheet(sheet: SafetyDataSheet) → bool

Whether a sheet is issued for a product that needs one.

SDB-76, SDB-142, SDB-154.

REACH Article 31(1) requires a safety data sheet for a classified product and Article 31(3) one on request where the label carries EUH210. So a sheet is required where section 2 classifies the product (stated_classification, as SDB-75 reads it), or where the label carries what only a classified product’s label does – an H statement, a signal word, a pictogram – or an EUH statement, or the sentence that a safety data sheet is to be had on request, under whichever law the label stands. P statements alone are advice a supplier may print on anything. A sheet without any of it is issued voluntarily.

A sheet that says of itself that it is issued voluntarily or that none is prescribed for its product (stated_voluntary, as SDB-142 reads it) is taken at its word where the duty allows it. For an article (stated_article: the sheet calls the product one, beside that sentence or by saying that as an article it is not subject to labelling, SDB-154) Article 31 knows no duty, whatever the label prints and whether or not the sheet calls itself voluntary. For a mixture it is so while the mixture is not classified: not where section 2 classifies it or the label carries an H statement, since Article 31(4) spares the supplier the sheet of a hazardous mixture only towards the general public and leaves it due to a downstream user or distributor who asks. In either case a label that carries EUH210 or the sentence that a sheet is to be had on request goes first: there the supplier says at the label that one is due.

A sheet kept as a record is read back with sheet_from_dict.

>>> from sdb_reader import HazardStatements
>>> def sheet(label=None, **stated):
...     return SafetyDataSheet(
...         None, None, None, None, "de",
...         hazard_statements=label or HazardStatements(), **stated
...     )
>>> requires_sheet(sheet(HazardStatements(hazard_codes=["H315"])))
True
>>> requires_sheet(sheet(HazardStatements(supplemental_codes=["EUH210"])))
True
>>> requires_sheet(sheet(HazardStatements(precautionary_codes=["P102"])))
False
>>> requires_sheet(
...     sheet(
...         HazardStatements(
...             supplemental_text="Sicherheitsdatenblatt auf Anfrage für "
...             "berufsmäßige Verwender erhältlich."
...         )
...     )
... )
True
>>> requires_sheet(sheet(stated_classification=StatedClassification.CLASSIFIED))
True
>>> requires_sheet(
...     sheet(
...         HazardStatements(hazard_codes=["H314"]),
...         stated_voluntary=True,
...         stated_article=True,
...     )
... )
False
>>> requires_sheet(
...     sheet(
...         stated_classification=StatedClassification.CLASSIFIED,
...         stated_article=True,
...     )
... )
False
>>> requires_sheet(
...     sheet(HazardStatements(supplemental_codes=["EUH210"]), stated_article=True)
... )
True
>>> requires_sheet(
...     sheet(HazardStatements(hazard_codes=["H314"]), stated_voluntary=True)
... )
True
>>> requires_sheet(
...     sheet(HazardStatements(supplemental_codes=["EUH208"]), stated_voluntary=True)
... )
False
>>> requires_sheet(
...     sheet(HazardStatements(supplemental_codes=["EUH210"]), stated_voluntary=True)
... )
True
contradicts_label(sheet: SafetyDataSheet) → bool

Whether section 2 says “not classified” while the label carries what only a classified product’s label does (SDB-79): an H statement, a signal word or a pictogram. An EUH statement is no contradiction; an unclassified mixture may have to carry one.

>>> from sdb_reader import HazardStatements
>>> def sheet(label):
...     return SafetyDataSheet(
...         None, None, None, None, "de", hazard_statements=label,
...         stated_classification=StatedClassification.NOT_CLASSIFIED,
...     )
>>> contradicts_label(sheet(HazardStatements(signal_word="Achtung")))
True
>>> contradicts_label(sheet(HazardStatements(supplemental_codes=["EUH210"])))
False
euh_outside_label(parser_warnings: Iterable[Message]) → list[Message]

The EUH statements the sheet prints only outside its label (SDB-28).

The parser’s messages about them, each with the statement’s code and the sentence as printed.

predates_annex_ii(revised: date) → bool

Whether a sheet last revised on revised cannot meet Annex II as amended by Regulation (EU) 2020/878.

>>> from datetime import date
>>> predates_annex_ii(date(2020, 12, 31)), predates_annex_ii(date(2021, 1, 1))
(True, False)
predates_clp(revised: date) → bool

Whether a sheet last revised on revised predates CLP for mixtures.

>>> from datetime import date
>>> predates_clp(date(2015, 5, 31)), predates_clp(date(2015, 6, 1))
(True, False)

Statements and pictograms

See Statements and pictograms.

label_statements(hazards: HazardStatements) → list[StatementWording]

Every H-, P- and EUH-statement of the label, each with both wordings (SDW-5).

Read from the statement texts, one statement per line (SDB-17), and only for codes the label carries. A code the sheet prints with a wording is listed with each wording it prints; a code it prints only bare, in a list (SDB-30) or in a row of codes, or not at all, once with none.

>>> label = HazardStatements(
...     hazard_codes=["H315"],
...     precautionary_codes=["P280"],
...     hazard_text="H315: Reizt die Haut.",
...     precautionary_text="P280: Schutzhandschuhe tragen.",
... )
>>> for statement in label_statements(label):
...     print(statement.code, "|", statement.sheet, "|", statement.regulation)
H315 | Reizt die Haut. | Verursacht Hautreizungen.
P280 | Schutzhandschuhe tragen. | None
class StatementWording(code: str, sheet: str | None, regulation: str | None)

One statement of a label: what the sheet prints and what the regulation says.

code: str
sheet: str | None
regulation: str | None
canonical_text(code: str) → str | None

The regulation’s wording for code, or None where it prescribes no single one.

>>> canonical_text("H315")
'Verursacht Hautreizungen.'
>>> canonical_text("P280") is None
True
normalize_statements(text: str, prefixes: Sequence[str]) → str

One statement per line, a colon after each code (SDB-17).

prefixes are the kinds of code the text holds (“H”, “EUH”, “P”). Codes joined by a plus or a dash stay on one line, as does a list of codes (“P102, P101, P501:”), which render_statements reads as one (SDB-30).

>>> print(
...     normalize_statements(
...         "H315 Verursacht Hautreizungen. H319 Verursacht schwere Augenreizung.",
...         ("H", "EUH"),
...     )
... )
H315: Verursacht Hautreizungen.
H319: Verursacht schwere Augenreizung.
tidy_statements(text: str) → str

Each statement once, and no code without its wording (SDB-47).

Runs after render_statements, on the statements from either source. A statement the field already holds with the same code and wording goes: the parser cuts its texts from the whole of section 2, and a sheet that prints the label’s statements in 2.1 as well gave each of them twice once the regulation’s wording made the two copies alike. A code standing alone goes too when the field gives the same code a wording – “H220” beside “H220: Extrem entzündbares Gas.” – and otherwise takes the regulation’s wording where it prescribes exactly one; a code it gives none keeps standing alone.

>>> print(
...     tidy_statements(
...         "H315: Verursacht Hautreizungen.\n"
...         "H315: Verursacht Hautreizungen.\n"
...         "H319"
...     )
... )
H315: Verursacht Hautreizungen.
H319: Verursacht schwere Augenreizung.
render_statements(text: str) → tuple[str, int]

Replace each line’s wording with the regulation’s, where there is one.

Works line by line and keeps the sheet’s order, so a paragraph that mixes rendered and untouched statements stays in the sequence the label used. Lines the pattern does not recognise are passed through untouched – this corrects wording, it never removes a statement.

A line that lists codes (SDB-30) becomes one line per code, with the regulation’s wording where it has one and the code alone where it does not. What followed the list is dropped when it holds none of their wordings: on one line of paints it was the start of 2.3, “P501: Andere Gefahren, die zu keiner Einstufung führen …”. When it does hold them, the line is the sheet’s own statement and stays: One supplier prints “H222, H229: Extrem entzündbares Aerosol. Behälter steht unter Druck: …”. EUH statements keep the sheet’s wording (SDB-18); the regulation’s is only taken for one that stands in a list.

Returns the text and how many lines were replaced.

>>> text, replaced = render_statements(
...     "H315: Reizt die Haut.\nP280: Schutzhandschuhe tragen."
... )
>>> print(text)
H315: Verursacht Hautreizungen.
P280: Schutzhandschuhe tragen.
>>> replaced
1
pictograms_for(h_codes: set[str], *, apply_precedence: bool = True) → set[str]

Derive GHS pictogram codes from a set of H-codes.

h_codes are H-statement codes, combined ones included ({"H225", "H302", "H300+H310"}); a code the table does not know adds nothing. With apply_precedence, the default, a pictogram that Article 26 of the CLP Regulation lets another one replace is left out.

>>> sorted(pictograms_for({"H225", "H302"}))
['GHS02', 'GHS07']
>>> sorted(pictograms_for({"H300", "H302"}))
['GHS06']

Messages and catalogs

See Messages and catalogs.

class Message(code: str, params: Mapping[str, ~typing.Any]=<factory>)

One thing the library notes about a file: a code and its values.

The code is one of MESSAGE_CODES; params holds exactly the values that code names, in types that can be written as JSON. A message carries no sentence: Catalog.render gives one in the language asked for.

>>> message = Message("pictograms-derived", {"pictograms": ["GHS07"]})
>>> shipped_catalog("en").render(message)
'Pictograms derived from the H statements, the sheet names none: GHS07'
>>> shipped_catalog("de").render(message)
'Piktogramme aus den H-Sätzen abgeleitet, das Blatt nennt keine: GHS07'
code: str
params: Mapping[str, Any]
to_dict() → dict[str, Any]

Code and values, without a sentence: the form to store.

classmethod from_dict(stored: Mapping[str, Any]) → Message

Read back what to_dict gave.

class Catalog(language: str, sentences: Mapping[str, str | Mapping[str, str]], date_format: str = '%Y-%m-%d')

The sentences of one language, by message code (BIB-11).

A sentence is a string with {name} for each value, or, for a message that counts something, two of them: one for exactly one and other for any other number. date_format says how the catalog writes a date (strftime); a message itself always carries dates in ISO form.

>>> german = shipped_catalog("de")
>>> german.render(Message("no-text-layer", {"pages": 1}))
'Das PDF hat keine Textschicht (1 Seite angesehen).'
>>> german.render(Message("no-text-layer", {"pages": 3}))
'Das PDF hat keine Textschicht (3 Seiten angesehen).'
>>> german.render(Message("predates-annex-ii", {"revised": "2019-05-02"}))[:27]
'Überarbeitet am 02.05.2019,'
language: str
sentences: Mapping[str, str | Mapping[str, str]]
date_format: str
render(message: Message) → str

The sentence for message.

A code this catalog lacks is said in English: a caller’s own catalog need not be complete.

to_dict(message: Message) → dict[str, Any]

Code, values and sentence: the form the command prints (SDW-17).

shipped_catalog(language: str = 'de') → Catalog

The catalog the package ships for language; German unless asked.

The language is always named by the caller and never taken from the machine, so the same file gives the same output everywhere. Raises ValueError for a language no catalog ships for.

load_catalog(path: Path) → Catalog

A caller’s own catalog: a TOML file like the shipped ones.

It may hold fewer codes than there are; the rest are said in English. A code or a placeholder the library does not know is refused, since nobody would ever see that sentence.

Choosing the current sheet

See Which sheet is the current one.

current_state(states: Sequence[SheetState], *, country: str | None = 'DE', today: date | None = None) → Choice

Choose the current one of states, the sheets of one product.

The newest revision date leads; among sheets of one date the one for country comes first, then the higher version, then the newer issue date, then the later one given (BIB-7). Where the sheet so chosen is issued for other countries only, the first sheet for country takes its place if both carry a readable version and its own is not lower (BIB-8). With country None, countries play no part (BIB-9).

today is the day the caller takes as the present. With it, a revision or issue date after that day counts as missing (BIB-19): a sheet that prints an impossible date is not the newest because of it, and ranks as a sheet without that date does. Without today every date counts as printed.

Raises ValueError when states is empty.

>>> from datetime import date
>>> choice = current_state(
...     [
...         SheetState(date(2022, 7, 20), version="2", countries=("DE",)),
...         SheetState(date(2023, 7, 10), version="2", countries=("CH",)),
...     ]
... )
>>> choice.index, choice.reason.value, choice.instead_of
(0, 'stands-in', 1)
class SheetState(revision_date: date | None = None, issue_date: date | None = None, version: str | None = None, countries: Sequence[str] = ())

What a sheet says about its own state: all the choice looks at.

revision_date: date | None
issue_date: date | None
version: str | None
countries: Sequence[str]
class Choice(index: int, reason: ChoiceReason, instead_of: int | None = None)

The current state among those given to current_state.

index: int
reason: ChoiceReason
instead_of: int | None
class ChoiceReason

Why a state is the current one.

NEWEST = 'newest'
STANDS_IN = 'stands-in'
OTHER_COUNTRY = 'other-country'

Embedded data

See Embedded data.

read_embedded(path: Path) → EmbeddedData | None

The first embedded eSDScom file of the PDF at path; None without one.

parse_embedded(name: str, content: bytes) → EmbeddedData

An eSDScom file’s content, as read_embedded reads it out of a PDF.

For a file that was taken out of its PDF before (sdb-reader xml). name is the file’s name. A file that is too large, carries a document type declaration or is no eSDScom file comes back with unreadable set.

>>> data = parse_embedded(
...     "sds.xml",
...     b"<DatasheetFeed><Datasheet><HazardIdentification><HazardLabelling>"
...     b"<ClpLabellingInfo><ClpHazardStatement><PhraseCode>315</PhraseCode>"
...     b"</ClpHazardStatement></ClpLabellingInfo></HazardLabelling>"
...     b"</HazardIdentification></Datasheet></DatasheetFeed>",
... )
>>> sorted(data.sheet.hazard_codes)
['H315']
>>> parse_embedded("other.xml", b"<other/>").unreadable.code
'embedded-wrong-root'
embedded_differences(embedded: EmbeddedSheet, sheet: SafetyDataSheet) → list[Difference]

The compared fields in which sheet as read differs from embedded.

class EmbeddedData(filename: str, sheet: EmbeddedSheet | None = None, unreadable: Message | None = None, content: bytes | None = None)

What a PDF’s embedded eSDScom file says, or why it could not be read.

filename: str
sheet: EmbeddedSheet | None = None
unreadable: Message | None = None
content: bytes | None = None
class EmbeddedSheet(format_version: str | None = None, authoring_system: str | None = None, date: str | None = None, signal_word: str | None = None, pictograms: frozenset[str] = frozenset({}), hazard_codes: frozenset[str] = frozenset({}), precautionary_codes: frozenset[str] = frozenset({}), supplemental_codes: frozenset[str] = frozenset({}), supplier_name: str | None = None, supplier_email: str | None = None)

The fields of an embedded eSDScom file that are compared.

format_version: str | None = None
authoring_system: str | None = None
date: str | None = None
signal_word: str | None = None
pictograms: frozenset[str] = frozenset({})
hazard_codes: frozenset[str] = frozenset({})
precautionary_codes: frozenset[str] = frozenset({})
supplemental_codes: frozenset[str] = frozenset({})
supplier_name: str | None = None
supplier_email: str | None = None
EmbeddedDifference

alias of Difference

Versions and codes

See Keeping texts for the two stage versions and Messages and catalogs for the codes.

EXTRACTION_VERSION: int

The version of the reading stage, the part that makes the text out of a PDF. It rises with every change after which the same PDF can give another text, and never falls (BIB-4). Compare extraction_stage(), which names it together with the PDF library’s version, with what a stored text says.

PARSER_VERSION: int

The version of the parser stage, the part that makes the reading out of the text. It rises with every change after which the same text can give another reading, and never falls (BIB-4). A reading kept at another value is made again from the text.

MESSAGE_CODES: Mapping[str, tuple[str, ...]]

Every message code with the names of the values it carries. The codes and these names are part of the interface: a code never changes its meaning, and one that goes is not given out again (BIB-10).