File: tools.py

package info (click to toggle)
pdf2djvu 0.9.18.2-2.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,248 kB
  • sloc: cpp: 6,873; sh: 4,327; xml: 4,193; python: 1,104; makefile: 715; perl: 17
file content (361 lines) | stat: -rw-r--r-- 10,750 bytes parent folder | download | duplicates (2)
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
# encoding=UTF-8

# Copyright © 2009-2021 Jakub Wilk <jwilk@jwilk.net>
#
# This file is part of pdf2djvu.
#
# pdf2djvu is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# pdf2djvu is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.

from __future__ import print_function

import ast
import codecs
import collections
import inspect
import itertools
import locale
import os
import pipes
import re
import signal
import subprocess as ipc
import sys

from nose import SkipTest
from nose.tools import (
    assert_equal,
    assert_greater,
    assert_in,
    assert_is,
    assert_is_none,
    assert_is_not,
    assert_is_not_none,
    assert_multi_line_equal,
    assert_not_equal,
    assert_regexp_matches as assert_regex,
    assert_true,
)

if {0} and not isinstance(b'', str):  # Python 2.7 is required
    raise RuntimeError('Python 2.7 is required')

re_type = type(re.compile(''))

def assert_fail(msg):
    assert_true(False, msg=msg)  # pylint: disable=redundant-unittest-assert

type(assert_multi_line_equal.__self__).maxDiff = None

def _get_signal_names():
    signame_pattern = re.compile('^SIG[A-Z0-9]*$')
    data = dict(
        (name, getattr(signal, name))
        for name in dir(signal)
        if signame_pattern.match(name)
    )
    try:
        if data['SIGABRT'] == data['SIGIOT']:
            del data['SIGIOT']
    except KeyError:
        pass
    try:
        if data['SIGCHLD'] == data['SIGCLD']:
            del data['SIGCLD']
    except KeyError:
        pass
    return dict((no, name) for name, no in data.iteritems())

class _ipc_rc(int):

    _signal_names = _get_signal_names()

    def __repr__(self):
        try:
            return '-' + self._signal_names[-self]
        except KeyError:
            return str(self)

class ipc_result(object):

    def __init__(self, stdout, stderr, rc):
        self.stdout = stdout
        self.stderr = stderr
        self.rc = rc

    def assert_(self, stdout='', stderr='', rc=0):
        if stderr is None:
            pass
        elif isinstance(stderr, re_type):
            assert_regex(self.stderr, stderr)
        else:
            assert_multi_line_equal(self.stderr, stderr)
        if rc is not None:
            assert_equal(_ipc_rc(self.rc), _ipc_rc(rc))
        if stdout is None:
            pass
        elif isinstance(stdout, re_type):
            assert_regex(self.stdout, stdout)
        else:
            assert_multi_line_equal(self.stdout, stdout)

def _get_locale_for_encoding(encoding):
    encoding = codecs.lookup(encoding).name
    candidates = {
        'utf-8': ['C.UTF-8', 'en_US.UTF-8'],
        'iso8859-1': ['en_US.ISO8859-1'],
    }[encoding]
    old_locale = locale.setlocale(locale.LC_ALL)
    try:
        for new_locale in candidates:
            try:
                locale.setlocale(locale.LC_ALL, new_locale)
            except locale.Error:
                continue
            locale_encoding = locale.getpreferredencoding(False)
            locale_encoding = codecs.lookup(locale_encoding).name
            if encoding == locale_encoding:
                return new_locale
    finally:
        locale.setlocale(locale.LC_ALL, old_locale)
    raise SkipTest(
        'locale {loc} is required'.format(loc=' or '.join(candidates))
    )

