# 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 argparse
import numpy as np
import os
import sys
import detectron.datasets.coco_to_cityscapes_id as cs
from detectron.utils.io import load_object
from detectron.utils.io import save_object
    # Replace random parameters with COCO parameters if class mapping exists
    for i in range(NUM_CS_CLS):
        coco_cls_id = getattr(cs, convert_func)(i)
        if coco_cls_id >= 0:  # otherwise ignore (rand init)
            cs_blob[i] = coco_blob[coco_cls_id]

    cs_shape = [NUM_CS_CLS * leading_factor] + tail_shape
    return cs_blob.reshape(cs_shape)


def remove_momentum(model_dict):
    for k in model_dict['blobs'].keys():
        if k.endswith('_momentum'):
            del model_dict['blobs'][k]


def load_and_convert_coco_model(args):
    model_dict = load_object(args.coco_model_file_name)
    remove_momentum(model_dict)
    convert_coco_blobs_to_cityscape_blobs(model_dict)
    return model_dict


if __name__ == '__main__':
    args = parse_args()
    print(args)
    assert os.path.exists(args.coco_model_file_name), \
        'Weights file does not exist'
    weights = load_and_convert_coco_model(args)


# 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: tools/convert_coco_model_to_cityscapes.py
import argparse
import numpy as np
import os
import sys
import detectron.datasets.coco_to_cityscapes_id as cs
from detectron.utils.io import load_object
from detectron.utils.io import save_object

    # Replace random parameters with COCO parameters if class mapping exists
    for i in range(NUM_CS_CLS):
        coco_cls_id = getattr(cs, convert_func)(i)
        if coco_cls_id >= 0:  # otherwise ignore (rand init)
            cs_blob[i] = coco_blob[coco_cls_id]

    cs_shape = [NUM_CS_CLS * leading_factor] + tail_shape
    return cs_blob.reshape(cs_shape)


def remove_momentum(model_dict):
    for k in model_dict['blobs'].keys():
        if k.endswith('_momentum'):
            del model_dict['blobs'][k]


def load_and_convert_coco_model(args):
    model_dict = load_object(args.coco_model_file_name)
    remove_momentum(model_dict)
    convert_coco_blobs_to_cityscape_blobs(model_dict)
    return model_dict


if __name__ == '__main__':
    args = parse_args()
    print(args)
    assert os.path.exists(args.coco_model_file_name), \
        'Weights file does not exist'
    weights = load_and_convert_coco_model(args)


    save_object(weights, args.out_file_name)