File size: 29,137 Bytes
e6adc05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06fc7a9
e6adc05
 
 
 
 
 
 
06fc7a9
 
e6adc05
 
 
 
 
 
 
06fc7a9
e6adc05
 
 
 
 
 
06fc7a9
 
e6adc05
06fc7a9
 
 
 
e6adc05
 
 
 
 
 
 
 
 
 
 
06fc7a9
 
 
 
 
 
 
e6adc05
 
 
06fc7a9
e6adc05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06fc7a9
 
 
 
 
 
e6adc05
06fc7a9
 
 
e6adc05
06fc7a9
 
 
e6adc05
06fc7a9
 
e6adc05
06fc7a9
 
 
e6adc05
 
 
 
06fc7a9
 
 
 
 
e6adc05
 
 
 
06fc7a9
e6adc05
 
 
 
 
 
06fc7a9
e6adc05
06fc7a9
e6adc05
 
 
06fc7a9
e6adc05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06fc7a9
 
 
 
 
 
 
 
 
 
 
 
e6adc05
 
 
 
 
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import requests\n",
    "import zipfile\n",
    "import io\n",
    "import os\n",
    "import shutil\n",
    "from PIL import Image as PILImage, ImageFile\n",
    "from tqdm import tqdm\n",
    "from datasets import Dataset, Features, Value, Image, load_dataset\n",
    "from huggingface_hub import login, HfApi\n",
    "import cv2\n",
    "import concurrent.futures\n",
    "import csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Allow loading of truncated images\n",
    "ImageFile.LOAD_TRUNCATED_IMAGES = True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def read_excel_and_get_urls(excel_file):\n",
    "    \"\"\"\n",
    "    Read Excel file and extract URLs, tilenames, and zones\n",
    "    \n",
    "    Args:\n",
    "        excel_file: Path to Excel file\n",
    "    \n",
    "    Returns:\n",
    "        DataFrame with TILENAME, ZONE, URL columns\n",
    "    \"\"\"\n",
    "    print(f\"Reading Excel file: {excel_file}\")\n",
    "    df = pd.read_excel(excel_file)\n",
    "    \n",
    "    # Ensure expected columns exist\n",
    "    required_columns = ['TILENAME', 'ZONE', 'URL']\n",
    "    for col in required_columns:\n",
    "        if col not in df.columns:\n",
    "            raise ValueError(f\"Required column '{col}' not found in Excel file.\")\n",
    "    \n",
    "    print(f\"Found {len(df)} entries in Excel file\")\n",
    "    return df\n",
    "\n",
    "def extract_filename_from_url(url):\n",
    "    \"\"\"\n",
    "    Extract the base filename from the URL\n",
    "    \n",
    "    Args:\n",
    "        url: URL of the zip file\n",
    "    \n",
    "    Returns:\n",
    "        Base filename without extension\n",
    "    \"\"\"\n",
    "    # Extract filename from URL\n",
    "    # This may need adjustment based on the URL format\n",
    "    filename = url.split('/')[-1]\n",
    "    # Remove .zip extension if present\n",
    "    if filename.lower().endswith('.zip'):\n",
    "        filename = os.path.splitext(filename)[0]\n",
    "    return filename\n",
    "\n",
    "\n",
    "def download_and_extract_jp2(tilename, zone, url, jp2_dir):\n",
    "    \"\"\"\n",
    "    Download a zip file from the given URL and extract only the JP2 image file\n",
    "    \n",
    "    Args:\n",
    "        tilename: Name of the tile\n",
    "        zone: Zone identifier\n",
    "        url: URL to the zip file\n",
    "        jp2_dir: Directory to save JP2 images\n",
    "    \n",
    "    Returns:\n",
    "        Dictionary with image information (jp2_path, tilename, zone)\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # Download the zip file\n",
    "        response = requests.get(url, stream=True)\n",
    "        \n",
    "        if response.status_code != 200:\n",
    "            print(f\"Failed to download {tilename}: {response.status_code}\")\n",
    "            return None\n",
    "        \n",
    "        # Ensure JP2 directory exists\n",
    "        os.makedirs(jp2_dir, exist_ok=True)\n",
    "        \n",
    "        # Extract image files\n",
    "        with zipfile.ZipFile(io.BytesIO(response.content)) as zip_ref:\n",
    "            # Get all files in the zip\n",
    "            all_files = zip_ref.namelist()\n",
    "            \n",
    "            # Filter for JP2 image files\n",
    "            jp2_files = [f for f in all_files if f.lower().endswith('.jp2')]\n",
    "            \n",
    "            if not jp2_files:\n",
    "                print(f\"No JP2 files found in {tilename} zip\")\n",
    "                return None\n",
    "            \n",
    "            # Get the first JP2 file (assuming one image per zip)\n",
    "            jp2_file = jp2_files[0]\n",
    "            jp2_filename = os.path.basename(jp2_file)\n",
    "            jp2_path = os.path.join(jp2_dir, jp2_filename)\n",
    "            \n",
    "            # Extract JP2 file\n",
    "            with zip_ref.open(jp2_file) as source, open(jp2_path, 'wb') as target:\n",
    "                shutil.copyfileobj(source, target)\n",
    "            \n",
    "            return {\n",
    "                \"jp2_path\": jp2_path,\n",
    "                \"tilename\": tilename,\n",
    "                \"zone\": zone\n",
    "            }\n",
    "            \n",
    "    except Exception as e:\n",
    "        print(f\"Error processing {tilename}: {e}\")\n",
    "        return None\n",
    "    \n",
    "def process_file(jp2_path, jpeg_path):\n",
    "    try:\n",
    "        # Read JP2 image\n",
    "        img = cv2.imread(jp2_path)\n",
    "        \n",
    "        # Check if the image is read properly\n",
    "        if img is None:\n",
    "            print(f\"Error reading {jp2_path}, skipping.\")\n",
    "            return\n",
    "            \n",
    "        # Save as JPEG\n",
    "        cv2.imwrite(jpeg_path, img, [int(cv2.IMWRITE_JPEG_QUALITY), 95])\n",
    "    except Exception as e:\n",
    "        print(f\"Error converting {jp2_path}: {e}\")\n",
    "\n",
    "def convert_jp2_to_jpeg(jp2_dir, jpeg_dir, max_workers=4):\n",
    "    \"\"\"\n",
    "    Convert all JP2 files in a directory to JPEG using OpenCV with multithreading.\n",
    "    \n",
    "    Args:\n",
    "        jp2_dir: Directory containing JP2 files\n",
    "        jpeg_dir: Directory to save converted JPEG images\n",
    "        max_workers: Number of threads to use for processing\n",
    "    \"\"\"\n",
    "    # Ensure output directory exists\n",
    "    os.makedirs(jpeg_dir, exist_ok=True)\n",
    "    \n",
    "    # Get all JP2 files\n",
    "    input_files = [f for f in os.listdir(jp2_dir) if f.lower().endswith('.jp2') and f != '.DS_Store']\n",
    "    \n",
    "    print(f\"Found {len(input_files)} JP2 files to convert\")\n",
    "    \n",
    "    # Prepare task list\n",
    "    tasks = []\n",
    "    for f in input_files:\n",
    "        jp2_path = os.path.join(jp2_dir, f)\n",
    "        jpeg_filename = os.path.splitext(f)[0] + \".jpg\"\n",
    "        jpeg_path = os.path.join(jpeg_dir, jpeg_filename)\n",
    "        \n",
    "        # Skip if already processed\n",
    "        if os.path.isfile(jpeg_path):\n",
    "            print(f\"Already processed: {f}\")\n",
    "            continue\n",
    "            \n",
    "        tasks.append((jp2_path, jpeg_path))\n",
    "    \n",
    "    # Process files in parallel\n",
    "    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:\n",
    "        list(tqdm(executor.map(lambda args: process_file(*args), tasks), total=len(tasks), desc=\"Converting JP2 to JPEG\"))\n",
    "\n",
    "def convert_jp2_to_jpeg(jp2_dir, jpeg_dir):\n",
    "    \"\"\"\n",
    "    Convert all JP2 files in a directory to JPEG using OpenCV.\n",
    "    \n",
    "    Args:\n",
    "        jp2_dir: Directory containing JP2 files\n",
    "        jpeg_dir: Directory to save converted JPEG images\n",
    "    \"\"\"\n",
    "    # Ensure output directory exists\n",
    "    os.makedirs(jpeg_dir, exist_ok=True)\n",
    "    \n",
    "    # Get all JP2 files\n",
    "    input_files = [f for f in os.listdir(jp2_dir) if f.lower().endswith('.jp2') and f != '.DS_Store']\n",
    "    \n",
    "    print(f\"Found {len(input_files)} JP2 files to convert\")\n",
    "    \n",
    "    # Process files\n",
    "    for f in tqdm(input_files, desc=\"Converting JP2 to JPEG\"):\n",
    "        try:\n",
    "            jp2_path = os.path.join(jp2_dir, f)\n",
    "            jpeg_filename = os.path.splitext(f)[0] + \".jpg\"\n",
    "            jpeg_path = os.path.join(jpeg_dir, jpeg_filename)\n",
    "            \n",
    "            # Skip if already processed\n",
    "            if os.path.isfile(jpeg_path):\n",
    "                print(f\"Already processed: {f}\")\n",
    "                continue\n",
    "                \n",
    "            # Read JP2 image\n",
    "            img = cv2.imread(jp2_path)\n",
    "            \n",
    "            # Check if the image is read properly\n",
    "            if img is None:\n",
    "                print(f\"Error reading {f}, skipping.\")\n",
    "                continue\n",
    "                \n",
    "            # Save as JPEG\n",
    "            cv2.imwrite(jpeg_path, img, [int(cv2.IMWRITE_JPEG_QUALITY), 95])\n",
    "        except Exception as e:\n",
    "            print(f\"Error converting {f}: {e}\")\n",
    "\n",
    "def convert_jp2_to_jpeg(jp2_dir, jpeg_dir):\n",
    "    \"\"\"\n",
    "    Convert all JP2 files in a directory to JPEG\n",
    "    \n",
    "    Args:\n",
    "        jp2_dir: Directory containing JP2 files\n",
    "        jpeg_dir: Directory to save converted JPEG images\n",
    "    \"\"\"\n",
    "    # Ensure directories exist\n",
    "    if not os.path.exists(jpeg_dir):\n",
    "        os.makedirs(jpeg_dir)\n",
    "    if not os.path.exists(jp2_dir):\n",
    "        os.makedirs(jp2_dir)\n",
    "    \n",
    "    # Get all JP2 files\n",
    "    input_files = os.listdir(jp2_dir)\n",
    "    input_files = [f for f in input_files if f.lower().endswith('.jp2') and f != '.DS_Store']\n",
    "    \n",
    "    print(f\"Found {len(input_files)} JP2 files to convert\")\n",
    "    \n",
    "    # Process files one by one\n",
    "    for f in tqdm(input_files, desc=\"Converting JP2 to JPEG\"):\n",
    "        try:\n",
    "            jp2_path = os.path.join(jp2_dir, f)\n",
    "            jpeg_filename = os.path.splitext(f)[0] + \".jpg\"\n",
    "            jpeg_path = os.path.join(jpeg_dir, jpeg_filename)\n",
    "            \n",
    "            # Skip if already processed\n",
    "            if os.path.isfile(jpeg_path):\n",
    "                print(f\"Already processed: {f}\")\n",
    "                continue\n",
    "                \n",
    "            # Open and convert the image\n",
    "            im = PILImage.open(jp2_path)\n",
    "            if im.mode != 'RGB':\n",
    "                im = im.convert('RGB')\n",
    "            \n",
    "            # Save as JPEG\n",
    "            im.save(jpeg_path, 'JPEG', quality=95)\n",
    "            im.close()\n",
    "        except Exception as e:\n",
    "            print(f\"Error converting {f}: {e}\")\n",
    "\n",
    "def recreate_image_info_list(excel_file, jpeg_dir):\n",
    "    \"\"\"\n",
    "    Recreate image_info_list by matching jpeg files with Excel entries\n",
    "    \n",
    "    Args:\n",
    "        excel_file: Path to Excel file\n",
    "        jpeg_dir: Directory containing JPEG files\n",
    "    \n",
    "    Returns:\n",
    "        List of dictionaries with image information\n",
    "    \"\"\"\n",
    "    # Read Excel file\n",
    "    df = read_excel_and_get_urls(excel_file)\n",
    "    \n",
    "    # Create mapping from filename to tilename and zone\n",
    "    filename_to_metadata = {}\n",
    "    \n",
    "    # Try different approaches to match filenames\n",
    "    for _, row in df.iterrows():\n",
    "        tilename = row['TILENAME']\n",
    "        zone = row['ZONE']\n",
    "        url = row['URL']\n",
    "        \n",
    "        # Extract filename from URL as a potential match criterion\n",
    "        extracted_filename = extract_filename_from_url(url)\n",
    "        filename_to_metadata[extracted_filename] = {'tilename': tilename, 'zone': zone}\n",
    "        \n",
    "        # Also map the tilename directly as another potential match\n",
    "        filename_to_metadata[tilename] = {'tilename': tilename, 'zone': zone}\n",
    "    \n",
    "    # Get all JPEG files\n",
    "    jpeg_files = [f for f in os.listdir(jpeg_dir) if f.lower().endswith('.jpg') or f.lower().endswith('.jpeg')]\n",
    "    print(f\"Found {len(jpeg_files)} JPEG files in the directory\")\n",
    "    \n",
    "    # Match JPEG files to metadata\n",
    "    image_info_list = []\n",
    "    unmatched_files = []\n",
    "    \n",
    "    for jpeg_file in tqdm(jpeg_files, desc=\"Matching JPEG files to metadata\"):\n",
    "        jpeg_path = os.path.join(jpeg_dir, jpeg_file)\n",
    "        base_name = os.path.splitext(jpeg_file)[0]\n",
    "        \n",
    "        # Try different matching strategies\n",
    "        metadata = None\n",
    "        \n",
    "        # Direct match with the extracted filename\n",
    "        if base_name in filename_to_metadata:\n",
    "            metadata = filename_to_metadata[base_name]\n",
    "        else:\n",
    "            # Try partial matches\n",
    "            matched_keys = [key for key in filename_to_metadata.keys() if key in base_name or base_name in key]\n",
    "            if matched_keys:\n",
    "                # Use the first match if multiple found\n",
    "                metadata = filename_to_metadata[matched_keys[0]]\n",
    "        \n",
    "        if metadata:\n",
    "            image_info_list.append({\n",
    "                \"path\": jpeg_path,\n",
    "                \"tilename\": metadata['tilename'],\n",
    "                \"zone\": metadata['zone']\n",
    "            })\n",
    "        else:\n",
    "            unmatched_files.append(jpeg_file)\n",
    "    \n",
    "    print(f\"Successfully matched {len(image_info_list)} JPEG files with metadata\")\n",
    "    \n",
    "    if unmatched_files:\n",
    "        print(f\"Warning: Could not match {len(unmatched_files)} files with metadata\")\n",
    "        if len(unmatched_files) < 10:\n",
    "            print(\"Unmatched files:\", unmatched_files)\n",
    "        else:\n",
    "            print(\"First 10 unmatched files:\", unmatched_files[:10])\n",
    "    \n",
    "    return image_info_list\n",
    "\n",
    "\n",
    "def organize_images_for_imagefolder(excel_file, jpeg_dir, output_dir, rename_instead_of_copy=True):\n",
    "    \"\"\"\n",
    "    Organize images and create metadata for ImageFolder format\n",
    "    \n",
    "    Args:\n",
    "        excel_file: Path to Excel file with metadata\n",
    "        jpeg_dir: Directory containing JPEG files\n",
    "        output_dir: Directory to save organized images and metadata\n",
    "        rename_instead_of_copy: If True, rename/move files instead of copying them\n",
    "    \n",
    "    Returns:\n",
    "        Path to the organized dataset directory\n",
    "    \"\"\"\n",
    "    print(f\"Reading Excel file: {excel_file}\")\n",
    "    df = pd.read_excel(excel_file)\n",
    "    \n",
    "    # Ensure required columns exist\n",
    "    required_columns = ['TILENAME', 'ZONE', 'URL']\n",
    "    for col in required_columns:\n",
    "        if col not in df.columns:\n",
    "            raise ValueError(f\"Required column '{col}' not found in Excel file.\")\n",
    "    \n",
    "    # Use the JPEG directory as the train directory if we're renaming\n",
    "    if rename_instead_of_copy:\n",
    "        # Create parent directory if it doesn't exist\n",
    "        os.makedirs(output_dir, exist_ok=True)\n",
    "        \n",
    "        # Just rename the jpeg_dir to be inside the output_dir\n",
    "        train_dir = os.path.join(output_dir, \"train\")\n",
    "        \n",
    "        # If the train directory already exists but is different from jpeg_dir, handle it\n",
    "        if os.path.exists(train_dir) and os.path.abspath(train_dir) != os.path.abspath(jpeg_dir):\n",
    "            response = input(f\"Train directory {train_dir} already exists. Do you want to replace it? (yes/no): \")\n",
    "            if response.lower() == 'yes':\n",
    "                shutil.rmtree(train_dir)\n",
    "            else:\n",
    "                print(\"Using existing train directory.\")\n",
    "                \n",
    "        # If train_dir doesn't exist, rename jpeg_dir to train_dir\n",
    "        if not os.path.exists(train_dir):\n",
    "            print(f\"Renaming directory {jpeg_dir} to {train_dir}\")\n",
    "            shutil.move(jpeg_dir, train_dir)\n",
    "        # If jpeg_dir is already the train_dir, do nothing\n",
    "        elif os.path.abspath(train_dir) == os.path.abspath(jpeg_dir):\n",
    "            print(f\"JPEG directory is already {train_dir}, no renaming needed\")\n",
    "    else:\n",
    "        # Create the output directory structure for copying\n",
    "        os.makedirs(output_dir, exist_ok=True)\n",
    "        train_dir = os.path.join(output_dir, \"train\")\n",
    "        os.makedirs(train_dir, exist_ok=True)\n",
    "    \n",
    "    # Get all JPEG files\n",
    "    jpeg_files = [f for f in os.listdir(train_dir) if f.lower().endswith('.jpg') or f.lower().endswith('.jpeg')]\n",
    "    print(f\"Found {len(jpeg_files)} JPEG files\")\n",
    "    \n",
    "    # Create a mapping of filename to metadata\n",
    "    filename_to_metadata = {}\n",
    "    for _, row in df.iterrows():\n",
    "        tilename = row['TILENAME']\n",
    "        zone = row['ZONE']\n",
    "        # Use both the full tilename and the base name for matching\n",
    "        filename_to_metadata[tilename] = {'tilename': tilename, 'zone': zone}\n",
    "        filename_to_metadata[os.path.basename(tilename)] = {'tilename': tilename, 'zone': zone}\n",
    "    \n",
    "    # Create metadata.csv file\n",
    "    metadata_path = os.path.join(train_dir, \"metadata.csv\")\n",
    "    with open(metadata_path, 'w', newline='') as csvfile:\n",
    "        fieldnames = ['file_name', 'tilename', 'zone']\n",
    "        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n",
    "        writer.writeheader()\n",
    "        \n",
    "        # Add files to metadata\n",
    "        successful_matches = 0\n",
    "        for jpeg_file in tqdm(jpeg_files, desc=\"Creating metadata for images\"):\n",
    "            # Try to match the image to metadata\n",
    "            base_name = os.path.splitext(jpeg_file)[0]\n",
    "            \n",
    "            # Find matching metadata using different strategies\n",
    "            metadata = None\n",
    "            if base_name in filename_to_metadata:\n",
    "                metadata = filename_to_metadata[base_name]\n",
    "            else:\n",
    "                # Try partial matches\n",
    "                matched_keys = [key for key in filename_to_metadata.keys() \n",
    "                                if key in base_name or base_name in key]\n",
    "                if matched_keys:\n",
    "                    metadata = filename_to_metadata[matched_keys[0]]\n",
    "            \n",
    "            if metadata:\n",
    "                # Add to metadata.csv\n",
    "                writer.writerow({\n",
    "                    'file_name': jpeg_file,\n",
    "                    'tilename': metadata['tilename'],\n",
    "                    'zone': metadata['zone']\n",
    "                })\n",
    "                successful_matches += 1\n",
    "            else:\n",
    "                print(f\"Could not find metadata for {jpeg_file}\")\n",
    "        \n",
    "        print(f\"Successfully matched {successful_matches} images with metadata\")\n",
    "    \n",
    "    return output_dir\n",
    "\n",
    "def upload_dataset_to_hub(dataset_dir, repo_name):\n",
    "    \"\"\"\n",
    "    Upload the dataset to the Hugging Face Hub\n",
    "    \n",
    "    Args:\n",
    "        dataset_dir: Directory containing the organized dataset\n",
    "        repo_name: Name of the repository on Hugging Face Hub\n",
    "    \"\"\"\n",
    "    # Load the dataset using ImageFolder\n",
    "    print(f\"Loading dataset from {dataset_dir}\")\n",
    "    dataset = load_dataset(\"imagefolder\", data_dir=dataset_dir)\n",
    "    \n",
    "    # Push to Hugging Face Hub\n",
    "    print(f\"Pushing dataset to Hugging Face Hub: {repo_name}\")\n",
    "    dataset.push_to_hub(repo_name)\n",
    "    print(\"Dataset uploaded successfully!\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step 4: Creating image info list\n",
      "Reading Excel file: /fsx/avijit/projects/datacommonsMA/massgis_2023_aerial_imagery/COQ2023INDEX_POLY.xlsx\n",
      "Found 10218 entries in Excel file\n",
      "Found 10218 JPEG files in the directory\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Matching JPEG files to metadata: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 10218/10218 [00:00<00:00, 616174.46it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully matched 10218 JPEG files with metadata\n",
      "Found 10218 matched JPEG files\n",
      "Step 5: Deleting JP2 files...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "JP2 files deleted\n"
     ]
    }
   ],
   "source": [
    "# Excel file path\n",
    "excel_file = \"/fsx/avijit/projects/datacommonsMA/massgis_2023_aerial_imagery/COQ2023INDEX_POLY.xlsx\"\n",
    "\n",
    "# Define directories\n",
    "base_dir = \"/fsx/avijit/projects/datacommonsMA/massgis_2023_aerial_imagery\"\n",
    "output_dir = \"/fsx/avijit/projects/datacommonsMA/massgis_2023_aerial_imagery/imagefolder-dataset\"\n",
    "\n",
    "jp2_dir = os.path.join(base_dir, \"jp2-files\")\n",
    "jpeg_dir = os.path.join(base_dir, \"jpeg-files\")\n",
    "\n",
    "# Ensure directories exist\n",
    "os.makedirs(jp2_dir, exist_ok=True)\n",
    "os.makedirs(jpeg_dir, exist_ok=True)\n",
    "\n",
    "Step 1: Read Excel file\n",
    "print(\"Step 1: Reading Excel file\")\n",
    "df = read_excel_and_get_urls(excel_file)\n",
    "\n",
    "# Step 2: Download and extract JP2 files\n",
    "print(\"Step 2: Downloading and extracting JP2 files\")\n",
    "jp2_info_list = []\n",
    "\n",
    "for idx, row in tqdm(df.iterrows(), total=len(df), desc=\"Downloading ZIP files\"):\n",
    "    tilename = row['TILENAME']\n",
    "    zone = row['ZONE']\n",
    "    url = row['URL']\n",
    "    \n",
    "    info = download_and_extract_jp2(tilename, zone, url, jp2_dir)\n",
    "    if info is not None:\n",
    "        jp2_info_list.append(info)\n",
    "\n",
    "print(f\"Successfully downloaded {len(jp2_info_list)} JP2 files\")\n",
    "\n",
    "# Step 3: Batch convert JP2 to JPEG\n",
    "print(\"Step 3: Converting JP2 to JPEG\")\n",
    "convert_jp2_to_jpeg(jp2_dir, jpeg_dir)\n",
    "\n",
    "#Step 4: Create image info list for dataset creation\n",
    "print(\"Step 4: Creating image info list\")\n",
    "image_info_list = recreate_image_info_list(excel_file, jpeg_dir)\n",
    "    \n",
    "print(f\"Found {len(image_info_list)} matched JPEG files\")\n",
    "\n",
    "# Step 5: Delete JP2 files to save space\n",
    "print(\"Step 5: Deleting JP2 files...\")\n",
    "shutil.rmtree(jp2_dir)\n",
    "print(\"JP2 files deleted\")\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Login to Hugging Face (use your API token)\n",
    "api_token = input(\"Enter your Hugging Face API token: \")\n",
    "login(token=api_token)\n",
    "\n",
    "\n",
    "# Create and push Hugging Face dataset\n",
    "hf_dataset_name = input(\"Enter the name for your Hugging Face dataset (username/dataset-name): \")\n",
    "upload_dataset_to_hub(image_info_list, hf_dataset_name)\n",
    "\n",
    "print(\"Done!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Reading metadata from /fsx/avijit/projects/datacommonsMA/massgis_2023_aerial_imagery/imagefolder-dataset/train/metadata.csv\n",
      "Selected 50 samples\n",
      "Loading and resizing images...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/fsx/avijit/anaconda3/envs/py312/lib/python3.12/site-packages/PIL/Image.py:3402: DecompressionBombWarning: Image size (100000000 pixels) exceeds limit of 89478485 pixels, could be decompression bomb DOS attack.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Resizing images...\n",
      "Saving to /fsx/avijit/projects/datacommonsMA/massgis_2023_aerial_imagery/imagefolder-dataset/data/sample_dataset_256x256.parquet...\n",
      "Saved sample dataset to /fsx/avijit/projects/datacommonsMA/massgis_2023_aerial_imagery/imagefolder-dataset/data/sample_dataset_256x256.parquet\n",
      "File size: 6.28 MB\n",
      "Verifying saved file...\n",
      "Columns in saved file: ['image', 'tilename', 'zone']\n",
      "Number of rows: 50\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "import pyarrow as pa\n",
    "import pyarrow.parquet as pq\n",
    "from PIL import Image as PILImage\n",
    "import numpy as np\n",
    "from tqdm import tqdm\n",
    "import io\n",
    "\n",
    "# Import the pandas_image_methods library\n",
    "from pandas_image_methods import PILMethods\n",
    "\n",
    "# Register the PIL methods accessor\n",
    "pd.api.extensions.register_series_accessor(\"pil\")(PILMethods)\n",
    "\n",
    "base_dir = \"/fsx/avijit/projects/datacommonsMA/massgis_2023_aerial_imagery/imagefolder-dataset\"\n",
    "train_dir = os.path.join(base_dir, \"train\")\n",
    "output_dir = os.path.join(base_dir, \"data\")\n",
    "output_path = os.path.join(output_dir, \"sample_dataset_256x256.parquet\")\n",
    "\n",
    "# Create the output directory if it doesn't exist\n",
    "os.makedirs(output_dir, exist_ok=True)\n",
    "\n",
    "target_size = (256, 256)\n",
    "num_samples = 50\n",
    "\n",
    "metadata_path = os.path.join(train_dir, \"metadata.csv\")\n",
    "print(f\"Reading metadata from {metadata_path}\")\n",
    "metadata_df = pd.read_csv(metadata_path)\n",
    "\n",
    "# Take a random sample of 50 rows\n",
    "if len(metadata_df) > num_samples:\n",
    "    metadata_df = metadata_df.sample(n=num_samples, random_state=42)\n",
    "\n",
    "print(f\"Selected {len(metadata_df)} samples\")\n",
    "\n",
    "# Create DataFrame with just the paths first\n",
    "df = pd.DataFrame({\n",
    "    'file_path': [os.path.join(train_dir, row['file_name']) for _, row in metadata_df.iterrows()],\n",
    "    'tilename': metadata_df['tilename'].tolist(),\n",
    "    'zone': metadata_df['zone'].astype('int64').tolist()\n",
    "})\n",
    "\n",
    "# Load images using the pil accessor\n",
    "print(\"Loading and resizing images...\")\n",
    "df['image'] = df['file_path'].pil.open()\n",
    "\n",
    "# Resize the images\n",
    "print(\"Resizing images...\")\n",
    "df['image'] = df['image'].pil.resize(target_size)\n",
    "\n",
    "# Keep only the required columns for the preview\n",
    "df = df[['image', 'tilename', 'zone']]\n",
    "\n",
    "# Save to Parquet (the library will handle the PIL images correctly)\n",
    "print(f\"Saving to {output_path}...\")\n",
    "df.to_parquet(output_path)\n",
    "\n",
    "print(f\"Saved sample dataset to {output_path}\")\n",
    "print(f\"File size: {os.path.getsize(output_path) / (1024 * 1024):.2f} MB\")\n",
    "\n",
    "# Verify the saved file\n",
    "print(\"Verifying saved file...\")\n",
    "df_check = pd.read_parquet(output_path)\n",
    "print(\"Columns in saved file:\", df_check.columns.tolist())\n",
    "print(\"Number of rows:\", len(df_check))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<pyarrow._parquet.FileMetaData object at 0x7fa0fc694f90>\n",
      "  created_by: parquet-cpp-arrow version 19.0.0\n",
      "  num_columns: 4\n",
      "  num_rows: 50\n",
      "  num_row_groups: 1\n",
      "  format_version: 2.6\n",
      "  serialized_size: 2731\n"
     ]
    }
   ],
   "source": [
    "parquet_file = pq.ParquetFile(output_path)\n",
    "print(parquet_file.metadata)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py312",
   "language": "python",
   "name": "py312"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}