# Path: cufacesearch/cufacesearch/imgio/imgio.py
# def get_buffer_from_URL(img_url, verbose=0, image_dl_timeout=4, retries=DEFAULT_RETRIES):
#   """Get image buffer from URL `img_url`.
# 
#   :param img_url: image URL
#   :param img_url: str
#   :param verbose: verbose level (optional, default:0)
#   :type verbose: int
#   :param image_dl_timeout: timeout in seconds (optional, default:4)
#   :type image_dl_timeout: int
#   :param retries: number of retries (optional, default:`DEFAULT_RETRIES`)
#   :type retries: int
#   :return: image buffer
#   :rtype: buffer
#   """
# 
#   # Sometime fails with a timeout, now using retries
#   #   see: https://stackoverflow.com/questions/15431044/can-i-set-max-retries-for-requests-request
#   # SSLError: [Errno 1] _ssl.c:510:
#   # error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
#   # should we pass verify=False to make sure we will download the image...
#   from cStringIO import StringIO
#   if verbose > 0:
#     print "Downloading image from {}".format(img_url)
#   if retries != 0:
#     if retries != DEFAULT_RETRIES:
#       retries_settings = Retry(total=retries, backoff_factor=DEFAULT_BOF,
#                                status_forcelist=DEFAULT_FL)
#       SESSION.mount('http://', HTTPAdapter(max_retries=retries_settings))
#       SESSION.mount('https://', HTTPAdapter(max_retries=retries_settings))
#     req = SESSION.get(img_url, timeout=10)
#     #r = s.get(img_url, timeout=image_dl_timeout)
#   else:
#     req = requests.get(img_url, timeout=image_dl_timeout)
#   if req.status_code == 200:
#     if 'content-length' in req.headers and int(req.headers['content-length']) == 0:
#       del req
#       raise ValueError("Empty image.")
#     else:
#       img_buffer = StringIO(req.content)
#       return img_buffer
#   else:
#     raise ValueError("Incorrect status code: {}".format(req.status_code))
# 
# def get_buffer_from_filepath(filepath):
#   """Read image from `filepath` and return buffer.
# 
#   :param filepath: image path
#   :type filepath: str
#   :return: image buffer
#   :rtype: buffer
#   """
#   # TODO: change that for python3 compatibility
#   from cStringIO import StringIO
#   with open(filepath, 'rb') as f_in:
#     return StringIO(f_in.read())
# 
# def get_buffer_from_B64(base64str):
#   """Decode base64 encoded image buffer as buffer.
# 
#   :param base64str: base64 encoded image buffer
#   :type base64str: str
#   :return: image buffer
#   :rtype: buffer
#   """
#   # TODO: change that for python3 compatibility
#   from cStringIO import StringIO
#   import base64
#   return StringIO(base64.b64decode(base64str))
# 
# def get_SHA1_img_info_from_buffer(img_buffer):
#   """Get SHA1 and image info from image buffer.
# 
#   :param img_buffer: image buffer
#   :type img_buffer: buffer
#   :return: (sha1, image type, width, height)
#   :rtype: type
#   """
#   width, height, img_type = get_image_size_and_format(img_buffer)
#   img_buffer.seek(0)
#   sha1 = get_SHA1_from_data(img_buffer.read())
#   return sha1, img_type, width, height
# 
# def load_image_from_buffer(img_buffer):
#   """Load an image from a buffer. Can deal with GIF and alpha channel
# 
#   :param img_buffer: image buffer
#   :type img_buffer: buffer
#   :returns: the loaded image
#   :rtype: :class:`numpy.ndarray`
#   """
#   import numpy as np
#   from skimage import io as skio
#   img = skio.imread(img_buffer)
#   # Deal with GIF
#   if len(img.shape) == 4:
#     # Get first 'frame' of GIF
#     img = np.squeeze(img[1, :, :, :])
#   # Deal with alpha channel in PNG
#   if img.shape[-1] == 4:
#     img = img[:, :, :3]
#   return img


from ..imgio.imgio import get_buffer_from_URL, get_buffer_from_filepath, get_buffer_from_B64, \
  get_SHA1_img_info_from_buffer, load_image_from_buffer
  def __init__(self):
    pass

  def detect_from_filepath(self, img_file_path, up_sample=DEFAULT_UPSAMPLING, with_infos=True):
    """Run detection in image at local path ``img_file_path``.
     The path has to be readable from within the docker

    :param img_file_path: full path of the image to process
    :type img_file_path: string
    :param up_sample: number of upsampling before detection to allow small detection. [optional]
    :type up_sample: int
    :param with_infos: wether or not we also compute image info. [optional]
    :type with_infos: bool

    :returns: (optionally image infos), loaded image, and the detections as a list of dict with
     keys: ``left``, ``top``, ``right``, ``bottom``, ``score``
    :rtype: tuple
    """
    # """
    # Args:
    #   img_file_path (str): full path of the image to process
    #   up_sample (int): number of upsampling before detection to allow small detection. [optional]
    #   with_infos (bool): wether or not we also compute image info. [optional]
    #
    #  Returns:
    #   output (tuple): (optionally image infos), loaded image, and the detections as a list of dict
    # with keys "left", "top", "right", "bottom"
    # """
    if with_infos:
      return self.detect_from_buffer(get_buffer_from_filepath(img_file_path), up_sample=up_sample)

