File: fabioutils.py

package info (click to toggle)
python-fabio 0.11.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 9,092 kB
  • sloc: python: 19,244; ansic: 1,085; makefile: 219; sh: 215
file content (715 lines) | stat: -rw-r--r-- 22,516 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
# coding: utf-8
#
#    Project: X-ray image reader
#             https://github.com/silx-kit/fabio
#
#
#    Copyright (C) European Synchrotron Radiation Facility, Grenoble, France
#
#    Principal author:       Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)
#
#  Permission is hereby granted, free of charge, to any person
#  obtaining a copy of this software and associated documentation files
#  (the "Software"), to deal in the Software without restriction,
#  including without limitation the rights to use, copy, modify, merge,
#  publish, distribute, sublicense, and/or sell copies of the Software,
#  and to permit persons to whom the Software is furnished to do so,
#  subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be
#  included in all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
#  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
#  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
#  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
#  OTHER DEALINGS IN THE SOFTWARE.

#
"""General purpose utilities functions for fabio

"""

__author__ = "Jérôme Kieffer"
__contact__ = "Jerome.Kieffer@ESRF.eu"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
__date__ = "03/11/2020"
__status__ = "stable"
__docformat__ = 'restructuredtext'

import re
import os
import logging
import sys
import json

logger = logging.getLogger(__name__)

from collections import OrderedDict as _OrderedDict

try:
    import pathlib
except ImportError:
    try:
        import pathlib2 as pathlib
    except ImportError:
        pathlib = None

StringTypes = (str, bytes)
from io import FileIO, BytesIO as _BytesIO


def to_str(s):
    return str(s, "ASCII")


PathTypes = StringTypes
if pathlib is not None:
    PathTypes += (pathlib.PurePath,)

from .compression import bz2, gzip, COMPRESSORS
import traceback
from math import ceil

import threading

dictAscii = {None: [chr(i) for i in range(32, 127)]}


def pad(mystr, pattern=" ", size=80):
    """
    Performs the padding of the string to the right size with the right pattern

    :param mystr: input string
    :param pattern: the filling pattern
    :param size: the size of the block
    :return: the padded string to a multiple of size
    """
    size = int(size)
    padded_size = (len(mystr) + size - 1) // size * size
    if len(pattern) == 1:
        return mystr.ljust(padded_size, pattern)
    else:
        return (mystr + pattern * int(ceil(float(padded_size - len(mystr)) / len(pattern))))[:padded_size]


def getnum(name):
    """
    # try to figure out a file number
    # guess it starts at the back
    """
    _stem, num, _post_num = numstem(name)
    try:
        return int(num)
    except ValueError:
        return None


COMPRESSED_EXTENSIONS = set(["gz", "bz2"])
"""Set of compressed file extensions provided by Fabio"""


class FilenameObject(object):
    """
    The 'meaning' of a filename ...
    """

    def __init__(self, stem=None,
                 num=None,
                 directory=None,
                 format_=None,
                 extension=None,
                 postnum=None,
                 digits=4,
                 filename=None):
        """
        This class can either be instanciated by a set of parameters like  directory, prefix, num, extension, ...

        :param stem: the stem is a kind of prefix (str)
        :param num: image number in the serie (int)
        :param directory: name of the directory (str)
        :param format_: ??
        :param extension:
        :param postnum:
        :param digits: Number of digits used to print num

        Alternative constructor:

        :param filename: fullpath of an image file to be deconstructed into directory, prefix, num, extension, ...

        """
        self.stem = stem
        self.num = num
        self.format = format_
        self.extension = extension
        self.digits = digits
        self.postnum = postnum
        self.directory = directory
        self.compressed = None
        if filename is not None:
            self.deconstruct_filename(filename)

    def str(self):
        """ Return a string representation """
        fmt = "stem %s, num %s format %s extension %s " + \
              "postnum = %s digits %s dir %s"
        attrs = [self.stem,
                 self.num,
                 self.format,
                 self.extension,
                 self.postnum,
                 self.digits,
                 self.directory]
        return fmt % tuple([str(x) for x in attrs])

    __repr__ = str

    def tostring(self):
        """
        convert yourself to a string
        """
        name = self.stem
        if self.digits is not None and self.num is not None:
            fmt = "%0" + str(self.digits) + "d"
            name += fmt % self.num
        if self.postnum is not None:
            name += self.postnum
        if self.extension is not None:
            name += self.extension
        if self.directory is not None:
            name = os.path.join(self.directory, name)
        return name

    def deconstruct_filename(self, filename):
        """
        Break up a filename to get image type and number
        """
        from . import fabioformats
        direc, name = os.path.split(filename)
        direc = direc or None
        parts = name.split(".")
        compressed = False
        stem = parts[0]
        extn = ""
        postnum = ""
        ndigit = 4
        num = None
        typ = None
        if parts[-1].lower() in COMPRESSED_EXTENSIONS:
            extn = "." + parts[-1]
            parts = parts[:-1]
            compressed = True
        codec_classes = fabioformats.get_classes_from_extension(parts[-1])
        if len(codec_classes) > 0:
            typ = []
            for codec in codec_classes:
                name = codec.codec_name()
                if name.endswith("image"):
                    name = name[:-5]
                typ.append(name)
            extn = "." + parts[-1] + extn
            try:
                stem, numstring, postnum = numstem(".".join(parts[:-1]))
                num = int(numstring)
                ndigit = len(numstring)
            except Exception as err:
                # There is no number - hence make num be None, not 0
                logger.debug("l242: %s" % err)
                num = None
                stem = "".join(parts[:-1])
        else:
            # Probably two type left
            if len(parts) == 1:
                # Probably GE format stem_numb
                parts2 = parts[0].split("_")
                if parts2[-1].isdigit():
                    num = int(parts2[-1])
                    ndigit = len(parts2[-1])
                    typ = ['GE']
                    stem = "_".join(parts2[:-1]) + "_"
            else:
                try:
                    num = int(parts[-1])
                    ndigit = len(parts[-1])
                    typ = ['bruker']
                    stem = ".".join(parts[:-1]) + "."
                except Exception as err:
                    logger.debug("l262: %s" % err)
                    typ = None
                    extn = "." + parts[-1] + extn
                    numstring = ""
                    try:
                        stem, numstring, postnum = numstem(".".join(parts[:-1]))
                    except Exception as err:
                        logger.debug("l269: %s" % err)
                        raise
                    if numstring.isdigit():
                        num = int(numstring)
                        ndigit = len(numstring)
                #            raise Exception("Cannot decode "+filename)

        self.codec_classes = codec_classes
        self.stem = stem
        self.num = num
        self.directory = direc
        self.format = typ
        self.extension = extn
        self.postnum = postnum
        self.digits = ndigit
        self.compressed = compressed