class case(object):

    _pdf2djvu_command = os.getenv('pdf2djvu') or 'pdf2djvu'
    _feature_cache = {}
    _poppler_version = None

    def get_pdf2djvu_command(self):
        if re.compile(r'\A[a-zA-Z0-9_+/=.,:%-]+\Z').match(self._pdf2djvu_command):
            return (self._pdf2djvu_command,)
        return ('sh', '-c', self._pdf2djvu_command + ' "$@"', 'sh')

    def get_source_path(self, strip_py=False):
        result = inspect.getsourcefile(type(self))
        if strip_py and result.endswith('.py'):
            return result[:-3]
        return result

    def get_pdf_path(self):
        return self.get_source_path(strip_py=True) + '.pdf'

    def get_djvu_path(self):
        return self.get_source_path(strip_py=True) + '.djvu'

    def run(self, *commandline, **kwargs):
        env = dict(os.environ,
            MALLOC_CHECK_='3',
            MALLOC_PERTURB_=str(0xA5),
        )
        for key, value in kwargs.items():
            if key.isupper():
                env[key] = value
                continue
            if key == 'encoding':
                env['LC_ALL'] = _get_locale_for_encoding(value)
                continue
            raise TypeError('{key!r} is an invalid keyword argument for this function'.format(key=key))
        env['LANGUAGE'] = 'en'
        print('$', ' '.join(map(pipes.quote, commandline)))
        try:
            child = ipc.Popen(list(commandline),
                stdout=ipc.PIPE,
                stderr=ipc.PIPE,
                env=env,
            )
        except OSError as exc:
            exc.filename = commandline[0]
            raise
        stdout, stderr = child.communicate()
        return ipc_result(stdout, stderr, child.returncode)

    def _pdf2djvu(self, *args, **kwargs):
        quiet = ('-q',) if kwargs.pop('quiet', True) else ()
        args = self.get_pdf2djvu_command() + quiet + (self.get_pdf_path(),) + args
        result = self.run(*args, **kwargs)
        if os.getenv('pdf2djvu_win32'):
            result.stderr = result.stderr.replace('\r\n', '\n')
        if sys.platform.startswith('openbsd'):
            # FIXME: https://github.com/jwilk/pdf2djvu/issues/108
            result.stderr = re.compile(
                r'Magick: Failed to close module [(]"\w*: Invalid handle\"[)].\n'
            ).sub('', result.stderr)
        return result

    def pdf2djvu(self, *args, **kwargs):
        return self._pdf2djvu('-o', self.get_djvu_path(), *args, **kwargs)

    def pdf2djvu_indirect(self, *args):
        return self._pdf2djvu('-i', self.get_djvu_path(), *args)

    def djvudump(self, *args):
        return self.run('djvudump', self.get_djvu_path(), *args)

    def djvused(self, expr, **kwargs):
        return self.run(
            'djvused',
            '-e', expr,
            self.get_djvu_path(),
            **kwargs
        )

    def print_text(self):
        return self.run('djvutxt', self.get_djvu_path())

    def print_outline(self):
        return self.djvused('print-outline')

    def print_ant(self, page):
        return self.djvused('select {0}; print-ant'.format(page))

    def print_meta(self):
        return self.djvused('print-meta')

    def ls(self):
        return self.djvused('ls', encoding='UTF-8')

    def decode(self, mode=None):
        args = []
        if mode is not None:
            args += ['-mode={m}'.format(m=mode)]
        return self.run(
            'ddjvu',
            self.get_djvu_path(),
            '-format=ppm',
            '-subsample=1',
            *args
        )

    def extract_xmp(self):
        r = self.djvused('output-ant')
        assert_equal(r.stderr, '')
        assert_equal(r.rc, 0)
        xmp_lines = [line for line in r.stdout.splitlines() if line.startswith('(xmp "')]
        if not xmp_lines:
            return None
        [xmp_line] = xmp_lines
        assert_equal(xmp_line[-2:], '")')
        xmp = xmp_line[5:-1]
        xmp = ast.literal_eval(xmp)
        return xmp

    def require_poppler(self, *version):
        if self._poppler_version is None:
            r = self.pdf2djvu('--version')
            r.assert_(stderr=re.compile('^pdf2djvu '), rc=0)
            print(r.stderr)
            match = re.compile('^[+] Poppler ([0-9.]+)$', re.M).search(r.stderr)
            self._poppler_version = tuple(int(x) for x in match.group(1).split('.'))
        if self._poppler_version < version:
            str_version = '.'.join(str(v) for v in version)
            raise SkipTest('Poppler >= {ver} is required'.format(ver=str_version))

    def require_feature(self, feature):
        try:
            feature_enabled = self._feature_cache[feature]
        except KeyError:
            if feature == 'POSIX':
                feature_enabled = not os.getenv('pdf2djvu_win32')
            else:
                r = self.pdf2djvu('--version')
                r.assert_(stdout=re.compile('^pdf2djvu '), rc=0)
                feature_enabled = feature in r.stdout
            self._feature_cache[feature] = feature_enabled
        if not feature_enabled:
            raise SkipTest(feature + ' support missing')

def rainbow(width, height):
    from PIL import Image
    from PIL import ImageColor
    image = Image.new('RGB', (width, height))
    pixels = image.load()
    for x in xrange(width):
        for y in xrange(height):
            hue = 255 * x // (width - 1)
            luminance = 100 * y // height
            color = ImageColor.getrgb('hsl({hue}, 100%, {lum}%)'.format(hue=hue, lum=luminance))
            pixels[x, y] = color
    return image

def checkboard(width, height):
    from PIL import Image
    image = Image.new('1', (width, height))
    pixels = image.load()
    for x in xrange(width):
        for y in xrange(height):
            color = 0xFF * ((x ^ y) & 1)
            pixels[x, y] = color
    return image

_ppm_re = re.compile(r'P6\s+\d+\s+\d+\s+255\s(.*)\Z', re.DOTALL)
def count_ppm_colors(b):
    match = _ppm_re.match(b)
    assert_is_not_none(match)
    pixels = match.group(1)
    ipixels = iter(pixels)
    result = collections.defaultdict(int)
    for pixel in itertools.izip(ipixels, ipixels, ipixels):
        result[pixel] += 1
    return dict(
        (''.join(key), value)
        for key, value in result.iteritems()
    )

xml_ns = dict(
    dc='http://purl.org/dc/elements/1.1/',
    xmpMM='http://ns.adobe.com/xap/1.0/mm/',
)

def xml_find_text(xml, tag):
    [elem] = xml.findall('.//' + tag, xml_ns)
    return elem.text

_uuid_regex = (
    r'\Aurn:uuid:XXXXXXXX-XXXX-4XXX-[89ab]XXX-XXXXXXXXXXXX\Z'
    .replace('X', '[0-9a-f]')
)

def assert_uuid_urn(uuid):
    return assert_regex(
        uuid,
        _uuid_regex,
    )

__all__ = [
    # nose:
    'assert_equal',
    'assert_greater',
    'assert_in',
    'assert_is',
    'assert_is_none',
    'assert_is_not',
    'assert_is_not_none',
    'assert_multi_line_equal',
    'assert_not_equal',
    'assert_regex',
    'assert_true',
    # misc assert:
    'assert_fail',
    # helper classes:
    'ipc_result',
    'case',
    # image handling:
    'rainbow',
    'checkboard',
    'count_ppm_colors',
    # XMP:
    'assert_uuid_urn',
    'xml_find_text',
    'xml_ns',
]

# vim:ts=4 sts=4 sw=4 et