{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":97837,"databundleVersionId":11654135,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":12657267,"sourceType":"datasetVersion","datasetId":7998858}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n# import os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-08-02T15:44:52.193338Z","iopub.execute_input":"2025-08-02T15:44:52.194020Z","iopub.status.idle":"2025-08-02T15:44:52.199848Z","shell.execute_reply.started":"2025-08-02T15:44:52.193990Z","shell.execute_reply":"2025-08-02T15:44:52.198371Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install -q ultralytics\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-03T14:31:47.926363Z","iopub.execute_input":"2025-08-03T14:31:47.926641Z","iopub.status.idle":"2025-08-03T14:31:51.167458Z","shell.execute_reply.started":"2025-08-03T14:31:47.926615Z","shell.execute_reply":"2025-08-03T14:31:51.166522Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\nmodel=YOLO('yolov8n-cls.pt')\nmodel.predict(source='/kaggle/input/a0-2025-object-detection/Dataset/Test/images/0026df6bcaf93ac5_jpg.rf.510f06f5d706b8924f3a8a411211dcf8.jpg')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-02T16:23:38.916035Z","iopub.execute_input":"2025-08-02T16:23:38.916852Z","iopub.status.idle":"2025-08-02T16:23:39.703057Z","shell.execute_reply.started":"2025-08-02T16:23:38.916817Z","shell.execute_reply":"2025-08-02T16:23:39.701344Z"},"collapsed":true,"jupyter":{"source_hidden":true,"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nlabel_dir = \"/kaggle/input/yolov8format/train/labels\"  # your label folder path\n\n# Output folder (optional, to avoid overwriting original labels)\noutput_dir = \"/kaggle/working/train/labels_fixed\"\nos.makedirs(output_dir, exist_ok=True)\n\nfor filename in os.listdir(label_dir):\n    if filename.endswith(\".txt\"):\n        input_path = os.path.join(label_dir, filename)\n        output_path = os.path.join(output_dir, filename)\n\n        with open(input_path, 'r') as f:\n            lines = f.readlines()\n\n        fixed_lines = []\n        for line in lines:\n            parts = line.strip().split()\n            if len(parts) != 5:\n                continue  # skip invalid lines\n\n            class_id = int(parts[0]) - 1  # subtract 1 to start from 0\n            if class_id < 0:\n                # ignore or handle invalid class ids here\n                continue\n\n            fixed_line = \" \".join([str(class_id)] + parts[1:])\n            fixed_lines.append(fixed_line)\n\n        # Save fixed label\n        with open(output_path, 'w') as f:\n            f.write(\"\\n\".join(fixed_lines) + \"\\n\")\n\nprint(f\"Fixed labels saved to {output_dir}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-03T14:28:20.329538Z","iopub.execute_input":"2025-08-03T14:28:20.329771Z","iopub.status.idle":"2025-08-03T14:28:21.108661Z","shell.execute_reply.started":"2025-08-03T14:28:20.329752Z","shell.execute_reply":"2025-08-03T14:28:21.107644Z"},"jupyter":{"source_hidden":true,"outputs_hidden":true},"collapsed":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\ndata_yaml = f\"\"\"\ntrain: /kaggle/input/yolov8format/train/images\nval: /kaggle/input/yolov8format/valid/images\n\nnc: 6\nnames: ['Apple', 'Banana', 'Grapes', 'Orange', 'Pineapple', 'Watermelon']\n\"\"\"\n\nwith open(\"/kaggle/working/data.yaml\", \"w\") as f:\n    f.write(data_yaml)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-03T14:29:13.887522Z","iopub.execute_input":"2025-08-03T14:29:13.888169Z","iopub.status.idle":"2025-08-03T14:29:13.892207Z","shell.execute_reply.started":"2025-08-03T14:29:13.888146Z","shell.execute_reply":"2025-08-03T14:29:13.891476Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\nmodel = YOLO('yolov8n.pt')\nresults=model.train(data='/kaggle/working/data.yaml', epochs=20, imgsz=640)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-03T14:31:58.422013Z","iopub.execute_input":"2025-08-03T14:31:58.422291Z","iopub.status.idle":"2025-08-03T14:57:01.843731Z","shell.execute_reply.started":"2025-08-03T14:31:58.422264Z","shell.execute_reply":"2025-08-03T14:57:01.842356Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!yolo detect val model=runs/detect/train/weights/best.pt data=data.yaml save=True\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-03T15:03:19.842894Z","iopub.execute_input":"2025-08-03T15:03:19.843817Z","iopub.status.idle":"2025-08-03T15:03:40.895094Z","shell.execute_reply.started":"2025-08-03T15:03:19.843785Z","shell.execute_reply":"2025-08-03T15:03:40.894326Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = YOLO('/kaggle/working/runs/detect/train/weights/best.pt')\nresults = model.predict(source='/kaggle/input/yolov8format/test/images', save=False, conf=0.25)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-03T15:31:08.627522Z","iopub.execute_input":"2025-08-03T15:31:08.627815Z","iopub.status.idle":"2025-08-03T15:31:17.769025Z","shell.execute_reply.started":"2025-08-03T15:31:08.627793Z","shell.execute_reply":"2025-08-03T15:31:17.768295Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport os\nimport json\n\nsubmission = []\n\nfor r in results:\n    file_name = os.path.basename(r.path).split('.')[0]  # e.g., '00123'\n    file_id = \"img\" + file_name[-4:]  # Convert to img format like 'img123'\n\n    bboxes = []\n\n    for box in r.boxes:\n        x_min, y_min, x_max, y_max = map(float, box.xyxy[0])\n        class_id = int(box.cls[0])\n        conf = float(box.conf[0])\n\n        bboxes.append({\n            \"x_min\": x_min,\n            \"y_min\": y_min,\n            \"x_max\": x_max,\n            \"y_max\": y_max,\n            \"class\": class_id,\n            \"confidence\": conf\n        })\n\n    # Ensure the bounding_boxes is a proper string with double quotes escaped\n    bbox_str = json.dumps(bboxes).replace('\"', '\"\"')\n\n    submission.append({\n        \"ID\": file_id,\n        \"bounding_boxes\": f'\"{bbox_str}\"'  # Enclose entire JSON string in quotes\n    })\n\ndf = pd.DataFrame(submission)\ndf.to_csv(\"submission.csv\", index=False)\nprint(\"✅ submission.csv saved!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-03T15:31:52.398903Z","iopub.execute_input":"2025-08-03T15:31:52.399705Z","iopub.status.idle":"2025-08-03T15:31:52.439385Z","shell.execute_reply.started":"2025-08-03T15:31:52.399676Z","shell.execute_reply":"2025-08-03T15:31:52.438761Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nimg_dir = \"/kaggle/input/a0-2025-object-detection/Dataset/Train/images\"\nlabel_dir = \"/kaggle/input/a0-2025-object-detection/Dataset/Train/labels\"\n\nimg_files = [f for f in os.listdir(img_dir) if f.endswith((\".jpg\", \".png\"))]\nmissing_labels = []\nempty_labels = []\nbad_format = []\n\nfor img in img_files:\n    base = os.path.splitext(img)[0]\n    label_file = os.path.join(label_dir, base + \".txt\")\n\n    if not os.path.exists(label_file):\n        missing_labels.append(img)\n        continue\n\n    with open(label_file) as f:\n        lines = f.readlines()\n        if not lines:\n            empty_labels.append(img)\n            continue\n        for line in lines:\n            parts = line.strip().split()\n            if len(parts) != 5:\n                bad_format.append((img, line))\n                break\n\nprint(f\"Total images: {len(img_files)}\")\nprint(f\"Missing labels: {len(missing_labels)}\")\nprint(f\"Empty labels: {len(empty_labels)}\")\nprint(f\"Badly formatted labels: {len(bad_format)}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-02T15:44:57.432557Z","iopub.execute_input":"2025-08-02T15:44:57.433870Z","iopub.status.idle":"2025-08-02T15:45:17.525371Z","shell.execute_reply.started":"2025-08-02T15:44:57.433835Z","shell.execute_reply":"2025-08-02T15:45:17.523763Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}