def numstem(name):
    """ cant see how to do without reversing strings
    Match 1 or more digits going backwards from the end of the string
    """
    reg = re.compile(r"^(.*?)(-?[0-9]{0,9})(\D*)$")
    # reg = re.compile("""(\D*)(\d\d*)(\w*)""")
    try:
        res = reg.match(name).groups()
        # res = reg.match(name[::-1]).groups()
        # return [ r[::-1] for r in res[::-1]]
        if len(res[0]) == len(res[1]) == 0:  # Hack for file without number
            return [res[2], '', '']
        return [r for r in res]
    except AttributeError:  # no digits found
        return [name, "", ""]


# @deprecated
def deconstruct_filename(filename):
    """
    Function for backward compatibility.
    Deprecated
    """
    return FilenameObject(filename=filename)


def construct_filename(filename, frame=None):
    "Try to construct the filename for a given frame"
    fobj = FilenameObject(filename=filename)
    if frame is not None:
        fobj.num = frame
    return fobj.tostring()


def next_filename(name, padding=True):
    """ increment number """
    fobj = FilenameObject(filename=name)
    fobj.num += 1
    if not padding:
        fobj.digits = 0
    return fobj.tostring()


def previous_filename(name, padding=True):
    """ decrement number """
    fobj = FilenameObject(filename=name)
    fobj.num -= 1
    if not padding:
        fobj.digits = 0
    return fobj.tostring()


def jump_filename(name, num, padding=True):
    """ jump to number """
    fobj = FilenameObject(filename=name)
    fobj.num = num
    if not padding:
        fobj.digits = 0
    return fobj.tostring()


def extract_filenumber(name):
    """ extract file number """
    fobj = FilenameObject(filename=name)
    return fobj.num


def isAscii(name, listExcluded=None):
    """
    :param name: string to check
    :param listExcluded: list of char or string excluded.
    :return: True of False whether  name is pure ascii or not
    """
    isascii = None
    try:
        name.encode("ASCII")
    except UnicodeDecodeError:
        isascii = False
    else:
        if listExcluded:
            isascii = not(any(bad in name for bad in listExcluded))
        else:
            isascii = True
    return isascii


def toAscii(name, excluded=None):
    """
    :param name: string to check
    :param excluded: tuple of char or string excluded (not list: they are mutable).
    :return: the name with all non valid char removed
    """
    if excluded not in dictAscii:
        ascii = dictAscii[None][:]
        for i in excluded:
            if i in ascii:
                ascii.remove(i)
            else:
                logger.error("toAscii: %s not in ascii table" % i)
        dictAscii[excluded] = ascii
    else:
        ascii = dictAscii[excluded]
    out = [i for i in str(name) if i in ascii]
    return "".join(out)


