rick003 commited on
Commit
c5936d5
·
verified ·
1 Parent(s): 0938fce

add full review and auto upload notebooks/colab_gas_valve_auto_label_train.ipynb

Browse files
notebooks/colab_gas_valve_auto_label_train.ipynb CHANGED
@@ -80,7 +80,7 @@
80
  "\n",
81
  "get_ipython().system(\n",
82
  " \"pip install -q ultralytics huggingface_hub opencv-python-headless \"\n",
83
- " \"tqdm pyyaml matplotlib pandas\"\n",
84
  ")\n",
85
  "\n",
86
  "import os\n",
@@ -89,6 +89,7 @@
89
  "import shutil\n",
90
  "import random\n",
91
  "import subprocess\n",
 
92
  "from pathlib import Path\n",
93
  "\n",
94
  "import cv2\n",
@@ -175,6 +176,7 @@
175
  "RAW_VALVE_PREFIX = \"raw/valve\"\n",
176
  "RAW_GAS_EXTRA_PREFIX = \"raw/gas_extra\"\n",
177
  "REVIEWED_VALVE_LABEL_PREFIX = \"reviewed_labels/valve\"\n",
 
178
  "PROCESS_SCRIPT_REPO_PATH = \"scripts/process_valve_to_polygon.py\"\n",
179
  "FORCE_REDOWNLOAD = True\n",
180
  "\n",
@@ -188,6 +190,7 @@
188
  " f\"{RAW_VALVE_PREFIX}/**\",\n",
189
  " f\"{RAW_GAS_EXTRA_PREFIX}/**\",\n",
190
  " f\"{REVIEWED_VALVE_LABEL_PREFIX}/**\",\n",
 
191
  " PROCESS_SCRIPT_REPO_PATH,\n",
192
  " \"dataset.yaml\",\n",
193
  "]\n",
@@ -205,6 +208,7 @@
205
  "RAW_VALVE_DIR = base / RAW_VALVE_PREFIX\n",
206
  "RAW_GAS_EXTRA_DIR = base / RAW_GAS_EXTRA_PREFIX\n",
207
  "REVIEWED_VALVE_LABEL_DIR = base / REVIEWED_VALVE_LABEL_PREFIX\n",
 
208
  "PROCESS_SCRIPT_LOCAL = base / PROCESS_SCRIPT_REPO_PATH\n",
209
  "\n",
210
  "print(\"下载结果统计\")\n",
@@ -214,6 +218,7 @@
214
  " RAW_VALVE_DIR,\n",
215
  " RAW_GAS_EXTRA_DIR,\n",
216
  " REVIEWED_VALVE_LABEL_DIR,\n",
 
217
  "]:\n",
218
  " n = len(list(p.glob(\"*\"))) if p.exists() else 0\n",
219
  " print(f\" {p}: {n} entries\")\n",
@@ -678,7 +683,21 @@
678
  " return keys\n",
679
  "\n",
680
  "\n",
681
- "EXCLUDED_SAMPLE_KEYS = parse_exclude_keys(EXCLUDE_SAMPLE_KEYS)\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
682
  "print(f\"Excluded sample keys: {len(EXCLUDED_SAMPLE_KEYS)}\")\n",
683
  "for key in sorted(EXCLUDED_SAMPLE_KEYS):\n",
684
  " print(f\" {key}\")\n",
@@ -874,7 +893,10 @@
874
  "source": [
875
  "# @title Step 10 - 构建两类训练集\n",
876
  "\n",
 
 
877
  "COMBINED_DATASET = Path(\"/content/gas_valve_dataset\")\n",
 
878
  "VAL_RATIO = 0.20 # 20% 做验证集,80% 做训练集。\n",
879
  "RANDOM_SEED = 42 # 固定随机种子,方便复现实验。\n",
880
  "INCLUDE_OLD_GAS_DATA = True # 保留原来的气瓶数据一起训练。\n",
@@ -946,6 +968,8 @@
946
  " })\n",
947
  "\n",
948
  "excluded_keys = globals().get(\"EXCLUDED_SAMPLE_KEYS\", set())\n",
 
 
949
  "if excluded_keys:\n",
950
  " before_filter = len(samples)\n",
951
  " samples = [\n",
@@ -976,6 +1000,8 @@
976
  "rng.shuffle(train_samples)\n",
977
  "rng.shuffle(val_samples)\n",
978
  "\n",
 
 
979
  "\n",
980
  "def materialize(split: str, split_samples: list[dict]) -> None:\n",
981
  " for idx, sample in enumerate(split_samples, 1):\n",
@@ -985,10 +1011,27 @@
985
  " dst_lbl = COMBINED_DATASET / f\"labels/{split}/{stem}.txt\"\n",
986
  " shutil.copy2(sample[\"image\"], dst_img)\n",
987
  " write_lines(dst_lbl, sample[\"lines\"])\n",
 
 
 
 
 
 
 
 
 
 
 
 
988
  "\n",
989
  "\n",
990
  "materialize(\"train\", train_samples)\n",
991
  "materialize(\"val\", val_samples)\n",
 
 
 
 
 
992
  "\n",
993
  "YAML_PATH = COMBINED_DATASET / \"dataset.yaml\"\n",
994
  "yaml_content = {\n",
@@ -1015,6 +1058,7 @@
1015
  "print(f\" val labels: {len(val_label_files)}\")\n",
1016
  "print(f\" train class counts: {class_counts(train_label_files)}\")\n",
1017
  "print(f\" val class counts: {class_counts(val_label_files)}\")\n",
 
1018
  "print(YAML_PATH.read_text(encoding=\"utf-8\"))"
1019
  ]