# Path: cufacesearch/cufacesearch/imgio/imgio.py
# def get_buffer_from_URL(img_url, verbose=0, image_dl_timeout=4, retries=DEFAULT_RETRIES):
#   """Get image buffer from URL `img_url`.
# 
#   :param img_url: image URL
#   :param img_url: str
#   :param verbose: verbose level (optional, default:0)
#   :type verbose: int
#   :param image_dl_timeout: timeout in seconds (optional, default:4)
#   :type image_dl_timeout: int
#   :param retries: number of retries (optional, default:`DEFAULT_RETRIES`)
#   :type retries: int
#   :return: image buffer
#   :rtype: buffer
#   """
# 
#   # Sometime fails with a timeout, now using retries
#   #   see: https://stackoverflow.com/questions/15431044/can-i-set-max-retries-for-requests-request
#   # SSLError: [Errno 1] _ssl.c:510:
#   # error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
#   # should we pass verify=False to make sure we will download the image...
#   from cStringIO import StringIO
#   if verbose > 0:
#     print "Downloading image from {}".format(img_url)
#   if retries != 0:
#     if retries != DEFAULT_RETRIES:
#       retries_settings = Retry(total=retries, backoff_factor=DEFAULT_BOF,
#                                status_forcelist=DEFAULT_FL)
#       SESSION.mount('http://', HTTPAdapter(max_retries=retries_settings))
#       SESSION.mount('https://', HTTPAdapter(max_retries=retries_settings))
#     req = SESSION.get(img_url, timeout=10)
#     #r = s.get(img_url, timeout=image_dl_timeout)
#   else:
#     req = requests.get(img_url, timeout=image_dl_timeout)
#   if req.status_code == 200:
#     if 'content-length' in req.headers and int(req.headers['content-length']) == 0:
#       del req
#       raise ValueError("Empty image.")
#     else:
#       img_buffer = StringIO(req.content)
#       return img_buffer
#   else:
#     raise ValueError("Incorrect status code: {}".format(req.status_code))
# 
# def get_buffer_from_filepath(filepath):
#   """Read image from `filepath` and return buffer.
# 
#   :param filepath: image path
#   :type filepath: str
#   :return: image buffer
#   :rtype: buffer
#   """
#   # TODO: change that for python3 compatibility
#   from cStringIO import StringIO
#   with open(filepath, 'rb') as f_in:
#     return StringIO(f_in.read())
# 
# def get_buffer_from_B64(base64str):
#   """Decode base64 encoded image buffer as buffer.
# 
#   :param base64str: base64 encoded image buffer
#   :type base64str: str
#   :return: image buffer
#   :rtype: buffer
#   """
#   # TODO: change that for python3 compatibility
#   from cStringIO import StringIO
#   import base64
#   return StringIO(base64.b64decode(base64str))
# 
# def get_SHA1_img_info_from_buffer(img_buffer):
#   """Get SHA1 and image info from image buffer.
# 
#   :param img_buffer: image buffer
#   :type img_buffer: buffer
#   :return: (sha1, image type, width, height)
#   :rtype: type
#   """
#   width, height, img_type = get_image_size_and_format(img_buffer)
#   img_buffer.seek(0)
#   sha1 = get_SHA1_from_data(img_buffer.read())
#   return sha1, img_type, width, height
# 
# def load_image_from_buffer(img_buffer):
#   """Load an image from a buffer. Can deal with GIF and alpha channel
# 
#   :param img_buffer: image buffer
#   :type img_buffer: buffer
#   :returns: the loaded image
#   :rtype: :class:`numpy.ndarray`
#   """
#   import numpy as np
#   from skimage import io as skio
#   img = skio.imread(img_buffer)
#   # Deal with GIF
#   if len(img.shape) == 4:
#     # Get first 'frame' of GIF
#     img = np.squeeze(img[1, :, :, :])
#   # Deal with alpha channel in PNG
#   if img.shape[-1] == 4:
#     img = img[:, :, :3]
#   return img


# Path: cufacesearch/cufacesearch/detector/generic_detector.py
from ..imgio.imgio import get_buffer_from_URL, get_buffer_from_filepath, get_buffer_from_B64, \
  get_SHA1_img_info_from_buffer, load_image_from_buffer

  def __init__(self):
    pass

  def detect_from_filepath(self, img_file_path, up_sample=DEFAULT_UPSAMPLING, with_infos=True):
    """Run detection in image at local path ``img_file_path``.
     The path has to be readable from within the docker

    :param img_file_path: full path of the image to process
    :type img_file_path: string
    :param up_sample: number of upsampling before detection to allow small detection. [optional]
    :type up_sample: int
    :param with_infos: wether or not we also compute image info. [optional]
    :type with_infos: bool

    :returns: (optionally image infos), loaded image, and the detections as a list of dict with
     keys: ``left``, ``top``, ``right``, ``bottom``, ``score``
    :rtype: tuple
    """
    # """
    # Args:
    #   img_file_path (str): full path of the image to process
    #   up_sample (int): number of upsampling before detection to allow small detection. [optional]
    #   with_infos (bool): wether or not we also compute image info. [optional]
    #
    #  Returns:
    #   output (tuple): (optionally image infos), loaded image, and the detections as a list of dict
    # with keys "left", "top", "right", "bottom"
    # """
    if with_infos:
      return self.detect_from_buffer(get_buffer_from_filepath(img_file_path), up_sample=up_sample)

    return self.detect_from_buffer_noinfos(get_buffer_from_filepath(img_file_path),