def nice_int(s):
    """
    Workaround that int('1.0') raises an exception

    :param s: string to be converted to integer
    """
    try:
        return int(s)
    except ValueError:
        return int(float(s))


class BytesIO(_BytesIO):
    """
    just an interface providing the name and mode property to a BytesIO

    BugFix for MacOSX mainly
    """

    def __init__(self, data, fname=None, mode="r"):
        _BytesIO.__init__(self, data)
        if "closed" not in dir(self):
            self.closed = False
        if fname is None:
            self.name = "fabioStream"
        else:
            self.name = fname
        self.mode = mode
        self.lock = threading.Semaphore()
        self.__size = None

    def getSize(self):
        if self.__size is None:
            logger.debug("Measuring size of %s" % self.name)
            with self.lock:
                pos = self.tell()
                self.seek(0, os.SEEK_END)
                self.__size = self.tell()
                self.seek(pos)
        return self.__size

    def setSize(self, size):
        self.__size = size

    size = property(getSize, setSize)


class File(FileIO):
    """
    wrapper for "file" with locking
    """

    def __init__(self, name, mode="rb", temporary=False):
        """file(name[, mode[, buffering]]) -> file object

        Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
        writing or appending.  The file will be created if it doesn't exist
        when opened for writing or appending; it will be truncated when
        opened for writing.  Add a 'b' to the mode for binary files.
        Add a '+' to the mode to allow simultaneous reading and writing.
        If the buffering argument is given, 0 means unbuffered, 1 means line
        buffered, and larger numbers specify the buffer size.  The preferred way
        to open a file is with the builtin open() function.
        Add a 'U' to mode to open the file for input with universal newline
        support.  Any line ending in the input file will be seen as a '\n'
        in Python.  Also, a file so opened gains the attribute 'newlines';
        the value for this attribute is one of None (no newline read yet),
        '\r', '\n', '\r\n' or a tuple containing all the newline types seen.

        'U' cannot be combined with 'w' or '+' mode.

        :param temporary: if True, destroy file at close.
        """
        FileIO.__init__(self, name, mode)
        self.lock = threading.Semaphore()
        self.__size = None
        self.__temporary = temporary

    def __del__(self):
        """Explicit close at deletion
        """
        if hasattr(self, "closed") and not self.closed:
            self.close()

    def close(self):
        name = self.name
        FileIO.close(self)
        if self.__temporary:
            try:
                os.unlink(name)
            except Exception as err:
                logger.error("Unable to remove %s: %s" % (name, err))
                raise(err)

    def getSize(self):
        if self.__size is None:
            logger.debug("Measuring size of %s" % self.name)
            with self.lock:
                pos = self.tell()
                self.seek(0, os.SEEK_END)
                self.__size = self.tell()
                self.seek(pos)
        return self.__size

    def setSize(self, size):
        self.__size = size

    size = property(getSize, setSize)

    def __enter__(self):
        return self

    def __exit__(self, *args):
        """
        Close the file.
        """
        return FileIO.close(self)


class UnknownCompressedFile(File):
    """
    wrapper for "File" with locking
    """

    def __init__(self, name, mode="rb", buffering=0):
        logger.warning("No decompressor found for this type of file (are gzip anf bz2 installed ???")
        File.__init__(self, name, mode, buffering)

    def __del__(self):
        """Explicit close at deletion
        """
        if hasattr(self, "closed") and not self.closed:
            self.close()


if gzip is None:
    GzipFile = UnknownCompressedFile
else:

    class GzipFile(gzip.GzipFile):
        """
        Just a wrapper for gzip.GzipFile providing the correct seek capabilities for python 2.5
        """

        def __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None):
            """
            Wrapper with locking for constructor for the GzipFile class.

            At least one of fileobj and filename must be given a
            non-trivial value.

            The new class instance is based on fileobj, which can be a regular
            file, a StringIO object, or any other object which simulates a file.
            It defaults to None, in which case filename is opened to provide
            a file object.

            When fileobj is not None, the filename argument is only used to be
            included in the gzip file header, which may includes the original
            filename of the uncompressed file.  It defaults to the filename of
            fileobj, if discernible; otherwise, it defaults to the empty string,
            and in this case the original filename is not included in the header.

            The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb',
            depending on whether the file will be read or written.  The default
            is the mode of fileobj if discernible; otherwise, the default is 'rb'.
            Be aware that only the 'rb', 'ab', and 'wb' values should be used
            for cross-platform portability.

            The compresslevel argument is an integer from 1 to 9 controlling the
            level of compression; 1 is fastest and produces the least compression,
            and 9 is slowest and produces the most compression.  The default is 9.
            """
            gzip.GzipFile.__init__(self, filename, mode, compresslevel, fileobj)
            self.lock = threading.Semaphore()
            self.__size = None

        def __del__(self):
            """Explicit close at deletion
            """
            if hasattr(self, "closed") and not self.closed:
                self.close()

        def __repr__(self):
            return "fabio." + gzip.GzipFile.__repr__(self)

        def measure_size(self):
            if self.mode == gzip.WRITE:
                return self.size
            if self.__size is None:
                with self.lock:
                    if self.__size is None:
                        if "offset" in dir(self):
                            pos = self.offset
                        elif "tell" in dir(self):
                            pos = self.tell()
                        end_pos = len(gzip.GzipFile.read(self)) + pos
                        self.seek(pos)
                        logger.debug("Measuring size of %s: %s @ %s == %s" % (self.name, end_pos, pos, pos))
                        self.__size = end_pos
            return self.__size

    def __enter__(self):
        return self

    def __exit__(self, *args):
        """
        Close the file.
        """
        gzip.GzipFile.close(self)

