thai_handwriting_dataset / convert_best2019.py
kobkrit's picture
Add convert_best2019.py
99bd55e
import os
import pandas as pd
from PIL import Image
import codecs
import numpy as np
import glob
import io
def create_dataset():
print("Starting dataset creation...")
# Create output directory for images
os.makedirs("processed_images", exist_ok=True)
# Find all label files matching pattern
print("Finding label files...")
label_files = glob.glob("./original/test/round3?_best2019.label")
print(f"Found {len(label_files)} label files")
# Parse image filenames and captions
data = []
for i, label_path in enumerate(label_files):
print(f"\nProcessing label file {i+1}/{len(label_files)}: {label_path}")
# Read label file with Windows-874 encoding
print("Reading label file...")
with codecs.open(label_path, 'r', encoding='cp874') as f:
lines = f.readlines()
print(f"Found {len(lines)} entries")
for j, line in enumerate(lines):
if j % 100 == 0:
print(f"Processing entry {j}/{len(lines)}")
filename, caption = line.strip().split(' ', 1)
# Get folder name from first 3 chars of filename
folder = filename[:3]
image_path = f"./original/test/{folder}/{filename}"
# Load and verify image exists
if os.path.exists(image_path):
try:
# Load image and convert to bytes
img = Image.open(image_path)
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='PNG') # Force PNG format
img_bytes = {"bytes":bytearray(img_byte_arr.getvalue())}
data.append({
'image': img_bytes, # Store as numpy array of bytes
'text': caption,
'label_file': os.path.basename(label_path)
})
except Exception as e:
print(f"Error processing image {image_path}: {e}")
print(f"\nProcessed {len(data)} total images successfully")
# Convert to dataframe and save as parquet
print("Converting to dataframe...")
df = pd.DataFrame(data)
print("Saving to parquet file...")
df.to_parquet("train-0000.parquet", index=False)
print("Dataset creation complete!")
if __name__ == "__main__":
create_dataset()