{"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":"none","dataSources":[{"sourceType":"competition","sourceId":114094,"databundleVersionId":13610510},{"sourceType":"datasetVersion","sourceId":15430653,"datasetId":9871317,"databundleVersionId":16349556},{"sourceType":"datasetVersion","sourceId":15336666,"datasetId":9809746,"databundleVersionId":16244900}],"dockerImageVersionId":31328,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install ultralytics ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-29T18:45:52.036945Z","iopub.execute_input":"2026-03-29T18:45:52.037763Z","iopub.status.idle":"2026-03-29T18:45:56.035535Z","shell.execute_reply.started":"2026-03-29T18:45:52.037714Z","shell.execute_reply":"2026-03-29T18:45:56.034547Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\n\n# 📁 Caminho do dataset\ndataset_path = \"/kaggle/working/\"\n\n# 📌 Classes (edite conforme seu problema)\nclass_names = ['cheerios', 'soup', 'candle'] \n\ndata = {\n    \"path\": dataset_path,\n    \"train\": \"/kaggle/input/competitions/grocery-items-multi-class-object-detection/train/train/images\",\n    \"val\": \"/kaggle/input/competitions/grocery-items-multi-class-object-detection/val/val/images\",\n    \"names\": {i: name for i, name in enumerate(class_names)}\n}\n\nyaml_path = os.path.join(dataset_path, \"data.yaml\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-29T18:45:58.905511Z","iopub.execute_input":"2026-03-29T18:45:58.906484Z","iopub.status.idle":"2026-03-29T18:45:58.912196Z","shell.execute_reply.started":"2026-03-29T18:45:58.906430Z","shell.execute_reply":"2026-03-29T18:45:58.911375Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ==========================================\n# 🔧 CONFIGURE AQUI (APENAS ISSO)\n# ==========================================\n\nMODEL_PATH = \"/kaggle/input/datasets/danielfreirejunior/yolo-mercado-v8m/detect/train3/weights/best.pt\"\n\nTEST_IMAGES_PATH = \"/kaggle/input/competitions/grocery-items-multi-class-object-detection/testImages/testImages/images\"\n\nOUTPUT_DIR = \"/kaggle/working/predictions\"\n\n\n# ==========================================\n# 🚀 IMPORTS\n# ==========================================\nfrom ultralytics import YOLO\nfrom pathlib import Path\nimport cv2\nimport os\n\n\n\n# ==========================================\n# 📁 PATHS\n# ==========================================\ntest_images = Path(TEST_IMAGES_PATH)\noutput_dir = Path(OUTPUT_DIR)\n\nimages_output_dir = output_dir / \"images\"\nlabels_output_dir = output_dir / \"labels\"\n\nimages_output_dir.mkdir(parents=True, exist_ok=True)\nlabels_output_dir.mkdir(parents=True, exist_ok=True)\n\n# ==========================================\n# 🤖 LOAD MODEL\n# ==========================================\nmodel = YOLO(MODEL_PATH)\n\n# ==========================================\n# 🔍 FUNÇÃO DE PREDIÇÃO\n# ==========================================\ndef predict_and_save(model, image_path, output_path_img, output_path_txt):\n    results = model.predict(image_path, conf=0.01, device=\"cpu\", verbose=False)\n\n    result = results[0]\n\n    # 🖼️ salvar imagem com bbox\n    img = result.plot()\n    cv2.imwrite(str(output_path_img), img)\n\n    # 📝 salvar txt\n    with open(output_path_txt, \"w\") as f:\n        if result.boxes is None:\n            return\n        \n        for box in result.boxes:\n            cls_id = int(box.cls)\n            conf = float(box.conf[0])\n\n            # 🔥 formato YOLO (igual seu código original)\n            x_center, y_center, width, height = box.xywhn[0].tolist()\n\n            f.write(f\"{cls_id} {conf:.6f} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\\n\")\n\n\n# ==========================================\n# 🔄 LOOP PRINCIPAL\n# ==========================================\nimage_list = sorted([\n    p for p in test_images.glob(\"*\")\n    if p.suffix.lower() in [\".jpg\", \".png\", \".jpeg\"]\n])\n\nprint(f\"🔍 {len(image_list)} imagens encontradas\")\n\nfor img_path in image_list:\n    output_img = images_output_dir / img_path.name\n    output_txt = labels_output_dir / f\"{img_path.stem}.txt\"\n\n    predict_and_save(model, img_path, output_img, output_txt)\n\n# ==========================================\n# ✅ FINAL\n# ==========================================\nprint(\"✅ Predições finalizadas!\")\nprint(f\"📁 Imagens: {images_output_dir}\")\nprint(f\"📁 Labels: {labels_output_dir}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-29T18:52:24.230355Z","iopub.execute_input":"2026-03-29T18:52:24.230882Z","iopub.status.idle":"2026-03-29T18:55:22.627908Z","shell.execute_reply.started":"2026-03-29T18:52:24.230844Z","shell.execute_reply":"2026-03-29T18:55:22.626925Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from pathlib import Path\nimport pandas as pd\nimport sys\n\ndef predictions_to_csv(\n    preds_folder: str = \"/kaggle/working/predictions/labels\", \n    output_csv: str = \"/kaggle/working/submission.csv\", \n    test_images_folder: str = \"/kaggle/input/competitions/grocery-items-multi-class-object-detection/testImages/testImages/images\",\n    allowed_extensions: tuple = (\".jpg\", \".png\", \".jpeg\")\n):\n    \"\"\"\n    Convert YOLO prediction files to Kaggle submission CSV format\n    \"\"\"\n\n    preds_path = Path(preds_folder)\n    if not preds_path.exists():\n        print(f\"ERROR: Prediction folder '{preds_folder}' does not exist\")\n        sys.exit(1)\n\n    test_images_path = Path(test_images_folder)\n    if not test_images_path.exists():\n        print(f\"ERROR: Test images folder '{test_images_folder}' not found\")\n        sys.exit(1)\n\n    # 🔥 ordenar garante consistência\n    test_images = sorted([\n        p.stem for p in test_images_path.glob(\"*\")\n        if p.suffix.lower() in allowed_extensions\n    ])\n\n    print(f\"Found {len(test_images)} test images\")\n\n    predictions_dict = {}\n\n    # ================================\n    # 🔍 LER TXT\n    # ================================\n    for txt_file in preds_path.glob(\"*.txt\"):\n        image_id = txt_file.stem\n\n        with open(txt_file, \"r\") as f:\n            valid_lines = []\n\n            for line in f:\n                line = line.strip()\n                if not line:\n                    continue\n\n                parts = line.split()\n                if len(parts) != 6:\n                    continue\n\n                try:\n                    [float(x) for x in parts]\n                    valid_lines.append(line)\n                except:\n                    continue\n\n        if valid_lines:\n            predictions_dict[image_id] = \" \".join(valid_lines)\n        else:\n            predictions_dict[image_id] = \"\"\n\n    # ================================\n    # 📊 DATAFRAME FINAL\n    # ================================\n    rows = []\n\n    for img_id in test_images:\n        rows.append({\n            \"image_id\": img_id,\n            \"prediction_string\": predictions_dict.get(img_id, \"\")\n        })\n\n    df = pd.DataFrame(rows)\n\n    # ================================\n    # 💾 SALVAR\n    # ================================\n    df.to_csv(output_csv, index=False)\n\n    print(f\"\\n✅ Submission salva em {output_csv}\")\n    print(df.head(30))\n\n\n# ================================\n# 🚀 EXECUTAR DIRETO (KAGGLE)\n# ================================\npredictions_to_csv()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-29T18:55:51.560044Z","iopub.execute_input":"2026-03-29T18:55:51.560414Z","iopub.status.idle":"2026-03-29T18:55:51.591884Z","shell.execute_reply.started":"2026-03-29T18:55:51.560378Z","shell.execute_reply":"2026-03-29T18:55:51.591022Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport cv2\n\n# ================================\n# CONFIG\n# ================================\nMODEL_PATH = \"/kaggle/input/datasets/danielfreirejunior/yolov8n-mercado/detect/train2/weights/best.pt\"\nTEST_PATH = \"/kaggle/input/competitions/grocery-items-multi-class-object-detection/testImages/testImages/images\"\n\n# ================================\n# LOAD MODEL\n# ================================\nmodel = YOLO(MODEL_PATH)\n\n# ================================\n# PEGAR ALGUMAS IMAGENS\n# ================================\nimages = list(Path(TEST_PATH).glob(\"*.jpg\"))[:5]\n\n# ================================\n# LOOP\n# ================================\nfor img_path in images:\n    \n    # 🔹 imagem original\n    original = cv2.imread(str(img_path))\n    original = cv2.cvtColor(original, cv2.COLOR_BGR2RGB)\n    \n    # 🔹 predição\n    results = model.predict(img_path, conf=0.25, verbose=False)\n    pred_img = results[0].plot()\n    \n    # ================================\n    # PLOT LADO A LADO\n    # ================================\n    plt.figure(figsize=(10,5))\n    \n    plt.subplot(1,2,1)\n    plt.imshow(original)\n    plt.title(\"Original\")\n    plt.axis(\"off\")\n    \n    plt.subplot(1,2,2)\n    plt.imshow(pred_img)\n    plt.title(\"Predição\")\n    plt.axis(\"off\")\n    \n    plt.suptitle(img_path.name)\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-29T18:59:11.586733Z","iopub.execute_input":"2026-03-29T18:59:11.587136Z","iopub.status.idle":"2026-03-29T18:59:25.384206Z","shell.execute_reply.started":"2026-03-29T18:59:11.587094Z","shell.execute_reply":"2026-03-29T18:59:25.383258Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}