sdb-reader 0.9.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.
sdb_reader/show.py ADDED
@@ -0,0 +1,370 @@
1
+ """A record of ``read`` as a report for a person (SDW-37 to SDW-41).
2
+
3
+ ``show`` reads a file exactly like ``read`` and words the same record: this
4
+ module looks at no PDF and no text, and judges nothing. Every label and
5
+ sentence comes from the message catalog; the sentences of the label and the
6
+ names a sheet prints stand as the sheet prints them. The text is for people
7
+ and may change with any release: a program takes the record itself.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Iterator, Mapping, Sequence
13
+ from typing import Any
14
+
15
+ from .messages import Catalog, Message
16
+
17
+ _INDENT = " "
18
+ # Between the parts of one line: the signal word and the pictograms, and the
19
+ # columns of a file's line in a folder.
20
+ _BETWEEN = " · "
21
+ _SHEET = "safety-data-sheet"
22
+ # What the parser notes about a label that lacks one kind of statement. For a
23
+ # sheet that prints no label at all they only repeat that (SDW-38).
24
+ _REPEATS_NO_LABEL = frozenset({"no-hazard-codes", "no-precautionary-codes"})
25
+ _KINDS: Mapping[str, str] = {
26
+ "safety-data-sheet-other-language": "show-kind-other-language",
27
+ "safety-information": "show-kind-safety-information",
28
+ "document": "show-kind-document",
29
+ }
30
+
31
+
32
+ def _say(catalog: Catalog, code: str, **params: Any) -> str:
33
+ return catalog.render(Message(code, params))
34
+
35
+
36
+ def _one_line(text: str) -> str:
37
+ """A value on one line: a name a sheet breaks over two lines is still one."""
38
+ return " ".join(text.split())
39
+
40
+
41
+ def _stated(catalog: Catalog, value: Any) -> str:
42
+ """A value as the sheet gives it, or the catalog's word for a missing one."""
43
+ text = _one_line(str(value)) if value is not None else ""
44
+ return text or _say(catalog, "show-not-stated")
45
+
46
+
47
+ def is_unreadable(record: Mapping[str, Any]) -> bool:
48
+ """Whether no text could be read from the record's file (SDW-4)."""
49
+ return "extraction" not in record
50
+
51
+
52
+ def is_sheet(record: Mapping[str, Any]) -> bool:
53
+ """Whether the record is of a German safety data sheet that was read."""
54
+ return "sheet" in record
55
+
56
+
57
+ def _kind(record: Mapping[str, Any], catalog: Catalog) -> str:
58
+ """What the file is, in the catalog's words (SDW-8)."""
59
+ if is_unreadable(record):
60
+ return _say(catalog, "show-kind-unreadable")
61
+ if is_sheet(record):
62
+ return _say(catalog, "show-kind-sheet", sheets=record["sheet_count"])
63
+ kind = record["verification"]["kind"]
64
+ # A German sheet the parser was not run on does not occur; said as what
65
+ # the verdict names it, should it ever.
66
+ return _say(catalog, _KINDS.get(kind, "show-kind-document"))
67
+
68
+
69
+ def _sentences(
70
+ messages: Sequence[Mapping[str, Any]], *, without: frozenset[str] = frozenset()
71
+ ) -> Iterator[str]:
72
+ """The sentences of *messages*, leaving out the codes in *without*."""
73
+ for message in messages:
74
+ if message["code"] not in without:
75
+ yield _one_line(message["message"])
76
+
77
+
78
+ def _unlabelled(
79
+ sheet: Mapping[str, Any], statements: Sequence[Mapping[str, Any]]
80
+ ) -> bool:
81
+ """Whether the sheet prints no label at all: no word, no sign, no statement."""
82
+ labelling = sheet["hazard_statements"]
83
+ return not (labelling["signal_word"] or labelling["pictograms"] or statements)
84
+
85
+
86
+ def _repeated(
87
+ sheet: Mapping[str, Any], statements: Sequence[Mapping[str, Any]]
88
+ ) -> frozenset[str]:
89
+ """The parser's notes the report leaves out for this sheet, by code."""
90
+ return _REPEATS_NO_LABEL if _unlabelled(sheet, statements) else frozenset()
91
+
92
+
93
+ def _unique(sentences: Iterator[str], seen: set[str]) -> list[str]:
94
+ """The sentences not said before, in their order; *seen* grows by them."""
95
+ fresh: list[str] = []
96
+ for sentence in sentences:
97
+ if sentence not in seen:
98
+ seen.add(sentence)
99
+ fresh.append(sentence)
100
+ return fresh
101
+
102
+
103
+ def _reasons(record: Mapping[str, Any]) -> list[str]:
104
+ """Why a file is no sheet that was read: the verdict's reasons (SDW-38)."""
105
+ verification = record["verification"]
106
+
107
+ def said() -> Iterator[str]:
108
+ yield from _sentences(record["errors"])
109
+ yield from _sentences(verification["errors"])
110
+ yield from _sentences(record["findings"])
111
+
112
+ reasons = _unique(said(), set())
113
+ # A verdict that names no reason of its own gave its doubts as warnings.
114
+ return reasons or _unique(_sentences(verification["warnings"]), set())
115
+
116
+
117
+ def _file_notes(record: Mapping[str, Any], seen: set[str]) -> list[str]:
118
+ """What is noted about a sheet's file: findings first, then the reading."""
119
+
120
+ def said() -> Iterator[str]:
121
+ yield from _sentences(record["findings"])
122
+ yield from _sentences(record["extraction"]["warnings"])
123
+ yield from _sentences(
124
+ record["parser"]["warnings"],
125
+ without=_repeated(record["sheet"], record["statements"]),
126
+ )
127
+
128
+ return _unique(said(), seen)
129
+
130
+
131
+ def _part_notes(part: Mapping[str, Any]) -> list[str]:
132
+ without = _repeated(part["sheet"], part["statements"])
133
+ return _unique(_sentences(part["warnings"], without=without), set())
134
+
135
+
136
+ def _notes(record: Mapping[str, Any]) -> tuple[list[list[str]], list[str]]:
137
+ """The notes of each sheet of a file of several, and those of the file.
138
+
139
+ A sentence a sheet carries stands with every sheet that carries it, and
140
+ not again with the file.
141
+ """
142
+ parts = [_part_notes(part) for part in record.get("parts", ())]
143
+ return parts, _file_notes(record, {note for notes in parts for note in notes})
144
+
145
+
146
+ def notes_count(record: Mapping[str, Any]) -> int:
147
+ """How many notes the full report of a sheet's file lists (SDW-40)."""
148
+ parts, whole = _notes(record)
149
+ return sum(len(notes) for notes in parts) + len(whole)
150
+
151
+
152
+ def _date(sheet: Mapping[str, Any], catalog: Catalog) -> tuple[str, str | None]:
153
+ """The label and the date a sheet is dated by: revised, else issued."""
154
+ if sheet["revision_date"]:
155
+ return "show-label-revised", _say(
156
+ catalog, "show-date", date=sheet["revision_date"]
157
+ )
158
+ if sheet["issue_date"]:
159
+ return "show-label-issued", _say(catalog, "show-date", date=sheet["issue_date"])
160
+ return "show-label-revised", None
161
+
162
+
163
+ def _sheet_block(
164
+ sheet: Mapping[str, Any],
165
+ statements: Sequence[Mapping[str, Any]],
166
+ notes: list[str] | None,
167
+ catalog: Catalog,
168
+ ) -> list[str]:
169
+ """One sheet: who and what, the label, whether it needs a sheet, the notes.
170
+
171
+ *notes* None leaves the notes out: a sheet of several shows them only
172
+ where it has some, the file as a whole always.
173
+ """
174
+ label_code, dated = _date(sheet, catalog)
175
+ when = dated or _say(catalog, "show-not-stated")
176
+ if sheet["version"]:
177
+ when = _say(
178
+ catalog,
179
+ "show-with-version",
180
+ value=when,
181
+ version=_one_line(sheet["version"]),
182
+ )
183
+ contact = sheet["contact_info"]
184
+ supplier = ", ".join(
185
+ _one_line(part)
186
+ for part in (contact["supplier_name"], contact["supplier_address"])
187
+ if part
188
+ )
189
+ # The office that gives information, named as such, where the sheet
190
+ # prints another address for it than the supplier's.
191
+ office = contact["information_email"]
192
+ if office and office == contact["supplier_email"]:
193
+ office = None
194
+ reached = ", ".join(
195
+ part
196
+ for part in (
197
+ _one_line(contact["supplier_phone"] or ""),
198
+ _one_line(contact["supplier_email"] or ""),
199
+ _say(catalog, "show-information-email", email=_one_line(office))
200
+ if office
201
+ else "",
202
+ )
203
+ if part
204
+ )
205
+ labelling = sheet["hazard_statements"]
206
+ # A sheet that prints no label at all says so in one word.
207
+ unlabelled = _unlabelled(sheet, statements)
208
+ head = (
209
+ _say(catalog, "show-no-labelling")
210
+ if unlabelled
211
+ else _BETWEEN.join(
212
+ (
213
+ _one_line(labelling["signal_word"])
214
+ if labelling["signal_word"]
215
+ else _say(catalog, "show-no-signal-word"),
216
+ ", ".join(labelling["pictograms"])
217
+ if labelling["pictograms"]
218
+ else _say(catalog, "show-no-pictograms"),
219
+ )
220
+ )
221
+ )
222
+ rows = (
223
+ ("show-label-product", _stated(catalog, sheet["product_identifier"])),
224
+ ("show-label-supplier", _stated(catalog, supplier or None)),
225
+ ("show-label-contact", _stated(catalog, reached or None)),
226
+ ("show-label-emergency", _stated(catalog, contact["emergency_phone"])),
227
+ (label_code, when),
228
+ ("show-label-labelling", head),
229
+ )
230
+ labels = [_say(catalog, code) for code, _ in rows]
231
+ width = max(len(label) for label in labels) + 2
232
+ lines = [
233
+ f"{label:<{width}}{value}"
234
+ for label, (_, value) in zip(labels, rows, strict=True)
235
+ ]
236
+ # The label stands apart from who and what, as on the sheet.
237
+ lines.insert(len(rows) - 1, "")
238
+ for statement in statements:
239
+ # The sheet's wording; a code it prints without one is said in the
240
+ # regulation's, and stands alone where that has none either.
241
+ wording = statement["sheet"] or statement["regulation"]
242
+ text = f"{statement['code']} {_one_line(wording)}" if wording else None
243
+ lines.append(_INDENT + (text or statement["code"]))
244
+ if not statements and not unlabelled:
245
+ lines.append(_INDENT + _say(catalog, "show-no-statements"))
246
+ lines.append("")
247
+ lines.append(
248
+ _say(
249
+ catalog,
250
+ "show-needs-sheet" if sheet["sheet_required"] else "show-needs-no-sheet",
251
+ )
252
+ )
253
+ if sheet["stated_voluntary"]:
254
+ lines.append(_INDENT + _say(catalog, "show-stated-voluntary"))
255
+ if sheet["stated_article"]:
256
+ lines.append(_INDENT + _say(catalog, "show-stated-article"))
257
+ if notes is not None:
258
+ lines.append("")
259
+ lines.extend(_notes_block(notes, catalog))
260
+ return lines
261
+
262
+
263
+ def _notes_block(notes: list[str], catalog: Catalog) -> list[str]:
264
+ listed = notes or [_say(catalog, "show-no-notes")]
265
+ return [
266
+ _say(catalog, "show-label-notes"),
267
+ *(f"{_INDENT}- {note}" for note in listed),
268
+ ]
269
+
270
+
271
+ def _indented(lines: Sequence[str], depth: int) -> list[str]:
272
+ return [(_INDENT * depth + line) if line else "" for line in lines]
273
+
274
+
275
+ def report(record: Mapping[str, Any], name: str, catalog: Catalog) -> list[str]:
276
+ """The full report of one file, as lines (SDW-38, SDW-39)."""
277
+ lines = [name, _INDENT + _kind(record, catalog)]
278
+ if not is_sheet(record):
279
+ lines.extend(f"{_INDENT * 2}- {reason}" for reason in _reasons(record))
280
+ return lines
281
+ cover = _cover(record, catalog, short=False)
282
+ if cover:
283
+ lines.append(_INDENT + cover)
284
+ part_notes, whole = _notes(record)
285
+ parts = record.get("parts", ())
286
+ if not parts:
287
+ lines.append("")
288
+ lines.extend(
289
+ _indented(
290
+ _sheet_block(record["sheet"], record["statements"], whole, catalog), 1
291
+ )
292
+ )
293
+ return lines
294
+ for number, (part, notes) in enumerate(
295
+ zip(parts, part_notes, strict=True), start=1
296
+ ):
297
+ lines.append("")
298
+ lines.append(
299
+ _INDENT + _say(catalog, "show-sheet-of", number=number, count=len(parts))
300
+ )
301
+ lines.extend(
302
+ _indented(
303
+ _sheet_block(part["sheet"], part["statements"], notes or None, catalog),
304
+ 2,
305
+ )
306
+ )
307
+ # What holds for the file: the sheets united need a sheet where one of
308
+ # them does, and the findings compare them with one another.
309
+ lines.append("")
310
+ lines.append(_INDENT + _say(catalog, "show-whole-file"))
311
+ needs = record["sheet"]["sheet_required"]
312
+ lines.append(
313
+ _INDENT * 2
314
+ + _say(catalog, "show-needs-sheet" if needs else "show-needs-no-sheet")
315
+ )
316
+ lines.append("")
317
+ lines.extend(_indented(_notes_block(whole, catalog), 2))
318
+ return lines
319
+
320
+
321
+ def _cover(record: Mapping[str, Any], catalog: Catalog, *, short: bool) -> str | None:
322
+ """What stands in front of a file's sheets, as a sentence or in a line."""
323
+ if not record["cover_page"]:
324
+ return None
325
+ term = record["display_term"]
326
+ if term:
327
+ return _say(
328
+ catalog,
329
+ "show-line-cover-page-display" if short else "show-cover-page-display",
330
+ term=_one_line(term),
331
+ )
332
+ return _say(catalog, "show-line-cover-page" if short else "show-cover-page")
333
+
334
+
335
+ def _product_and_date(sheet: Mapping[str, Any], catalog: Catalog) -> tuple[str, str]:
336
+ """A sheet's product and date for a line; the catalog's words where missing."""
337
+ _, dated = _date(sheet, catalog)
338
+ product = sheet["product_identifier"]
339
+ return (
340
+ _one_line(product) if product else _say(catalog, "show-no-product"),
341
+ dated or _say(catalog, "show-undated"),
342
+ )
343
+
344
+
345
+ def line(record: Mapping[str, Any], name: str, catalog: Catalog) -> str:
346
+ """One file of a folder on one line (SDW-40)."""
347
+ kind = _kind(record, catalog)
348
+ if not is_sheet(record):
349
+ return f"{name}: {kind}"
350
+ parts = record.get("parts", ())
351
+ if parts:
352
+ # Every sheet of the file, in its order: the first alone would hide
353
+ # that a file holds the sheets of different products.
354
+ sheets = "; ".join(
355
+ _say(catalog, "show-product-dated", product=product, dated=dated)
356
+ for product, dated in (
357
+ _product_and_date(part["sheet"], catalog) for part in parts
358
+ )
359
+ )
360
+ columns = [kind, _cover(record, catalog, short=True), sheets]
361
+ else:
362
+ columns = [kind, *_product_and_date(record["sheet"], catalog)]
363
+ columns.append(_say(catalog, "show-notes", notes=notes_count(record)))
364
+ return f"{name}: " + _BETWEEN.join(column for column in columns if column)
365
+
366
+
367
+ def broke(name: str, catalog: Catalog, *, full: bool) -> list[str]:
368
+ """A file whose reading broke: it has no record, and is named all the same."""
369
+ said = _say(catalog, "show-kind-broke")
370
+ return [name, _INDENT + said] if full else [f"{name}: {said}"]