{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":5048288,"sourceType":"datasetVersion","datasetId":2919095},{"sourceId":8942261,"sourceType":"datasetVersion","datasetId":5380641}],"dockerImageVersionId":12836,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"! pip install  ultralytics\n! pip install opencv-python-headless\n! pip install -U ipywidgets","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:59:09.523412Z","iopub.execute_input":"2024-07-13T14:59:09.523776Z","iopub.status.idle":"2024-07-13T14:59:45.655836Z","shell.execute_reply.started":"2024-07-13T14:59:09.523725Z","shell.execute_reply":"2024-07-13T14:59:45.65502Z"},"trusted":true},"outputs":[{"name":"stdout","text":"Collecting ultralytics\n\u001b[31m  Could not find a version that satisfies the requirement ultralytics (from versions: )\u001b[0m\n\u001b[31mNo matching distribution found for ultralytics\u001b[0m\n\u001b[33mYou are using pip version 10.0.1, however version 21.3.1 is available.\nYou should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\nCollecting opencv-python-headless\n\u001b[?25l  Downloading https://files.pythonhosted.org/packages/2f/7e/d20f68a5f1487adf19d74378d349932a386b1ece3be9be9915e5986db468/opencv-python-headless-4.10.0.84.tar.gz (95.1MB)\n\u001b[K    100% |████████████████████████████████| 95.1MB 418kB/s eta 0:00:01\n\u001b[33m  Missing build time requirements in pyproject.toml for opencv-python-headless from https://files.pythonhosted.org/packages/2f/7e/d20f68a5f1487adf19d74378d349932a386b1ece3be9be9915e5986db468/opencv-python-headless-4.10.0.84.tar.gz#sha256=f2017c6101d7c2ef8d7bc3b414c37ff7f54d64413a1847d89970b6b7069b4e1a: 'wheel'.\u001b[0m\n\u001b[33m  This version of pip does not implement PEP 517 so it cannot build a wheel without 'setuptools' and 'wheel'.\u001b[0m\n\u001b[31m  Could not find a version that satisfies the requirement numpy==1.21.0 (from versions: 1.11.3, 1.12.0, 1.12.1, 1.13.0, 1.13.1, 1.13.3, 1.14.0, 1.14.1, 1.14.2, 1.14.3, 1.14.4, 1.14.5, 1.14.6, 1.15.0, 1.15.1, 1.15.2, 1.15.3, 1.15.4, 1.16.0, 1.16.1, 1.16.2, 1.16.3, 1.16.4, 1.16.5, 1.16.6, 1.17.0, 1.17.1, 1.17.2, 1.17.3, 1.17.4, 1.17.5, 1.18.0, 1.18.1, 1.18.2, 1.18.3, 1.18.4, 1.18.5, 1.19.0, 1.19.1, 1.19.2, 1.19.3, 1.19.4, 1.19.5)\u001b[0m\n\u001b[31mNo matching distribution found for numpy==1.21.0\u001b[0m\n\u001b[33mYou are using pip version 10.0.1, however version 21.3.1 is available.\nYou should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n\u001b[?25hCollecting ipywidgets\n\u001b[?25l  Downloading https://files.pythonhosted.org/packages/59/e8/a4e5ba5ca8f4e5d49b3f90bb3c0705842b27f94b58491b1d1529e6071415/ipywidgets-7.8.2-py2.py3-none-any.whl (124kB)\n\u001b[K    100% |████████████████████████████████| 133kB 2.2MB/s ta 0:00:01\n\u001b[?25hRequirement not upgraded as not directly required: traitlets>=4.3.1 in /opt/conda/lib/python3.6/site-packages (from ipywidgets) (4.3.2)\nCollecting widgetsnbextension~=3.6.7 (from ipywidgets)\n\u001b[?25l  Downloading https://files.pythonhosted.org/packages/c3/5c/f211dbc95aa8957ec33f8b7c53a70bd0c2802c929a344a3aab4e8c2ef07b/widgetsnbextension-3.6.7-py2.py3-none-any.whl (1.5MB)\n\u001b[K    100% |████████████████████████████████| 1.5MB 12.9MB/s ta 0:00:01\n\u001b[?25hCollecting jupyterlab-widgets<3,>=1.0.0; python_version >= \"3.6\" (from ipywidgets)\n\u001b[?25l  Downloading https://files.pythonhosted.org/packages/98/3d/de86d1e3978c7191b1c8ff1fb14d271276eb0d6605f4cc62b939c5e8872d/jupyterlab_widgets-1.1.8-py3-none-any.whl (237kB)\n\u001b[K    100% |████████████████████████████████| 245kB 33.6MB/s ta 0:00:01\n\u001b[?25hRequirement not upgraded as not directly required: ipython-genutils~=0.2.0 in /opt/conda/lib/python3.6/site-packages (from ipywidgets) (0.2.0)\nCollecting comm>=0.1.3 (from ipywidgets)\n  Downloading https://files.pythonhosted.org/packages/fe/47/0133ac1b7dc476ed77710715e98077119b3d9bae56b13f6f9055e7da1c53/comm-0.1.4-py3-none-any.whl\nRequirement not upgraded as not directly required: ipython>=4.0.0; python_version >= \"3.3\" in /opt/conda/lib/python3.6/site-packages (from ipywidgets) (7.0.1)\nRequirement not upgraded as not directly required: six in /opt/conda/lib/python3.6/site-packages (from traitlets>=4.3.1->ipywidgets) (1.11.0)\nRequirement not upgraded as not directly required: decorator in /opt/conda/lib/python3.6/site-packages (from traitlets>=4.3.1->ipywidgets) (4.3.0)\nRequirement not upgraded as not directly required: notebook>=4.4.1 in /opt/conda/lib/python3.6/site-packages (from widgetsnbextension~=3.6.7->ipywidgets) (5.5.0)\nRequirement not upgraded as not directly required: pexpect; sys_platform != \"win32\" in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (4.6.0)\nRequirement not upgraded as not directly required: prompt-toolkit<2.1.0,>=2.0.0 in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (2.0.6)\nRequirement not upgraded as not directly required: pickleshare in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (0.7.5)\nRequirement not upgraded as not directly required: setuptools>=18.5 in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (39.1.0)\nRequirement not upgraded as not directly required: backcall in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (0.1.0)\nRequirement not upgraded as not directly required: simplegeneric>0.8 in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (0.8.1)\nRequirement not upgraded as not directly required: pygments in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (2.2.0)\nRequirement not upgraded as not directly required: jedi>=0.10 in /opt/conda/lib/python3.6/site-packages (from ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (0.13.1)\nRequirement not upgraded as not directly required: ipykernel in /opt/conda/lib/python3.6/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (5.0.0)\nRequirement not upgraded as not directly required: jinja2 in /opt/conda/lib/python3.6/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (2.10)\nRequirement not upgraded as not directly required: nbformat in /opt/conda/lib/python3.6/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (4.4.0)\nRequirement not upgraded as not directly required: Send2Trash in /opt/conda/lib/python3.6/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (1.5.0)\nRequirement not upgraded as not directly required: jupyter-client>=5.2.0 in /opt/conda/lib/python3.6/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (5.2.3)\nRequirement not upgraded as not directly required: pyzmq>=17 in /opt/conda/lib/python3.6/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (17.1.2)\nRequirement not upgraded as not directly required: tornado>=4 in /opt/conda/lib/python3.6/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (5.1.1)\nRequirement not upgraded as not directly required: jupyter-core>=4.4.0 in /opt/conda/lib/python3.6/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (4.4.0)\nRequirement not upgraded as not directly required: nbconvert in /opt/conda/lib/python3.6/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (5.4.0)\nRequirement not upgraded as not directly required: terminado>=0.8.1 in /opt/conda/lib/python3.6/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (0.8.1)\nRequirement not upgraded as not directly required: ptyprocess>=0.5 in /opt/conda/lib/python3.6/site-packages (from pexpect; sys_platform != \"win32\"->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (0.6.0)\nRequirement not upgraded as not directly required: wcwidth in /opt/conda/lib/python3.6/site-packages (from prompt-toolkit<2.1.0,>=2.0.0->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (0.1.7)\nRequirement not upgraded as not directly required: parso>=0.3.0 in /opt/conda/lib/python3.6/site-packages (from jedi>=0.10->ipython>=4.0.0; python_version >= \"3.3\"->ipywidgets) (0.3.1)\nRequirement not upgraded as not directly required: MarkupSafe>=0.23 in /opt/conda/lib/python3.6/site-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (1.0)\nRequirement not upgraded as not directly required: jsonschema!=2.5.0,>=2.4 in /opt/conda/lib/python3.6/site-packages (from nbformat->notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (2.6.0)\nRequirement not upgraded as not directly required: python-dateutil>=2.1 in /opt/conda/lib/python3.6/site-packages (from jupyter-client>=5.2.0->notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (2.6.0)\nRequirement not upgraded as not directly required: mistune>=0.8.1 in /opt/conda/lib/python3.6/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (0.8.4)\nRequirement not upgraded as not directly required: entrypoints>=0.2.2 in /opt/conda/lib/python3.6/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (0.2.3)\nRequirement not upgraded as not directly required: bleach in /opt/conda/lib/python3.6/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (3.0.2)\nRequirement not upgraded as not directly required: pandocfilters>=1.4.1 in /opt/conda/lib/python3.6/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (1.4.2)\nRequirement not upgraded as not directly required: testpath in /opt/conda/lib/python3.6/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (0.4.2)\nRequirement not upgraded as not directly required: defusedxml in /opt/conda/lib/python3.6/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (0.5.0)\nRequirement not upgraded as not directly required: webencodings in /opt/conda/lib/python3.6/site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.6.7->ipywidgets) (0.5.1)\n\u001b[31mmxnet 1.3.0.post0 has requirement numpy<1.15.0,>=1.8.2, but you'll have numpy 1.15.2 which is incompatible.\u001b[0m\n\u001b[31mkmeans-smote 0.1.0 has requirement imbalanced-learn<0.4,>=0.3.1, but you'll have imbalanced-learn 0.5.0.dev0 which is incompatible.\u001b[0m\n\u001b[31mkmeans-smote 0.1.0 has requirement numpy<1.15,>=1.13, but you'll have numpy 1.15.2 which is incompatible.\u001b[0m\n\u001b[31mfastai 0.7.0 has requirement torch<0.4, but you'll have torch 0.4.1.post2 which is incompatible.\u001b[0m\n\u001b[31manaconda-client 1.7.2 has requirement python-dateutil>=2.6.1, but you'll have python-dateutil 2.6.0 which is incompatible.\u001b[0m\n\u001b[31mimbalanced-learn 0.5.0.dev0 has requirement scikit-learn>=0.20, but you'll have scikit-learn 0.19.1 which is incompatible.\u001b[0m\nInstalling collected packages: widgetsnbextension, jupyterlab-widgets, comm, ipywidgets\n  Found existing installation: widgetsnbextension 3.4.2\n    Uninstalling widgetsnbextension-3.4.2:\n      Successfully uninstalled widgetsnbextension-3.4.2\n  Found existing installation: ipywidgets 7.4.2\n    Uninstalling ipywidgets-7.4.2:\n      Successfully uninstalled ipywidgets-7.4.2\nSuccessfully installed comm-0.1.4 ipywidgets-7.8.2 jupyterlab-widgets-1.1.8 widgetsnbextension-3.6.7\n\u001b[33mYou are using pip version 10.0.1, however version 21.3.1 is available.\nYou should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n","output_type":"stream"}],"execution_count":1},{"cell_type":"code","source":"pip install --upgrade pip","metadata":{"execution":{"iopub.status.busy":"2024-07-13T15:02:24.921639Z","iopub.execute_input":"2024-07-13T15:02:24.921949Z","iopub.status.idle":"2024-07-13T15:02:24.926813Z","shell.execute_reply.started":"2024-07-13T15:02:24.921903Z","shell.execute_reply":"2024-07-13T15:02:24.925905Z"},"trusted":true},"outputs":[{"name":"stdout","text":"\nThe following command must be run outside of the IPython shell:\n\n    $ pip install --upgrade pip\n\nThe Python package manager (pip) can only be used from outside of IPython.\nPlease reissue the `pip` command in a separate terminal or command prompt.\n\nSee the Python documentation for more information on how to install packages:\n\n    https://docs.python.org/3/installing/\n","output_type":"stream"}],"execution_count":2},{"cell_type":"code","source":"! nvidia-smi -L","metadata":{"execution":{"iopub.status.busy":"2024-07-13T15:02:29.891868Z","iopub.execute_input":"2024-07-13T15:02:29.892154Z","iopub.status.idle":"2024-07-13T15:02:30.88791Z","shell.execute_reply.started":"2024-07-13T15:02:29.892113Z","shell.execute_reply":"2024-07-13T15:02:30.886982Z"},"trusted":true},"outputs":[],"execution_count":3},{"cell_type":"code","source":"! wandb disabled","metadata":{"execution":{"iopub.status.busy":"2024-07-13T15:02:37.292632Z","iopub.execute_input":"2024-07-13T15:02:37.29294Z","iopub.status.idle":"2024-07-13T15:02:38.28933Z","shell.execute_reply.started":"2024-07-13T15:02:37.292895Z","shell.execute_reply":"2024-07-13T15:02:38.288493Z"},"trusted":true},"outputs":[{"name":"stdout","text":"/bin/sh: 1: wandb: not found\n","output_type":"stream"}],"execution_count":4},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport os\nimport re\nimport glob\nimport random\nimport yaml\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\nimport seaborn as sns\n\nimport IPython.display as display\nfrom PIL import Image\nimport cv2\n\nfrom ultralytics import YOLO","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:32:07.265891Z","iopub.execute_input":"2024-07-13T14:32:07.266215Z","iopub.status.idle":"2024-07-13T14:32:07.272936Z","shell.execute_reply.started":"2024-07-13T14:32:07.266182Z","shell.execute_reply":"2024-07-13T14:32:07.271972Z"},"trusted":true},"outputs":[],"execution_count":19},{"cell_type":"code","source":"    FRACTION = 1.0\n    SEED = 88\n\n    CLASSES = ['Hardhat', 'Mask', 'NO-Hardhat', 'NO-Mask',\n               'NO-Safety Vest', 'Person', 'Safety Cone',\n               'Safety Vest', 'machinery', 'vehicle']\n    NUM_CLASSES_TO_TRAIN = len(CLASSES)\n\n    EPOCHS = 70 \n    BATCH_SIZE = 16\n    \n    BASE_MODEL = 'yolov10x' \n    BASE_MODEL_WEIGHTS = f'{BASE_MODEL}.pt'\n    EXP_NAME = f'ppe_cssss_{EPOCHS}_epochs'\n    \n    OPTIMIZER = 'auto' \n    LR = 1e-3\n    LR_FACTOR = 0.01\n    WEIGHT_DECAY = 5e-4\n    DROPOUT = 0.0\n    PATIENCE = 20\n    PROFILE = False\n    LABEL_SMOOTHING = 0.0    \n\n    # paths\n    CUSTOM_DATASET_DIR = '/kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/'\n    OUTPUT_DIR = './'","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:32:07.274189Z","iopub.execute_input":"2024-07-13T14:32:07.27444Z","iopub.status.idle":"2024-07-13T14:32:07.285276Z","shell.execute_reply.started":"2024-07-13T14:32:07.274419Z","shell.execute_reply":"2024-07-13T14:32:07.284519Z"},"trusted":true},"outputs":[],"execution_count":20},{"cell_type":"code","source":"dict_file = {\n    'train': os.path.join(CUSTOM_DATASET_DIR, 'train'),\n    'val': os.path.join(CUSTOM_DATASET_DIR, 'valid'),\n    'test': os.path.join(CUSTOM_DATASET_DIR, 'test'),\n    'nc': NUM_CLASSES_TO_TRAIN,\n    'names': CLASSES\n    }\n\nwith open(os.path.join(OUTPUT_DIR, 'data.yaml'), 'w+') as file:\n    yaml.dump(dict_file, file)","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:32:07.286511Z","iopub.execute_input":"2024-07-13T14:32:07.286849Z","iopub.status.idle":"2024-07-13T14:32:07.303911Z","shell.execute_reply.started":"2024-07-13T14:32:07.286819Z","shell.execute_reply":"2024-07-13T14:32:07.303161Z"},"trusted":true},"outputs":[],"execution_count":21},{"cell_type":"code","source":"def read_yaml_file(file_path = CUSTOM_DATASET_DIR):\n    with open(file_path, 'r') as file:\n        try:\n            data = yaml.safe_load(file)\n            return data\n        except yaml.YAMLError as e:\n            print(\"Error reading YAML:\", e)\n            return None\n\ndef print_yaml_data(data):\n    formatted_yaml = yaml.dump(data, default_style=False)\n    print(formatted_yaml)\n\nfile_path = os.path.join(OUTPUT_DIR, 'data.yaml')\nyaml_data = read_yaml_file(file_path)\n\nif yaml_data:\n    print_yaml_data(yaml_data)","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:32:07.305076Z","iopub.execute_input":"2024-07-13T14:32:07.305488Z","iopub.status.idle":"2024-07-13T14:32:07.319581Z","shell.execute_reply.started":"2024-07-13T14:32:07.305457Z","shell.execute_reply":"2024-07-13T14:32:07.318739Z"},"trusted":true},"outputs":[{"name":"stdout","text":"names:\n- Hardhat\n- Mask\n- NO-Hardhat\n- NO-Mask\n- NO-Safety Vest\n- Person\n- Safety Cone\n- Safety Vest\n- machinery\n- vehicle\nnc: 10\ntest: /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/test\ntrain: /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train\nval: /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/valid\n\n","output_type":"stream"}],"execution_count":22},{"cell_type":"code","source":"def get_image_properties(image_path):\n    # Read the image file\n    img = cv2.imread(image_path)\n\n    # Check if the image file is read successfully\n    if img is None:\n        raise ValueError(\"Could not read image file\")\n\n    # Get image properties\n    properties = {\n        \"width\": img.shape[1],\n        \"height\": img.shape[0],\n        \"channels\": img.shape[2] if len(img.shape) == 3 else 1,\n        \"dtype\": img.dtype,\n    }\n\n    return properties","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:32:07.320968Z","iopub.execute_input":"2024-07-13T14:32:07.321751Z","iopub.status.idle":"2024-07-13T14:32:07.334635Z","shell.execute_reply.started":"2024-07-13T14:32:07.321715Z","shell.execute_reply":"2024-07-13T14:32:07.333974Z"},"trusted":true},"outputs":[],"execution_count":23},{"cell_type":"code","source":"example_image_path = '/kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/images/-2297-_png_jpg.rf.9fff3740d864fbec9cda50d783ad805e.jpg'\nimg_properties = get_image_properties(example_image_path)\nimg_properties","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:32:07.338152Z","iopub.execute_input":"2024-07-13T14:32:07.338502Z","iopub.status.idle":"2024-07-13T14:32:07.365969Z","shell.execute_reply.started":"2024-07-13T14:32:07.338473Z","shell.execute_reply":"2024-07-13T14:32:07.365185Z"},"trusted":true},"outputs":[{"execution_count":24,"output_type":"execute_result","data":{"text/plain":"{'width': 640, 'height': 640, 'channels': 3, 'dtype': dtype('uint8')}"},"metadata":{}}],"execution_count":24},{"cell_type":"code","source":"BASE_MODEL_WEIGHTS","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:32:07.366838Z","iopub.execute_input":"2024-07-13T14:32:07.367119Z","iopub.status.idle":"2024-07-13T14:32:07.372642Z","shell.execute_reply.started":"2024-07-13T14:32:07.367097Z","shell.execute_reply":"2024-07-13T14:32:07.371767Z"},"trusted":true},"outputs":[{"execution_count":25,"output_type":"execute_result","data":{"text/plain":"'yolov10x.pt'"},"metadata":{}}],"execution_count":25},{"cell_type":"code","source":"model = YOLO(BASE_MODEL_WEIGHTS)","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:32:07.373783Z","iopub.execute_input":"2024-07-13T14:32:07.374052Z","iopub.status.idle":"2024-07-13T14:32:07.600898Z","shell.execute_reply.started":"2024-07-13T14:32:07.374029Z","shell.execute_reply":"2024-07-13T14:32:07.600096Z"},"trusted":true},"outputs":[],"execution_count":26},{"cell_type":"code","source":"\n\nmodel = YOLO('/kaggle/working/runs/detect/yolov10x_ppe_css_70_epochs/weights/last.pt')\n\nmodel.train(\n\n\n    resume=True,\n \n)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:32:07.602017Z","iopub.execute_input":"2024-07-13T14:32:07.60231Z","iopub.status.idle":"2024-07-13T14:33:34.187938Z","shell.execute_reply.started":"2024-07-13T14:32:07.602285Z","shell.execute_reply":"2024-07-13T14:33:34.185717Z"},"trusted":true},"outputs":[{"name":"stdout","text":"Ultralytics YOLOv8.2.55 🚀 Python-3.10.13 torch-2.1.2 CUDA:0 (Tesla T4, 15095MiB)\n                                                      CUDA:1 (Tesla T4, 15095MiB)\n\u001b[34m\u001b[1mengine/trainer: \u001b[0mtask=detect, mode=train, model=/kaggle/working/runs/detect/yolov10x_ppe_css_70_epochs/weights/last.pt, data=./data.yaml, epochs=70, time=None, patience=20, batch=16, imgsz=640, save=True, save_period=-1, cache=False, device=[0, 1], workers=8, project=None, name=yolov10x_ppe_css_70_epochs, exist_ok=True, pretrained=True, optimizer=auto, verbose=False, seed=88, deterministic=True, single_cls=False, rect=False, cos_lr=False, close_mosaic=10, resume=/kaggle/working/runs/detect/yolov10x_ppe_css_70_epochs/weights/last.pt, amp=True, fraction=1.0, profile=False, freeze=None, multi_scale=False, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, split=val, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, vid_stride=1, stream_buffer=False, visualize=False, augment=False, agnostic_nms=False, classes=None, retina_masks=False, embed=None, show=False, save_frames=False, save_txt=False, save_conf=False, save_crop=False, show_labels=True, show_conf=True, show_boxes=True, line_width=None, format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=None, workspace=4, nms=False, lr0=0.001, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.0, box=7.5, cls=0.5, dfl=1.5, pose=12.0, kobj=1.0, label_smoothing=0.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, bgr=0.0, mosaic=1.0, mixup=0.0, copy_paste=0.0, auto_augment=randaugment, erasing=0.4, crop_fraction=1.0, cfg=None, tracker=botsort.yaml, save_dir=runs/detect/yolov10x_ppe_css_70_epochs\n\u001b[34m\u001b[1mDDP:\u001b[0m debug command /opt/conda/bin/python3.10 -m torch.distributed.run --nproc_per_node 2 --master_port 40087 /root/.config/Ultralytics/DDP/_temp_ne4nq56g135860682981232.py\nUltralytics YOLOv8.2.55 🚀 Python-3.10.13 torch-2.1.2 CUDA:0 (Tesla T4, 15095MiB)\n                                                      CUDA:1 (Tesla T4, 15095MiB)\n\u001b[34m\u001b[1mTensorBoard: \u001b[0mStart with 'tensorboard --logdir runs/detect/yolov10x_ppe_css_70_epochs', view at http://localhost:6006/\nTransferred 1135/1135 items from pretrained weights\nFreezing layer 'model.23.dfl.conv.weight'\n\u001b[34m\u001b[1mAMP: \u001b[0mrunning Automatic Mixed Precision (AMP) checks with YOLOv8n...\n\u001b[34m\u001b[1mAMP: \u001b[0mchecks passed ✅\n","output_type":"stream"},{"name":"stderr","text":"\u001b[34m\u001b[1mtrain: \u001b[0mScanning /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/labels... 2605 images, 6 backgrounds, 0 corrupt: 100%|██████████| 2605/2605 [00:04<00:00, 633.26it/s]\n","output_type":"stream"},{"name":"stdout","text":"\u001b[34m\u001b[1mtrain: \u001b[0mWARNING ⚠️ /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/images/004720_jpg.rf.afc486560a4004c7cfd67910af31a29c.jpg: 1 duplicate labels removed\n\u001b[34m\u001b[1mtrain: \u001b[0mWARNING ⚠️ /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/images/construction-813-_jpg.rf.b085952261fd98f2e76b8065de149b5f.jpg: 1 duplicate labels removed\n\u001b[34m\u001b[1mtrain: \u001b[0mWARNING ⚠️ Cache directory /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train is not writeable, cache not saved.\n\u001b[34m\u001b[1malbumentations: \u001b[0mBlur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01), CLAHE(p=0.01, clip_limit=(1, 4.0), tile_grid_size=(8, 8))\n","output_type":"stream"},{"name":"stderr","text":"/opt/conda/lib/python3.10/multiprocessing/popen_fork.py:66: RuntimeWarning: os.fork() was called. os.fork() is incompatible with multithreaded code, and JAX is multithreaded, so this will likely lead to a deadlock.\n  self.pid = os.fork()\n\u001b[34m\u001b[1mval: \u001b[0mScanning /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/valid/labels... 114 images, 10 backgrounds, 0 corrupt: 100%|██████████| 114/114 [00:00<00:00, 429.44it/s]s]\n\u001b[34m\u001b[1mtrain: \u001b[0mScanning /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/labels... 179 images, 0 backgrounds, 0 corrupt:   7%|▋         | 179/2605 [00:00<00:04, 564.89it/s]","output_type":"stream"},{"name":"stdout","text":"\u001b[34m\u001b[1mval: \u001b[0mWARNING ⚠️ Cache directory /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/valid is not writeable, cache not saved.\n","output_type":"stream"},{"name":"stderr","text":"\u001b[34m\u001b[1mtrain: \u001b[0mScanning /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/labels... 696 images, 0 backgrounds, 0 corrupt:  27%|██▋       | 696/2605 [00:01<00:03, 627.31it/s]","output_type":"stream"},{"name":"stdout","text":"Plotting labels to runs/detect/yolov10x_ppe_css_70_epochs/labels.jpg... \n","output_type":"stream"},{"name":"stderr","text":"\u001b[34m\u001b[1mtrain: \u001b[0mScanning /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/labels... 2605 images, 6 backgrounds, 0 corrupt: 100%|██████████| 2605/2605 [00:04<00:00, 650.45it/s]\n","output_type":"stream"},{"name":"stdout","text":"\u001b[34m\u001b[1moptimizer:\u001b[0m 'optimizer=auto' found, ignoring 'lr0=0.001' and 'momentum=0.937' and determining best 'optimizer', 'lr0' and 'momentum' automatically... \n\u001b[34m\u001b[1moptimizer:\u001b[0m AdamW(lr=0.000714, momentum=0.9) with parameter groups 185 weight(decay=0.0), 198 weight(decay=0.0005), 197 bias(decay=0.0)\nResuming training /kaggle/working/runs/detect/yolov10x_ppe_css_70_epochs/weights/last.pt from epoch 25 to 70 total epochs\n\u001b[34m\u001b[1mTensorBoard: \u001b[0mmodel graph visualization added ✅\nImage sizes 640 train, 640 val\nUsing 4 dataloader workers\nLogging results to \u001b[1mruns/detect/yolov10x_ppe_css_70_epochs\u001b[0m\nStarting training for 70 epochs...\n\n      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n","output_type":"stream"},{"name":"stderr","text":"      25/70      10.8G      1.953      1.641      2.406        133        640:  32%|███▏      | 52/163 [00:36<01:14,  1.49it/s][2024-07-13 14:33:33,732] torch.distributed.elastic.agent.server.api: [WARNING] Received Signals.SIGINT death signal, shutting down workers\n[2024-07-13 14:33:33,732] torch.distributed.elastic.multiprocessing.api: [WARNING] Sending process 333 closing signal SIGINT\n[2024-07-13 14:33:33,732] torch.distributed.elastic.multiprocessing.api: [WARNING] Sending process 334 closing signal SIGINT\n      25/70      10.8G      1.953      1.641      2.406        133        640:  32%|███▏      | 52/163 [00:36<01:18,  1.42it/s]\nTraceback (most recent call last):\n  File \"/root/.config/Ultralytics/DDP/_temp_ne4nq56g135860682981232.py\", line 13, in <module>\n    results = trainer.train()\n  File \"/opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py\", line 204, in train\n    self._do_train(world_size)\n  File \"/opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py\", line 393, in _do_train\n    self.optimizer_step()\n  File \"/opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py\", line 554, in optimizer_step\n    self.scaler.step(self.optimizer)\n  File \"/opt/conda/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py\", line 416, in step\n    retval = self._maybe_opt_step(optimizer, optimizer_state, *args, **kwargs)\n  File \"/opt/conda/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py\", line 314, in _maybe_opt_step\n    if not sum(v.item() for v in optimizer_state[\"found_inf_per_device\"].values()):\n  File \"/opt/conda/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py\", line 314, in <genexpr>\n    if not sum(v.item() for v in optimizer_state[\"found_inf_per_device\"].values()):\nKeyboardInterrupt\nTraceback (most recent call last):\n  File \"/root/.config/Ultralytics/DDP/_temp_ne4nq56g135860682981232.py\", line 13, in <module>\n    results = trainer.train()\n  File \"/opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py\", line 204, in train\n    self._do_train(world_size)\n  File \"/opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py\", line 393, in _do_train\n    self.optimizer_step()\n  File \"/opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py\", line 554, in optimizer_step\n    self.scaler.step(self.optimizer)\n  File \"/opt/conda/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py\", line 416, in step\n    retval = self._maybe_opt_step(optimizer, optimizer_state, *args, **kwargs)\n  File \"/opt/conda/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py\", line 314, in _maybe_opt_step\n    if not sum(v.item() for v in optimizer_state[\"found_inf_per_device\"].values()):\n  File \"/opt/conda/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py\", line 314, in <genexpr>\n    if not sum(v.item() for v in optimizer_state[\"found_inf_per_device\"].values()):\nKeyboardInterrupt\nTraceback (most recent call last):\n  File \"/root/.config/Ultralytics/DDP/_temp_ne4nq56g135860682981232.py\", line 13, in <module>\n    results = trainer.train()\n  File \"/opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py\", line 204, in train\n    self._do_train(world_size)\n  File \"/opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py\", line 393, in _do_train\n    self.optimizer_step()\n  File \"/opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py\", line 554, in optimizer_step\n    self.scaler.step(self.optimizer)\n  File \"/opt/conda/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py\", line 416, in step\n    retval = self._maybe_opt_step(optimizer, optimizer_state, *args, **kwargs)\n  File \"/opt/conda/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py\", line 314, in _maybe_opt_step\n    if not sum(v.item() for v in optimizer_state[\"found_inf_per_device\"].values()):\n  File \"/opt/conda/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py\", line 314, in <genexpr>\n    if not sum(v.item() for v in optimizer_state[\"found_inf_per_device\"].values()):\nKeyboardInterrupt\n","output_type":"stream"},{"traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)","Cell \u001b[0;32mIn[27], line 3\u001b[0m\n\u001b[1;32m      1\u001b[0m model \u001b[38;5;241m=\u001b[39m YOLO(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m/kaggle/working/runs/detect/yolov10x_ppe_css_70_epochs/weights/last.pt\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[0;32m----> 3\u001b[0m \u001b[43mmodel\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtrain\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m      4\u001b[0m \n\u001b[1;32m      5\u001b[0m \n\u001b[1;32m      6\u001b[0m \u001b[43m    \u001b[49m\u001b[43mresume\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[1;32m      7\u001b[0m \u001b[43m \u001b[49m\n\u001b[1;32m      8\u001b[0m \u001b[43m)\u001b[49m\n","File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/ultralytics/engine/model.py:650\u001b[0m, in \u001b[0;36mModel.train\u001b[0;34m(self, trainer, **kwargs)\u001b[0m\n\u001b[1;32m    647\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mmodel \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtrainer\u001b[38;5;241m.\u001b[39mmodel\n\u001b[1;32m    649\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtrainer\u001b[38;5;241m.\u001b[39mhub_session \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msession  \u001b[38;5;66;03m# attach optional HUB session\u001b[39;00m\n\u001b[0;32m--> 650\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtrainer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtrain\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    651\u001b[0m \u001b[38;5;66;03m# Update model and cfg after training\u001b[39;00m\n\u001b[1;32m    652\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m RANK \u001b[38;5;129;01min\u001b[39;00m {\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m0\u001b[39m}:\n","File \u001b[0;32m/opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py:197\u001b[0m, in \u001b[0;36mBaseTrainer.train\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m    195\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m    196\u001b[0m     LOGGER\u001b[38;5;241m.\u001b[39minfo(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcolorstr(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mDDP:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m debug command \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m \u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;241m.\u001b[39mjoin(cmd)\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m)\n\u001b[0;32m--> 197\u001b[0m     \u001b[43msubprocess\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcmd\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcheck\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m)\u001b[49m\n\u001b[1;32m    198\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m    199\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m e\n","File \u001b[0;32m/opt/conda/lib/python3.10/subprocess.py:505\u001b[0m, in \u001b[0;36mrun\u001b[0;34m(input, capture_output, timeout, check, *popenargs, **kwargs)\u001b[0m\n\u001b[1;32m    503\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m Popen(\u001b[38;5;241m*\u001b[39mpopenargs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs) \u001b[38;5;28;01mas\u001b[39;00m process:\n\u001b[1;32m    504\u001b[0m     \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 505\u001b[0m         stdout, stderr \u001b[38;5;241m=\u001b[39m \u001b[43mprocess\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcommunicate\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtimeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtimeout\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    506\u001b[0m     \u001b[38;5;28;01mexcept\u001b[39;00m TimeoutExpired \u001b[38;5;28;01mas\u001b[39;00m exc:\n\u001b[1;32m    507\u001b[0m         process\u001b[38;5;241m.\u001b[39mkill()\n","File \u001b[0;32m/opt/conda/lib/python3.10/subprocess.py:1146\u001b[0m, in \u001b[0;36mPopen.communicate\u001b[0;34m(self, input, timeout)\u001b[0m\n\u001b[1;32m   1144\u001b[0m         stderr \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstderr\u001b[38;5;241m.\u001b[39mread()\n\u001b[1;32m   1145\u001b[0m         \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstderr\u001b[38;5;241m.\u001b[39mclose()\n\u001b[0;32m-> 1146\u001b[0m     \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mwait\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m   1147\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m   1148\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m timeout \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n","File \u001b[0;32m/opt/conda/lib/python3.10/subprocess.py:1209\u001b[0m, in \u001b[0;36mPopen.wait\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m   1207\u001b[0m     endtime \u001b[38;5;241m=\u001b[39m _time() \u001b[38;5;241m+\u001b[39m timeout\n\u001b[1;32m   1208\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m-> 1209\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_wait\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtimeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtimeout\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m   1210\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mKeyboardInterrupt\u001b[39;00m:\n\u001b[1;32m   1211\u001b[0m     \u001b[38;5;66;03m# https://bugs.python.org/issue25942\u001b[39;00m\n\u001b[1;32m   1212\u001b[0m     \u001b[38;5;66;03m# The first keyboard interrupt waits briefly for the child to\u001b[39;00m\n\u001b[1;32m   1213\u001b[0m     \u001b[38;5;66;03m# exit under the common assumption that it also received the ^C\u001b[39;00m\n\u001b[1;32m   1214\u001b[0m     \u001b[38;5;66;03m# generated SIGINT and will exit rapidly.\u001b[39;00m\n\u001b[1;32m   1215\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m timeout \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n","File \u001b[0;32m/opt/conda/lib/python3.10/subprocess.py:1959\u001b[0m, in \u001b[0;36mPopen._wait\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m   1957\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mreturncode \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m   1958\u001b[0m     \u001b[38;5;28;01mbreak\u001b[39;00m  \u001b[38;5;66;03m# Another thread waited.\u001b[39;00m\n\u001b[0;32m-> 1959\u001b[0m (pid, sts) \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_try_wait\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m   1960\u001b[0m \u001b[38;5;66;03m# Check the pid and loop as waitpid has been known to\u001b[39;00m\n\u001b[1;32m   1961\u001b[0m \u001b[38;5;66;03m# return 0 even without WNOHANG in odd situations.\u001b[39;00m\n\u001b[1;32m   1962\u001b[0m \u001b[38;5;66;03m# http://bugs.python.org/issue14396.\u001b[39;00m\n\u001b[1;32m   1963\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m pid \u001b[38;5;241m==\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mpid:\n","File \u001b[0;32m/opt/conda/lib/python3.10/subprocess.py:1917\u001b[0m, in \u001b[0;36mPopen._try_wait\u001b[0;34m(self, wait_flags)\u001b[0m\n\u001b[1;32m   1915\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"All callers to this function MUST hold self._waitpid_lock.\"\"\"\u001b[39;00m\n\u001b[1;32m   1916\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m-> 1917\u001b[0m     (pid, sts) \u001b[38;5;241m=\u001b[39m \u001b[43mos\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mwaitpid\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mpid\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mwait_flags\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m   1918\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mChildProcessError\u001b[39;00m:\n\u001b[1;32m   1919\u001b[0m     \u001b[38;5;66;03m# This happens if SIGCLD is set to be ignored or waiting\u001b[39;00m\n\u001b[1;32m   1920\u001b[0m     \u001b[38;5;66;03m# for child processes has otherwise been disabled for our\u001b[39;00m\n\u001b[1;32m   1921\u001b[0m     \u001b[38;5;66;03m# process.  This child is dead, we can't get the status.\u001b[39;00m\n\u001b[1;32m   1922\u001b[0m     pid \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mpid\n","\u001b[0;31mKeyboardInterrupt\u001b[0m: "],"ename":"KeyboardInterrupt","evalue":"","output_type":"error"}],"execution_count":27},{"cell_type":"code","source":"model.train(\n    data = os.path.join(OUTPUT_DIR, 'data.yaml'),\n\n    task = 'detect',\n\n    imgsz = (img_properties['height'], img_properties['width']),\n\n    epochs = EPOCHS,\n    batch = BATCH_SIZE,\n    optimizer = OPTIMIZER,\n    lr0 = LR,\n    lrf = LR_FACTOR,\n    weight_decay = WEIGHT_DECAY,\n    dropout = DROPOUT,\n    fraction = FRACTION,\n    patience = PATIENCE,\n    profile = PROFILE,\n    label_smoothing = LABEL_SMOOTHING,\n\n    name = f'{BASE_MODEL}_{EXP_NAME}',\n    seed = SEED,\n    \n    val = True,\n    amp = True,    \n    exist_ok = True,\n    resume = False,\n    device = [0,1], # 0\n    verbose = False,\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:54.060119Z","iopub.execute_input":"2024-07-13T14:33:54.060748Z"},"trusted":true},"outputs":[{"name":"stdout","text":"Ultralytics YOLOv8.2.55 🚀 Python-3.10.13 torch-2.1.2 CUDA:0 (Tesla T4, 15095MiB)\n                                                      CUDA:1 (Tesla T4, 15095MiB)\n\u001b[34m\u001b[1mengine/trainer: \u001b[0mtask=detect, mode=train, model=/kaggle/working/runs/detect/yolov10x_ppe_css_70_epochs/weights/last.pt, data=./data.yaml, epochs=70, time=None, patience=20, batch=16, imgsz=(640, 640), save=True, save_period=-1, cache=False, device=[0, 1], workers=8, project=None, name=yolov10x_ppe_cssss_70_epochs, exist_ok=True, pretrained=True, optimizer=auto, verbose=False, seed=88, deterministic=True, single_cls=False, rect=False, cos_lr=False, close_mosaic=10, resume=False, amp=True, fraction=1.0, profile=False, freeze=None, multi_scale=False, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, split=val, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, vid_stride=1, stream_buffer=False, visualize=False, augment=False, agnostic_nms=False, classes=None, retina_masks=False, embed=None, show=False, save_frames=False, save_txt=False, save_conf=False, save_crop=False, show_labels=True, show_conf=True, show_boxes=True, line_width=None, format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=None, workspace=4, nms=False, lr0=0.001, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=7.5, cls=0.5, dfl=1.5, pose=12.0, kobj=1.0, label_smoothing=0.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, bgr=0.0, mosaic=1.0, mixup=0.0, copy_paste=0.0, auto_augment=randaugment, erasing=0.4, crop_fraction=1.0, cfg=None, tracker=botsort.yaml, save_dir=runs/detect/yolov10x_ppe_cssss_70_epochs\n\n                   from  n    params  module                                       arguments                     \n  0                  -1  1      2320  ultralytics.nn.modules.conv.Conv             [3, 80, 3, 2]                 \n  1                  -1  1    115520  ultralytics.nn.modules.conv.Conv             [80, 160, 3, 2]               \n  2                  -1  3    436800  ultralytics.nn.modules.block.C2f             [160, 160, 3, True]           \n  3                  -1  1    461440  ultralytics.nn.modules.conv.Conv             [160, 320, 3, 2]              \n  4                  -1  6   3281920  ultralytics.nn.modules.block.C2f             [320, 320, 6, True]           \n  5                  -1  1    213120  ultralytics.nn.modules.block.SCDown          [320, 640, 3, 2]              \n  6                  -1  6   4604160  ultralytics.nn.modules.block.C2fCIB          [640, 640, 6, True]           \n  7                  -1  1    417920  ultralytics.nn.modules.block.SCDown          [640, 640, 3, 2]              \n  8                  -1  3   2712960  ultralytics.nn.modules.block.C2fCIB          [640, 640, 3, True]           \n  9                  -1  1   1025920  ultralytics.nn.modules.block.SPPF            [640, 640, 5]                 \n 10                  -1  1   1545920  ultralytics.nn.modules.block.PSA             [640, 640]                    \n 11                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']          \n 12             [-1, 6]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n 13                  -1  3   3122560  ultralytics.nn.modules.block.C2fCIB          [1280, 640, 3, True]          \n 14                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']          \n 15             [-1, 4]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n 16                  -1  3   1948800  ultralytics.nn.modules.block.C2f             [960, 320, 3]                 \n 17                  -1  1    922240  ultralytics.nn.modules.conv.Conv             [320, 320, 3, 2]              \n 18            [-1, 13]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n 19                  -1  3   2917760  ultralytics.nn.modules.block.C2fCIB          [960, 640, 3, True]           \n 20                  -1  1    417920  ultralytics.nn.modules.block.SCDown          [640, 640, 3, 2]              \n 21            [-1, 10]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n 22                  -1  3   3122560  ultralytics.nn.modules.block.C2fCIB          [1280, 640, 3, True]          \n 23        [16, 19, 22]  1   4404300  ultralytics.nn.modules.head.v10Detect        [10, [320, 640, 640]]         \nYOLOv10x summary: 688 layers, 31,674,140 parameters, 31,674,124 gradients, 171.1 GFLOPs\n\nTransferred 1135/1135 items from pretrained weights\n\u001b[34m\u001b[1mDDP:\u001b[0m debug command /opt/conda/bin/python3.10 -m torch.distributed.run --nproc_per_node 2 --master_port 56607 /root/.config/Ultralytics/DDP/_temp_kwi2myed135860822435696.py\nUltralytics YOLOv8.2.55 🚀 Python-3.10.13 torch-2.1.2 CUDA:0 (Tesla T4, 15095MiB)\n                                                      CUDA:1 (Tesla T4, 15095MiB)\n\u001b[34m\u001b[1mTensorBoard: \u001b[0mStart with 'tensorboard --logdir runs/detect/yolov10x_ppe_cssss_70_epochs', view at http://localhost:6006/\nTransferred 1135/1135 items from pretrained weights\nFreezing layer 'model.23.dfl.conv.weight'\n\u001b[34m\u001b[1mAMP: \u001b[0mrunning Automatic Mixed Precision (AMP) checks with YOLOv8n...\n\u001b[34m\u001b[1mAMP: \u001b[0mchecks passed ✅\nWARNING ⚠️ updating to 'imgsz=640'. 'train' and 'val' imgsz must be an integer, while 'predict' and 'export' imgsz may be a [h, w] list or an integer, i.e. 'yolo export imgsz=640,480' or 'yolo export imgsz=640'\n","output_type":"stream"},{"name":"stderr","text":"\u001b[34m\u001b[1mtrain: \u001b[0mScanning /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/labels... 2605 images, 6 backgrounds, 0 corrupt: 100%|██████████| 2605/2605 [00:03<00:00, 680.00it/s]\n","output_type":"stream"},{"name":"stdout","text":"\u001b[34m\u001b[1mtrain: \u001b[0mWARNING ⚠️ /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/images/004720_jpg.rf.afc486560a4004c7cfd67910af31a29c.jpg: 1 duplicate labels removed\n\u001b[34m\u001b[1mtrain: \u001b[0mWARNING ⚠️ /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/images/construction-813-_jpg.rf.b085952261fd98f2e76b8065de149b5f.jpg: 1 duplicate labels removed\n\u001b[34m\u001b[1mtrain: \u001b[0mWARNING ⚠️ Cache directory /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train is not writeable, cache not saved.\n\u001b[34m\u001b[1malbumentations: \u001b[0mBlur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01), CLAHE(p=0.01, clip_limit=(1, 4.0), tile_grid_size=(8, 8))\n","output_type":"stream"},{"name":"stderr","text":"/opt/conda/lib/python3.10/multiprocessing/popen_fork.py:66: RuntimeWarning: os.fork() was called. os.fork() is incompatible with multithreaded code, and JAX is multithreaded, so this will likely lead to a deadlock.\n  self.pid = os.fork()\n\u001b[34m\u001b[1mval: \u001b[0mScanning /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/valid/labels... 114 images, 10 backgrounds, 0 corrupt: 100%|██████████| 114/114 [00:00<00:00, 546.56it/s]s]\n\u001b[34m\u001b[1mtrain: \u001b[0mScanning /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/labels... 196 images, 0 backgrounds, 0 corrupt:   8%|▊         | 196/2605 [00:00<00:03, 604.28it/s]","output_type":"stream"},{"name":"stdout","text":"\u001b[34m\u001b[1mval: \u001b[0mWARNING ⚠️ Cache directory /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/valid is not writeable, cache not saved.\n","output_type":"stream"},{"name":"stderr","text":"\u001b[34m\u001b[1mtrain: \u001b[0mScanning /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/labels... 809 images, 0 backgrounds, 0 corrupt:  31%|███       | 809/2605 [00:01<00:02, 693.75it/s]","output_type":"stream"},{"name":"stdout","text":"Plotting labels to runs/detect/yolov10x_ppe_cssss_70_epochs/labels.jpg... \n","output_type":"stream"},{"name":"stderr","text":"\u001b[34m\u001b[1mtrain: \u001b[0mScanning /kaggle/input/construction-site-safety-image-dataset-roboflow/css-data/train/labels... 2605 images, 6 backgrounds, 0 corrupt: 100%|██████████| 2605/2605 [00:03<00:00, 695.35it/s]\n","output_type":"stream"},{"name":"stdout","text":"\u001b[34m\u001b[1moptimizer:\u001b[0m 'optimizer=auto' found, ignoring 'lr0=0.001' and 'momentum=0.937' and determining best 'optimizer', 'lr0' and 'momentum' automatically... \n\u001b[34m\u001b[1moptimizer:\u001b[0m AdamW(lr=0.000714, momentum=0.9) with parameter groups 185 weight(decay=0.0), 198 weight(decay=0.0005), 197 bias(decay=0.0)\n\u001b[34m\u001b[1mTensorBoard: \u001b[0mmodel graph visualization added ✅\nImage sizes 640 train, 640 val\nUsing 4 dataloader workers\nLogging results to \u001b[1mruns/detect/yolov10x_ppe_cssss_70_epochs\u001b[0m\nStarting training for 70 epochs...\n\n      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n","output_type":"stream"},{"name":"stderr","text":"       1/70      10.7G      1.796      1.445      2.298        141        640: 100%|██████████| 163/163 [02:02<00:00,  1.33it/s]\n                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 8/8 [00:04<00:00,  2.00it/s]\n","output_type":"stream"},{"name":"stdout","text":"                   all        114        697      0.867      0.709      0.794      0.493\n\n      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n","output_type":"stream"},{"name":"stderr","text":"       2/70      10.4G      1.874      1.524      2.333        112        640: 100%|██████████| 163/163 [01:55<00:00,  1.42it/s]\n                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 8/8 [00:03<00:00,  2.10it/s]\n","output_type":"stream"},{"name":"stdout","text":"                   all        114        697      0.835      0.718      0.794      0.473\n\n      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n","output_type":"stream"},{"name":"stderr","text":"       3/70      10.4G      1.902      1.522      2.359        205        640:   1%|          | 1/163 [00:00<01:48,  1.50it/s]","output_type":"stream"}],"execution_count":null},{"cell_type":"code","source":"import os\nimport tarfile\nfrom IPython.display import FileLink\n# Chemin du répertoire à archiver\ndirectory = '/kaggle/working/runs'\n\n# Nom du fichier archive\narchive_name = '/kaggle/working/runs_archive.tar.gz'\n\n# Créer une archive tar.gz du répertoire\nwith tarfile.open(archive_name, 'w:gz') as tar:\n    tar.add(directory, arcname=os.path.basename(directory))\n\nprint(f'Archive created: {archive_name}')\n\n# Créer un lien de téléchargement pour l'archive\ndisplay(FileLink(archive_name))\n","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.191424Z","iopub.status.idle":"2024-07-13T14:33:34.19217Z","shell.execute_reply.started":"2024-07-13T14:33:34.191903Z","shell.execute_reply":"2024-07-13T14:33:34.191924Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport os\nimport re\nimport glob\nimport yaml\nimport subprocess\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_palette('Set3')\n\nimport IPython.display as display\nfrom IPython.display import Video\n\nfrom PIL import Image\nimport cv2\n\nimport torch\n\nfrom ultralytics import YOLO","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.193352Z","iopub.status.idle":"2024-07-13T14:33:34.19402Z","shell.execute_reply.started":"2024-07-13T14:33:34.193768Z","shell.execute_reply":"2024-07-13T14:33:34.193787Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CFG:\n    ### inference: use any pretrained or custom model\n    # WEIGHTS = 'yolov8x.pt' # yolov8n.pt, yolov8s.pt, yolov8m.pt, yolov8l.pt, yolov8x.pt\n    WEIGHTS = '/kaggle/working/runs/detect/yolov10x_ppe_css_70_epochs/weights/best.pt'\n    \n    CONFIDENCE = 0.55 # 0.35\n    CONFIDENCE_INT = int( round(CONFIDENCE * 100, 0) )\n    \n    CLASSES_TO_DETECT = [0, 2, 4, 5, 7] # Hardhat, NO-Hardhat, NO-Safety Vest, Person, Safety Vest\n    \n    VERTICES_POLYGON = np.array([[200,720], [0,700], [500,620], [990,690], [820,720]])\n\n    EXP_NAME = 'ppe'\n\n    ### just some video examples\n    VID_001 = '/kaggle/input/video-example-abdou007/example_video.mp4'\n\n    ### choose filepath to make inference on (image or video)\n    PATH_TO_INFER_ON = VID_001\n    EXT = PATH_TO_INFER_ON.split('.')[-1] # get file extension\n    FILENAME_TO_INFER_ON = PATH_TO_INFER_ON.split('/')[-1].split('.')[0] # get filename\n\n    ### paths\n    ROOT_DIR = '/kaggle/input/video-example-abdou007/'\n    OUTPUT_DIR = './'","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.195268Z","iopub.status.idle":"2024-07-13T14:33:34.195968Z","shell.execute_reply.started":"2024-07-13T14:33:34.195694Z","shell.execute_reply":"2024-07-13T14:33:34.195713Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"glob.glob(CFG.ROOT_DIR + '*')\n","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.197187Z","iopub.status.idle":"2024-07-13T14:33:34.197858Z","shell.execute_reply.started":"2024-07-13T14:33:34.197616Z","shell.execute_reply":"2024-07-13T14:33:34.197636Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_image_properties(image):\n    if isinstance(image, str):\n        # If image is a file path, read the image\n        img = cv2.imread(image)\n        if img is None:\n            raise ValueError(\"Could not read image file\")\n    elif isinstance(image, np.ndarray):\n        # If image is already a NumPy array, use it directly\n        img = image\n    else:\n        raise ValueError(\"Input must be a file path or a NumPy array\")\n\n    # Get image properties\n    properties = {\n        \"width\": img.shape[1],\n        \"height\": img.shape[0],\n        \"channels\": img.shape[2] if len(img.shape) == 3 else 1,\n        \"dtype\": img.dtype,\n    }\n\n    return properties","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.199135Z","iopub.status.idle":"2024-07-13T14:33:34.199771Z","shell.execute_reply.started":"2024-07-13T14:33:34.199536Z","shell.execute_reply":"2024-07-13T14:33:34.199554Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def display_image(image, print_info = True, hide_axis = False):\n    if isinstance(image, str):  # Check if it's a file path\n        img = Image.open(image)\n        plt.imshow(img)\n    elif isinstance(image, np.ndarray):  # Check if it's a NumPy array\n        image = image[..., ::-1]  # BGR to RGB\n        img = Image.fromarray(image)\n        plt.imshow(img);\n    else:\n        raise ValueError(\"Unsupported image format\")\n\n    if print_info:\n        print('Type: ', type(img), '\\n')\n        print('Shape: ', np.array(img).shape, '\\n')\n        \n    if hide_axis:\n        plt.axis('off')\n        \n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.200988Z","iopub.status.idle":"2024-07-13T14:33:34.20167Z","shell.execute_reply.started":"2024-07-13T14:33:34.201427Z","shell.execute_reply":"2024-07-13T14:33:34.201448Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_video_properties(video_path):\n    # Open the video file\n    cap = cv2.VideoCapture(video_path)\n\n    # Check if the video file is opened successfully\n    if not cap.isOpened():\n        raise ValueError(\"Could not open video file\")\n\n    # Get video properties\n    properties = {\n        \"fps\": int(cap.get(cv2.CAP_PROP_FPS)),\n        \"frame_count\": int(cap.get(cv2.CAP_PROP_FRAME_COUNT)),\n        \"duration_seconds\": int( cap.get(cv2.CAP_PROP_FRAME_COUNT) / cap.get(cv2.CAP_PROP_FPS) ),\n        \"width\": int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),\n        \"height\": int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),\n        \"codec\": int(cap.get(cv2.CAP_PROP_FOURCC)),\n    }\n\n    # Release the video capture object\n    cap.release()\n\n    return properties","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.20295Z","iopub.status.idle":"2024-07-13T14:33:34.20363Z","shell.execute_reply.started":"2024-07-13T14:33:34.203385Z","shell.execute_reply":"2024-07-13T14:33:34.203406Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"### testing function\nvideo_properties = get_video_properties(CFG.VID_001)\nvideo_properties","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.204904Z","iopub.status.idle":"2024-07-13T14:33:34.205626Z","shell.execute_reply.started":"2024-07-13T14:33:34.205376Z","shell.execute_reply":"2024-07-13T14:33:34.205397Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"OUT_VIDEO_NAME = './video_to_infer.mp4'\n\nsubprocess.run(\n    [\n        \"ffmpeg\",  \"-i\", CFG.PATH_TO_INFER_ON, \"-crf\",\n        \"18\", \"-preset\", \"veryfast\", \"-hide_banner\", \"-loglevel\",\n        \"error\", \"-vcodec\", \"libx264\", OUT_VIDEO_NAME\n    ]\n)\n\nVideo(data=OUT_VIDEO_NAME, embed=True, height=int(video_properties['height'] * 0.5), width=int(video_properties['width'] * 0.5))","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.206971Z","iopub.status.idle":"2024-07-13T14:33:34.207637Z","shell.execute_reply.started":"2024-07-13T14:33:34.207398Z","shell.execute_reply":"2024-07-13T14:33:34.207417Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cap = cv2.VideoCapture(CFG.PATH_TO_INFER_ON)\n\nif not cap.isOpened():\n    print(\"Error: Could not open video file.\")\nelse:\n    # Read the first frame\n    ret, frame_test = cap.read()\n    cap.release()\n\nvertices_polygon = np.array([[200,720], [0,700], [500,620], [990,690], [820,720]]) # manually adjusted\n\ncv2.polylines(frame_test, [vertices_polygon.reshape(-1, 1, 2)], True, (0, 0, 128), 4)\n\nmod = frame_test.copy()\noverlay = cv2.fillPoly(mod, pts = [vertices_polygon], color=(0, 0, 128))\nbackground = frame_test.copy()\n\nframe_test = cv2.addWeighted(\n    src1 = background, # fisrt image\n    alpha = 0.6, # first image weight\n    src2 = overlay, # second image\n    beta = 0.4, # second image weight\n    gamma = 0.1, # scalar factor\n    dst = overlay # output array shape\n)","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.209015Z","iopub.status.idle":"2024-07-13T14:33:34.209729Z","shell.execute_reply.started":"2024-07-13T14:33:34.209474Z","shell.execute_reply":"2024-07-13T14:33:34.209496Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"display_image(frame_test)\n","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.211126Z","iopub.status.idle":"2024-07-13T14:33:34.211856Z","shell.execute_reply.started":"2024-07-13T14:33:34.211588Z","shell.execute_reply":"2024-07-13T14:33:34.21161Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_properties = get_image_properties(frame_test)\nimg_properties","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.213145Z","iopub.status.idle":"2024-07-13T14:33:34.21387Z","shell.execute_reply.started":"2024-07-13T14:33:34.213603Z","shell.execute_reply":"2024-07-13T14:33:34.213624Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = YOLO(CFG.WEIGHTS)\n","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.215189Z","iopub.status.idle":"2024-07-13T14:33:34.215859Z","shell.execute_reply.started":"2024-07-13T14:33:34.215618Z","shell.execute_reply":"2024-07-13T14:33:34.215637Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if torch.cuda.is_available():\n    model.to('cuda:0')\nelse:\n    print(\"CUDA device is not available. Running on CPU.\")","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.217119Z","iopub.status.idle":"2024-07-13T14:33:34.21782Z","shell.execute_reply.started":"2024-07-13T14:33:34.217566Z","shell.execute_reply":"2024-07-13T14:33:34.217587Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.names\n","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.219092Z","iopub.status.idle":"2024-07-13T14:33:34.219757Z","shell.execute_reply.started":"2024-07-13T14:33:34.219518Z","shell.execute_reply":"2024-07-13T14:33:34.219538Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model)","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.22098Z","iopub.status.idle":"2024-07-13T14:33:34.221641Z","shell.execute_reply.started":"2024-07-13T14:33:34.221409Z","shell.execute_reply":"2024-07-13T14:33:34.221429Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"results = model.predict(\n    source = CFG.PATH_TO_INFER_ON,\n    save = True,\n    classes = CFG.CLASSES_TO_DETECT,\n    conf = CFG.CONFIDENCE,\n    save_txt = True,\n    save_conf = True,\n    show = False,\n    device = 0,\n#     stream = True,\n)","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.22289Z","iopub.status.idle":"2024-07-13T14:33:34.223561Z","shell.execute_reply.started":"2024-07-13T14:33:34.22333Z","shell.execute_reply":"2024-07-13T14:33:34.223351Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"RAW_INFERENCE_VIDEO = glob.glob('/kaggle/working/runs/detect/predict/example_video*')[0] # avi or mp4\nOUT_VIDEO_NAME = './raw_inference.mp4'\n\nsubprocess.run(\n    [\n        \"ffmpeg\",  \"-i\", RAW_INFERENCE_VIDEO, \"-crf\",\n        \"18\", \"-preset\", \"veryfast\", \"-hide_banner\", \"-loglevel\",\n        \"error\", \"-vcodec\", \"libx264\", OUT_VIDEO_NAME\n    ]\n)\n\nVideo(data=OUT_VIDEO_NAME, embed=True, height=int(video_properties['height'] * 0.5), width=int(video_properties['width'] * 0.5))\n","metadata":{"execution":{"iopub.status.busy":"2024-07-13T14:33:34.22475Z","iopub.status.idle":"2024-07-13T14:33:34.2254Z","shell.execute_reply.started":"2024-07-13T14:33:34.225173Z","shell.execute_reply":"2024-07-13T14:33:34.225192Z"},"trusted":true},"outputs":[],"execution_count":null}]}