{ "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": [ "\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 }