1020
  },
@@ -1023,7 +1067,7 @@
1023
  "metadata": {},
1024
  "source": [
1025
  "---\n",
1026
- "## Step 11 - 可视化抽查训练集"
1027
  ]
1028
  },
1029
  {
@@ -1034,14 +1078,19 @@
1034
  },
1035
  "outputs": [],
1036
  "source": [
1037
- "# @title Step 11 - 可视化抽查训练集\n",
 
 
 
 
1038
  "\n",
1039
- "def draw_label_overlay(img_path: Path, label_path: Path) -> np.ndarray:\n",
 
1040
  " img = read_image(img_path)\n",
1041
  " if img is None:\n",
1042
  " raise ValueError(f\"Cannot read {img_path}\")\n",
1043
  " h, w = img.shape[:2]\n",
1044
- " scale = 720 / max(w, h)\n",
1045
  " disp = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)\n",
1046
  " dh, dw = disp.shape[:2]\n",
1047
  " colors = {\n",
@@ -1065,23 +1114,184 @@
1065
  " return cv2.cvtColor(disp, cv2.COLOR_BGR2RGB)\n",
1066
  "\n",
1067
  "\n",
1068
- "preview_imgs = list_images(COMBINED_DATASET / \"images/train\")\n",
1069
- "preview_imgs = random.sample(preview_imgs, min(6, len(preview_imgs)))\n",
 
 
 
 
 
 
1070
  "\n",
1071
- "if preview_imgs:\n",
1072
- " fig, axes = plt.subplots(2, 3, figsize=(18, 10))\n",
1073
- " axes = axes.flatten()\n",
1074
- " for ax, img_path in zip(axes, preview_imgs):\n",
1075
- " lbl_path = COMBINED_DATASET / \"labels/train\" / f\"{img_path.stem}.txt\"\n",
1076
- " ax.imshow(draw_label_overlay(img_path, lbl_path))\n",
1077
- " ax.set_title(img_path.name, fontsize=9)\n",
1078
- " ax.axis(\"off\")\n",
1079
- " for ax in axes[len(preview_imgs):]:\n",
1080
- " ax.axis(\"off\")\n",
1081
- " plt.tight_layout()\n",
1082
- " plt.show()\n",
1083
- "else:\n",
1084
- " print(\"没有找到可预览图片\")"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1085
  ]
1086
  },
1087
  {
@@ -1111,6 +1321,7 @@
1111
  "BATCH = -1 # 让 Ultralytics 自动选择显存能承受的 batch。\n",
1112
  "PATIENCE = 35 # 验证集 35 轮不提升就早停。\n",
1113
  "RUN_NAME = f\"gas_valve_seg_reviewed_{time.strftime('%Y%m%d_%H%M')}\"\n",
 
1114
  "\n",
1115
  "print(\"训练参数\")\n",
1116
  "print(f\" model: {TRAIN_MODEL}\")\n",
@@ -1120,6 +1331,65 @@
1120
  "print(f\" batch: {BATCH}\")\n",
1121
  "print(f\" run: {RUN_NAME}\")\n",
1122
  "\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1123
  "model = YOLO(TRAIN_MODEL)\n",
1124
  "t_start = time.time()\n",
1125
  "train_results = model.train(\n",
@@ -1153,7 +1423,15 @@
1153
  "elapsed = time.time() - t_start\n",
1154
  "print(f\"训练完成,用时 {elapsed / 60:.1f} 分钟\")\n",
1155
  "print(f\"Run dir: {RUN_DIR}\")\n",
1156
- "print(f\"Best weights: {RUN_DIR / 'weights/best.pt'}\")"
 
 
 
 
 
 
 
 
1157
  ]
1158
  },
