Skip to content

comicbox.box.load

Parsing methods.

CarriedFormats dataclass

The tag formats a comic carries that comicbox read, and what it could not.

formats come from the archive’s own tag files, its ComicBookInfo comment and a PDF’s metadata: not the file name, nor the command line, an import or an online lookup. unreadable names the tag files that did not parse. in_comment is whether the comic carries ComicBookInfo as its archive comment rather than as a file.

Source code in comicbox/box/load.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@dataclass(frozen=True, slots=True)
class CarriedFormats:
    """
    The tag formats a comic carries that comicbox read, and what it could not.

    ``formats`` come from the archive's own tag files, its ComicBookInfo
    comment and a PDF's metadata: not the file name, nor the command line,
    an import or an online lookup. ``unreadable`` names the tag files that
    did not parse. ``in_comment`` is whether the comic carries ComicBookInfo
    as its archive comment rather than as a file.
    """

    formats: frozenset[MetadataFormats]
    unreadable: tuple[str, ...]
    in_comment: bool
    # An archive comment that is not ComicBookInfo: free text.
    free_comment: bool = False

ComicboxLoad

Bases: ComicboxSources

Parsing methods.

Source code in comicbox/box/load.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
class ComicboxLoad(ComicboxSources):
    """Parsing methods."""

    def _load_cli_yaml(
        self, fmt: MetadataFormats, schema: Any, source_md: str | bytes | Mapping
    ) -> dict:
        result = {}
        try:
            md = YAML().load(source_md)
            result = schema.load(md)
            if not result:
                # try a wrapped version
                key_path = fmt.value.schema_class.ROOT_KEYPATH
                assign = Assign(key_path, md, missing=dict)
                wrapped_md = glom({}, assign)
                result = schema.load(wrapped_md)
        except Exception as exc:
            logger.debug(
                f'Attempt to load CLI Metadata as {fmt.value.label} "{source_md}": {exc}'
            )
        return result

    def _call_load(
        self,
        source: MetadataSources,
        fmt: MetadataFormats,
        source_md: bytes | str | Mapping,
    ) -> Mapping | None:
        """Load string or dict."""
        schema_class = fmt.value.schema_class
        schema = get_schema(
            schema_class, path=self._path, exclude=self._config.general.delete_keys
        )
        if source == MetadataSources.CLI:
            return self._load_cli_yaml(fmt, schema, source_md)

        if isinstance(source_md, str | bytes):
            return schema.loads(source_md)  # pyright: ignore[reportReturnType]

        return schema.load(source_md)  # pyright: ignore[reportReturnType]

    @staticmethod
    def _is_comment_not_json(source: MetadataSources, exc: Exception) -> bool:
        """Is this an archive comment and not JSON."""
        return (
            source == MetadataSources.ARCHIVE_COMMENT
            and isinstance(exc, JSONDecodeError)
            # and exc.pos == 0
            and exc.lineno == 1
            # and exc.colno == 1
        )

    def _except_on_load(
        self,
        source: MetadataSources,
        fmt: MetadataFormats | None,
        exc: Exception,
        level: str = "WARNING",
    ) -> None:
        """When loading fails warn or give stack trace in debug."""
        name = fmt.value.schema_class.__name__ if fmt else "Unknown Schema"
        if self._is_comment_not_json(source, exc):
            # Demote not json as json to debug warning because there are so many
            # archive comments that are not intended to be CBI
            logger.debug(f"{self._path}: {name} metadata is not JSON: {exc}")
            return

        logger.log(
            level,
            f"{self._path}: Unable to load {source.value.label}:{name} metadata: {exc}",
        )
        logger.opt(lazy=True).trace(format_exc())

    def _load_unknown_metadata(
        self, source: MetadataSources, data: str | bytes | Mapping
    ) -> tuple[Mapping | None, MetadataFormats | None]:
        """Parse import data string from file trying many different file schemas."""
        success_md = None
        fmt = None
        for fmt in source.value.formats:
            if not fmt.value.enabled:
                continue
            try:
                if (success_md := self._call_load(source, fmt, data)) and glom(
                    success_md, fmt.value.schema_class.ROOT_KEYPATH
                ):
                    logger.debug(f"Parsed {source.value.label} with {fmt.value.label}")
                    break
            except Exception as exc:
                self._except_on_load(source, fmt, exc, level="DEBUG")
        if not success_md:
            reason = f"Unable to load {source.value.label}."
            raise MetadataError(reason)
        return success_md, fmt

    def _load_metadata(
        self, source: MetadataSources, source_data: SourceData | None
    ) -> tuple[MappingProxyType | None, MetadataFormats | None]:
        if not source_data:
            return None, None
        fmt = source_data.fmt
        try:
            if fmt:
                md = self._call_load(source, fmt, source_data.data)
            else:
                md, fmt = self._load_unknown_metadata(source, source_data.data)
            if md and fmt:
                return MappingProxyType(md), fmt
        except Exception as exc:
            self._except_on_load(source, fmt, exc)
            self._failed_loads.add((source, str(source_data.path)))
        return None, None

    def _set_loaded_metadata(self, source: MetadataSources) -> None:
        source_metadata = self.get_source_metadata(source)
        if not source_metadata:
            return
        # Also populate the parsed_list
        loaded_list = []
        for source_data in source_metadata:
            md, fmt = self._load_metadata(source, source_data)
            if md:
                path = (
                    Path(source_data.path)
                    if isinstance(source_data.path, str)
                    else source_data.path
                )
                loaded_md = LoadedMetadata(md, path, fmt, source_data.from_archive)
                loaded_list.append(loaded_md)

        if loaded_list:
            if source not in self._loaded:
                self._loaded[source] = ()
            self._loaded[source] += tuple(loaded_list)

    def get_carried_formats(self) -> CarriedFormats:
        """
        Get the tag formats the comic carries that were read, and those that failed.

        Only what the read configuration reads is seen: a tag file it
        excludes is neither. An archive comment of free text is not a tag
        file, so it is neither too.
        """
        carried = _Carrying()
        for source in TAG_SOURCES:
            # Loads the source, recording any file whose parser failed.
            self.get_loaded_metadata(source)
            for data in self.get_source_metadata(source) or ():
                carried.add(source, data, self._failed_loads)
        return carried.result()

    def get_loaded_metadata(
        self, source: MetadataSources
    ) -> tuple[LoadedMetadata, ...] | None:
        """Get loaded metadata by key."""
        try:
            if source not in self._loaded:
                self._set_loaded_metadata(source)
            return self._loaded.get(source)
        except Exception as exc:
            logger.warning(
                f"{self._path} Parsing or Loading {source.value.label}: {exc}"
            )
            if os.environ.get("DEBUG"):
                logger.exception(exc)

