<commit_before>#
# Copyright 2015 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing
# permissions and limitations under the License.
"""
Arrow IPC format dataset builders.
"""
__all__ = ['build_binary_dataset']

import io
import json
import pathlib
import numpy as np
import pyarrow as pa
import tempfile

from PIL import Image, UnidentifiedImageError
from collections import Counter
from typing import Optional, List, Union, Callable, Tuple, Dict
from multiprocessing import Pool
from kraken.lib import functional_im_transforms as F_t
from kraken.lib.segmentation import extract_polygons
from kraken.lib.xml import parse_xml, parse_alto, parse_page
from kraken.lib.util import is_bitonal, make_printable
from kraken.lib.exceptions import KrakenInputException

import logging

logger = logging.getLogger(__name__)


def _extract_line(xml_record):
    lines = []
    try:
        im = Image.open(xml_record['image'])
    except (FileNotFoundError, UnidentifiedImageError):
        return lines, None, None
    if is_bitonal(im):
        im = im.convert('1')
    seg_key = 'lines' if 'lines' in xml_record else 'boxes'
    recs = xml_record.pop(seg_key)
    for idx, rec in enumerate(recs):
        try:
            line_im, line = next(extract_polygons(im, {**xml_record, seg_key: [rec]}))
        except KrakenInputException:
            logger.warning(f'Invalid line {idx} in {im.filename}')
            continue
        if not line['text']:
            continue
        fp = io.BytesIO()
        line_im.save(fp, format='png')
        lines.append({'text': line['text'], 'im': fp.getvalue()})
    return lines, im.mode
<commit_msg>catch-all exceptions in arrow dataset builder<commit_after>#
# Copyright 2015 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing
# permissions and limitations under the License.
"""
Arrow IPC format dataset builders.
"""
__all__ = ['build_binary_dataset']

import io
import json
import pathlib
import numpy as np
import pyarrow as pa
import tempfile

from PIL import Image, UnidentifiedImageError
from collections import Counter
from typing import Optional, List, Union, Callable, Tuple, Dict
from multiprocessing import Pool
from kraken.lib import functional_im_transforms as F_t
from kraken.lib.segmentation import extract_polygons
from kraken.lib.xml import parse_xml, parse_alto, parse_page
from kraken.lib.util import is_bitonal, make_printable
from kraken.lib.exceptions import KrakenInputException

import logging

logger = logging.getLogger(__name__)


def _extract_line(xml_record):
    lines = []
    try:
        im = Image.open(xml_record['image'])
    except (FileNotFoundError, UnidentifiedImageError):
        return lines, None, None
    if is_bitonal(im):
        im = im.convert('1')
    seg_key = 'lines' if 'lines' in xml_record else 'boxes'
    recs = xml_record.pop(seg_key)
    for idx, rec in enumerate(recs):
        try:
            line_im, line = next(extract_polygons(im, {**xml_record, seg_key: [rec]}))
        except KrakenInputException:
            logger.warning(f'Invalid line {idx} in {im.filename}')
            continue
        except Exception as e:
            logger.warning(f'Unexpected exception {e} from line {idx} in {im.filename}')
            continue
        if not line['text']:
            continue
        fp = io.BytesIO()
        line_im.save(fp, format='png')
        lines.append({'text': line['text'], 'im': fp.getvalue()})
    return lines, im.mode

{'fraction_non_alphanumeric': 0.08896058999769532, 'fraction_numerical': 0.004148421295229315, 'mean_word_length': 3.707158351409978, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 14}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7559713', 'n_tokens_mistral': 1257, 'n_tokens_neox': 1246, 'n_words': 454}