Unify the way backends are defined and loaded, unify the fs_cleanup function
This commit is contained in:
+22
-32
@@ -1,48 +1,26 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from django.utils.importlib import import_module
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from common.conf.settings import TEMPORARY_DIRECTORY
|
||||
from common.utils import fs_cleanup
|
||||
from converter.api import convert
|
||||
from documents.models import DocumentPage
|
||||
|
||||
from .backends import ocr_backend
|
||||
from .conf.settings import UNPAPER_PATH, LANGUAGE
|
||||
from .exceptions import UnpaperError
|
||||
from .literals import (DEFAULT_OCR_FILE_FORMAT, UNPAPER_FILE_FORMAT,
|
||||
DEFAULT_OCR_FILE_EXTENSION)
|
||||
from .parsers import parse_document_page
|
||||
from .parsers.exceptions import ParserError, ParserUnknownFile
|
||||
from .runtime import language_backend, ocr_backend
|
||||
|
||||
|
||||
def get_language_backend():
|
||||
"""
|
||||
Return the OCR cleanup language backend using the selected language
|
||||
in the configuration settings
|
||||
"""
|
||||
try:
|
||||
module = import_module(u'.'.join([u'ocr', u'lang', LANGUAGE]))
|
||||
except ImportError:
|
||||
sys.stderr.write(u'\nWarning: No OCR app language backend for language: %s\n\n' % LANGUAGE)
|
||||
return None
|
||||
return module
|
||||
|
||||
language_backend = get_language_backend()
|
||||
|
||||
|
||||
def cleanup(filename):
|
||||
"""
|
||||
Try to remove the given filename, ignoring non-existent files
|
||||
"""
|
||||
try:
|
||||
os.remove(filename)
|
||||
except OSError:
|
||||
pass
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def do_document_ocr(queue_document):
|
||||
@@ -58,15 +36,21 @@ def do_document_ocr(queue_document):
|
||||
parse_document_page(document_page)
|
||||
except (ParserError, ParserUnknownFile):
|
||||
# Fall back to doing visual OCR
|
||||
ocr_transformations, warnings = queue_document.get_transformation_list()
|
||||
|
||||
document_filepath = document_page.document.get_image_cache_name(page=document_page.page_number, version=document_page.document_version.pk)
|
||||
unpaper_output_filename = u'%s_unpaper_out_page_%s%s%s' % (document_page.document.uuid, document_page.page_number, os.extsep, UNPAPER_FILE_FORMAT)
|
||||
unpaper_output_filepath = os.path.join(TEMPORARY_DIRECTORY, unpaper_output_filename)
|
||||
|
||||
unpaper_input = convert(document_filepath, file_format=UNPAPER_FILE_FORMAT, transformations=ocr_transformations)
|
||||
logger.debug('document_filepath: %s' % document_filepath)
|
||||
|
||||
unpaper_input = convert(document_filepath, file_format=UNPAPER_FILE_FORMAT)
|
||||
|
||||
logger.debug('unpaper_input: %s' % unpaper_input)
|
||||
|
||||
execute_unpaper(input_filepath=unpaper_input, output_filepath=unpaper_output_filepath)
|
||||
|
||||
logger.debug('unpaper_output_filepath: %s' % unpaper_output_filepath)
|
||||
|
||||
# from PIL import Image, ImageOps
|
||||
# im = Image.open(document_filepath)
|
||||
# #if im.mode=='RGBA':
|
||||
@@ -77,8 +61,14 @@ def do_document_ocr(queue_document):
|
||||
|
||||
# Convert to TIFF
|
||||
pre_ocr_filepath = convert(input_filepath=unpaper_output_filepath, file_format=DEFAULT_OCR_FILE_FORMAT)
|
||||
|
||||
logger.debug('pre_ocr_filepath: %s' % pre_ocr_filepath)
|
||||
|
||||
# Tesseract needs an explicit file extension
|
||||
pre_ocr_filepath_w_ext = os.extsep.join([pre_ocr_filepath, DEFAULT_OCR_FILE_EXTENSION])
|
||||
|
||||
logger.debug('pre_ocr_filepath_w_ext: %s' % pre_ocr_filepath_w_ext)
|
||||
|
||||
os.rename(pre_ocr_filepath, pre_ocr_filepath_w_ext)
|
||||
try:
|
||||
ocr_text = ocr_backend.execute(pre_ocr_filepath_w_ext, LANGUAGE)
|
||||
@@ -87,10 +77,10 @@ def do_document_ocr(queue_document):
|
||||
document_page.page_label = _(u'Text from OCR')
|
||||
document_page.save()
|
||||
finally:
|
||||
cleanup(pre_ocr_filepath_w_ext)
|
||||
cleanup(unpaper_input)
|
||||
cleanup(document_filepath)
|
||||
cleanup(unpaper_output_filepath)
|
||||
fs_cleanup(pre_ocr_filepath_w_ext)
|
||||
fs_cleanup(unpaper_input)
|
||||
fs_cleanup(document_filepath)
|
||||
fs_cleanup(unpaper_output_filepath)
|
||||
|
||||
|
||||
def ocr_cleanup(text):
|
||||
|
||||
@@ -1,28 +1,3 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import sys
|
||||
|
||||
from django.utils.importlib import import_module
|
||||
|
||||
from ..conf.settings import BACKEND
|
||||
|
||||
|
||||
class BackendBase(object):
|
||||
def execute(input_filename, language=None):
|
||||
raise NotImplemented
|
||||
|
||||
|
||||
def get_ocr_backend():
|
||||
"""
|
||||
Return the OCR backend using the path specified in the configuration
|
||||
settings
|
||||
"""
|
||||
try:
|
||||
module = import_module(BACKEND)
|
||||
except ImportError:
|
||||
sys.stderr.write(u'\nWarning: No OCR backend named: %s\n\n' % BACKEND)
|
||||
raise
|
||||
else:
|
||||
return module
|
||||
|
||||
ocr_backend = get_ocr_backend()
|
||||
|
||||
@@ -5,6 +5,8 @@ import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from common.utils import fs_cleanup
|
||||
|
||||
from . import BackendBase
|
||||
from ..conf.settings import TESSERACT_PATH
|
||||
from ..exceptions import OCRError
|
||||
@@ -27,8 +29,8 @@ class Tesseract(BackendBase):
|
||||
return_code = proc.wait()
|
||||
if return_code != 0:
|
||||
error_text = proc.stderr.read()
|
||||
cleanup(filepath)
|
||||
cleanup(ocr_output)
|
||||
fs_cleanup(filepath)
|
||||
fs_cleanup(ocr_output)
|
||||
if language:
|
||||
# If tesseract gives an error with a language parameter
|
||||
# re-run it with no parameter again
|
||||
@@ -43,14 +45,3 @@ class Tesseract(BackendBase):
|
||||
os.unlink(filepath)
|
||||
|
||||
return text
|
||||
|
||||
|
||||
# TODO: Reduntant, also in api.py
|
||||
def cleanup(filename):
|
||||
"""
|
||||
Try to remove the given filename, ignoring non-existent files
|
||||
"""
|
||||
try:
|
||||
os.remove(filename)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
@@ -16,6 +16,6 @@ register_settings(
|
||||
{'name': u'QUEUE_PROCESSING_INTERVAL', 'global_name': u'OCR_QUEUE_PROCESSING_INTERVAL', 'default': 10},
|
||||
{'name': u'UNPAPER_PATH', 'global_name': u'OCR_UNPAPER_PATH', 'default': u'/usr/bin/unpaper', 'description': _(u'File path to unpaper program.'), 'exists': True},
|
||||
{'name': u'PDFTOTEXT_PATH', 'global_name': u'OCR_PDFTOTEXT_PATH', 'default': u'/usr/bin/pdftotext', 'description': _(u'File path to poppler\'s pdftotext program used to extract text from PDF files.'), 'exists': True},
|
||||
{'name': u'BACKEND', 'global_name': u'OCR_BACKEND', 'default': u'ocr.backends.tesseract', 'description': _(u'Full path to the backend to be used to do OCR.')},
|
||||
{'name': u'BACKEND', 'global_name': u'OCR_BACKEND', 'default': u'ocr.backends.tesseract.Tesseract', 'description': _(u'Full path to the backend to be used to do OCR.')},
|
||||
]
|
||||
)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
class BackendBase(object):
|
||||
def check_word(word):
|
||||
raise NotImplemented
|
||||
|
||||
+32
-27
@@ -1,38 +1,43 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import re
|
||||
|
||||
from . import BackendBase
|
||||
|
||||
def check_word(word):
|
||||
ALL_ALPHANUM = re.compile('([0-9a-z])', re.I)
|
||||
NON_ALPHANUM = re.compile('([^0-9a-z])', re.I)
|
||||
|
||||
TOO_MANY_VOWELS = re.compile('[aeiou]{3}', re.I)
|
||||
TOO_MANY_CONSONANTS = re.compile('[bcdfghjklmnpqrstvwxyz]{5}', re.I)
|
||||
ALL_ALPHA = re.compile('^[a-z]+$', re.I)
|
||||
SINGLE_LETTER_WORDS = re.compile('^[ai]$', re.I)
|
||||
class LanguageBackend(BackendBase):
|
||||
def check_word(word):
|
||||
ALL_ALPHANUM = re.compile('([0-9a-z])', re.I)
|
||||
NON_ALPHANUM = re.compile('([^0-9a-z])', re.I)
|
||||
|
||||
# (L) If a string is longer than 20 characters, it is garbage
|
||||
if len(word) > 20:
|
||||
return None
|
||||
TOO_MANY_VOWELS = re.compile('[aeiou]{3}', re.I)
|
||||
TOO_MANY_CONSONANTS = re.compile('[bcdfghjklmnpqrstvwxyz]{5}', re.I)
|
||||
ALL_ALPHA = re.compile('^[a-z]+$', re.I)
|
||||
SINGLE_LETTER_WORDS = re.compile('^[ai]$', re.I)
|
||||
|
||||
# (A) If a string's ratio of alphanumeric characters to total
|
||||
# characters is less than 50%, the string is garbage
|
||||
if len(ALL_ALPHANUM.findall(word)) < len(word) / 2:
|
||||
return None
|
||||
# (L) If a string is longer than 20 characters, it is garbage
|
||||
if len(word) > 20:
|
||||
return None
|
||||
|
||||
# Remove word if all the letters in the word are non alphanumeric
|
||||
if len(NON_ALPHANUM.findall(word)) == len(word):
|
||||
return None
|
||||
# (A) If a string's ratio of alphanumeric characters to total
|
||||
# characters is less than 50%, the string is garbage
|
||||
if len(ALL_ALPHANUM.findall(word)) < len(word) / 2:
|
||||
return None
|
||||
|
||||
# Removed words with too many consecutie vowels
|
||||
if TOO_MANY_VOWELS.findall(word):
|
||||
return None
|
||||
# Remove word if all the letters in the word are non alphanumeric
|
||||
if len(NON_ALPHANUM.findall(word)) == len(word):
|
||||
return None
|
||||
|
||||
# Removed words with too many consecutie consonants
|
||||
if TOO_MANY_CONSONANTS.findall(word):
|
||||
return None
|
||||
# Removed words with too many consecutie vowels
|
||||
if TOO_MANY_VOWELS.findall(word):
|
||||
return None
|
||||
|
||||
# Only allow specific single letter words
|
||||
if len(word) == 1 and not SINGLE_LETTER_WORDS.findall(word):
|
||||
return None
|
||||
# Removed words with too many consecutie consonants
|
||||
if TOO_MANY_CONSONANTS.findall(word):
|
||||
return None
|
||||
|
||||
return word
|
||||
# Only allow specific single letter words
|
||||
if len(word) == 1 and not SINGLE_LETTER_WORDS.findall(word):
|
||||
return None
|
||||
|
||||
return word
|
||||
|
||||
+32
-27
@@ -1,39 +1,44 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import
|
||||
|
||||
import re
|
||||
|
||||
from . import BackendBase
|
||||
|
||||
def check_word(word):
|
||||
ALL_ALPHANUM = re.compile('([0-9ёйцукенгшщзхъфывапролджэячсмитьбю])', re.I)
|
||||
NON_ALPHANUM = re.compile('([^0-9ёйцукенгшщзхъфывапролджэячсмитьбю])', re.I)
|
||||
|
||||
TOO_MANY_VOWELS = re.compile('[ёуеыаоэяию]{3}', re.I)
|
||||
TOO_MANY_CONSONANTS = re.compile('[йцкнгшщзхъфвпрлджчсмтьб{5}', re.I)
|
||||
ALL_ALPHA = re.compile('^[ёйцукенгшщзхъфывапролджэячсмитьбю]+$', re.I)
|
||||
SINGLE_LETTER_WORDS = re.compile('^[уквояси]$', re.I)
|
||||
class LanguageBackend(BackendBase):
|
||||
def check_word(word):
|
||||
ALL_ALPHANUM = re.compile('([0-9ёйцукенгшщзхъфывапролджэячсмитьбю])', re.I)
|
||||
NON_ALPHANUM = re.compile('([^0-9ёйцукенгшщзхъфывапролджэячсмитьбю])', re.I)
|
||||
|
||||
# (L) If a string is longer than 25 characters, it is garbage
|
||||
if len(word) > 25:
|
||||
return None
|
||||
TOO_MANY_VOWELS = re.compile('[ёуеыаоэяию]{3}', re.I)
|
||||
TOO_MANY_CONSONANTS = re.compile('[йцкнгшщзхъфвпрлджчсмтьб{5}', re.I)
|
||||
ALL_ALPHA = re.compile('^[ёйцукенгшщзхъфывапролджэячсмитьбю]+$', re.I)
|
||||
SINGLE_LETTER_WORDS = re.compile('^[уквояси]$', re.I)
|
||||
|
||||
# (A) If a string's ratio of alphanumeric characters to total
|
||||
# characters is less than 50%, the string is garbage
|
||||
if len(ALL_ALPHANUM.findall(word)) < len(word) / 2:
|
||||
return None
|
||||
# (L) If a string is longer than 25 characters, it is garbage
|
||||
if len(word) > 25:
|
||||
return None
|
||||
|
||||
# Remove word if all the letters in the word are non alphanumeric
|
||||
if len(NON_ALPHANUM.findall(word)) == len(word):
|
||||
return None
|
||||
# (A) If a string's ratio of alphanumeric characters to total
|
||||
# characters is less than 50%, the string is garbage
|
||||
if len(ALL_ALPHANUM.findall(word)) < len(word) / 2:
|
||||
return None
|
||||
|
||||
# Removed words with too many consecutie vowels
|
||||
if TOO_MANY_VOWELS.findall(word):
|
||||
return None
|
||||
# Remove word if all the letters in the word are non alphanumeric
|
||||
if len(NON_ALPHANUM.findall(word)) == len(word):
|
||||
return None
|
||||
|
||||
# Removed words with too many consecutie consonants
|
||||
if TOO_MANY_CONSONANTS.findall(word):
|
||||
return None
|
||||
# Removed words with too many consecutie vowels
|
||||
if TOO_MANY_VOWELS.findall(word):
|
||||
return None
|
||||
|
||||
# Only allow specific single letter words
|
||||
if len(word) == 1 and not SINGLE_LETTER_WORDS.findall(word):
|
||||
return None
|
||||
# Removed words with too many consecutie consonants
|
||||
if TOO_MANY_CONSONANTS.findall(word):
|
||||
return None
|
||||
|
||||
return word
|
||||
# Only allow specific single letter words
|
||||
if len(word) == 1 and not SINGLE_LETTER_WORDS.findall(word):
|
||||
return None
|
||||
|
||||
return word
|
||||
|
||||
+32
-27
@@ -1,39 +1,44 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import
|
||||
|
||||
import re
|
||||
|
||||
from . import BackendBase
|
||||
|
||||
def check_word(word):
|
||||
ALL_ALPHANUM = re.compile('([0-9a-záéíóúüñ])', re.I)
|
||||
NON_ALPHANUM = re.compile('([^0-9a-záéíóúüñ])', re.I)
|
||||
|
||||
TOO_MANY_VOWELS = re.compile('[aáeéiíoóuúü]{3}', re.I)
|
||||
TOO_MANY_CONSONANTS = re.compile('[bcdfghjklmnñpqrstvwxyz]{5}', re.I)
|
||||
ALL_ALPHA = re.compile('^[a-z]+$', re.I)
|
||||
SINGLE_LETTER_WORDS = re.compile('^[aeoóuy]$', re.I)
|
||||
class LanguageBackend(BackendBase):
|
||||
def check_word(word):
|
||||
ALL_ALPHANUM = re.compile('([0-9a-záéíóúüñ])', re.I)
|
||||
NON_ALPHANUM = re.compile('([^0-9a-záéíóúüñ])', re.I)
|
||||
|
||||
# (L) If a string is longer than 20 characters, it is garbage
|
||||
if len(word) > 20:
|
||||
return None
|
||||
TOO_MANY_VOWELS = re.compile('[aáeéiíoóuúü]{3}', re.I)
|
||||
TOO_MANY_CONSONANTS = re.compile('[bcdfghjklmnñpqrstvwxyz]{5}', re.I)
|
||||
ALL_ALPHA = re.compile('^[a-z]+$', re.I)
|
||||
SINGLE_LETTER_WORDS = re.compile('^[aeoóuy]$', re.I)
|
||||
|
||||
# (A) If a string’s ratio of alphanumeric characters to total
|
||||
# characters is less than 50%, the string is garbage
|
||||
if len(ALL_ALPHANUM.findall(word)) < len(word) / 2:
|
||||
return None
|
||||
# (L) If a string is longer than 20 characters, it is garbage
|
||||
if len(word) > 20:
|
||||
return None
|
||||
|
||||
# Remove word if all the letters in the word are non alphanumeric
|
||||
if len(NON_ALPHANUM.findall(word)) == len(word):
|
||||
return None
|
||||
# (A) If a string’s ratio of alphanumeric characters to total
|
||||
# characters is less than 50%, the string is garbage
|
||||
if len(ALL_ALPHANUM.findall(word)) < len(word) / 2:
|
||||
return None
|
||||
|
||||
# Removed words with too many consecutie vowels
|
||||
if TOO_MANY_VOWELS.findall(word):
|
||||
return None
|
||||
# Remove word if all the letters in the word are non alphanumeric
|
||||
if len(NON_ALPHANUM.findall(word)) == len(word):
|
||||
return None
|
||||
|
||||
# Removed words with too many consecutie consonants
|
||||
if TOO_MANY_CONSONANTS.findall(word):
|
||||
return None
|
||||
# Removed words with too many consecutie vowels
|
||||
if TOO_MANY_VOWELS.findall(word):
|
||||
return None
|
||||
|
||||
# Only allow specific single letter words
|
||||
if len(word) == 1 and not SINGLE_LETTER_WORDS.findall(word):
|
||||
return None
|
||||
# Removed words with too many consecutie consonants
|
||||
if TOO_MANY_CONSONANTS.findall(word):
|
||||
return None
|
||||
|
||||
return word
|
||||
# Only allow specific single letter words
|
||||
if len(word) == 1 and not SINGLE_LETTER_WORDS.findall(word):
|
||||
return None
|
||||
|
||||
return word
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
from common.utils import load_backend
|
||||
|
||||
from .conf.settings import BACKEND, LANGUAGE
|
||||
|
||||
try:
|
||||
language_backend = load_backend(u'.'.join([u'ocr', u'lang', LANGUAGE, u'LanguageBackend']))
|
||||
except ImportError:
|
||||
language_backend = None
|
||||
|
||||
ocr_backend = load_backend(BACKEND)
|
||||
Reference in New Issue
Block a user