TARGET = ".data/kh-noviny.vert"
import os
import re
from typing import Dict
import jsonlines
from tqdm import tqdm
def process_vert_format(vert_content: str) -> Dict[str, str]:
# Pattern to match document boundaries and extract metadata
doc_pattern = re.compile(r']*>.*?', re.DOTALL)
metadata_pattern = re.compile(
r''
)
# 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_id, doc in tqdm(enumerate(documents)):
# Extract metadata
metadata_match = re.search(metadata_pattern, doc)
if metadata_match:
r = metadata_match.group(1)
m = metadata_match.group(2)
d = metadata_match.group(3)
t = metadata_match.group(4)
c = metadata_match.group(5)
h = metadata_match.group(6)
a = metadata_match.group(7)
metadata_str = (f"{d} {m} {r}, "
f"Zdroj: {t}, "
f"Část: {c}, "
f"Titulek: {h}, "
f"Autor: {a}")
else:
raise ValueError("Metadata not found in document")
# Initialize an empty list to hold processed document text
# Find all speaker turns within the document
# remove tags from each line, and join text
tokens = [line.split("\t")[0].strip() for line in doc.split("\n") if line.strip() != ""]
doc_text = " ".join(tokens)
# remove any text with <...> tag
doc_text = re.sub(r'<[^>]*>', '', doc_text)
# replace more than one space with one space
doc_text = re.sub(r'\s+', ' ', doc_text).strip()
# remove whitespace before ., !, ?
doc_text = re.sub(ws_before_punct, r'\1', doc_text)
# - sometimes lines in oral are empty? e.g. 08A009N // REMOVE THESE LINES
if doc_text.strip() == "":
continue
processed_documents[doc_id] = metadata_str + "\n" + doc_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_khnews/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})