{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport gc\ngc.enable()\nfrom multiprocessing import Pool, cpu_count\n\nimport matplotlib.pyplot as plt\nfrom six import BytesIO\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom pprint import pprint\n\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior() \nimport tensorflow_hub as hub\nfrom PIL import Image, ImageColor, ImageDraw, ImageFont, ImageOps","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"def form_one_prediction_strings(result, i):\n    class_name = result['detection_class_names'][i].decode(\"utf-8\")\n    boxes = result['detection_boxes'][i]\n    score = result['detection_scores'][i]\n    return f\"{class_name} {score} \" + \" \".join(map(str, boxes))\n\n\ndef format_prediction_string(detected):\n    image_id, result = detected\n    prediction_strings = [form_one_prediction_strings(result, i) for i in range(len(result['detection_scores']))]\n    return {\n        \"ImageID\": image_id,\n        \"PredictionString\": \" \".join(prediction_strings)\n    }\n\n\ndef inference_one_chunk(data_path, list_image_ids, session, result, image_string_placeholder, predictions):\n    img_files = {\n        i: tf.gfile.Open(\n            os.sep.join([data_path, 'test', f'{i}.jpg']), \"rb\").read() for i in list_image_ids}\n    \n    for image_id in tqdm(list_image_ids):\n        result_out = session.run(\n            result, feed_dict={image_string_placeholder: img_files[image_id]})\n\n        predictions.append((image_id, result_out))\n        \n    del img_files\n    gc.collect()\n    return\n\n\ndef inference():\n    \n    # load model\n    module_handle = \"https://tfhub.dev/google/openimages_v4/ssd/mobilenet_v2/1\"\n    with tf.device('/device:GPU:0'):\n        with tf.Graph().as_default():\n            detector = hub.Module(module_handle)\n            image_string_placeholder = tf.placeholder(tf.string)\n            decoded_image = tf.image.decode_jpeg(image_string_placeholder)\n            decoded_image_float = tf.image.convert_image_dtype(image=decoded_image, dtype=tf.float32)\n            module_input = tf.expand_dims(decoded_image_float, 0)\n            result = detector(module_input, as_dict=True)\n            init_ops = [tf.global_variables_initializer(), tf.tables_initializer()]\n\n            session = tf.Session()\n            session.run(init_ops)\n\n    data_path = \"/kaggle/input/open-images-object-detection-rvc-2020\"\n    sample_submission_df = pd.read_csv(f'{data_path}/sample_submission.csv')\n    image_ids = sample_submission_df['ImageId']\n    \n    predictions = []\n    with tf.device('/device:GPU:0'):\n        step = 10\n        for ii in range(0, len(image_ids), step):\n            list_image_ids = image_ids.tolist()[ii: ii+step]\n            inference_one_chunk(data_path, list_image_ids, session, result, image_string_placeholder, predictions)\n    \n    predictions_df = pd.DataFrame(list(map(format_prediction_string, predictions)))\n    predictions_df.to_csv('submission.csv', index=False)\n    session.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inference()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}