1159
  {
@@ -1214,59 +1492,12 @@
1214
  "outputs": [],
1215
  "source": [
1216
  "# @title Step 14 - 上传训练结果\n",
 
1217
  "\n",
1218
- "UPLOAD_TRAINING_RESULTS = True\n",
1219
- "UPLOAD_REPO = DATASET_REPO\n",
1220
- "UPLOAD_REPO_TYPE = \"dataset\"\n",
1221
- "\n",
1222
- "if UPLOAD_TRAINING_RESULTS:\n",
1223
- " upload_items = [\n",
1224
- " \"weights/best.pt\",\n",
1225
- " \"weights/last.pt\",\n",
1226
- " \"results.png\",\n",
1227
- " \"results.csv\",\n",
1228
- " \"args.yaml\",\n",
1229
- " \"confusion_matrix_normalized.png\",\n",
1230
- " \"confusion_matrix.png\",\n",
1231
- " \"BoxP_curve.png\",\n",
1232
- " \"BoxR_curve.png\",\n",
1233
- " \"BoxF1_curve.png\",\n",
1234
- " \"BoxPR_curve.png\",\n",
1235
- " \"MaskP_curve.png\",\n",
1236
- " \"MaskR_curve.png\",\n",
1237
- " \"MaskF1_curve.png\",\n",
1238
- " \"MaskPR_curve.png\",\n",
1239
- " ]\n",
1240
- "\n",
1241
- " operations = []\n",
1242
- " for rel in upload_items:\n",
1243
- " local_file = RUN_DIR / rel\n",
1244
- " if not local_file.exists():\n",
1245
- " continue\n",
1246
- " operations.append(CommitOperationAdd(\n",
1247
- " path_in_repo=f\"runs/{RUN_NAME}/{rel}\",\n",
1248
- " path_or_fileobj=local_file.read_bytes(),\n",
1249
- " ))\n",
1250
- " print(f\"Prepared {rel}\")\n",
1251
  "\n",
1252
- " operations.append(CommitOperationAdd(\n",
1253
- " path_in_repo=f\"runs/{RUN_NAME}/dataset.yaml\",\n",
1254
- " path_or_fileobj=YAML_PATH.read_bytes(),\n",
1255
- " ))\n",
1256
- "\n",
1257
- " if operations:\n",
1258
- " api.create_commit(\n",
1259
- " repo_id=UPLOAD_REPO,\n",
1260
- " repo_type=UPLOAD_REPO_TYPE,\n",
1261
- " token=HF_TOKEN,\n",
1262
- " operations=operations,\n",
1263
- " commit_message=f\"Training_results_{RUN_NAME}\",\n",
1264
- " )\n",
1265
- " print(f\"Uploaded results to https://huggingface.co/datasets/{UPLOAD_REPO}/tree/main/runs/{RUN_NAME}\")\n",
1266
- " else:\n",
1267
- " print(\"No result files found to upload\")\n",
1268
- "else:\n",
1269
- " print(\"Skipping result upload\")"
1270
  ]
1271
  },
