# Path: kraken/kraken.py
# @click.group(chain=True)
# @click.version_option()
# @click.option('-i', '--input',
#               type=(click.Path(exists=True),  # type: ignore
#                     click.Path(writable=True)),
#               multiple=True,
#               help='Input-output file pairs. Each input file (first argument) is mapped to one '
#                    'output file (second argument), e.g. `-i input.png output.txt`')
# @click.option('-I', '--batch-input', multiple=True, help='Glob expression to add multiple files at once.')
# @click.option('-o', '--suffix', default='', show_default=True,
#               help='Suffix for output files from batch and PDF inputs.')
# @click.option('-v', '--verbose', default=0, count=True, show_default=True)
# @click.option('-f', '--format-type', type=click.Choice(['image', 'alto', 'page', 'pdf', 'xml']), default='image',
#               help='Sets the default input type. In image mode inputs are image '
#                    'files, alto/page expects XML files in the respective format, pdf '
#                    'expects PDF files with numbered suffixes added to output file '
#                    'names as needed.')
# @click.option('-p', '--pdf-format', default='{src}_{idx:06d}',
#               show_default=True,
#               help='Format for output of PDF files. valid fields '
#                    'are `src` (source file), `idx` (page number), and `uuid` (v4 uuid). '
#                    '`-o` suffixes are appended to this format string.')
# @click.option('-h', '--hocr', 'serializer',
#               help='Switch between hOCR, ALTO, abbyyXML, PageXML or "native" '
#               'output. Native are plain image files for image, JSON for '
#               'segmentation, and text for transcription output.',
#               flag_value='hocr')
# @click.option('-a', '--alto', 'serializer', flag_value='alto')
# @click.option('-y', '--abbyy', 'serializer', flag_value='abbyyxml')
# @click.option('-x', '--pagexml', 'serializer', flag_value='pagexml')
# @click.option('-n', '--native', 'serializer', flag_value='native', default=True,
#               show_default=True)
# @click.option('-d', '--device', default='cpu', show_default=True,
#               help='Select device to use (cpu, cuda:0, cuda:1, ...)')
# @click.option('-r', '--raise-on-error/--no-raise-on-error', default=False, show_default=True,
#               help='Raises the exception that caused processing to fail in the case of an error')
# def cli(input, batch_input, suffix, verbose, format_type, pdf_format, serializer, device, raise_on_error):
#     """
#     Base command for recognition functionality.
# 
#     Inputs are defined as one or more pairs `-i input_file output_file`
#     followed by one or more chainable processing commands. Likewise, verbosity
#     is set on all subcommands with the `-v` switch.
#     """
#     ctx = click.get_current_context()
#     if device != 'cpu':
#         import torch
#         try:
#             torch.ones(1, device=device)
#         except AssertionError as e:
#             if raise_on_error:
#                 raise
#             logger.error(f'Device {device} not available: {e.args[0]}.')
#             ctx.exit(1)
#     ctx.meta['device'] = device
#     ctx.meta['input_format_type'] = format_type if format_type != 'pdf' else 'image'
#     ctx.meta['raise_failed'] = raise_on_error
#     ctx.meta['output_mode'] = serializer
#     ctx.meta['verbose'] = verbose
#     log.set_logger(logger, level=30 - min(10 * verbose, 20))


import os
import click
import unittest
import tempfile
import numpy as np
from PIL import Image
from pathlib import Path
from click.testing import CliRunner
from kraken.kraken import cli
from pytest import raises

    def tearDown(self):
        self.temp.close()
        os.unlink(self.temp.name)

    def test_binarize_color(self):
        """
        Tests binarization of color images.
        """
        with tempfile.NamedTemporaryFile() as fp:
            result = self.runner.invoke(cli, ['-i', self.color_img, fp.name, 'binarize'])
            self.assertEqual(result.exit_code, 0)
            self.assertEqual(tuple(map(lambda x: x[1], Image.open(fp).getcolors())), (0, 255))

    def test_binarize_bw(self):
        """
        Tests binarization of b/w images.
        """
        with tempfile.NamedTemporaryFile() as fp:
            result = self.runner.invoke(cli, ['-i', self.bw_img, fp.name, 'binarize'])
            self.assertEqual(result.exit_code, 0)
            bw = np.array(Image.open(self.bw_img))
            new = np.array(Image.open(fp.name))
            self.assertTrue(np.all(bw == new))

    def test_segment_color(self):
        """
        Tests that segmentation is aborted when given color image.
        """
        with tempfile.NamedTemporaryFile() as fp:

# Path: kraken/kraken.py
# @click.group(chain=True)
# @click.version_option()
# @click.option('-i', '--input',
#               type=(click.Path(exists=True),  # type: ignore
#                     click.Path(writable=True)),
#               multiple=True,
#               help='Input-output file pairs. Each input file (first argument) is mapped to one '
#                    'output file (second argument), e.g. `-i input.png output.txt`')
# @click.option('-I', '--batch-input', multiple=True, help='Glob expression to add multiple files at once.')
# @click.option('-o', '--suffix', default='', show_default=True,
#               help='Suffix for output files from batch and PDF inputs.')
# @click.option('-v', '--verbose', default=0, count=True, show_default=True)
# @click.option('-f', '--format-type', type=click.Choice(['image', 'alto', 'page', 'pdf', 'xml']), default='image',
#               help='Sets the default input type. In image mode inputs are image '
#                    'files, alto/page expects XML files in the respective format, pdf '
#                    'expects PDF files with numbered suffixes added to output file '
#                    'names as needed.')
# @click.option('-p', '--pdf-format', default='{src}_{idx:06d}',
#               show_default=True,
#               help='Format for output of PDF files. valid fields '
#                    'are `src` (source file), `idx` (page number), and `uuid` (v4 uuid). '
#                    '`-o` suffixes are appended to this format string.')
# @click.option('-h', '--hocr', 'serializer',
#               help='Switch between hOCR, ALTO, abbyyXML, PageXML or "native" '
#               'output. Native are plain image files for image, JSON for '
#               'segmentation, and text for transcription output.',
#               flag_value='hocr')
# @click.option('-a', '--alto', 'serializer', flag_value='alto')
# @click.option('-y', '--abbyy', 'serializer', flag_value='abbyyxml')
# @click.option('-x', '--pagexml', 'serializer', flag_value='pagexml')
# @click.option('-n', '--native', 'serializer', flag_value='native', default=True,
#               show_default=True)
# @click.option('-d', '--device', default='cpu', show_default=True,
#               help='Select device to use (cpu, cuda:0, cuda:1, ...)')
# @click.option('-r', '--raise-on-error/--no-raise-on-error', default=False, show_default=True,
#               help='Raises the exception that caused processing to fail in the case of an error')
# def cli(input, batch_input, suffix, verbose, format_type, pdf_format, serializer, device, raise_on_error):
#     """
#     Base command for recognition functionality.
# 
#     Inputs are defined as one or more pairs `-i input_file output_file`
#     followed by one or more chainable processing commands. Likewise, verbosity
#     is set on all subcommands with the `-v` switch.
#     """
#     ctx = click.get_current_context()
#     if device != 'cpu':
#         import torch
#         try:
#             torch.ones(1, device=device)
#         except AssertionError as e:
#             if raise_on_error:
#                 raise
#             logger.error(f'Device {device} not available: {e.args[0]}.')
#             ctx.exit(1)
#     ctx.meta['device'] = device
#     ctx.meta['input_format_type'] = format_type if format_type != 'pdf' else 'image'
#     ctx.meta['raise_failed'] = raise_on_error
#     ctx.meta['output_mode'] = serializer
#     ctx.meta['verbose'] = verbose
#     log.set_logger(logger, level=30 - min(10 * verbose, 20))


# Path: tests/test_cli.py
import os
import click
import unittest
import tempfile
import numpy as np
from PIL import Image
from pathlib import Path
from click.testing import CliRunner
from kraken.kraken import cli
from pytest import raises


    def tearDown(self):
        self.temp.close()
        os.unlink(self.temp.name)

    def test_binarize_color(self):
        """
        Tests binarization of color images.
        """
        with tempfile.NamedTemporaryFile() as fp:
            result = self.runner.invoke(cli, ['-i', self.color_img, fp.name, 'binarize'])
            self.assertEqual(result.exit_code, 0)
            self.assertEqual(tuple(map(lambda x: x[1], Image.open(fp).getcolors())), (0, 255))

    def test_binarize_bw(self):
        """
        Tests binarization of b/w images.
        """
        with tempfile.NamedTemporaryFile() as fp:
            result = self.runner.invoke(cli, ['-i', self.bw_img, fp.name, 'binarize'])
            self.assertEqual(result.exit_code, 0)
            bw = np.array(Image.open(self.bw_img))
            new = np.array(Image.open(fp.name))
            self.assertTrue(np.all(bw == new))

    def test_segment_color(self):
        """
        Tests that segmentation is aborted when given color image.
        """
        with tempfile.NamedTemporaryFile() as fp:

            result = self.runner.invoke(cli, ['-r', '-i', self.color_img, fp.name, 'segment'])