File size: 5,112 Bytes
151ec26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from pathlib import Path
import csv
import random
from collections import defaultdict

# ============================================================
# PATHS
# ============================================================

BASE_DIR = Path(__file__).resolve().parents[1]

OCR_ROOT = (
    BASE_DIR
    / "datasets"
    / "ocr"
    / "mobile_packages"
)

OUTPUT_DIR = (
    BASE_DIR
    / "datasets"
    / "ocr"
    / "prepared"
)

OUTPUT_DIR.mkdir(
    parents=True,
    exist_ok=True
)

# ============================================================
# IMAGE EXTENSIONS
# ============================================================

IMAGE_EXTENSIONS = {
    ".jpg",
    ".jpeg",
    ".png",
    ".bmp",
    ".webp"
}

# ============================================================
# FIND IMAGES BY MEDICINE
# ============================================================

print("=" * 70)
print("SANJEEVANI OCR DATASET PREPARATION")
print("=" * 70)

print("\nSearching:")
print(OCR_ROOT)

medicine_images = defaultdict(list)

for image_path in OCR_ROOT.rglob("*"):

    if not image_path.is_file():
        continue

    if image_path.suffix.lower() not in IMAGE_EXTENSIONS:
        continue

    # Immediate parent folder = medicine/package name
    medicine_name = image_path.parent.name.strip()

    if not medicine_name:
        continue

    medicine_images[medicine_name].append(image_path)

print("\nUnique medicine/package classes:")
print(len(medicine_images))

print("\nTotal images:")

total_images = sum(
    len(images)
    for images in medicine_images.values()
)

print(total_images)

# ============================================================
# CHECK
# ============================================================

if total_images == 0:

    print("\nERROR: No images found.")
    print("Check the mobile_packages directory.")

    raise SystemExit

# ============================================================
# SHUFFLE MEDICINE CLASSES
# ============================================================

random.seed(42)

medicine_names = list(
    medicine_images.keys()
)

random.shuffle(medicine_names)

# ============================================================
# SPLIT BY MEDICINE
# ============================================================

total_medicines = len(medicine_names)

train_medicine_end = int(
    total_medicines * 0.80
)

validation_medicine_end = int(
    total_medicines * 0.90
)

train_medicines = medicine_names[:train_medicine_end
]

validation_medicines = medicine_names[
    train_medicine_end:validation_medicine_end
]

test_medicines = medicine_names[
    validation_medicine_end:
]

# ============================================================
# CREATE RECORDS
# ============================================================


def create_records(medicine_list):

    records = []

    for medicine_name in medicine_list:

        for image_path in medicine_images[
            medicine_name
        ]:

            records.append({
                "image": str(
                    image_path.relative_to(BASE_DIR)
                ),
                "text": medicine_name
            })

    return records


train_records = create_records(
    train_medicines
)

validation_records = create_records(
    validation_medicines
)

test_records = create_records(
    test_medicines
)

# ============================================================
# SHUFFLE IMAGES WITHIN EACH SPLIT
# ============================================================

random.shuffle(train_records)
random.shuffle(validation_records)
random.shuffle(test_records)

# ============================================================
# SAVE CSV
# ============================================================


def save_csv(records, filename):

    output_path = OUTPUT_DIR / filename

    with open(
        output_path,
        "w",
        newline="",
        encoding="utf-8"
    ) as f:

        writer = csv.DictWriter(
            f,
            fieldnames=[
                "image",
                "text"
            ]
        )

        writer.writeheader()

        writer.writerows(records)

    print(
        f"Saved {filename}: "
        f"{len(records)} images"
    )


save_csv(
    train_records,
    "train.csv"
)

save_csv(
    validation_records,
    "validation.csv"
)

save_csv(
    test_records,
    "test.csv"
)

# ============================================================
# SUMMARY
# ============================================================

print("\n" + "=" * 70)
print("SPLIT SUMMARY")
print("=" * 70)

print(
    f"Training medicines:   {len(train_medicines)}"
)

print(
    f"Validation medicines: {len(validation_medicines)}"
)

print(
    f"Test medicines:       {len(test_medicines)}"
)

print()

print(
    f"Training images:       {len(train_records)}"
)

print(
    f"Validation images:     {len(validation_records)}"
)

print(
    f"Test images:           {len(test_records)}"
)

print("\nIMPORTANT:")
print(
    "The same medicine/package is NOT present "
    "across train, validation and test."
)

print("=" * 70)
print("DONE")
print("=" * 70)