1272
  {
 
80
  "\n",
81
  "get_ipython().system(\n",
82
  " \"pip install -q ultralytics huggingface_hub opencv-python-headless \"\n",
83
+ " \"tqdm pyyaml matplotlib pandas ipywidgets\"\n",
84
  ")\n",
85
  "\n",
86
  "import os\n",
 
89
  "import shutil\n",
90
  "import random\n",
91
  "import subprocess\n",
92
+ "import base64\n",
93
  "from pathlib import Path\n",
94
  "\n",
95
  "import cv2\n",
 
176
  "RAW_VALVE_PREFIX = \"raw/valve\"\n",
177
  "RAW_GAS_EXTRA_PREFIX = \"raw/gas_extra\"\n",
178
  "REVIEWED_VALVE_LABEL_PREFIX = \"reviewed_labels/valve\"\n",
179
+ "CLEANING_PREFIX = \"cleaning\"\n",
180
  "PROCESS_SCRIPT_REPO_PATH = \"scripts/process_valve_to_polygon.py\"\n",
181
  "FORCE_REDOWNLOAD = True\n",
182
  "\n",
 
190
  " f\"{RAW_VALVE_PREFIX}/**\",\n",
191
  " f\"{RAW_GAS_EXTRA_PREFIX}/**\",\n",
192
  " f\"{REVIEWED_VALVE_LABEL_PREFIX}/**\",\n",
193
+ " f\"{CLEANING_PREFIX}/**\",\n",
194
  " PROCESS_SCRIPT_REPO_PATH,\n",
195
  " \"dataset.yaml\",\n",
196
  "]\n",
 
208
  "RAW_VALVE_DIR = base / RAW_VALVE_PREFIX\n",
209
  "RAW_GAS_EXTRA_DIR = base / RAW_GAS_EXTRA_PREFIX\n",
210
  "REVIEWED_VALVE_LABEL_DIR = base / REVIEWED_VALVE_LABEL_PREFIX\n",
211
+ "CLEANING_DIR = base / CLEANING_PREFIX\n",
212
  "PROCESS_SCRIPT_LOCAL = base / PROCESS_SCRIPT_REPO_PATH\n",
213
  "\n",
214
  "print(\"下载结果统计\")\n",
 
218
  " RAW_VALVE_DIR,\n",
219
  " RAW_GAS_EXTRA_DIR,\n",
220
  " REVIEWED_VALVE_LABEL_DIR,\n",
221
+ " CLEANING_DIR,\n",
222
  "]:\n",
223
  " n = len(list(p.glob(\"*\"))) if p.exists() else 0\n",
224
  " print(f\" {p}: {n} entries\")\n",
 
683
  " return keys\n",
684
  "\n",
685
  "\n",
686
+ "def read_exclude_keys_file(path: Path) -> set[str]:\n",
687
+ " if not path.exists():\n",
688
+ " return set()\n",
689
+ " return parse_exclude_keys(path.read_text(encoding=\"utf-8\", errors=\"ignore\"))\n",
690
+ "\n",
691
+ "\n",
692
+ "PERSISTED_EXCLUDE_PATH = CLEANING_DIR / \"excluded_sample_keys.txt\"\n",
693
+ "PERSISTED_EXCLUDED_SAMPLE_KEYS = read_exclude_keys_file(PERSISTED_EXCLUDE_PATH)\n",
694
+ "MANUAL_EXCLUDED_SAMPLE_KEYS = parse_exclude_keys(EXCLUDE_SAMPLE_KEYS)\n",
695
+ "EXCLUDED_SAMPLE_KEYS = PERSISTED_EXCLUDED_SAMPLE_KEYS | MANUAL_EXCLUDED_SAMPLE_KEYS\n",
696
+ "\n",
697
+ "if PERSISTED_EXCLUDED_SAMPLE_KEYS:\n",
698
+ " print(f\"HuggingFace 已保存排除样本: {len(PERSISTED_EXCLUDED_SAMPLE_KEYS)}\")\n",
699
+ "if MANUAL_EXCLUDED_SAMPLE_KEYS:\n",
700
+ " print(f\"本次手动填写排除样本: {len(MANUAL_EXCLUDED_SAMPLE_KEYS)}\")\n",
701
  "print(f\"Excluded sample keys: {len(EXCLUDED_SAMPLE_KEYS)}\")\n",
702
  "for key in sorted(EXCLUDED_SAMPLE_KEYS):\n",
703
  " print(f\" {key}\")\n",
 
893
  "source": [
894
  "# @title Step 10 - 构建两类训练集\n",
895
  "\n",
896
+ "import pandas as pd\n",
897
+ "\n",
898
  "COMBINED_DATASET = Path(\"/content/gas_valve_dataset\")\n",
899
+ "COMBINED_MANIFEST_PATH = COMBINED_DATASET / \"training_manifest.csv\"\n",
900
  "VAL_RATIO = 0.20 # 20% 做验证集,80% 做训练集。\n",
901
  "RANDOM_SEED = 42 # 固定随机种子,方便复现实验。\n",
902
  "INCLUDE_OLD_GAS_DATA = True # 保留原来的气瓶数据一起训练。\n",
 
968
  " })\n",
969
  "\n",
970
  "excluded_keys = globals().get(\"EXCLUDED_SAMPLE_KEYS\", set())\n",
971
+ "if \"read_exclude_keys_file\" in globals():\n",
972
+ " excluded_keys = set(excluded_keys) | read_exclude_keys_file(CLEANING_DIR / \"excluded_sample_keys.txt\")\n",
973
  "if excluded_keys:\n",
974
  " before_filter = len(samples)\n",
975
  " samples = [\n",
 
1000
  "rng.shuffle(train_samples)\n",
1001
  "rng.shuffle(val_samples)\n",
1002
  "\n",
1003
+ "training_manifest_rows: list[dict] = []\n",
1004
+ "\n",
1005
  "\n",
1006
  "def materialize(split: str, split_samples: list[dict]) -> None:\n",
1007
  " for idx, sample in enumerate(split_samples, 1):\n",
 
1011
  " dst_lbl = COMBINED_DATASET / f\"labels/{split}/{stem}.txt\"\n",
1012
  " shutil.copy2(sample[\"image\"], dst_img)\n",
1013
  " write_lines(dst_lbl, sample[\"lines\"])\n",
1014
+ " training_manifest_rows.append({\n",
1015
+ " \"split\": split,\n",
1016
+ " \"dataset_stem\": stem,\n",
1017
+ " \"image_path\": str(dst_img),\n",
1018
+ " \"label_path\": str(dst_lbl),\n",
1019
+ " \"source_key\": sample[\"source_key\"],\n",
1020
+ " \"source\": sample[\"source\"],\n",
1021
+ " \"source_stem\": sample[\"source_stem\"],\n",
1022
+ " \"group\": sample[\"group\"],\n",
1023
+ " \"classes\": \",\".join(sorted({line.split()[0] for line in sample[\"lines\"]})),\n",
1024
+ " \"objects\": len(sample[\"lines\"]),\n",
1025
+ " })\n",
1026
  "\n",
1027
  "\n",
1028
  "materialize(\"train\", train_samples)\n",
1029
  "materialize(\"val\", val_samples)\n",
1030
+ "pd.DataFrame(training_manifest_rows).to_csv(\n",
1031
+ " COMBINED_MANIFEST_PATH,\n",
1032
+ " index=False,\n",
1033
+ " encoding=\"utf-8-sig\",\n",
1034
+ ")\n",
1035
  "\n",
1036
  "YAML_PATH = COMBINED_DATASET / \"dataset.yaml\"\n",
1037
  "yaml_content = {\n",
 
1058
  "print(f\" val labels: {len(val_label_files)}\")\n",
1059
  "print(f\" train class counts: {class_counts(train_label_files)}\")\n",
1060
  "print(f\" val class counts: {class_counts(val_label_files)}\")\n",
1061
+ "print(f\" manifest: {COMBINED_MANIFEST_PATH}\")\n",
1062
  "print(YAML_PATH.read_text(encoding=\"utf-8\"))"
1063
  ]
1064
  },
 
