# Path: detectron/utils/io.py
# def load_object(file_name):
#     with open(file_name, 'rb') as f:
#         # The default encoding used while unpickling is 7-bit (ASCII.) However,
#         # the blobs are arbitrary 8-bit bytes which don't agree. The absolute
#         # correct way to do this is to use `encoding="bytes"` and then interpret
#         # the blob names either as ASCII, or better, as unicode utf-8. A
#         # reasonable fix, however, is to treat it the encoding as 8-bit latin1
#         # (which agrees with the first 256 characters of Unicode anyway.)
#         if six.PY2:
#             return pickle.load(f)
#         else:
#             return pickle.load(f, encoding='latin1')
# 
# Path: detectron/utils/io.py
# def save_object(obj, file_name, pickle_format=2):
#     """Save a Python object by pickling it.
# 
# Unless specifically overridden, we want to save it in Pickle format=2 since this
# will allow other Python2 executables to load the resulting Pickle. When we want
# to completely remove Python2 backward-compatibility, we can bump it up to 3. We
# should never use pickle.HIGHEST_PROTOCOL as far as possible if the resulting
# file is manifested or used, external to the system.
#     """
#     file_name = os.path.abspath(file_name)
#     # Avoid filesystem race conditions (particularly on network filesystems)
#     # by saving to a random tmp file on the same filesystem, and then
#     # atomically rename to the target filename.
#     tmp_file_name = file_name + ".tmp." + uuid4().hex
#     try:
#         with open(tmp_file_name, 'wb') as f:
#             pickle.dump(obj, f, pickle_format)
#             f.flush()  # make sure it's written to disk
#             os.fsync(f.fileno())
#         os.rename(tmp_file_name, file_name)
#     finally:
#         # Clean up the temp file on failure. Rather than using os.path.exists(),
#         # which can be unreliable on network filesystems, attempt to delete and
#         # ignore os errors.
#         try:
#             os.remove(tmp_file_name)
#         except EnvironmentError as e:  # parent class of IOError, OSError
#             if getattr(e, 'errno', None) != errno.ENOENT:  # We expect ENOENT
#                 logger.info("Could not delete temp file %r",
#                     tmp_file_name, exc_info=True)
#                 # pass through since we don't want the job to crash


import logging
import numpy as np
import os
import xml.etree.ElementTree as ET
from detectron.utils.io import load_object
from detectron.utils.io import save_object
    [ovthresh]: Overlap threshold (default = 0.5)
    [use_07_metric]: Whether to use VOC07's 11 point AP computation
        (default False)
    """
    # assumes detections are in detpath.format(classname)
    # assumes annotations are in annopath.format(imagename)
    # assumes imagesetfile is a text file with each line an image name
    # cachedir caches the annotations in a pickle file

    # first load gt
    if not os.path.isdir(cachedir):
        os.mkdir(cachedir)
    imageset = os.path.splitext(os.path.basename(imagesetfile))[0]
    cachefile = os.path.join(cachedir, imageset + '_annots.pkl')
    # read list of images
    with open(imagesetfile, 'r') as f:
        lines = f.readlines()
    imagenames = [x.strip() for x in lines]

    if not os.path.isfile(cachefile):
        # load annots
        recs = {}
        for i, imagename in enumerate(imagenames):
            recs[imagename] = parse_rec(annopath.format(imagename))
            if i % 100 == 0:
                logger.info(
                    'Reading annotation for {:d}/{:d}'.format(
                        i + 1, len(imagenames)))
        # save
        logger.info('Saving cached annotations to {:s}'.format(cachefile))

# Path: detectron/utils/io.py
# def load_object(file_name):
#     with open(file_name, 'rb') as f:
#         # The default encoding used while unpickling is 7-bit (ASCII.) However,
#         # the blobs are arbitrary 8-bit bytes which don't agree. The absolute
#         # correct way to do this is to use `encoding="bytes"` and then interpret
#         # the blob names either as ASCII, or better, as unicode utf-8. A
#         # reasonable fix, however, is to treat it the encoding as 8-bit latin1
#         # (which agrees with the first 256 characters of Unicode anyway.)
#         if six.PY2:
#             return pickle.load(f)
#         else:
#             return pickle.load(f, encoding='latin1')
# 
# Path: detectron/utils/io.py
# def save_object(obj, file_name, pickle_format=2):
#     """Save a Python object by pickling it.
# 
# Unless specifically overridden, we want to save it in Pickle format=2 since this
# will allow other Python2 executables to load the resulting Pickle. When we want
# to completely remove Python2 backward-compatibility, we can bump it up to 3. We
# should never use pickle.HIGHEST_PROTOCOL as far as possible if the resulting
# file is manifested or used, external to the system.
#     """
#     file_name = os.path.abspath(file_name)
#     # Avoid filesystem race conditions (particularly on network filesystems)
#     # by saving to a random tmp file on the same filesystem, and then
#     # atomically rename to the target filename.
#     tmp_file_name = file_name + ".tmp." + uuid4().hex
#     try:
#         with open(tmp_file_name, 'wb') as f:
#             pickle.dump(obj, f, pickle_format)
#             f.flush()  # make sure it's written to disk
#             os.fsync(f.fileno())
#         os.rename(tmp_file_name, file_name)
#     finally:
#         # Clean up the temp file on failure. Rather than using os.path.exists(),
#         # which can be unreliable on network filesystems, attempt to delete and
#         # ignore os errors.
#         try:
#             os.remove(tmp_file_name)
#         except EnvironmentError as e:  # parent class of IOError, OSError
#             if getattr(e, 'errno', None) != errno.ENOENT:  # We expect ENOENT
#                 logger.info("Could not delete temp file %r",
#                     tmp_file_name, exc_info=True)
#                 # pass through since we don't want the job to crash


# Path: detectron/datasets/voc_eval.py
import logging
import numpy as np
import os
import xml.etree.ElementTree as ET
from detectron.utils.io import load_object
from detectron.utils.io import save_object

    [ovthresh]: Overlap threshold (default = 0.5)
    [use_07_metric]: Whether to use VOC07's 11 point AP computation
        (default False)
    """
    # assumes detections are in detpath.format(classname)
    # assumes annotations are in annopath.format(imagename)
    # assumes imagesetfile is a text file with each line an image name
    # cachedir caches the annotations in a pickle file

    # first load gt
    if not os.path.isdir(cachedir):
        os.mkdir(cachedir)
    imageset = os.path.splitext(os.path.basename(imagesetfile))[0]
    cachefile = os.path.join(cachedir, imageset + '_annots.pkl')
    # read list of images
    with open(imagesetfile, 'r') as f:
        lines = f.readlines()
    imagenames = [x.strip() for x in lines]

    if not os.path.isfile(cachefile):
        # load annots
        recs = {}
        for i, imagename in enumerate(imagenames):
            recs[imagename] = parse_rec(annopath.format(imagename))
            if i % 100 == 0:
                logger.info(
                    'Reading annotation for {:d}/{:d}'.format(
                        i + 1, len(imagenames)))
        # save
        logger.info('Saving cached annotations to {:s}'.format(cachefile))

        save_object(recs, cachefile)