Passed
Push — master ( 0ea71f...5b7c9f )
by Konstantin
03:16
created

ocrd_utils.str.batched()   A

Complexity

Conditions 3

Size

Total Lines 8
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nop 2
1
"""
2
Utility functions for strings, paths and URL.
3
"""
4
5
import re
6
import json
7
from .constants import REGEX_FILE_ID
8
from .deprecate import deprecation_warning
9
from warnings import warn
10
from numpy import array_split
11
12
__all__ = [
13
    'assert_file_grp_cardinality',
14
    'concat_padded',
15
    'get_local_filename',
16
    'is_local_filename',
17
    'partition_list',
18
    'is_string',
19
    'make_file_id',
20
    'nth_url_segment',
21
    'parse_json_string_or_file',
22
    'parse_json_string_with_comments',
23
    'remove_non_path_from_url',
24
    'safe_filename',
25
]
26
27
28
def assert_file_grp_cardinality(grps, n, msg=None):
29
    """
30
    Assert that a string of comma-separated fileGrps contains exactly ``n`` entries.
31
    """
32
    if isinstance(grps, str):
33
        grps = grps.split(',')
34
    assert len(grps) == n, \
35
            "Expected exactly %d output file group%s%s, but '%s' has %d" % (
36
                n,
37
                '' if n == 1 else 's',
38
                ' (%s)' % msg if msg else '',
39
                grps,
40
                len(grps)
41
            )
42
43
def concat_padded(base, *args):
44
    """
45
    Concatenate string and zero-padded 4 digit number
46
    """
47
    ret = base
48
    for n in args:
49
        if is_string(n):
50
            ret = "%s_%s" % (ret, n)
51
        else:
52
            ret = "%s_%04i"  % (ret, n)
53
    return ret
54
55
def remove_non_path_from_url(url):
56
    """
57
    Remove everything from URL after path.
58
    """
59
    url = url.split('?', 1)[0]    # query
60
    url = url.split('#', 1)[0]    # fragment identifier
61
    url = re.sub(r"/+$", "", url) # trailing slashes
62
    return url
63
64
def make_file_id(ocrd_file, output_file_grp):
65
    """
66
    Derive a new file ID for an output file from an existing input file ``ocrd_file``
67
    and the name of the output file's ``fileGrp/@USE``, ``output_file_grp``.
68
    If ``ocrd_file``'s ID contains the input file's fileGrp name, then replace it by ``output_file_grp``.
69
    Else if ``ocrd_file`` has a ``pageId`` but it is not contained in the ``ocrd_file.ID``, then
70
        concatenate ``output_file_grp`` and ``ocrd_file.pageId``.
71
    Otherwise concatenate ``output_file_grp`` with the ``ocrd_file.ID``.
72
73
    Note: ``make_file_id`` cannot guarantee that the new ID is unique within an actual
74
    :py:class:`ocrd_models.ocrd_mets.OcrdMets`.
75
    The caller is responsible for ensuring uniqueness of files to be added.
76
    Ultimately, ID conflicts will lead to :py:meth:`ocrd_models.ocrd_mets.OcrdMets.add_file`
77
    raising an exception.
78
    This can be avoided if all processors use ``make_file_id`` consistently for ID generation.
79
80
    Note: ``make_file_id`` generates page-specific IDs. For IDs representing page segments
81
    or ``pc:AlternativeImage`` files, the output of ``make_file_id`` may need to be concatenated
82
    with a unique string for that sub-page element, such as `".IMG"` or the segment ID.
83
    """
84
    # considerations for this behaviour:
85
    # - uniqueness (in spite of different METS and processor conventions)
86
    # - predictability (i.e. output name can be anticipated from the input name)
87
    # - stability (i.e. output at least as much sorted and consistent as the input)
88
    # ... and all this in spite of --page-id selection and --overwrite
89
    # (i.e. --overwrite should target the existing ID, and input vs output
90
    #  IDs should be different, except when overwriting the input fileGrp)
91
    ret = ocrd_file.ID.replace(ocrd_file.fileGrp, output_file_grp)
92
    if ret == ocrd_file.ID and output_file_grp != ocrd_file.fileGrp:
93
        if ocrd_file.pageId and ocrd_file.pageId not in ocrd_file.ID:
94
            ret = output_file_grp + '_' + ocrd_file.pageId
95
        else:
96
            ret = output_file_grp + '_' + ocrd_file.ID
97
    if not REGEX_FILE_ID.fullmatch(ret):
98
        ret = ret.replace(':', '_')
99
        ret = re.sub(r'^([^a-zA-Z_])', r'id_\1', ret)
100
        ret = re.sub(r'[^\w.-]', r'', ret)
101
    return ret