1067
  "metadata": {},
1068
  "source": [
1069
  "---\n",
1070
+ "## Step 11 - 全量审核训练集并删除坏样本"
1071
  ]
1072
  },
1073
  {
 
1078
  },
1079
  "outputs": [],
1080
  "source": [
1081
+ "# @title Step 11 - 全量审核训练集并删除坏样本\n",
1082
+ "# @markdown 这一步会显示 train/val 全部样本。勾选错误样本后点击红色按钮,会从当前 Colab 训练集删除,并把排除清单保存到 HuggingFace。\n",
1083
+ "\n",
1084
+ "from IPython.display import display\n",
1085
+ "import ipywidgets as widgets\n",
1086
  "\n",
1087
+ "\n",
1088
+ "def draw_label_overlay(img_path: Path, label_path: Path, max_side: int = 720) -> np.ndarray:\n",
1089
  " img = read_image(img_path)\n",
1090
  " if img is None:\n",
1091
  " raise ValueError(f\"Cannot read {img_path}\")\n",
1092
  " h, w = img.shape[:2]\n",
1093
+ " scale = max_side / max(w, h)\n",
1094
  " disp = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)\n",
1095
  " dh, dw = disp.shape[:2]\n",
1096
  " colors = {\n",
 
1114
  " return cv2.cvtColor(disp, cv2.COLOR_BGR2RGB)\n",
1115
  "\n",
1116
  "\n",
1117
+ "def overlay_data_url(img_path: Path, label_path: Path, max_side: int = 320) -> str:\n",
1118
+ " rgb = draw_label_overlay(img_path, label_path, max_side=max_side)\n",
1119
+ " bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)\n",
1120
+ " ok, buf = cv2.imencode(\".jpg\", bgr, [int(cv2.IMWRITE_JPEG_QUALITY), 82])\n",
1121
+ " if not ok:\n",
1122
+ " raise ValueError(f\"Cannot encode overlay for {img_path}\")\n",
1123
+ " encoded = base64.b64encode(buf.tobytes()).decode(\"ascii\")\n",
1124
+ " return f\"data:image/jpeg;base64,{encoded}\"\n",
1125
  "\n",
1126
+ "\n",
1127
+ "def write_persisted_exclusions(keys: set[str], selected_df: pd.DataFrame) -> tuple[Path, Path]:\n",
1128
+ " CLEANING_DIR.mkdir(parents=True, exist_ok=True)\n",
1129
+ " txt_path = CLEANING_DIR / \"excluded_sample_keys.txt\"\n",
1130
+ " csv_path = CLEANING_DIR / \"excluded_sample_keys_latest.csv\"\n",
1131
+ "\n",
1132
+ " txt_path.write_text(\n",
1133
+ " \"\\n\".join(sorted(keys)) + (\"\\n\" if keys else \"\"),\n",
1134
+ " encoding=\"utf-8\",\n",
1135
+ " )\n",
1136
+ "\n",
1137
+ " selected_out = selected_df[\n",
1138
+ " [\"source_key\", \"source\", \"source_stem\", \"group\", \"split\", \"dataset_stem\"]\n",
1139
+ " ].copy()\n",
1140
+ " selected_out[\"deleted_at\"] = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n",
1141
+ " selected_out.to_csv(csv_path, index=False, encoding=\"utf-8-sig\")\n",
1142
+ " return txt_path, csv_path\n",
1143
+ "\n",
1144
+ "\n",
1145
+ "def upload_persisted_exclusions(txt_path: Path, csv_path: Path) -> None:\n",
1146
+ " api.upload_file(\n",
1147
+ " repo_id=DATASET_REPO,\n",
1148
+ " repo_type=\"dataset\",\n",
1149
+ " token=HF_TOKEN,\n",
1150
+ " path_or_fileobj=str(txt_path),\n",
1151
+ " path_in_repo=f\"{CLEANING_PREFIX}/excluded_sample_keys.txt\",\n",
1152
+ " commit_message=\"update excluded training sample keys\",\n",
1153
+ " )\n",
1154
+ " api.upload_file(\n",
1155
+ " repo_id=DATASET_REPO,\n",
1156
+ " repo_type=\"dataset\",\n",
1157
+ " token=HF_TOKEN,\n",
1158
+ " path_or_fileobj=str(csv_path),\n",
1159
+ " path_in_repo=f\"{CLEANING_PREFIX}/excluded_sample_keys_latest.csv\",\n",
1160
+ " commit_message=\"update latest excluded training sample table\",\n",
1161
+ " )\n",
1162
+ "\n",
1163
+ "\n",
1164
+ "if not COMBINED_MANIFEST_PATH.exists():\n",
1165
+ " raise FileNotFoundError(\n",
1166
+ " f\"Missing {COMBINED_MANIFEST_PATH}. Please run Step 10 before Step 11.\"\n",
1167
+ " )\n",
1168
+ "\n",
1169
+ "training_review_df = pd.read_csv(COMBINED_MANIFEST_PATH)\n",
1170
+ "training_review_df = training_review_df.sort_values(\n",
1171
+ " [\"split\", \"source\", \"source_key\"]\n",
1172
+ ").reset_index(drop=True)\n",
1173
+ "\n",
1174
+ "print(f\"全量训练集样本数: {len(training_review_df)}\")\n",
1175
+ "print(training_review_df.groupby([\"split\", \"source\"]).size().to_string())\n",
1176
+ "print(\"\")\n",
1177
+ "print(\"绿色是 class 0 气瓶,橙蓝色是 class 1 阀门。确认有问题的样本后,勾选图片下方复选框。\")\n",
1178
+ "\n",
1179
+ "checkboxes: dict[int, widgets.Checkbox] = {}\n",
1180
+ "cards: list[widgets.Widget] = []\n",
1181
+ "\n",
1182
+ "for idx, row in training_review_df.iterrows():\n",
1183
+ " img_path = Path(row[\"image_path\"])\n",
1184
+ " lbl_path = Path(row[\"label_path\"])\n",
1185
+ " if img_path.exists() and lbl_path.exists():\n",
1186
+ " img_html = (\n",
1187
+ " f\"<img src='{overlay_data_url(img_path, lbl_path)}' \"\n",
1188
+ " \"style='width:260px; height:auto; display:block;'>\"\n",
1189
+ " )\n",
1190
+ " else:\n",
1191
+ " img_html = \"<div style='width:260px;height:160px;background:#eee;'>missing file</div>\"\n",
1192
+ "\n",
1193
+ " title = (\n",
1194
+ " \"<div style='font-size:12px;line-height:1.35;\"\n",
1195
+ " \"font-family:Arial, sans-serif;word-break:break-all;'>\"\n",
1196
+ " f\"<b>{row['split']}</b> | {row['source_key']}<br>\"\n",
1197
+ " f\"{row['dataset_stem']} | class {row['classes']} | objects {row['objects']}\"\n",
1198
+ " \"</div>\"\n",
1199
+ " )\n",
1200
+ " checkbox = widgets.Checkbox(\n",
1201
+ " value=False,\n",
1202
+ " description=\"删除这个样本\",\n",
1203
+ " indent=False,\n",
1204
+ " layout=widgets.Layout(width=\"260px\"),\n",
1205
+ " )\n",
1206
+ " checkboxes[idx] = checkbox\n",
1207
+ " cards.append(widgets.VBox(\n",
1208
+ " [\n",
1209
+ " widgets.HTML(title + img_html),\n",
1210
+ " checkbox,\n",
1211
+ " ],\n",
1212
+ " layout=widgets.Layout(\n",
1213
+ " width=\"280px\",\n",
1214
+ " border=\"1px solid #ddd\",\n",
1215
+ " padding=\"6px\",\n",
1216
+ " margin=\"4px\",\n",
1217
+ " ),\n",
1218
+ " ))\n",
1219
+ "\n",
1220
+ "delete_button = widgets.Button(\n",
1221
+ " description=\"删除勾选样本并保存到 HuggingFace\",\n",
1222
+ " button_style=\"danger\",\n",
1223
+ " layout=widgets.Layout(width=\"280px\"),\n",
1224
+ ")\n",
1225
+ "summary_label = widgets.HTML(\n",
1226
+ " value=\"<b>操作提示:</b>删除后不用重新跑 Step 10,直接运行 Step 12 训练即可。\"\n",
1227
+ ")\n",
1228
+ "delete_output = widgets.Output()\n",
1229
+ "\n",
1230
+ "\n",
1231
+ "def on_delete_clicked(_button):\n",
1232
+ " selected_indices = [idx for idx, cb in checkboxes.items() if cb.value]\n",
1233
+ " with delete_output:\n",
1234
+ " delete_output.clear_output()\n",
1235
+ " if not selected_indices:\n",
1236
+ " print(\"没有勾选任何样本。\")\n",
1237
+ " return\n",
1238
+ "\n",
1239
+ " selected_df = training_review_df.loc[selected_indices].copy()\n",
1240
+ " selected_keys = set(selected_df[\"source_key\"].astype(str))\n",
1241
+ "\n",
1242
+ " existing_keys = set(globals().get(\"EXCLUDED_SAMPLE_KEYS\", set()))\n",
1243
+ " if \"read_exclude_keys_file\" in globals():\n",
1244
+ " existing_keys |= read_exclude_keys_file(CLEANING_DIR / \"excluded_sample_keys.txt\")\n",
1245
+ " merged_keys = existing_keys | selected_keys\n",
1246
+ "\n",
1247
+ " deleted_files = 0\n",
1248
+ " for _, selected_row in selected_df.iterrows():\n",
1249
+ " for col in [\"image_path\", \"label_path\"]:\n",
1250
+ " p = Path(selected_row[col])\n",
1251
+ " if p.exists():\n",
1252
+ " p.unlink()\n",
1253
+ " deleted_files += 1\n",
1254
+ "\n",
1255
+ " remaining_df = training_review_df.drop(index=selected_indices).reset_index(drop=True)\n",
1256
+ " remaining_df.to_csv(COMBINED_MANIFEST_PATH, index=False, encoding=\"utf-8-sig\")\n",
1257
+ "\n",
1258
+ " txt_path, csv_path = write_persisted_exclusions(merged_keys, selected_df)\n",
1259
+ " globals()[\"EXCLUDED_SAMPLE_KEYS\"] = merged_keys\n",
1260
+ "\n",
1261
+ " print(f\"当前 Colab 训练集已删除样本: {len(selected_df)}\")\n",
1262
+ " print(f\"删除 image/label 文件数: {deleted_files}\")\n",
1263
+ " print(f\"累计排除 source_key 数: {len(merged_keys)}\")\n",
1264
+ " print(f\"本地清单: {txt_path}\")\n",
1265
+ " train_labels_now = list((COMBINED_DATASET / \"labels/train\").glob(\"*.txt\"))\n",
1266
+ " val_labels_now = list((COMBINED_DATASET / \"labels/val\").glob(\"*.txt\"))\n",
1267
+ " print(f\"剩余 train 图片: {len(list_images(COMBINED_DATASET / 'images/train'))}\")\n",
1268
+ " print(f\"剩余 val 图片: {len(list_images(COMBINED_DATASET / 'images/val'))}\")\n",
1269
+ " print(f\"剩余 train 类别计数: {class_counts(train_labels_now)}\")\n",
1270
+ " print(f\"剩余 val 类别计数: {class_counts(val_labels_now)}\")\n",
1271
+ "\n",
1272
+ " try:\n",
1273
+ " upload_persisted_exclusions(txt_path, csv_path)\n",
1274
+ " print(\"HuggingFace 排除清单已保存。以后重新跑 Step 3-10 会自动排除这些样本。\")\n",
1275
+ " except Exception as exc:\n",
1276
+ " print(\"HuggingFace 上传排除清单失败,但当前 Colab 训练集已经删除。\")\n",
1277
+ " print(repr(exc))\n",
1278
+ "\n",
1279
+ " for idx in selected_indices:\n",
1280
+ " checkboxes[idx].disabled = True\n",
1281
+ "\n",
1282
+ "\n",
1283
+ "delete_button.on_click(on_delete_clicked)\n",
1284
+ "\n",
1285
+ "grid = widgets.GridBox(\n",
1286
+ " cards,\n",
1287
+ " layout=widgets.Layout(\n",
1288
+ " grid_template_columns=\"repeat(3, 300px)\",\n",
1289
+ " grid_gap=\"8px\",\n",
1290
+ " align_items=\"flex-start\",\n",
1291
+ " ),\n",
1292
+ ")\n",
1293
+ "\n",
1294
+ "display(widgets.VBox([summary_label, delete_button, delete_output, grid]))"
1295
  ]
