|
| 1 | +# Copyright (c) 2026, Inria |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# Redistribution and use in source and binary forms, with or without |
| 5 | +# modification, are permitted provided that the following conditions are met: |
| 6 | +# |
| 7 | +# * Redistributions of source code must retain the above copyright notice, this |
| 8 | +# list of conditions and the following disclaimer. |
| 9 | +# |
| 10 | +# * Redistributions in binary form must reproduce the above copyright notice, |
| 11 | +# this list of conditions and the following disclaimer in the documentation |
| 12 | +# and/or other materials provided with the distribution. |
| 13 | +# |
| 14 | +# * Neither the name of the copyright holder nor the names of its |
| 15 | +# contributors may be used to endorse or promote products derived from |
| 16 | +# this software without specific prior written permission. |
| 17 | +# |
| 18 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 19 | +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 20 | +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 21 | +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE |
| 22 | +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 23 | +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| 24 | +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| 25 | +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 26 | +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 27 | +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 28 | + |
| 29 | +from abc import ABC, abstractmethod |
| 30 | +from io import TextIOWrapper |
| 31 | +from pathlib import Path |
| 32 | +from typing import Literal, TextIO, ClassVar |
| 33 | + |
| 34 | + |
| 35 | +_OPEN_MODES = Literal['r', 'w'] |
| 36 | + |
| 37 | +class FileHandler(ABC): |
| 38 | + """ |
| 39 | + Base class for JSON file opening strategies. |
| 40 | + """ |
| 41 | + compression_method: str = '' |
| 42 | + supported_suffixes: tuple[str, ...] = () |
| 43 | + |
| 44 | + @classmethod |
| 45 | + @abstractmethod |
| 46 | + def open(cls, filepath: Path, mode: _OPEN_MODES) -> TextIO: |
| 47 | + """ |
| 48 | + Open a file as a UTF-8 text stream using the handler strategy. |
| 49 | + :param filepath: Path to the file to open |
| 50 | + :param mode: Text mode used to open the file |
| 51 | + :return: Open text stream |
| 52 | + """ |
| 53 | + ... |
| 54 | + |
| 55 | + |
| 56 | +class RawFileHandler(FileHandler): |
| 57 | + """ |
| 58 | + File handler for uncompressed JSON files. |
| 59 | + """ |
| 60 | + compression_method = 'none' |
| 61 | + supported_suffixes = ('.jsonl', '.jsonlines', '.ndjson', '.json', '') |
| 62 | + |
| 63 | + @classmethod |
| 64 | + def open(cls, filepath: Path, mode: _OPEN_MODES) -> TextIO: |
| 65 | + return open(filepath, mode, encoding='utf-8') |
| 66 | + |
| 67 | + |
| 68 | +class GzipFileHandler(FileHandler): |
| 69 | + """ |
| 70 | + File handler for gzip-compressed JSON files. |
| 71 | + """ |
| 72 | + compression_method = 'gzip' |
| 73 | + supported_suffixes = ('.gz', '.gzip') |
| 74 | + |
| 75 | + @classmethod |
| 76 | + def open(cls, filepath: Path, mode: _OPEN_MODES) -> TextIO: |
| 77 | + from gzip import GzipFile |
| 78 | + gzip_file = GzipFile(filepath, mode) |
| 79 | + text_handler = TextIOWrapper(gzip_file, encoding='utf-8') |
| 80 | + return text_handler |
| 81 | + |
| 82 | + |
| 83 | +class LzmaFileHandler(FileHandler): |
| 84 | + """" |
| 85 | + File handler for lzma-compressed JSON files. |
| 86 | + """ |
| 87 | + compression_method = 'lzma' |
| 88 | + supported_suffixes = ('.xz', '.lzma') |
| 89 | + |
| 90 | + @classmethod |
| 91 | + def open(cls, filepath: Path, mode: _OPEN_MODES) -> TextIO: |
| 92 | + from lzma import LZMAFile |
| 93 | + lzma_file = LZMAFile(filepath, mode) |
| 94 | + text_handler = TextIOWrapper(lzma_file, encoding='utf-8') |
| 95 | + return text_handler |
| 96 | + |
| 97 | + |
| 98 | +class FileHandlerRegistry: |
| 99 | + """ |
| 100 | + Registry of JSON file handlers. |
| 101 | + """ |
| 102 | + _file_handlers: ClassVar[list[type[FileHandler]]] = [] |
| 103 | + |
| 104 | + @classmethod |
| 105 | + def register(cls, handler: type[FileHandler]) -> None: |
| 106 | + """ |
| 107 | + Register a file handler in lookup order. |
| 108 | + :param handler: Handler class to register |
| 109 | + """ |
| 110 | + cls._file_handlers.append(handler) |
| 111 | + |
| 112 | + @classmethod |
| 113 | + def _get_from_compression_method(cls, compression_method: str) -> type[FileHandler]: |
| 114 | + """ |
| 115 | + Retrieve a handler from its compression method name. |
| 116 | + :param compression_method: Name of the compression method to resolve |
| 117 | + :return: File handler matching the requested compression method |
| 118 | + :raises ValueError: If the compression method is not recognized |
| 119 | + """ |
| 120 | + for handler in cls._file_handlers: |
| 121 | + if handler.compression_method == compression_method: |
| 122 | + return handler |
| 123 | + |
| 124 | + raise ValueError(f'Unknown compression method: {compression_method}') |
| 125 | + |
| 126 | + @classmethod |
| 127 | + def _get_from_file_extension(cls, filepath: Path) -> type[FileHandler]: |
| 128 | + """ |
| 129 | + Infer a handler from the suffix of the given filepath. |
| 130 | + :param filepath: Path to the file |
| 131 | + :return: Handler matching the filepath suffix |
| 132 | + :raises ValueError: If the file extension is not recognized |
| 133 | + """ |
| 134 | + suffix = filepath.suffix.casefold() |
| 135 | + for handler in cls._file_handlers: |
| 136 | + if suffix in handler.supported_suffixes: |
| 137 | + return handler |
| 138 | + |
| 139 | + raise ValueError(f'Unknown file extension for: {filepath}') |
| 140 | + |
| 141 | + @classmethod |
| 142 | + def get(cls, compression_method: str, filepath: Path) -> type[FileHandler]: |
| 143 | + """ |
| 144 | + Resolve the file handler for a JSON file. |
| 145 | +
|
| 146 | + When the ``compression_method`` parameter is ``auto``, the handler is inferred from the filepath suffix. |
| 147 | + Otherwise, the compression method is resolved explicitly. |
| 148 | +
|
| 149 | + :param compression_method: Compression method name or ``auto`` |
| 150 | + :param filepath: Path to the file associated with the handler lookup |
| 151 | + :return: Matching file handler |
| 152 | + :raises ValueError: If no handler matches the requested method or file suffix |
| 153 | + """ |
| 154 | + method = compression_method.casefold() |
| 155 | + if method == 'auto': |
| 156 | + handler = cls._get_from_file_extension(filepath) |
| 157 | + else: |
| 158 | + handler = cls._get_from_compression_method(method) |
| 159 | + |
| 160 | + return handler |
| 161 | + |
| 162 | + |
| 163 | +FileHandlerRegistry.register(RawFileHandler) |
| 164 | +FileHandlerRegistry.register(GzipFileHandler) |
| 165 | +FileHandlerRegistry.register(LzmaFileHandler) |
0 commit comments