File size: 15,169 Bytes
5028850 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | #!/usr/bin/env python3
"""
prepare_data.py โ ๅฐไธ่ฝฝ็ๆฐๆฎ้็ปไธไธบ JSONL ๆ ผๅผ
====================================================
่ฏปๅ PlantVillage / PlantDoc / IP102 ็็ฎๅฝ็ปๆ, ็ๆ:
{"image_path": "...", "label_en": "...", "label_cn": "...", "crop": "...", "source": "..."}
็จๆณ:
python prepare_data.py --input-dir data/raw --output-file data/processed/unified_dataset.jsonl
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from collections import Counter, defaultdict
from pathlib import Path
# ---------------------------------------------------------------------------
# ่ฑๆ โ ไธญๆ ๆ ็ญพๆ ๅฐ (่ฆ็ PlantVillage ๅ
จ้จ 38 ็ฑป + PlantDoc ๅธธ่ง็ฑป)
# ---------------------------------------------------------------------------
LABEL_CN_MAP: dict[str, str] = {
# โโ Tomato (็ช่) โโ
"Tomato___Late_blight": "็ช่ๆ็ซ็
",
"Tomato___Early_blight": "็ช่ๆฉ็ซ็
",
"Tomato___Bacterial_spot": "็ช่็ป่ๆงๆ็น็
",
"Tomato___Leaf_Mold": "็ช่ๅถ้็
",
"Tomato___Septoria_leaf_spot": "็ช่ๅฃณ้ๅญขๅถๆ็
",
"Tomato___Spider_mites Two-spotted_spider_mite": "็ช่ไบๆๅถ่จ",
"Tomato___Target_Spot": "็ช่้ถๆ็
",
"Tomato___Tomato_Yellow_Leaf_Curl_Virus": "็ช่้ปๅๆฒๅถ็
ๆฏ็
",
"Tomato___Tomato_mosaic_virus": "็ช่่ฑๅถ็
ๆฏ็
",
"Tomato___healthy": "็ช่ๅฅๅบท",
# โโ Apple (่นๆ) โโ
"Apple___Apple_scab": "่นๆ้ปๆ็
",
"Apple___Black_rot": "่นๆ้ป่
็
",
"Apple___Cedar_apple_rust": "่นๆ้ชๆพ้็
",
"Apple___healthy": "่นๆๅฅๅบท",
# โโ Grape (่ก่) โโ
"Grape___Black_rot": "่ก่้ป่
็
",
"Grape___Esca_(Black_Measles)": "่ก่้ป้บป็น็
",
"Grape___Leaf_blight_(Isariopsis_Leaf_Spot)": "่ก่ๅถๆฏ็
",
"Grape___healthy": "่ก่ๅฅๅบท",
# โโ Corn / Maize (็็ฑณ) โโ
"Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot": "็็ฑณ็ฐๆ็
",
"Corn_(maize)___Common_rust_": "็็ฑณๆฎ้้็
",
"Corn_(maize)___Northern_Leaf_Blight": "็็ฑณๅๆนๅถๆฏ็
",
"Corn_(maize)___healthy": "็็ฑณๅฅๅบท",
# โโ Potato (้ฉฌ้่ฏ) โโ
"Potato___Early_blight": "้ฉฌ้่ฏๆฉ็ซ็
",
"Potato___Late_blight": "้ฉฌ้่ฏๆ็ซ็
",
"Potato___healthy": "้ฉฌ้่ฏๅฅๅบท",
# โโ Strawberry (่่) โโ
"Strawberry___Leaf_scorch": "่่ๅถ็ฆ็
",
"Strawberry___healthy": "่่ๅฅๅบท",
# โโ Cherry (ๆจฑๆก) โโ
"Cherry_(including_sour)___Powdery_mildew": "ๆจฑๆก็ฝ็ฒ็
",
"Cherry_(including_sour)___healthy": "ๆจฑๆกๅฅๅบท",
# โโ Peach (ๆก) โโ
"Peach___Bacterial_spot": "ๆก็ป่ๆงๆ็น็
",
"Peach___healthy": "ๆกๅฅๅบท",
# โโ Pepper (่พฃๆค) โโ
"Pepper,_bell___Bacterial_spot": "่พฃๆค็ป่ๆงๆ็น็
",
"Pepper,_bell___healthy": "่พฃๆคๅฅๅบท",
# โโ Squash (ๅ็) โโ
"Squash___Powdery_mildew": "ๅ็็ฝ็ฒ็
",
# โโ Soybean (ๅคง่ฑ) โโ
"Soybean___healthy": "ๅคง่ฑๅฅๅบท",
# โโ Raspberry (่ฆ็ๅญ) โโ
"Raspberry___healthy": "่ฆ็ๅญๅฅๅบท",
# โโ Blueberry (่่) โโ
"Blueberry___healthy": "่่ๅฅๅบท",
# โโ Orange (ๆๆฉ) โโ
"Orange___Haunglongbing_(Citrus_greening)": "ๆๆฉ้ป้พ็
",
# โโ PlantDoc ๅธธ่ง่กฅๅ
โโ
"Tomato leaf late blight": "็ช่ๅถ็ๆ็ซ็
",
"Tomato leaf early blight": "็ช่ๅถ็ๆฉ็ซ็
",
"Tomato leaf bacterial spot": "็ช่ๅถ็็ป่ๆงๆ็น็
",
"Tomato leaf yellow virus": "็ช่ๅถ็้ปๅ็
ๆฏ",
"Tomato leaf mosaic virus": "็ช่ๅถ็่ฑๅถ็
ๆฏ",
"Tomato leaf": "็ช่ๅถ็ๅฅๅบท",
"Apple leaf": "่นๆๅถ็ๅฅๅบท",
"Apple rust leaf": "่นๆ้็
ๅถ็",
"Apple Scab Leaf": "่นๆ้ปๆ็
ๅถ็",
"Corn leaf blight": "็็ฑณๅถๆฏ็
",
"Corn rust leaf": "็็ฑณ้็
ๅถ็",
"Corn Gray leaf spot": "็็ฑณ็ฐๆ็
",
"Potato leaf early blight": "้ฉฌ้่ฏๆฉ็ซ็
ๅถ็",
"Potato leaf late blight": "้ฉฌ้่ฏๆ็ซ็
ๅถ็",
"Grape leaf": "่ก่ๅถ็ๅฅๅบท",
"Grape leaf black rot": "่ก่ๅถ็้ป่
็
",
"Cherry leaf": "ๆจฑๆกๅถ็ๅฅๅบท",
"Peach leaf": "ๆกๅถ็ๅฅๅบท",
"Raspberry leaf": "่ฆ็ๅญๅถ็ๅฅๅบท",
"Strawberry leaf": "่่ๅถ็ๅฅๅบท",
"Soybean leaf": "ๅคง่ฑๅถ็ๅฅๅบท",
"Squash Powdery mildew leaf": "ๅ็็ฝ็ฒ็
ๅถ็",
"Blueberry leaf": "่่ๅถ็ๅฅๅบท",
"Bell pepper leaf": "่พฃๆคๅถ็ๅฅๅบท",
"Bell pepper leaf spot": "่พฃๆคๅถ็ๆ็น็
",
}
# ไปๆ ็ญพๆจๆญไฝ็ฉๅ (ไธญๆ)
CROP_CN_MAP: dict[str, str] = {
"tomato": "็ช่",
"apple": "่นๆ",
"grape": "่ก่",
"corn": "็็ฑณ",
"maize": "็็ฑณ",
"potato": "้ฉฌ้่ฏ",
"strawberry": "่่",
"cherry": "ๆจฑๆก",
"peach": "ๆก",
"pepper": "่พฃๆค",
"bell pepper": "่พฃๆค",
"squash": "ๅ็",
"soybean": "ๅคง่ฑ",
"raspberry": "่ฆ็ๅญ",
"blueberry": "่่",
"orange": "ๆๆฉ",
"citrus": "ๆๆฉ",
"rice": "ๆฐด็จป",
"wheat": "ๅฐ้บฆ",
"cotton": "ๆฃ่ฑ",
}
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
def _infer_crop(label: str) -> str:
"""ไป่ฑๆๆ ็ญพๆจๆญไฝ็ฉไธญๆๅ."""
lower = label.lower().replace("_", " ").replace("(", "").replace(")", "")
for key, cn in CROP_CN_MAP.items():
if key in lower:
return cn
return "ๆช็ฅไฝ็ฉ"
def _translate_label(label: str) -> str:
"""่ฑๆๆ ็ญพ โ ไธญๆๆ ็ญพ, ๆพไธๅฐๅ่ฟๅๅๆ."""
if label in LABEL_CN_MAP:
return LABEL_CN_MAP[label]
# Try with spaces replacing underscores
label_spaces = label.replace("_", " ").strip()
if label_spaces in LABEL_CN_MAP:
return LABEL_CN_MAP[label_spaces]
return label
# ---------------------------------------------------------------------------
# ๅค็ๅๆฐๆฎ้
# ---------------------------------------------------------------------------
def process_plantvillage(input_dir: Path) -> list[dict]:
"""Process PlantVillage: class directories with images inside."""
root = input_dir / "PlantVillage"
records = []
if not root.exists():
print(" [PlantVillage] ็ฎๅฝไธๅญๅจ, ่ทณ่ฟ")
return records
class_dirs = sorted([d for d in root.iterdir() if d.is_dir()])
for class_dir in class_dirs:
label_en = class_dir.name
label_cn = _translate_label(label_en)
crop = _infer_crop(label_en)
for img in sorted(class_dir.iterdir()):
if img.suffix.lower() in IMAGE_EXTS:
records.append({
"image_path": str(img),
"label_en": label_en,
"label_cn": label_cn,
"crop": crop,
"source": "PlantVillage",
})
print(f" [PlantVillage] {len(records)} ๆก่ฎฐๅฝ, {len(class_dirs)} ไธช็ฑปๅซ")
return records
def process_plantdoc(input_dir: Path) -> list[dict]:
"""Process PlantDoc: look for train/test directories with class subdirectories."""
root = input_dir / "PlantDoc"
records = []
if not root.exists():
print(" [PlantDoc] ็ฎๅฝไธๅญๅจ, ่ทณ่ฟ")
return records
# PlantDoc-Dataset typically has train/ and test/ inside
# Search recursively for class directories containing images
search_roots = []
for candidate in ["train", "test", "Train", "Test",
"PlantDoc-Dataset/train", "PlantDoc-Dataset/test"]:
p = root / candidate
if p.exists():
search_roots.append(p)
if not search_roots:
# Fallback: use root itself
search_roots = [root]
seen_paths = set()
for sr in search_roots:
for class_dir in sorted(sr.iterdir()):
if not class_dir.is_dir():
continue
label_en = class_dir.name
label_cn = _translate_label(label_en)
crop = _infer_crop(label_en)
for img in sorted(class_dir.iterdir()):
if img.suffix.lower() in IMAGE_EXTS and str(img) not in seen_paths:
seen_paths.add(str(img))
records.append({
"image_path": str(img),
"label_en": label_en,
"label_cn": label_cn,
"crop": crop,
"source": "PlantDoc",
})
print(f" [PlantDoc] {len(records)} ๆก่ฎฐๅฝ")
return records
def process_ip102(input_dir: Path) -> list[dict]:
"""Process IP102: numbered class directories (0โ101)."""
root = input_dir / "IP102"
records = []
if not root.exists():
print(" [IP102] ็ฎๅฝไธๅญๅจ, ่ทณ่ฟ")
return records
# Try to load class name mapping
classes_file = root / "classes.txt"
class_names: dict[str, str] = {}
if classes_file.exists():
for line in classes_file.read_text(encoding="utf-8").splitlines():
parts = line.strip().split(maxsplit=1)
if len(parts) == 2:
class_names[parts[0]] = parts[1]
# Scan train/val/test splits
found_any = False
for split in ["train", "val", "test"]:
split_dir = root / split
if not split_dir.exists():
continue
found_any = True
for class_dir in sorted(split_dir.iterdir()):
if not class_dir.is_dir():
continue
class_id = class_dir.name
label_en = class_names.get(class_id, f"pest_class_{class_id}")
label_cn = _translate_label(label_en)
crop = _infer_crop(label_en)
for img in sorted(class_dir.iterdir()):
if img.suffix.lower() in IMAGE_EXTS:
records.append({
"image_path": str(img),
"label_en": label_en,
"label_cn": label_cn,
"crop": crop,
"source": "IP102",
})
# Fallback: flat numbered directories at root level
if not found_any:
for class_dir in sorted(root.iterdir()):
if not class_dir.is_dir() or not class_dir.name.isdigit():
continue
class_id = class_dir.name
label_en = class_names.get(class_id, f"pest_class_{class_id}")
label_cn = _translate_label(label_en)
crop = _infer_crop(label_en)
for img in sorted(class_dir.iterdir()):
if img.suffix.lower() in IMAGE_EXTS:
records.append({
"image_path": str(img),
"label_en": label_en,
"label_cn": label_cn,
"crop": crop,
"source": "IP102",
})
print(f" [IP102] {len(records)} ๆก่ฎฐๅฝ")
return records
# ---------------------------------------------------------------------------
# ็ป่ฎก่พๅบ
# ---------------------------------------------------------------------------
def print_statistics(records: list[dict]) -> None:
"""Print detailed statistics about the unified dataset."""
if not records:
print("\nโ ๆฒกๆไปปไฝ่ฎฐๅฝ, ่ฏทๅ
่ฟ่ก download_datasets.py")
return
source_counts = Counter(r["source"] for r in records)
crop_counts = Counter(r["crop"] for r in records)
label_counts = Counter(r["label_en"] for r in records)
print("\n" + "โ" * 60)
print("ๆฐๆฎ็ป่ฎก")
print("โ" * 60)
print(f"\n ๆปๅพ็ๆฐ: {len(records)}")
print("\n โโ ๆๆฐๆฎ้ โโ")
for src, cnt in source_counts.most_common():
print(f" {src:<20} {cnt:>8}")
print("\n โโ ๆไฝ็ฉ (ๅ 15) โโ")
for crop, cnt in crop_counts.most_common(15):
print(f" {crop:<20} {cnt:>8}")
if len(crop_counts) > 15:
print(f" ... ๅ
ฑ {len(crop_counts)} ็งไฝ็ฉ")
print("\n โโ ๆ็ฑปๅซ (ๅ 20) โโ")
for label, cnt in label_counts.most_common(20):
print(f" {label:<50} {cnt:>6}")
if len(label_counts) > 20:
print(f" ... ๅ
ฑ {len(label_counts)} ไธช็ฑปๅซ")
print()
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(
description="ๅฐๅไธๅพๅๆฐๆฎ้็ปไธไธบ JSONL ๆ ผๅผ",
)
parser.add_argument(
"--input-dir",
type=str,
default="data/raw",
help="ๅๅงๆฐๆฎ้ๆ น็ฎๅฝ (default: data/raw)",
)
parser.add_argument(
"--output-file",
type=str,
default="data/processed/unified_dataset.jsonl",
help="่พๅบ JSONL ๆไปถ่ทฏๅพ (default: data/processed/unified_dataset.jsonl)",
)
args = parser.parse_args()
input_dir = Path(args.input_dir).resolve()
output_file = Path(args.output_file).resolve()
if not input_dir.exists():
print(f"้่ฏฏ: ่พๅ
ฅ็ฎๅฝไธๅญๅจ: {input_dir}")
print("่ฏทๅ
่ฟ่ก download_datasets.py")
sys.exit(1)
print(f"่พๅ
ฅ็ฎๅฝ: {input_dir}")
print(f"่พๅบๆไปถ: {output_file}\n")
# Process each dataset
all_records: list[dict] = []
print("โ" * 60)
print("ๅค็ๆฐๆฎ้")
print("โ" * 60)
all_records.extend(process_plantvillage(input_dir))
all_records.extend(process_plantdoc(input_dir))
all_records.extend(process_ip102(input_dir))
# Write JSONL
output_file.parent.mkdir(parents=True, exist_ok=True)
with open(output_file, "w", encoding="utf-8") as f:
for record in all_records:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
print(f"\nๅทฒๅๅ
ฅ {len(all_records)} ๆก่ฎฐๅฝๅฐ: {output_file}")
# Statistics
print_statistics(all_records)
if __name__ == "__main__":
main()
|