__author__ = 'paulo.rodenas'

import logging
from PIL import Image
import pyocr
import pyocr.builders
from pyocr.cuneiform import CuneiformError


class PyOCRIntegration(object):

    def __init__(self, lang):
        self.logger = logging.getLogger(__name__)
        self.tools = pyocr.get_available_tools()
        self.lang = lang

    def image_to_string(self, filename):
        if len(self.tools) == 0:
            raise PyOCRIntegrationNoOCRFound('No OCR tool has been found on '
                                             'this system. Make sure it\'s on'
                                             'PATH variable of your system')
        result = []
        for tool in self.tools:
            logging.debug("Running %s tool" % tool.get_name())
            if tool.get_name() == "Tesseract":
                txt = tool.image_to_string(
                    Image.open(filename),
                    lang=self.lang
                )
                result.append(txt)
                logging.debug("Result %s" % txt)
            else:
                # Default Cuneiform parameters
                try:
                    txt = tool.image_to_string(
                        Image.open(filename),
                        lang=self.lang
                    )
                    result.append(txt)
                    logging.debug("Result %s" % txt)
                except CuneiformError:
                    logging.error('I got an error when trying to process this '
                                  'image with Cuneiform')

                # Fax Cuneiform ocr
                try:
                    txt = tool.image_to_string(
                        Image.open(filename),
                        lang=self.lang,
                        builder=pyocr.builders.TextBuilder(
                            cuneiform_fax=True
                        )
                    )
                    result.append(txt)
                    logging.debug("Result %s" % txt)
                except CuneiformError:
                    logging.error('I got an error when trying to process this '
                                  'image with Cuneiform')
        return result

    @staticmethod
    def check_required_software():
        logger = logging.getLogger(__name__)
        tools = pyocr.get_available_tools()
        if len(tools) == 0:
            raise PyOCRIntegrationNoOCRFound('No OCR tool has been found on '
                                             'this system. Make sure it\'s on')
        elif len(tools) == 1:
            logger.info("I've found only one ocr tool [%s]. This is not exactly an error but you should get better " \
                  "results if you have both Tesseract and Cuneiform installed" % tools[0].get_name())
        else:
            logger.info("I've found all required software. We're good to go =)")

class PyOCRIntegrationNoOCRFound(Exception):

    def __init__(self, message):
        super(Exception, self).__init__(message)
@@ -38,16 +38,26 @@
 logging%0A
+import os%0A
 from PIL
@@ -148,16 +148,45 @@
 rmError%0A
+from wand.image import Image%0A
 %0A%0Aclass 
@@ -671,24 +671,312 @@
 ur system')%0A
+%0A        filename_split, fileextension_split = os.path.splitext(filename)%0A        grayscaled_filename = filename_split + 'grayscale' + fileextension_split%0A        with Image(filename=filename) as img:%0A            img.type = 'grayscale'%0A            img.save(filename=grayscaled_filename)%0A%0A
         resu
@@ -1192,32 +1192,43 @@
      Image.open(
+grayscaled_
 filename),%0A     
@@ -1520,32 +1520,43 @@
      Image.open(
+grayscaled_
 filename),%0A     
@@ -1978,32 +1978,32 @@
 mage_to_string(%0A
-
                 
@@ -2021,16 +2021,27 @@
 ge.open(
+grayscaled_
 filename

Set images to be converted in grayscale before send it to OCR due to an incompatibility between some images exported from OpenCV and CuneiForm