# Path: kraken/rpred.py
# class ocr_record(object):
#     """
#     A record object containing the recognition result of a single line
#     """
#     def __init__(self, prediction: str, cuts, confidences: List[float], line: Union[List, Dict[str, List]]) -> None:
#         self.prediction = prediction
#         self.cuts = cuts
#         self.confidences = confidences
#         self.tags = None if 'tags' not in line else line['tags']
#         self.type = 'baselines' if 'baseline' in line else 'box'
#         self.base_dir = None
#         if self.type == 'baselines':
#             self.line = line['boundary']
#             self.baseline = line['baseline']
#         else:
#             self.line = line
# 
#     def __len__(self) -> int:
#         return len(self.prediction)
# 
#     def __str__(self) -> str:
#         return self.prediction
# 
#     def __iter__(self):
#         self.idx = -1
#         return self
# 
#     def __next__(self) -> Tuple[str, int, float]:
#         if self.idx + 1 < len(self):
#             self.idx += 1
#             return (self.prediction[self.idx], self.cuts[self.idx],
#                     self.confidences[self.idx])
#         else:
#             raise StopIteration
# 
#     def __getitem__(self, key: Union[int, slice]):
#         if isinstance(key, slice):
#             return [self[i] for i in range(*key.indices(len(self)))]
#         elif isinstance(key, int):
#             if key < 0:
#                 key += len(self)
#             if key >= len(self):
#                 raise IndexError('Index (%d) is out of range' % key)
#             return (self.prediction[key], self.cuts[key],
#                     self.confidences[key])
#         else:
#             raise TypeError('Invalid argument type')
# 
# Path: kraken/lib/util.py
# def make_printable(char: str) -> str:
#     """
#     Takes a Unicode code point and return a printable representation of it.
# 
#     Args:
#         char (str): Input code point
# 
#     Returns:
#         Either the original code point, the name of the code point if it is a
#         combining mark, whitespace etc., or the hex code if it is a control
#         symbol.
#     """
#     if not char or is_printable(char):
#         return char
#     elif unicodedata.category(char) in ('Cc', 'Cs', 'Co'):
#         return '0x{:x}'.format(ord(char))
#     else:
#         return unicodedata.name(char)
# 
# Path: kraken/lib/segmentation.py
# def is_in_region(line, region) -> bool:
#     """
#     Tests if a line is inside a region, i.e. if the mid point of the baseline
#     is inside the region.
# 
#     Args:
#         line (geom.LineString): line to test
#         region (geom.Polygon): region to test against
# 
#     Returns:
#         False if line is not inside region, True otherwise.
#     """
#     l_obj = line.interpolate(0.5, normalized=True)
#     return region.contains(l_obj)


from jinja2 import Environment, PackageLoader
from shapely.ops import unary_union
from collections import Counter
from kraken.rpred import ocr_record
from kraken.lib.util import make_printable
from kraken.lib.segmentation import is_in_region
from typing import List, Tuple, Iterable, Optional, Sequence, Dict, Any
import regex
import logging
import datetime
import numpy as np
import shapely.geometry as geom
    env = Environment(loader=PackageLoader('kraken', 'templates'),
                      trim_blocks=True,
                      lstrip_blocks=False,
                      autoescape=True)
    env.tests['whitespace'] = str.isspace
    env.filters['rescale'] = _rescale
    logger.debug('Retrieving template.')
    tmpl = env.get_template(template)
    logger.debug('Rendering data.')
    return tmpl.render(page=page)


def serialize_segmentation(segresult: Dict[str, Any],
                           image_name: str = None,
                           image_size: Tuple[int, int] = (0, 0),
                           template: str = 'hocr') -> str:
    """
    Serializes a segmentation result into an output document.

    Args:
        segresult: Result of blla.segment
        image_name (str): Name of the source image
        image_size (tuple): Dimensions of the source image
        template (str): Selector for the serialization format. May be
                        'hocr' or 'alto'.

    Returns:
            (str) rendered template.
    """
    if 'type' in segresult and segresult['type'] == 'baselines':