get_carried_formats()

Get the tag formats the comic carries that were read, and those that failed.

Only what the read configuration reads is seen: a tag file it excludes is neither. An archive comment of free text is not a tag file, so it is neither too.

Source code in comicbox/box/load.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def get_carried_formats(self) -> CarriedFormats:
    """
    Get the tag formats the comic carries that were read, and those that failed.

    Only what the read configuration reads is seen: a tag file it
    excludes is neither. An archive comment of free text is not a tag
    file, so it is neither too.
    """
    carried = _Carrying()
    for source in TAG_SOURCES:
        # Loads the source, recording any file whose parser failed.
        self.get_loaded_metadata(source)
        for data in self.get_source_metadata(source) or ():
            carried.add(source, data, self._failed_loads)
    return carried.result()

get_loaded_metadata(source)

Get loaded metadata by key.

Source code in comicbox/box/load.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def get_loaded_metadata(
    self, source: MetadataSources
) -> tuple[LoadedMetadata, ...] | None:
    """Get loaded metadata by key."""
    try:
        if source not in self._loaded:
            self._set_loaded_metadata(source)
        return self._loaded.get(source)
    except Exception as exc:
        logger.warning(
            f"{self._path} Parsing or Loading {source.value.label}: {exc}"
        )
        if os.environ.get("DEBUG"):
            logger.exception(exc)

is_comic_book_info(text)

Tell a ComicBookInfo comment from free text.

It is ComicBookInfo only as JSON with ComicBookInfo’s root key: any other comment, a brace or JSON included, is free text.

Source code in comicbox/box/load.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def is_comic_book_info(text: Any) -> bool:
    """
    Tell a ComicBookInfo comment from free text.

    It is ComicBookInfo only as JSON with ComicBookInfo's root key: any
    other comment, a brace or JSON included, is free text.
    """
    from comicbox.formats.comic_book_info.schema import ComicBookInfoSchema

    if isinstance(text, bytes):
        text = text.decode(errors="replace")
    try:
        data = json.loads(text)
    except (TypeError, ValueError):
        return False
    return isinstance(data, dict) and ComicBookInfoSchema.ROOT_DATA_KEY in data