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()