102
103
def nth_url_segment(url, n=-1):
104
    """
105
    Return the last /-delimited segment of a URL-like string
106
107
    Arguments:
108
        url (string):
109
        n (integer): index of segment, default: -1
110
    """
111
    segments = remove_non_path_from_url(url).split('/')
112
    try:
113
        return segments[n]
114
    except IndexError:
115
        return ''
116
117
def get_local_filename(url, start=None):
118
    """
119
    Return local filename, optionally relative to ``start``
120
121
    Arguments:
122
        url (string): filename or URL
123
        start (string): Base path to remove from filename. Raise an exception if not a prefix of url
124
    """
125
    if url.startswith('https://') or url.startswith('http:'):
126
        raise ValueError("Can't determine local filename of http(s) URL")
127
    if url.startswith('file://'):
128
        url = url[len('file://'):]
129
    # Goobi/Kitodo produces those, they are always absolute
130
    if url.startswith('file:/'):
131
        url = url[len('file:'):]
132
    if start:
133
        if not url.startswith(start):
134
            raise ValueError("Cannot remove prefix %s from url %s" % (start, url))
135
        if not start.endswith('/'):
136
            start += '/'
137
        url = url[len(start):]
138
    return url
139
140
def is_local_filename(url):
141
    """
142
    Whether a url is a local filename.
143
    """
144
    # deprecation_warning("Deprecated so we spot inconsistent URL/file handling")
145
    return url.startswith('file://') or not('://' in url)
146
147
def is_string(val):
148
    """
149
    Return whether a value is a ``str``.
150
    """
151
    return isinstance(val, str)
152
153
154
def parse_json_string_with_comments(val):
155
    """
156
    Parse a string of JSON interspersed with #-prefixed full-line comments
157
    """
158
    jsonstr = re.sub(r'^\s*#.*$', '', val, flags=re.MULTILINE)
159
    return json.loads(jsonstr)
160
161
def parse_json_string_or_file(*values):    # pylint: disable=unused-argument
162
    """
163
    Parse a string as either the path to a JSON object or a literal JSON object.
164
165
    Empty strings are equivalent to '{}'
166
    """
167
    ret = {}
168
    for value in values:
169
        err = None
170
        value_parsed = None
171
        if re.fullmatch(r"\s*", value):
172
            continue
173
        try:
174
            try:
175
                with open(value, 'r') as f:
176
                    value_parsed = parse_json_string_with_comments(f.read())
177
            except (FileNotFoundError, OSError):
178
                value_parsed = parse_json_string_with_comments(value.strip())
179
            if not isinstance(value_parsed, dict):
180
                err = ValueError("Not a valid JSON object: '%s' (parsed as '%s')" % (value, value_parsed))
181
        except json.decoder.JSONDecodeError as e:
182
            err = ValueError("Error parsing '%s': %s" % (value, e))
183
        if err:
184
            raise err       # pylint: disable=raising-bad-type
185
        ret = {**ret, **value_parsed}
186
    return ret
187
188
def safe_filename(url):
189
    """
190
    Sanitize input to be safely used as the basename of a local file.
191
    """
192
    ret = re.sub(r'[^\w]+', '_', url)
193
    ret = re.sub(r'^\.*', '', ret)
194
    ret = re.sub(r'\.\.*', '.', ret)
195
    #  print('safe filename: %s -> %s' % (url, ret))
196
    return ret
197
198
def generate_range(start, end):
199
    """
200
    Generate a list of strings by incrementing the number part of ``start`` until including ``end``.
201
    """
202
    ret = []
203
    try:
204
        start_num, end_num = re.findall(r'\d+', start)[-1], re.findall(r'\d+', end)[-1]
205
    except IndexError:
206
        raise ValueError("Range '%s..%s': could not find numeric part" % (start, end))
207
    if start_num == end_num:
208
        warn("Range '%s..%s': evaluates to the same number")
209
    for i in range(int(start_num), int(end_num) + 1):
210
        ret.append(start.replace(start_num, str(i).zfill(len(start_num))))
211
    return ret
212
213
214
def partition_list(lst, chunks, chunk_index=None):
215
    """
216
    Partition a list into roughly equally-sized chunks
217
218
    Args:
219
        lst (list): list to partition
220
        chunks (int): number of chunks to generate (not per chunk!)
221
222
    Keyword Args:
223
        chunk_index (None|int): If provided, return only a list consisting of this chunk
224
225
    Returns:
226
        list(list())
227
    """
228
    if not lst:
229
        return []
230
    # Catch potential empty ranges returned by numpy.array_split
231
    #  which are problematic in the ocr-d scope
232
    if chunks > len(lst):
233
        raise ValueError("Amount of chunks bigger than list size")
234
    ret = [x.tolist() for x in array_split(lst, chunks)]
235
    if chunk_index is not None:
236
        return [ret[chunk_index]]
237
    return ret
238