1296
  },
1297
  {
 
1321
  "BATCH = -1 # 让 Ultralytics 自动选择显存能承受的 batch。\n",
1322
  "PATIENCE = 35 # 验证集 35 轮不提升就早停。\n",
1323
  "RUN_NAME = f\"gas_valve_seg_reviewed_{time.strftime('%Y%m%d_%H%M')}\"\n",
1324
+ "AUTO_UPLOAD_TRAINING_RESULTS = True\n",
1325
  "\n",
1326
  "print(\"训练参数\")\n",
1327
  "print(f\" model: {TRAIN_MODEL}\")\n",
 
1331
  "print(f\" batch: {BATCH}\")\n",
1332
  "print(f\" run: {RUN_NAME}\")\n",
1333
  "\n",
1334
+ "\n",
1335
+ "TRAINING_UPLOAD_ITEMS = [\n",
1336
+ " \"weights/best.pt\",\n",
1337
+ " \"weights/last.pt\",\n",
1338
+ " \"results.png\",\n",
1339
+ " \"results.csv\",\n",
1340
+ " \"args.yaml\",\n",
1341
+ " \"confusion_matrix_normalized.png\",\n",
1342
+ " \"confusion_matrix.png\",\n",
1343
+ " \"BoxP_curve.png\",\n",
1344
+ " \"BoxR_curve.png\",\n",
1345
+ " \"BoxF1_curve.png\",\n",
1346
+ " \"BoxPR_curve.png\",\n",
1347
+ " \"MaskP_curve.png\",\n",
1348
+ " \"MaskR_curve.png\",\n",
1349
+ " \"MaskF1_curve.png\",\n",
1350
+ " \"MaskPR_curve.png\",\n",
1351
+ "]\n",
1352
+ "\n",
1353
+ "\n",
1354
+ "def upload_training_outputs(run_dir: Path, run_name: str) -> None:\n",
1355
+ " operations = []\n",
1356
+ " for rel in TRAINING_UPLOAD_ITEMS:\n",
1357
+ " local_file = run_dir / rel\n",
1358
+ " if not local_file.exists():\n",
1359
+ " continue\n",
1360
+ " operations.append(CommitOperationAdd(\n",
1361
+ " path_in_repo=f\"runs/{run_name}/{rel}\",\n",
1362
+ " path_or_fileobj=str(local_file),\n",
1363
+ " ))\n",
1364
+ " print(f\"准备上传: {rel}\")\n",
1365
+ "\n",
1366
+ " extra_files = [\n",
1367
+ " (YAML_PATH, \"dataset.yaml\"),\n",
1368
+ " (COMBINED_MANIFEST_PATH, \"training_manifest.csv\"),\n",
1369
+ " (CLEANING_DIR / \"excluded_sample_keys.txt\", \"excluded_sample_keys.txt\"),\n",
1370
+ " ]\n",
1371
+ " for local_file, rel in extra_files:\n",
1372
+ " if local_file.exists():\n",
1373
+ " operations.append(CommitOperationAdd(\n",
1374
+ " path_in_repo=f\"runs/{run_name}/{rel}\",\n",
1375
+ " path_or_fileobj=str(local_file),\n",
1376
+ " ))\n",
1377
+ " print(f\"准备上传: {rel}\")\n",
1378
+ "\n",
1379
+ " if not operations:\n",
1380
+ " print(\"没有找到可上传的训练结果文件。\")\n",
1381
+ " return\n",
1382
+ "\n",
1383
+ " api.create_commit(\n",
1384
+ " repo_id=DATASET_REPO,\n",
1385
+ " repo_type=\"dataset\",\n",
1386
+ " token=HF_TOKEN,\n",
1387
+ " operations=operations,\n",
1388
+ " commit_message=f\"Training_results_{run_name}\",\n",
1389
+ " )\n",
1390
+ " print(f\"训练结果已上传: https://huggingface.co/datasets/{DATASET_REPO}/tree/main/runs/{run_name}\")\n",
1391
+ "\n",
1392
+ "\n",
1393
  "model = YOLO(TRAIN_MODEL)\n",
1394
  "t_start = time.time()\n",
1395
  "train_results = model.train(\n",
 
1423
  "elapsed = time.time() - t_start\n",
1424
  "print(f\"训练完成,用时 {elapsed / 60:.1f} 分钟\")\n",
1425
  "print(f\"Run dir: {RUN_DIR}\")\n",
1426
+ "print(f\"Best weights: {RUN_DIR / 'weights/best.pt'}\")\n",
1427
+ "\n",
1428
+ "if AUTO_UPLOAD_TRAINING_RESULTS:\n",
1429
+ " print(\"开始自动上传训练结果到 HuggingFace...\")\n",
1430
+ " try:\n",
1431
+ " upload_training_outputs(RUN_DIR, RUN_NAME)\n",
1432
+ " except Exception as exc:\n",
1433
+ " print(\"自动上传失败。训练结果仍保存在当前 Colab 的 RUN_DIR,可以运行 Step 14 手动重传。\")\n",
1434
+ " print(repr(exc))"
1435
  ]
1436
  },
1437
  {
 
1492
  "outputs": [],
1493
  "source": [
1494
  "# @title Step 14 - 上传训练结果\n",
1495
+ "# @markdown Step 12 训练完成后已经会自动上传。本步骤只用于自动上传失败后的手动重传。\n",
1496
  "\n",
1497
+ "if \"RUN_DIR\" not in globals() or \"RUN_NAME\" not in globals():\n",
1498
+ " raise RuntimeError(\"还没有训练结果。请先运行 Step 12。\")\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1499
  "\n",
1500
+ "upload_training_outputs(RUN_DIR, RUN_NAME)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1501
  ]
1502
  },
1503
  {