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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
|
| 490 |
COMBINED_DATASET = Path("/content/gas_valve_dataset")
|
| 491 |
VAL_RATIO = 0.20 # @param {type:"number"}
|
|
@@ -516,6 +727,8 @@ if INCLUDE_OLD_GAS_DATA:
|
|
| 516 |
"lines": lines,
|
| 517 |
"group": "gas",
|
| 518 |
"source": "old_gas",
|
|
|
|
|
|
|
| 519 |
})
|
| 520 |
|
| 521 |
for img_path in list_images(RAW_GAS_EXTRA_DIR):
|
|
@@ -527,6 +740,8 @@ for img_path in list_images(RAW_GAS_EXTRA_DIR):
|
|
| 527 |
"lines": lines,
|
| 528 |
"group": "gas",
|
| 529 |
"source": "gas_extra",
|
|
|
|
|
|
|
| 530 |
})
|
| 531 |
|
| 532 |
for img_path in list_images(RAW_VALVE_DIR):
|
|
@@ -539,8 +754,19 @@ for img_path in list_images(RAW_VALVE_DIR):
|
|
| 539 |
"lines": gas_lines + valve_lines,
|
| 540 |
"group": "valve",
|
| 541 |
"source": "valve",
|
|
|
|
|
|
|
| 542 |
})
|
| 543 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 544 |
print(f"Collected labeled samples: {len(samples)}")
|
| 545 |
print(f" gas samples: {sum(1 for s in samples if s['group'] == 'gas')}")
|
| 546 |
print(f" valve samples: {sum(1 for s in samples if s['group'] == 'valve')}")
|
|
@@ -607,11 +833,11 @@ print(YAML_PATH.read_text(encoding="utf-8"))
|
|
| 607 |
|
| 608 |
# %% [markdown]
|
| 609 |
# ---
|
| 610 |
-
# ## Step
|
| 611 |
|
| 612 |
|
| 613 |
# %%
|
| 614 |
-
# @title Step
|
| 615 |
|
| 616 |
def draw_label_overlay(img_path: Path, label_path: Path) -> np.ndarray:
|
| 617 |
img = read_image(img_path)
|
|
@@ -663,11 +889,11 @@ else:
|
|
| 663 |
|
| 664 |
# %% [markdown]
|
| 665 |
# ---
|
| 666 |
-
# ## Step
|
| 667 |
|
| 668 |
|
| 669 |
# %%
|
| 670 |
-
# @title Step
|
| 671 |
|
| 672 |
from ultralytics import YOLO
|
| 673 |
|
|
@@ -724,11 +950,11 @@ print(f"Best weights: {RUN_DIR / 'weights/best.pt'}")
|
|
| 724 |
|
| 725 |
# %% [markdown]
|
| 726 |
# ---
|
| 727 |
-
# ## Step
|
| 728 |
|
| 729 |
|
| 730 |
# %%
|
| 731 |
-
# @title Step
|
| 732 |
|
| 733 |
import pandas as pd
|
| 734 |
import matplotlib.image as mpimg
|
|
@@ -755,11 +981,11 @@ for name in ["results.png", "confusion_matrix_normalized.png", "confusion_matrix
|
|
| 755 |
|
| 756 |
# %% [markdown]
|
| 757 |
# ---
|
| 758 |
-
# ## Step
|
| 759 |
|
| 760 |
|
| 761 |
# %%
|
| 762 |
-
# @title Step
|
| 763 |
|
| 764 |
UPLOAD_TRAINING_RESULTS = True # @param {type:"boolean"}
|
| 765 |
UPLOAD_REPO = DATASET_REPO # @param {type:"string"}
|
|
|
|
| 481 |
|
| 482 |
# %% [markdown]
|
| 483 |
# ---
|
| 484 |
+
# ## Step 9 - Review and cleaning controls
|
| 485 |
|
| 486 |
|
| 487 |
# %%
|
| 488 |
+
# @title Step 9 - Review and cleaning controls
|
| 489 |
+
# @markdown The manifest uses `source/stem` keys, for example `valve/Pic_阀门_60` or `gas_extra/Pic_气瓶_125`.
|
| 490 |
+
# @markdown Put one key per line in `EXCLUDE_SAMPLE_KEYS` to remove those samples from the training dataset.
|
| 491 |
+
|
| 492 |
+
import pandas as pd
|
| 493 |
+
|
| 494 |
+
EXCLUDE_SAMPLE_KEYS = """
|
| 495 |
+
""" # @param {type:"string"}
|
| 496 |
+
|
| 497 |
+
REVIEW_SOURCE = "valve" # @param ["valve", "gas_extra", "old_gas", "all"]
|
| 498 |
+
REVIEW_OFFSET = 0 # @param {type:"integer"}
|
| 499 |
+
REVIEW_COUNT = 9 # @param {type:"integer"}
|
| 500 |
+
|
| 501 |
+
DELETE_EXCLUDED_FROM_HF = False # @param {type:"boolean"}
|
| 502 |
+
CONFIRM_HF_DELETE = "" # @param {type:"string"}
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def parse_exclude_keys(text: str) -> set[str]:
|
| 506 |
+
keys: set[str] = set()
|
| 507 |
+
for raw in text.replace(",", "\n").splitlines():
|
| 508 |
+
line = raw.strip()
|
| 509 |
+
if not line or line.startswith("#"):
|
| 510 |
+
continue
|
| 511 |
+
keys.add(line)
|
| 512 |
+
return keys
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
EXCLUDED_SAMPLE_KEYS = parse_exclude_keys(EXCLUDE_SAMPLE_KEYS)
|
| 516 |
+
print(f"Excluded sample keys: {len(EXCLUDED_SAMPLE_KEYS)}")
|
| 517 |
+
for key in sorted(EXCLUDED_SAMPLE_KEYS):
|
| 518 |
+
print(f" {key}")
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def label_summary(lines: list[str]) -> tuple[str, str]:
|
| 522 |
+
classes: list[str] = []
|
| 523 |
+
points: list[str] = []
|
| 524 |
+
for line in lines:
|
| 525 |
+
parts = line.split()
|
| 526 |
+
if not parts:
|
| 527 |
+
continue
|
| 528 |
+
classes.append(parts[0])
|
| 529 |
+
points.append(str((len(parts) - 1) // 2))
|
| 530 |
+
return ",".join(classes), ",".join(points)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
manifest_rows: list[dict] = []
|
| 534 |
+
|
| 535 |
+
include_old_in_review = globals().get("INCLUDE_OLD_GAS_DATA", True)
|
| 536 |
+
if include_old_in_review:
|
| 537 |
+
old_img_dir = base / "images/train"
|
| 538 |
+
old_lbl_dir = base / "labels/train"
|
| 539 |
+
for lbl_path in sorted(old_lbl_dir.glob("*.txt")):
|
| 540 |
+
img_path = find_image_by_stem(old_img_dir, lbl_path.stem)
|
| 541 |
+
lines = valid_seg_lines(lbl_path, {0})
|
| 542 |
+
classes, points = label_summary(lines)
|
| 543 |
+
manifest_rows.append({
|
| 544 |
+
"source_key": f"old_gas/{lbl_path.stem}",
|
| 545 |
+
"source": "old_gas",
|
| 546 |
+
"stem": lbl_path.stem,
|
| 547 |
+
"image_path": str(img_path) if img_path else "",
|
| 548 |
+
"status": "ok" if img_path and lines else "missing_image_or_label",
|
| 549 |
+
"classes": classes,
|
| 550 |
+
"points": points,
|
| 551 |
+
})
|
| 552 |
+
|
| 553 |
+
for img_path in list_images(RAW_GAS_EXTRA_DIR):
|
| 554 |
+
lines = valid_seg_lines(GAS_EXTRA_LABEL_DIR / f"{img_path.stem}.txt", {0})
|
| 555 |
+
classes, points = label_summary(lines)
|
| 556 |
+
manifest_rows.append({
|
| 557 |
+
"source_key": f"gas_extra/{img_path.stem}",
|
| 558 |
+
"source": "gas_extra",
|
| 559 |
+
"stem": img_path.stem,
|
| 560 |
+
"image_path": str(img_path),
|
| 561 |
+
"status": "ok" if lines else "missing_gas_label",
|
| 562 |
+
"classes": classes,
|
| 563 |
+
"points": points,
|
| 564 |
+
})
|
| 565 |
+
|
| 566 |
+
for img_path in list_images(RAW_VALVE_DIR):
|
| 567 |
+
gas_lines = valid_seg_lines(VALVE_GAS_LABEL_DIR / f"{img_path.stem}.txt", {0})
|
| 568 |
+
valve_lines = valid_seg_lines(VALVE_LABEL_DIR / f"{img_path.stem}.txt", {1})
|
| 569 |
+
classes, points = label_summary(gas_lines + valve_lines)
|
| 570 |
+
status = "ok" if valve_lines else "missing_valve_label"
|
| 571 |
+
manifest_rows.append({
|
| 572 |
+
"source_key": f"valve/{img_path.stem}",
|
| 573 |
+
"source": "valve",
|
| 574 |
+
"stem": img_path.stem,
|
| 575 |
+
"image_path": str(img_path),
|
| 576 |
+
"status": status,
|
| 577 |
+
"classes": classes,
|
| 578 |
+
"points": points,
|
| 579 |
+
})
|
| 580 |
+
|
| 581 |
+
manifest_df = pd.DataFrame(manifest_rows)
|
| 582 |
+
manifest_path = Path("/content/gas_valve_review_manifest.csv")
|
| 583 |
+
manifest_df.to_csv(manifest_path, index=False, encoding="utf-8-sig")
|
| 584 |
+
|
| 585 |
+
print("Review manifest written:", manifest_path)
|
| 586 |
+
print(manifest_df.groupby(["source", "status"]).size().to_string())
|
| 587 |
+
print("")
|
| 588 |
+
print("First rows:")
|
| 589 |
+
try:
|
| 590 |
+
display(manifest_df.head(20))
|
| 591 |
+
except Exception:
|
| 592 |
+
print(manifest_df.head(20).to_string(index=False))
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def draw_lines_overlay(img_path: Path, lines: list[str]) -> np.ndarray:
|
| 596 |
+
img = read_image(img_path)
|
| 597 |
+
if img is None:
|
| 598 |
+
raise ValueError(f"Cannot read {img_path}")
|
| 599 |
+
h, w = img.shape[:2]
|
| 600 |
+
scale = 720 / max(w, h)
|
| 601 |
+
disp = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)
|
| 602 |
+
dh, dw = disp.shape[:2]
|
| 603 |
+
colors = {0: (0, 220, 0), 1: (255, 80, 0)}
|
| 604 |
+
for line in lines:
|
| 605 |
+
parts = line.split()
|
| 606 |
+
if len(parts) < 7:
|
| 607 |
+
continue
|
| 608 |
+
cls = int(parts[0])
|
| 609 |
+
vals = np.array([float(v) for v in parts[1:]], dtype=np.float32).reshape(-1, 2)
|
| 610 |
+
pts = (vals * np.array([dw, dh], dtype=np.float32)).astype(np.int32).reshape(-1, 1, 2)
|
| 611 |
+
color = colors.get(cls, (0, 255, 255))
|
| 612 |
+
overlay = disp.copy()
|
| 613 |
+
cv2.fillPoly(overlay, [pts], color)
|
| 614 |
+
cv2.addWeighted(overlay, 0.25, disp, 0.75, 0, disp)
|
| 615 |
+
cv2.polylines(disp, [pts], True, color, 2)
|
| 616 |
+
x, y = pts[0, 0]
|
| 617 |
+
cv2.putText(disp, str(cls), (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
|
| 618 |
+
return cv2.cvtColor(disp, cv2.COLOR_BGR2RGB)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
review_df = manifest_df if REVIEW_SOURCE == "all" else manifest_df[manifest_df["source"] == REVIEW_SOURCE]
|
| 622 |
+
review_df = review_df.iloc[max(0, REVIEW_OFFSET): max(0, REVIEW_OFFSET) + max(1, REVIEW_COUNT)]
|
| 623 |
+
|
| 624 |
+
if len(review_df):
|
| 625 |
+
ncols = 3
|
| 626 |
+
nrows = int(np.ceil(len(review_df) / ncols))
|
| 627 |
+
fig, axes = plt.subplots(nrows, ncols, figsize=(18, 5 * nrows))
|
| 628 |
+
axes = np.array(axes).reshape(-1)
|
| 629 |
+
for ax, (_, row) in zip(axes, review_df.iterrows()):
|
| 630 |
+
source = row["source"]
|
| 631 |
+
stem = row["stem"]
|
| 632 |
+
img_path = Path(row["image_path"])
|
| 633 |
+
if source == "old_gas":
|
| 634 |
+
lines = valid_seg_lines(base / "labels/train" / f"{stem}.txt", {0})
|
| 635 |
+
elif source == "gas_extra":
|
| 636 |
+
lines = valid_seg_lines(GAS_EXTRA_LABEL_DIR / f"{stem}.txt", {0})
|
| 637 |
+
else:
|
| 638 |
+
lines = (
|
| 639 |
+
valid_seg_lines(VALVE_GAS_LABEL_DIR / f"{stem}.txt", {0}) +
|
| 640 |
+
valid_seg_lines(VALVE_LABEL_DIR / f"{stem}.txt", {1})
|
| 641 |
+
)
|
| 642 |
+
ax.imshow(draw_lines_overlay(img_path, lines))
|
| 643 |
+
ax.set_title(f"{row['source_key']}\\n{row['status']}", fontsize=9)
|
| 644 |
+
ax.axis("off")
|
| 645 |
+
for ax in axes[len(review_df):]:
|
| 646 |
+
ax.axis("off")
|
| 647 |
+
plt.tight_layout()
|
| 648 |
+
plt.show()
|
| 649 |
+
else:
|
| 650 |
+
print("No samples selected for review.")
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
if DELETE_EXCLUDED_FROM_HF:
|
| 654 |
+
if CONFIRM_HF_DELETE != "DELETE":
|
| 655 |
+
print("HF delete skipped: set CONFIRM_HF_DELETE to DELETE to enable deletion.")
|
| 656 |
+
else:
|
| 657 |
+
from huggingface_hub import CommitOperationDelete
|
| 658 |
+
|
| 659 |
+
remote_files = set(api.list_repo_files(DATASET_REPO, repo_type="dataset"))
|
| 660 |
+
delete_ops = []
|
| 661 |
+
for key in EXCLUDED_SAMPLE_KEYS:
|
| 662 |
+
if "/" not in key:
|
| 663 |
+
continue
|
| 664 |
+
source, stem = key.split("/", 1)
|
| 665 |
+
candidates: list[str] = []
|
| 666 |
+
if source == "valve":
|
| 667 |
+
candidates += [f for f in remote_files if f.startswith(f"{RAW_VALVE_PREFIX}/{stem}.")]
|
| 668 |
+
candidates += [
|
| 669 |
+
f"{GENERATED_LABELS_REPO_DIR}/valve/{stem}.txt",
|
| 670 |
+
f"{GENERATED_LABELS_REPO_DIR}/valve_gas/{stem}.txt",
|
| 671 |
+
]
|
| 672 |
+
elif source == "gas_extra":
|
| 673 |
+
candidates += [f for f in remote_files if f.startswith(f"{RAW_GAS_EXTRA_PREFIX}/{stem}.")]
|
| 674 |
+
candidates += [f"{GENERATED_LABELS_REPO_DIR}/gas_extra/{stem}.txt"]
|
| 675 |
+
else:
|
| 676 |
+
print(f"Skipping HF delete for {key}; old_gas is the original dataset.")
|
| 677 |
+
for path in candidates:
|
| 678 |
+
if path in remote_files:
|
| 679 |
+
delete_ops.append(CommitOperationDelete(path_in_repo=path))
|
| 680 |
+
if delete_ops:
|
| 681 |
+
api.create_commit(
|
| 682 |
+
repo_id=DATASET_REPO,
|
| 683 |
+
repo_type="dataset",
|
| 684 |
+
token=HF_TOKEN,
|
| 685 |
+
operations=delete_ops,
|
| 686 |
+
commit_message="delete_excluded_review_samples",
|
| 687 |
+
)
|
| 688 |
+
print(f"Deleted {len(delete_ops)} files from HF.")
|
| 689 |
+
else:
|
| 690 |
+
print("No HF files matched the excluded sample keys.")
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
# %% [markdown]
|
| 694 |
+
# ---
|
| 695 |
+
# ## Step 10 - Build the two-class training dataset
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
# %%
|
| 699 |
+
# @title Step 10 - Build the two-class training dataset
|
| 700 |
|
| 701 |
COMBINED_DATASET = Path("/content/gas_valve_dataset")
|
| 702 |
VAL_RATIO = 0.20 # @param {type:"number"}
|
|
|
|
| 727 |
"lines": lines,
|
| 728 |
"group": "gas",
|
| 729 |
"source": "old_gas",
|
| 730 |
+
"source_stem": lbl_path.stem,
|
| 731 |
+
"source_key": f"old_gas/{lbl_path.stem}",
|
| 732 |
})
|
| 733 |
|
| 734 |
for img_path in list_images(RAW_GAS_EXTRA_DIR):
|
|
|
|
| 740 |
"lines": lines,
|
| 741 |
"group": "gas",
|
| 742 |
"source": "gas_extra",
|
| 743 |
+
"source_stem": img_path.stem,
|
| 744 |
+
"source_key": f"gas_extra/{img_path.stem}",
|
| 745 |
})
|
| 746 |
|
| 747 |
for img_path in list_images(RAW_VALVE_DIR):
|
|
|
|
| 754 |
"lines": gas_lines + valve_lines,
|
| 755 |
"group": "valve",
|
| 756 |
"source": "valve",
|
| 757 |
+
"source_stem": img_path.stem,
|
| 758 |
+
"source_key": f"valve/{img_path.stem}",
|
| 759 |
})
|
| 760 |
|
| 761 |
+
excluded_keys = globals().get("EXCLUDED_SAMPLE_KEYS", set())
|
| 762 |
+
if excluded_keys:
|
| 763 |
+
before_filter = len(samples)
|
| 764 |
+
samples = [
|
| 765 |
+
s for s in samples
|
| 766 |
+
if s["source_key"] not in excluded_keys and s["source_stem"] not in excluded_keys
|
| 767 |
+
]
|
| 768 |
+
print(f"Excluded from training: {before_filter - len(samples)} samples")
|
| 769 |
+
|
| 770 |
print(f"Collected labeled samples: {len(samples)}")
|
| 771 |
print(f" gas samples: {sum(1 for s in samples if s['group'] == 'gas')}")
|
| 772 |
print(f" valve samples: {sum(1 for s in samples if s['group'] == 'valve')}")
|
|
|
|
| 833 |
|
| 834 |
# %% [markdown]
|
| 835 |
# ---
|
| 836 |
+
# ## Step 11 - Visual sanity check
|
| 837 |
|
| 838 |
|
| 839 |
# %%
|
| 840 |
+
# @title Step 11 - Visual sanity check
|
| 841 |
|
| 842 |
def draw_label_overlay(img_path: Path, label_path: Path) -> np.ndarray:
|
| 843 |
img = read_image(img_path)
|
|
|
|
| 889 |
|
| 890 |
# %% [markdown]
|
| 891 |
# ---
|
| 892 |
+
# ## Step 12 - Train YOLO-seg
|
| 893 |
|
| 894 |
|
| 895 |
# %%
|
| 896 |
+
# @title Step 12 - Train YOLO-seg
|
| 897 |
|
| 898 |
from ultralytics import YOLO
|
| 899 |
|
|
|
|
| 950 |
|
| 951 |
# %% [markdown]
|
| 952 |
# ---
|
| 953 |
+
# ## Step 13 - Review results
|
| 954 |
|
| 955 |
|
| 956 |
# %%
|
| 957 |
+
# @title Step 13 - Review results
|
| 958 |
|
| 959 |
import pandas as pd
|
| 960 |
import matplotlib.image as mpimg
|
|
|
|
| 981 |
|
| 982 |
# %% [markdown]
|
| 983 |
# ---
|
| 984 |
+
# ## Step 14 - Upload training results
|
| 985 |
|
| 986 |
|
| 987 |
# %%
|
| 988 |
+
# @title Step 14 - Upload training results
|
| 989 |
|
| 990 |
UPLOAD_TRAINING_RESULTS = True # @param {type:"boolean"}
|
| 991 |
UPLOAD_REPO = DATASET_REPO # @param {type:"string"}
|