# Path: kraken/rpred.py
# class ocr_record(object):
#     """
#     A record object containing the recognition result of a single line
#     """
#     def __init__(self, prediction: str, cuts, confidences: List[float], line: Union[List, Dict[str, List]]) -> None:
#         self.prediction = prediction
#         self.cuts = cuts
#         self.confidences = confidences
#         self.tags = None if 'tags' not in line else line['tags']
#         self.type = 'baselines' if 'baseline' in line else 'box'
#         self.base_dir = None
#         if self.type == 'baselines':
#             self.line = line['boundary']
#             self.baseline = line['baseline']
#         else:
#             self.line = line
# 
#     def __len__(self) -> int:
#         return len(self.prediction)
# 
#     def __str__(self) -> str:
#         return self.prediction
# 
#     def __iter__(self):
#         self.idx = -1
#         return self
# 
#     def __next__(self) -> Tuple[str, int, float]:
#         if self.idx + 1 < len(self):
#             self.idx += 1
#             return (self.prediction[self.idx], self.cuts[self.idx],
#                     self.confidences[self.idx])
#         else:
#             raise StopIteration
# 
#     def __getitem__(self, key: Union[int, slice]):
#         if isinstance(key, slice):
#             return [self[i] for i in range(*key.indices(len(self)))]
#         elif isinstance(key, int):
#             if key < 0:
#                 key += len(self)
#             if key >= len(self):
#                 raise IndexError('Index (%d) is out of range' % key)
#             return (self.prediction[key], self.cuts[key],
#                     self.confidences[key])
#         else:
#             raise TypeError('Invalid argument type')
# 
# Path: kraken/lib/util.py
# def make_printable(char: str) -> str:
#     """
#     Takes a Unicode code point and return a printable representation of it.
# 
#     Args:
#         char (str): Input code point
# 
#     Returns:
#         Either the original code point, the name of the code point if it is a
#         combining mark, whitespace etc., or the hex code if it is a control
#         symbol.
#     """
#     if not char or is_printable(char):
#         return char
#     elif unicodedata.category(char) in ('Cc', 'Cs', 'Co'):
#         return '0x{:x}'.format(ord(char))
#     else:
#         return unicodedata.name(char)
# 
# Path: kraken/lib/segmentation.py
# def is_in_region(line, region) -> bool:
#     """
#     Tests if a line is inside a region, i.e. if the mid point of the baseline
#     is inside the region.
# 
#     Args:
#         line (geom.LineString): line to test
#         region (geom.Polygon): region to test against
# 
#     Returns:
#         False if line is not inside region, True otherwise.
#     """
#     l_obj = line.interpolate(0.5, normalized=True)
#     return region.contains(l_obj)


# Path: kraken/serialization.py
from jinja2 import Environment, PackageLoader
from shapely.ops import unary_union
from collections import Counter
from kraken.rpred import ocr_record
from kraken.lib.util import make_printable
from kraken.lib.segmentation import is_in_region
from typing import List, Tuple, Iterable, Optional, Sequence, Dict, Any
import regex
import logging
import datetime
import numpy as np
import shapely.geometry as geom

    env = Environment(loader=PackageLoader('kraken', 'templates'),
                      trim_blocks=True,
                      lstrip_blocks=False,
                      autoescape=True)
    env.tests['whitespace'] = str.isspace
    env.filters['rescale'] = _rescale
    logger.debug('Retrieving template.')
    tmpl = env.get_template(template)
    logger.debug('Rendering data.')
    return tmpl.render(page=page)


def serialize_segmentation(segresult: Dict[str, Any],
                           image_name: str = None,
                           image_size: Tuple[int, int] = (0, 0),
                           template: str = 'hocr') -> str:
    """
    Serializes a segmentation result into an output document.

    Args:
        segresult: Result of blla.segment
        image_name (str): Name of the source image
        image_size (tuple): Dimensions of the source image
        template (str): Selector for the serialization format. May be
                        'hocr' or 'alto'.

    Returns:
            (str) rendered template.
    """
    if 'type' in segresult and segresult['type'] == 'baselines':

        records = [ocr_record('', '', '', bl) for bl in segresult['lines']]