zoengjyutgaai / add_jyutping_column.py
laubonghaudoi's picture
Add jyutping script
276233c
#!/usr/bin/env python3
"""
Script to add jyutping column to all metadata.csv files in the dataset.
Includes custom entries for specific terms.
"""
import csv
import os
import ToJyutping
from pathlib import Path
def add_jyutping_to_csv(csv_path, converter):
"""Add jyutping column to a CSV file using the provided converter."""
print(f"Processing {csv_path}...")
# Read the CSV file
rows = []
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
fieldnames = reader.fieldnames
# Add jyutping to fieldnames if not already present
if 'jyutping' not in fieldnames:
fieldnames = fieldnames + ['jyutping']
# Process each row
for i, row in enumerate(reader):
# Get jyutping for the transcription
transcription = row['transcription']
jyutping = converter.get_jyutping_text(transcription)
row['jyutping'] = jyutping
rows.append(row)
# Progress indicator
if (i + 1) % 1000 == 0:
print(f" Processed {i + 1} rows...")
# Write the updated CSV
output_path = csv_path.with_suffix('.tmp')
with open(output_path, 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
# Replace the original file
output_path.replace(csv_path)
print(f" Completed! Total rows processed: {len(rows)}")
def main():
"""Main function to process all metadata.csv files."""
# Create a customized converter with specific entries
# Add more custom entries here as needed
custom_entries = {
'刻': 'hak1',
}
# Create the customized converter
converter = ToJyutping.customize(custom_entries)
# Define the paths to all metadata.csv files
csv_files = [
Path("/Users/laufei/Documents/GitHub/zoengjyutgaai_saamgwokjinji/opus/seoiwuzyun/metadata.csv"),
Path("/Users/laufei/Documents/GitHub/zoengjyutgaai_saamgwokjinji/opus/saamgwokjinji/metadata.csv"),
Path("/Users/laufei/Documents/GitHub/zoengjyutgaai_saamgwokjinji/opus/mouzaakdung/metadata.csv"),
Path("/Users/laufei/Documents/GitHub/zoengjyutgaai_saamgwokjinji/opus/lukdinggei/metadata.csv")
]
print("Using custom entries:")
for term, jyutping in custom_entries.items():
print(f" {term} -> {jyutping}")
print()
# Process each file
for csv_file in csv_files:
if csv_file.exists():
add_jyutping_to_csv(csv_file, converter)
else:
print(f"Warning: {csv_file} not found!")
print("\nAll files processed successfully!")
if __name__ == "__main__":
main()