cantomap / convert.py
wcyat's picture
initial commit
b586e31 unverified
raw
history blame
6.41 kB
import xml.etree.ElementTree as ET
import csv
import pandas as pd
from pydub import AudioSegment
import re
import sys
from typing import List, Tuple, Dict
# Global dictionary to store custom character choices for each pinyin
custom_choices: Dict[str, str] = {}
def parse_xml(xml_content: str) -> List[Tuple[int, int, str]]:
root = ET.fromstring(xml_content)
time_order = {ts.get('TIME_SLOT_ID'): int(ts.get('TIME_VALUE'))
for ts in root.iter('TIME_SLOT')}
tier_data = []
for tier in root.iter('TIER'):
tier_id = tier.get('TIER_ID')
if not ('-' in tier_id) and (tier_id == 'G' or tier_id == 'E'):
for annotation in tier.iter('ALIGNABLE_ANNOTATION'):
start_time = time_order[annotation.get('TIME_SLOT_REF1')]
end_time = time_order[annotation.get('TIME_SLOT_REF2')]
text = annotation.find('./ANNOTATION_VALUE').text
tier_data.append((start_time, end_time, text))
return tier_data
def transform_latin_to_chinese(text: str, dict_df: pd.DataFrame, output_wav: str) -> Tuple[str, pd.DataFrame]:
global custom_choices
transformed_text = ""
i = 0
while i < len(text):
char = text[i]
if char == "&":
j = i + 1
while j < i + 7 and j < len(text) and text[j].isalpha():
j += 1
if j < len(text) and text[j].isdigit():
term = text[(i+1):j + 1].lower()
pinyin_entries = dict_df[dict_df['拼音'] == term]['繁體']
if not pinyin_entries.empty:
if len(pinyin_entries) > 1:
full_sentence = f"Full Sentence: {text}"
print(full_sentence)
print(f"Path: {output_wav}")
print(f"Multiple entries found for {
term}. Choose one (or enter a custom character):")
for idx, entry in enumerate(pinyin_entries):
print(f"{idx + 1}. {entry}")
print(f"{len(pinyin_entries) +
1}. Enter a custom character")
choice = input("Enter the number of your choice: ")
if choice.isdigit() and int(choice) <= len(pinyin_entries):
choice = int(choice) - 1
transformed_text += pinyin_entries.values[choice]
custom_choices[term] = pinyin_entries.values[choice]
elif choice == str(len(pinyin_entries) + 1):
custom_choice = input(
f"Enter a custom character for {term}: ")
transformed_text += custom_choice
custom_choices[term] = custom_choice
# Update DataFrame with the custom character
dict_df = pd.concat([dict_df, pd.DataFrame(
[{'拼音': term, '繁體': custom_choice}])], ignore_index=True)
else:
print("Invalid choice. Using the default character.")
transformed_text += pinyin_entries.values[0]
else:
try:
transformed_text += pinyin_entries.values[0] or ""
except:
pass
else:
print(f"Full Sentence: {text}")
print(f"Path: {output_wav}")
custom_choice = input(f"No corresponding character found for {
term}. Enter a custom character: ")
transformed_text += custom_choice
custom_choices[term] = custom_choice
# Update DataFrame with the custom character
dict_df = pd.concat([dict_df, pd.DataFrame(
[{'拼音': term, '繁體': custom_choice}])], ignore_index=True)
i = j + 1
else:
transformed_text += char
i += 1
else:
transformed_text += char
i += 1
return transformed_text, dict_df
def clean_transformed_text(text: str) -> str:
# Replace "#" with a blank space
text = text.replace("#", " ")
# Remove special characters and symbols
text = re.sub(r"[^a-zA-Z0-9\u4e00-\u9fff ]", "", text)
# Remove HTML entities (e.g., &amp;)
text = re.sub(r"&[a-zA-Z]+;", "", text)
return text
def extract_audio_segments(input_wav: str, output_wav: str, start_time: int, end_time: int) -> None:
audio = AudioSegment.from_wav(input_wav)
segment = audio[start_time:end_time]
segment.export(output_wav, format="wav")
def main() -> None:
with open(sys.argv[1], "r", encoding="utf-8") as file:
xml_content = file.read()
tier_data = parse_xml(xml_content)
with open("./粵語字典_(耶魯_數字).csv", "r", encoding="utf-8") as dict_file:
dict_csv = dict_file.name
dict_df = pd.read_csv(dict_csv)
# Replace with your actual audio file
audio_file = sys.argv[1].replace("eaf", "wav")
transformed_tier_data = []
for i, (start_time, end_time, text) in enumerate(tier_data):
output_wav = f"audio/{sys.argv[1].split('/')
[-1].replace('.eaf', '')}_ts{i+1}.wav"
extract_audio_segments(audio_file, output_wav, start_time, end_time)
transformed_text, dict_df = transform_latin_to_chinese(text, dict_df, output_wav)
transformed_text = clean_transformed_text(transformed_text)
transformed_tier_data.append(
(start_time, end_time, transformed_text, output_wav.split("/")[-1]))
# Save the updated DataFrame to the CSV file
dict_df.to_csv(dict_csv, index=False, encoding='utf-8')
tsv_filename = "transcript/" + \
sys.argv[1].split("/")[-1].replace("eaf", "tsv")
with open(tsv_filename, "w", newline="", encoding="utf-8") as tsvfile:
tsv_writer = csv.writer(tsvfile, delimiter='\t')
tsv_writer.writerow(
["timestamp_start", "timestamp_end", "text", "path"])
tsv_writer.writerows(transformed_tier_data)
if __name__ == "__main__":
main()