if bz2 is None:
    BZ2File = UnknownCompressedFile
else:

    class BZ2File(bz2.BZ2File):
        "Wrapper with lock"

        def __init__(self, name, mode='r', compresslevel=9):
            """
            BZ2File(name [, mode='r', compresslevel=9]) -> file object

            Open a bz2 file. The mode can be 'r' or 'w', for reading (default) or
            writing. When opened for writing, the file will be created if it doesn't
            exist, and truncated otherwise.

            If compresslevel is given, must be a number between 1 and 9.

            Add a 'U' to mode to open the file for input with universal newline
            support. Any line ending in the input file will be seen as a '\n' in
            Python. Also, a file so opened gains the attribute 'newlines'; the value
            for this attribute is one of None (no newline read yet), '\r', '\n',
            '\r\n' or a tuple containing all the newline types seen. Universal
            newlines are available only when reading.
            """
            bz2.BZ2File.__init__(self, name, mode, compresslevel=compresslevel)
            self.lock = threading.Semaphore()
            self.__size = None

        def __del__(self):
            """Explicit close at deletion
            """
            if hasattr(self, "closed") and not self.closed:
                self.close()

        def getSize(self):
            if self.__size is None:
                logger.debug("Measuring size of %s" % self.name)
                with self.lock:
                    pos = self.tell()
                    _ = self.read()
                    self.__size = self.tell()
                    self.seek(pos)
            return self.__size

        def setSize(self, value):
            self.__size = value

        size = property(getSize, setSize)

        def __enter__(self):
            return self

        def __exit__(self, *args):
            """
            Close the file at exit
            """
            bz2.BZ2File.close(self)


class NotGoodReader(RuntimeError):
    """The reader used is probably not the good one
    """
    pass


class DebugSemaphore(threading.Semaphore):
    """
    threading.Semaphore like class with helper for fighting dead-locks
    """
    write_lock = threading.Semaphore()
    blocked = []

    def __init__(self, *arg, **kwarg):
        threading.Semaphore.__init__(self, *arg, **kwarg)

    def acquire(self, *arg, **kwarg):
        if self._Semaphore__value == 0:
            with self.write_lock:
                self.blocked.append(id(self))
                sys.stderr.write(os.linesep.join(["Blocking sem %s" % id(self)] +
                                 traceback.format_stack()[:-1] + [""]))

        return threading.Semaphore.acquire(self, *arg, **kwarg)

    def release(self, *arg, **kwarg):
        with self.write_lock:
            uid = id(self)
            if uid in self.blocked:
                self.blocked.remove(uid)
                sys.stderr.write("Released sem %s %s" % (uid, os.linesep))
        threading.Semaphore.release(self, *arg, **kwarg)

    def __enter__(self):
        self.acquire()
        return self

    def __exit__(self, *arg, **kwarg):
        self.release()


def exists(path):
    """Test whether a path exists.

    Replaces os.path.exists and handles in addition "::" based URI as defined in
    http://odo.pydata.org/en/latest/uri.html#separating-parts-with

    :param path: string
    :return: boolean
    """
    return os.path.exists(path.split("::")[0])


class OrderedDict(_OrderedDict):
    """Ordered dictionary with pretty print"""

    def __repr__(self):
        try:
            res = json.dumps(self, indent=2)
        except Exception as err:
            logger.warning("Header is not JSON-serializable: %s", err)
            tmp = _OrderedDict()
            for key, value in self.items():
                tmp[str(key)] = str(value)
            res = json.dumps(tmp, indent=2)
        return res


AVAILABLE_COMPRESSED_EXTENSIONS = set([])
"""Set of available compressed file extensions. Do not contains extensions for
uninstalled optional dependancies."""
if GzipFile != UnknownCompressedFile:
    AVAILABLE_COMPRESSED_EXTENSIONS.add("gz")
if BZ2File != UnknownCompressedFile:
    AVAILABLE_COMPRESSED_EXTENSIONS.add("bz2")