# Path: pycoral/adapters/classify.py
# def num_classes(interpreter):
# def get_scores(interpreter):
# def get_classes_from_scores(scores,
#                             top_k=float('inf'),
#                             score_threshold=-float('inf')):
# def get_classes(interpreter, top_k=float('inf'), score_threshold=-float('inf')):
# 
# Path: pycoral/adapters/common.py
# def output_tensor(interpreter, i):
# def input_details(interpreter, key):
# def input_size(interpreter):
# def input_tensor(interpreter):
# def set_input(interpreter, data):
# def set_resized_input(interpreter, size, resize):
# 
# Path: pycoral/utils/dataset.py
# def read_label_file(file_path):
#   """Reads labels from a text file and returns it as a dictionary.
# 
#   This function supports label files with the following formats:
# 
#   + Each line contains id and description separated by colon or space.
#     Example: ``0:cat`` or ``0 cat``.
#   + Each line contains a description only. The returned label id's are based on
#     the row number.
# 
#   Args:
#     file_path (str): path to the label file.
# 
#   Returns:
#     Dict of (int, string) which maps label id to description.
#   """
#   with open(file_path, 'r', encoding='utf-8') as f:
#     lines = f.readlines()
#   ret = {}
#   for row_number, content in enumerate(lines):
#     pair = re.split(r'[:\s]+', content.strip(), maxsplit=1)
#     if len(pair) == 2 and pair[0].strip().isdigit():
#       ret[int(pair[0])] = pair[1].strip()
#     else:
#       ret[row_number] = content.strip()
#   return ret
# 
# Path: pycoral/utils/edgetpu.py
# def make_interpreter(model_path_or_content, device=None, delegate=None):
#   """Creates a new ``tf.lite.Interpreter`` instance using the given model.
# 
#   **Note:** If you have multiple Edge TPUs, you should always specify the
#   ``device`` argument.
# 
#   Args:
#      model_path_or_content (str or bytes): `str` object is interpreted as
#        model path, `bytes` object is interpreted as model content.
#      device (str): The Edge TPU device you want:
# 
#        + None      -- use any Edge TPU (this is the default)
#        + ":<N>"    -- use N-th Edge TPU (this corresponds to the enumerated
#          index position from :func:`list_edge_tpus`)
#        + "usb"     -- use any USB Edge TPU
#        + "usb:<N>" -- use N-th USB Edge TPU
#        + "pci"     -- use any PCIe Edge TPU
#        + "pci:<N>" -- use N-th PCIe Edge TPU
# 
#        If left as None, you cannot reliably predict which device you'll get.
#        So if you have multiple Edge TPUs and want to run a specific model on
#        each one, then you must specify the device.
#      delegate: A pre-loaded Edge TPU delegate object, as provided by
#        :func:`load_edgetpu_delegate`. If provided, the `device` argument
#        is ignored.
# 
#   Returns:
#      New ``tf.lite.Interpreter`` instance.
#   """
#   if delegate:
#     delegates = [delegate]
#   else:
#     delegates = [load_edgetpu_delegate({'device': device} if device else {})]
#   if isinstance(model_path_or_content, bytes):
#     return tflite.Interpreter(
#         model_content=model_path_or_content, experimental_delegates=delegates)
#   else:
#     return tflite.Interpreter(
#         model_path=model_path_or_content, experimental_delegates=delegates)


import argparse
import time
import numpy as np
from PIL import Image
from pycoral.adapters import classify
from pycoral.adapters import common
from pycoral.utils.dataset import read_label_file
from pycoral.utils.edgetpu import make_interpreter
  interpreter.allocate_tensors()

  # Model must be uint8 quantized
  if common.input_details(interpreter, 'dtype') != np.uint8:
    raise ValueError('Only support uint8 input type.')

  size = common.input_size(interpreter)
  image = Image.open(args.input).convert('RGB').resize(size, Image.ANTIALIAS)

  # Image data must go through two transforms before running inference:
  # 1. normalization: f = (input - mean) / std
  # 2. quantization: q = f / scale + zero_point
  # The following code combines the two steps as such:
  # q = (input - mean) / (std * scale) + zero_point
  # However, if std * scale equals 1, and mean - zero_point equals 0, the input
  # does not need any preprocessing (but in practice, even if the results are
  # very close to 1 and 0, it is probably okay to skip preprocessing for better
  # efficiency; we use 1e-5 below instead of absolute zero).
  params = common.input_details(interpreter, 'quantization_parameters')
  scale = params['scales']
  zero_point = params['zero_points']
  mean = args.input_mean
  std = args.input_std
  if abs(scale * std - 1) < 1e-5 and abs(mean - zero_point) < 1e-5:
    # Input data does not require preprocessing.
    common.set_input(interpreter, image)
  else:
    # Input data requires preprocessing
    normalized_input = (np.asarray(image) - mean) / (std * scale) + zero_point
    np.clip(normalized_input, 0, 255, out=normalized_input)

