"""Run with Python 3: python compare-inputs.py [local UDHR XML directory].
Writes passages.json and tokenizer-coverage.csv in the current directory.
"""
import csv
import json
import sys
import base64
import urllib.request
import unicodedata
import xml.etree.ElementTree as ET
from pathlib import Path

# Plain-text token splitting routines adapted from Hugging Face Transformers
# v4.53.0, Apache-2.0, tokenization_byt5.py and tokenization_canine.py.
def byt5( text: str) -> list[str]:
    tokens = [chr(i) for i in text.encode("utf-8")]
    return tokens

def canine( text: str) -> list[str]:
    return list(text)

BLOBS = {"eng":"a23b138999f3b9645aabec6f82b9618ea59f838c","hin":"2550d0569ca3815d60013b2cd5f291f5229d0b92","kan":"701cd6f263a396f33736cdeb4017f9fc371570bb","tam":"2090fa6a36e3b82d16e0cf621debd7906ba4bbc6","tel":"bdd4644ca11cedb83beae6e74d4573fccdd8cb90"}
corpus = {}
with open("tokenizer-coverage.csv", "w", newline="") as out:
    rows = csv.writer(out)
    rows.writerow(["language","article","byt5_end","canine_end"])
    for lang, blob in BLOBS.items():
        if len(sys.argv) > 1:
            xml = (Path(sys.argv[1]) / f"udhr_{lang}.xml").read_bytes()
        else:
            with urllib.request.urlopen(f"https://api.github.com/repos/eric-muller/udhr/git/blobs/{blob}") as response:
                xml = base64.b64decode(json.load(response)["content"])
        articles = ET.fromstring(xml).findall("{*}article")
        assert [int(a.attrib["number"]) for a in articles] == list(range(1,31))
        corpus[lang] = []
        for number, article in enumerate(articles,1):
            paragraphs = ["".join(p.itertext()) for p in article.findall(".//{*}para")]
            corpus[lang].append(unicodedata.normalize("NFC"," ".join(" ".join(paragraphs).split())))
            prefix = "\n".join(corpus[lang])
            rows.writerow([lang,number,len(byt5(prefix)),len(canine(prefix))])
Path("passages.json").write_text(json.dumps(corpus,ensure_ascii=False,separators=(",",":")), encoding="utf-8")
