{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":129750,"databundleVersionId":15563344,"sourceType":"competition"}],"dockerImageVersionId":31260,"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\nimport os\nfor 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":"2026-02-03T12:31:26.952222Z","iopub.execute_input":"2026-02-03T12:31:26.952511Z","iopub.status.idle":"2026-02-03T12:31:34.750828Z","shell.execute_reply.started":"2026-02-03T12:31:26.952463Z","shell.execute_reply":"2026-02-03T12:31:34.750154Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Install Ultralytics (YOLO)\n!pip install -q ultralytics\nimport os\nimport pandas as pd\nimport numpy as np\nfrom ultralytics import YOLO\nimport yaml\nfrom tqdm.notebook import tqdm","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-03T12:31:53.348794Z","iopub.execute_input":"2026-02-03T12:31:53.349545Z","iopub.status.idle":"2026-02-03T12:32:06.432177Z","shell.execute_reply.started":"2026-02-03T12:31:53.349503Z","shell.execute_reply":"2026-02-03T12:32:06.431345Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define the dataset configuration\ndataset_config = {\n    'path': '/kaggle/input/dal-shemagh-detection-challenge', # Root dir\n    'train': 'images/train',  # Train images (relative to path)\n    'val': 'images/train',    # Using train as val for demo (Split this properly for real training!)\n    'names': {\n        0: 'person',\n        1: 'shemagh'\n    }\n}\n\n# Write to data.yaml\nwith open('data.yaml', 'w') as f:\n    yaml.dump(dataset_config, f)\n\nprint(\"data.yaml created successfully!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-03T12:32:17.318271Z","iopub.execute_input":"2026-02-03T12:32:17.318739Z","iopub.status.idle":"2026-02-03T12:32:17.325348Z","shell.execute_reply.started":"2026-02-03T12:32:17.318708Z","shell.execute_reply":"2026-02-03T12:32:17.324558Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load a pre-trained YOLO model (Recommended: yolo11s.pt or yolo11m.pt)\nmodel = YOLO('yolo11s.pt') \n\n# Train the model\nresults = model.train(\n    data='data.yaml',\n    epochs=10,            # Increase this for better results!\n    imgsz=640,\n    batch=16,\n    project='dal_challenge',\n    name='shemagh_detector',\n    exist_ok=True\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-03T12:32:19.928087Z","iopub.execute_input":"2026-02-03T12:32:19.928885Z","iopub.status.idle":"2026-02-03T12:36:10.366654Z","shell.execute_reply.started":"2026-02-03T12:32:19.928841Z","shell.execute_reply":"2026-02-03T12:36:10.365927Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import glob\n\n# 1. Setup paths\ntest_images = glob.glob('/kaggle/input/dal-shemagh-detection-challenge/images/test/*.jpg')\nsubmission_data = []\n\n# 2. Define a function to calculate IoU (Intersection over Union)\ndef calculate_iou(box1, box2):\n    \"\"\"\n    Calculate IoU between two boxes (x, y, w, h normalized).\n    \"\"\"\n    # Convert from xywh to x1, y1, x2, y2\n    b1_x1, b1_x2 = box1[0] - box1[2]/2, box1[0] + box1[2]/2\n    b1_y1, b1_y2 = box1[1] - box1[3]/2, box1[1] + box1[3]/2\n    \n    b2_x1, b2_x2 = box2[0] - box2[2]/2, box2[0] + box2[2]/2\n    b2_y1, b2_y2 = box2[1] - box2[3]/2, box2[1] + box2[3]/2\n\n    # Intersection coordinates\n    inter_x1 = max(b1_x1, b2_x1)\n    inter_y1 = max(b1_y1, b2_y1)\n    inter_x2 = min(b1_x2, b2_x2)\n    inter_y2 = min(b1_y2, b2_y2)\n\n    inter_area = max(0, inter_x2 - inter_x1) * max(0, inter_y2 - inter_y1)\n    b1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)\n    b2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)\n    \n    union_area = b1_area + b2_area - inter_area\n    return inter_area / union_area if union_area > 0 else 0\n\n# 3. Inference Loop\nprint(f\"Processing {len(test_images)} images...\")\n\nfor img_path in tqdm(test_images):\n    filename = os.path.basename(img_path)\n    \n    # Run inference\n    results = model.predict(img_path, conf=0.25, verbose=False)[0]\n    \n    prediction_strings = []\n    person_boxes = []\n    shemagh_boxes = []\n    \n    # Process detections\n    if len(results.boxes) == 0:\n        prediction_str = \"-\"\n        right_place = 0\n    else:\n        for box in results.boxes:\n            # Extract data\n            cls = int(box.cls[0])\n            conf = float(box.conf[0])\n            \n            # YOLO returns xywh normalized if we access .xywhn\n            x, y, w, h = box.xywhn[0].tolist()\n            \n            # Append to prediction string\n            prediction_strings.append(f\"{cls} {conf:.4f} {x:.4f} {y:.4f} {w:.4f} {h:.4f}\")\n            \n            # Store boxes for logic check\n            if cls == 0: # Assuming 0 is Person\n                person_boxes.append([x, y, w, h])\n            elif cls == 1: # Assuming 1 is Shemagh\n                shemagh_boxes.append([x, y, w, h])\n        \n        prediction_str = \" \".join(prediction_strings)\n        \n        # --- LOGIC FOR \"RIGHT PLACE\" ---\n        # Heuristic: If we found at least one person and one shemagh\n        # and they overlap (IoU > threshold), predict 1.\n        \n        right_place = 0 # Default to 0\n        if person_boxes and shemagh_boxes:\n            # Check every shemagh against every person\n            for s_box in shemagh_boxes:\n                for p_box in person_boxes:\n                    iou = calculate_iou(s_box, p_box)\n                    # Threshold: 0.1 means 10% overlap. Adjust this based on validation!\n                    if iou > 0.1: \n                        right_place = 1\n                        break\n                if right_place == 1:\n                    break\n    \n    submission_data.append([filename, right_place, prediction_str])\n\n# 4. Save to CSV\ndf_sub = pd.DataFrame(submission_data, columns=['filename', 'right_place', 'prediction_string'])\ndf_sub.to_csv('submission.csv', index=False)\n\nprint(\"Submission.csv generated successfully!\")\nprint(df_sub.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-03T12:36:14.886339Z","iopub.execute_input":"2026-02-03T12:36:14.886900Z","iopub.status.idle":"2026-02-03T12:36:35.978992Z","shell.execute_reply.started":"2026-02-03T12:36:14.886851Z","shell.execute_reply":"2026-02-03T12:36:35.978198Z"}},"outputs":[],"execution_count":null}]}