# Path: pycoral/adapters/classify.py
# def num_classes(interpreter):
# def get_scores(interpreter):
# def get_classes_from_scores(scores,
#                             top_k=float('inf'),
#                             score_threshold=-float('inf')):
# def get_classes(interpreter, top_k=float('inf'), score_threshold=-float('inf')):
# 
# Path: pycoral/adapters/common.py
# def output_tensor(interpreter, i):
# def input_details(interpreter, key):
# def input_size(interpreter):
# def input_tensor(interpreter):
# def set_input(interpreter, data):
# def set_resized_input(interpreter, size, resize):
# 
# Path: pycoral/utils/dataset.py
# def read_label_file(file_path):
#   """Reads labels from a text file and returns it as a dictionary.
# 
#   This function supports label files with the following formats:
# 
#   + Each line contains id and description separated by colon or space.
#     Example: ``0:cat`` or ``0 cat``.
#   + Each line contains a description only. The returned label id's are based on
#     the row number.
# 
#   Args:
#     file_path (str): path to the label file.
# 
#   Returns:
#     Dict of (int, string) which maps label id to description.
#   """
#   with open(file_path, 'r', encoding='utf-8') as f:
#     lines = f.readlines()
#   ret = {}
#   for row_number, content in enumerate(lines):
#     pair = re.split(r'[:\s]+', content.strip(), maxsplit=1)
#     if len(pair) == 2 and pair[0].strip().isdigit():
#       ret[int(pair[0])] = pair[1].strip()
#     else:
#       ret[row_number] = content.strip()
#   return ret
# 
# Path: pycoral/utils/edgetpu.py
# def make_interpreter(model_path_or_content, device=None, delegate=None):
#   """Creates a new ``tf.lite.Interpreter`` instance using the given model.
# 
#   **Note:** If you have multiple Edge TPUs, you should always specify the
#   ``device`` argument.
# 
#   Args:
#      model_path_or_content (str or bytes): `str` object is interpreted as
#        model path, `bytes` object is interpreted as model content.
#      device (str): The Edge TPU device you want:
# 
#        + None      -- use any Edge TPU (this is the default)
#        + ":<N>"    -- use N-th Edge TPU (this corresponds to the enumerated
#          index position from :func:`list_edge_tpus`)
#        + "usb"     -- use any USB Edge TPU
#        + "usb:<N>" -- use N-th USB Edge TPU
#        + "pci"     -- use any PCIe Edge TPU
#        + "pci:<N>" -- use N-th PCIe Edge TPU
# 
#        If left as None, you cannot reliably predict which device you'll get.
#        So if you have multiple Edge TPUs and want to run a specific model on
#        each one, then you must specify the device.
#      delegate: A pre-loaded Edge TPU delegate object, as provided by
#        :func:`load_edgetpu_delegate`. If provided, the `device` argument
#        is ignored.
# 
#   Returns:
#      New ``tf.lite.Interpreter`` instance.
#   """
#   if delegate:
#     delegates = [delegate]
#   else:
#     delegates = [load_edgetpu_delegate({'device': device} if device else {})]
#   if isinstance(model_path_or_content, bytes):
#     return tflite.Interpreter(
#         model_content=model_path_or_content, experimental_delegates=delegates)
#   else:
#     return tflite.Interpreter(
#         model_path=model_path_or_content, experimental_delegates=delegates)


# Path: examples/classify_image.py
import argparse
import time
import numpy as np
from PIL import Image
from pycoral.adapters import classify
from pycoral.adapters import common
from pycoral.utils.dataset import read_label_file
from pycoral.utils.edgetpu import make_interpreter

  interpreter.allocate_tensors()

  # Model must be uint8 quantized
  if common.input_details(interpreter, 'dtype') != np.uint8:
    raise ValueError('Only support uint8 input type.')

  size = common.input_size(interpreter)
  image = Image.open(args.input).convert('RGB').resize(size, Image.ANTIALIAS)

  # Image data must go through two transforms before running inference:
  # 1. normalization: f = (input - mean) / std
  # 2. quantization: q = f / scale + zero_point
  # The following code combines the two steps as such:
  # q = (input - mean) / (std * scale) + zero_point
  # However, if std * scale equals 1, and mean - zero_point equals 0, the input
  # does not need any preprocessing (but in practice, even if the results are
  # very close to 1 and 0, it is probably okay to skip preprocessing for better
  # efficiency; we use 1e-5 below instead of absolute zero).
  params = common.input_details(interpreter, 'quantization_parameters')
  scale = params['scales']
  zero_point = params['zero_points']
  mean = args.input_mean
  std = args.input_std
  if abs(scale * std - 1) < 1e-5 and abs(mean - zero_point) < 1e-5:
    # Input data does not require preprocessing.
    common.set_input(interpreter, image)
  else:
    # Input data requires preprocessing
    normalized_input = (np.asarray(image) - mean) / (std * scale) + zero_point
    np.clip(normalized_input, 0, 255, out=normalized_input)

    common.set_input(interpreter, normalized_input.astype(np.uint8))