Datasets:
CZLC
/

Modalities:
Text
Formats:
json
Languages:
Czech
Size:
< 1K
Libraries:
Datasets
pandas
License:
CNC_Dialekt / convert_dialekt.py
mfajcik's picture
Upload 2 files
6d6b04d verified
import os
import re
from typing import Dict
import jsonlines
from tqdm import tqdm
TARGET = ".data/dialekt_v2_ort.vert"
def process_vert_format(vert_content: str) -> Dict[str, str]:
# Pattern to match document boundaries and extract metadata
doc_pattern = re.compile(r'<doc[^>]*>.*?</doc>', re.DOTALL)
metadata_pattern = re.compile(
r'<doc id="([^"]*)".+?rok="([^"]*)".+?misto="([^"]*)" sidlotyp="([^"]*)".+?tema="([^"]*)" pocetml="([^"]*)"')
# Pattern to match speaker turns
sp_pattern = re.compile(r'<sp[^>]*id="([^"]*)"[^>]*prezdivka="([^"]*)"\s*[^>]*>(.*?)</sp>', re.DOTALL)
# Pattern to remove whitespace before punctuation
ws_before_punct = re.compile(r'\s+([.,!?])')
# Find all documents
documents = re.findall(doc_pattern, vert_content)
processed_documents = {}
for doc in tqdm(documents):
# Extract metadata
metadata_match = re.search(metadata_pattern, doc)
if metadata_match:
# r'<doc id="([^"]*)".+?rok="([^"]*)".+?misto="([^"]*)" sidlotyp="([^"]*)".+?tema="([^"]*)" pocetml="([^"]*)"')
doc_id = metadata_match.group(1)
year = metadata_match.group(2)
place = metadata_match.group(3)
settlement_type = metadata_match.group(4)
topic = metadata_match.group(5)
speakers = metadata_match.group(6)
metadata_str = (f"Rok: {year}, "
f"Typ sídla: {settlement_type}, "
f"Místo: {place}, "
f"Téma: {topic}, "
f"Počet mluvčích: {speakers}")
else:
raise ValueError("Metadata not found in document")
# Initialize an empty list to hold processed document text
processed_document = [metadata_str]
# Find all speaker turns within the document
for sp_match in re.findall(sp_pattern, doc):
speaker_id = sp_match[0]
speaker_nickname = sp_match[1]
sp_content = sp_match[2]
# if speaker is Y, rename him as Jiný zvuk
if speaker_id == "Y":
speaker_id = "Zvuk"
# remove symbols ---, ...:,
sp_content = sp_content.replace("---", "")
sp_content = sp_content.replace("...:", "")
sp_content = sp_content.replace("...", "")
sp_content = sp_content.replace("..", "")
sp_content = sp_content.replace("?.", "?")
# remove tags from each line, and join text
tokens = [line.split("\t")[0].strip() for line in sp_content.split("\n") if line.strip() != ""]
speaker_text = " ".join(tokens)
# replace more than one space with one space
speaker_text = re.sub(r'\s+', ' ', speaker_text).strip()
# remove whitespace before ., !, ?
speaker_text = re.sub(ws_before_punct, r'\1', speaker_text)
# - sometimes lines in oral are empty? e.g. 08A009N // REMOVE THESE LINES
if speaker_text.strip() == "":
continue
# If the turn is not finished by ., ?, !, add .
if speaker_text[-1] not in [".", "!", "?"]:
speaker_text += "."
# Capitalize the first letter of the speaker turn
speaker_text = speaker_text[0].upper() + speaker_text[1:]
# sometimes there is @ in the text, remove it
speaker_text = speaker_text.replace("@", "")
# capitalize first (non whitespace) letter after ., !, ?
speaker_text = re.sub(r'([.!?]\s*)(\w)', lambda m: m.group(1) + m.group(2).upper(), speaker_text)
speaker_text = speaker_text.replace("overlap", "překryv mluvčích")
# Format the speaker turn and add to the processed document list
if speakers == "1":
processed_document.append(speaker_text)
else:
processed_document.append(f"[mluvčí: {speaker_nickname}] {speaker_text}")
# Join all speaker turns into a single string for the document
if speakers == "1":
final_text = processed_document[0] + "\n" + " ".join(processed_document[1:])
else:
final_text = '\n'.join(processed_document)
processed_documents[doc_id] = final_text
return processed_documents
# Read the content from the file
with open(TARGET, "r") as f:
vert_content = f.read()
# Process the content
processed_documents = process_vert_format(vert_content)
# write all splits into same json file in .data/hf_dataset/cnc_fictree/test.jsonl
OF = ".data/hf_dataset/cnc_dialekt/test.jsonl"
os.makedirs(os.path.dirname(OF), exist_ok=True)
with jsonlines.open(OF, "w") as writer:
for doc_id, doc in list(processed_documents.items()):
writer.write({"text": doc, "id": doc_id})