#!/usr/bin/env python3
"""
Mark the works that are translations.

Usage:
    python translations.py          # after group.py, before compact.py
    python translations.py --show   # also print each translation and its evidence

Adds the field "tl" to every work that is a translation: the language of the original
(ISO 639-1 code, or the library's three-letter code where there is none), or "?" when the
record says the work is a translation but not from which language. Running it again
recomputes the field. The evidence, per library:

- Gallica: the UNIMARC 101 field of the BnF record (first indicator 1 = translation,
  $c = language of the original), read from the records in cache/bnf/.
- Project Gutenberg: a credited translator ("[Translator]") among the authors.
- Internet Archive: a creator credited as translator ("..., translator", "(Translator)",
  "..., tr."), read from cache/ia/scrape.jsonl.
- Wikisource: a translator in the page's metadata template (ÜBERSETZER in {{Textdaten}},
  translator in {{header}}, traducteur, traductor, traduttore), fetched once through the
  MediaWiki API and cached in translations_ws.json.
- Darwin and Wallace Online: every edition not in English.
- Darwin, Wallace and Alexander von Humboldt in every library: Darwin's and Wallace's works in
  any language but English; Humboldt's in the other language than the original for the works
  listed in HUMBOLDT (the Voyage aux régions équinoxiales and Essai politique are French, Kosmos
  and Ansichten der Natur German), and any of his works in a language other than French or German.
  The edition humboldt digital is left out: it edits his manuscripts.
- Europeana (BNE, Complutense, BNP): the creators, contributors and descriptions in
  cache/europeana/*.jsonl.
- Every library: the title, subjects, imprint or description name a translation
  ("translated from the Norwegian", "aus dem Englischen übersetzt", "traduit de l'anglois",
  "traducido", "Übers. v."). A phrase that names the book's own language as the source
  ("traduicte du françois au langage des peuples sauvages" in a French book) does not count.

For merged volumes and editions, the work counts as a translation when any of them is one.
"""
import argparse
import glob
import json
import re
import sys
import unicodedata
import xml.etree.ElementTree as ET
from collections import Counter
from pathlib import Path

HERE = Path(__file__).resolve().parent
MARC = {"eng": "en", "ger": "de", "fre": "fr", "spa": "es", "por": "pt", "ita": "it", "lat": "la", "grc": "grc",
        "gre": "el", "dut": "nl", "swe": "sv", "dan": "da", "nor": "no", "rus": "ru", "pol": "pl", "ara": "ar",
        "per": "fa", "chi": "zh", "jpn": "ja", "tur": "tr", "heb": "he", "cze": "cs", "hun": "hu", "fin": "fi",
        "ice": "is", "san": "sa", "cat": "ca", "arm": "hy", "may": "ms", "mul": "?"}  # mul: several
# Language names as they follow "from the", "aus dem", "traduit de l'", "traducido del" ...
NAMES = {"en": "english|anglois|anglais|angloise|englischen|engländischen|inglés|ingles|inglese|inglez",
         "de": "german|high dutch|allemand|alleman|allemant|deutschen|teutschen|hochdeutschen|alemán|aleman|tedesco",
         "fr": "french|françois|francois|françoys|francoys|français|francais|französischen|frantzösischen|francés|frances|francese",
         "es": "spanish|espagnol|espaignol|espagnole|spanischen|castellano|español|espanol|spagnuolo|spagnolo",
         "pt": "portuguese|portugais|portugois|portugiesischen|portuguez|portugues|português|portoghese",
         "it": "italian|italien|italienischen|italiänischen|italiaenschen|italiano",
         "la": "latin|latine|lateinischen|latín|latino",
         "grc": "greek|grec|griechischen|griego|greco",
         "nl": "dutch|low dutch|hollandois|hollandais|flamand|flemish|holländischen|niederländischen|flamändischen",
         "sv": "swedish|suédois|suedois|schwedischen|sueco|svedese",
         "da": "danish|danois|dänischen|danés",
         "no": "norwegian|norvégien|norwegischen|noruego",
         "ru": "russian|russe|russischen|ruso|russo",
         "pl": "polish|polonois|polonais|polnischen",
         "ar": "arabic|arabick|arabe|arabischen|árabe",
         "fa": "persian|persan|persischen",
         "zh": "chinese|chinois|chinesischen|chino|cinese",
         "ja": "japanese|japonais|japanischen",
         "tr": "turkish|turc|türkischen|turco",
         "he": "hebrew|hébreu|hebräischen|hebreo",
         "cs": "czech|bohemian|böhmischen|tschechischen",
         "hu": "hungarian|hongrois|ungarischen",
         "fi": "finnish|finnois|finnischen",
         "is": "icelandic|islandais|isländischen"}
WORD = {w: code for code, ws in NAMES.items() for w in ws.split("|")}
# a source language: a preposition, a few filler words, a language name
SOURCE = re.compile(r"\b(?:from|out\s+of|aus|de|du|d['’]|del|dal|dall['’]|dalla|di|do|da|of)\s*"
                    r"(?:(?:the|l['’]|la|langue|lengua|língua|lingua|idioma|original|abridged|ancient|old|dem|alt|ancien|antiguo)\s*)*"
                    r"(" + "|".join(sorted(WORD, key=len, reverse=True)) + r")(?![a-zà-ÿ])", re.I)
MARKER = re.compile(
    r"\btranslat(?:ed|ion|ions|or|ors)\b|\btransl\.|\btr\.(?=\s+(?:from|by)\b)"
    r"|[üu]e?bers(?:etzt|ezt|etzung|etzer|\.)|[üu]e?bertragen\s+(?:aus|von|ins)|\bverdeutscht|\bins\s+deutsche\s+übert"
    r"|autori[sz]i[er]?te\s+(?:deutsche\s+)?(?:ausgabe|übersetzung)|\bdeutsche\s+ausgabe\b"
    r"|\btradu(?:i[ct]+|ct)(?:e|es|s)?\b|\btraduction\b|\btraducteur|\btrad\.(?=\s+(?:de|du|d['’]|par|en)\b)|\btranslat[ée]"
    r"|\bmis\s+en\s+fran[cç]ois|\btraducid[oa]s?\b|\btraduc(?:c)?i[oó]n\b|\btraductor\b|\btraduzid[oa]s?\b|\btradu[cç][ãa]o\b"
    r"|\btradott[oa]\b|\btraduzione\b|\bvolgarizzat|\bvertid[oa]\s+al\b|\bvertaald|\bvertaling|\boversat|\böversatt", re.I)
# Subject headings that call the work itself a translation ("Translation from Spanish to English").
# A bare "translated" tag on the Internet Archive is left out (it is also set on English originals), and
# so is "Greek poetry -- Translations into English", which also marks books that
# merely contain translated poems (Thoreau's A Yankee in Canada).
SUBJECT = re.compile(r"^\s*translation from\b", re.I)
# Creator credits ("Ogilby, John, 1600-1676, translator", "Lee, Samuel (Translator)", "Burke, Edward, tr")
CREDIT = re.compile(r"[,(\[]\s*(?:editor\s*(?:and|,)\s*)?(?:translator|tr\.?|trad\.?|traductor|traducteur|übersetzer|transl\.?)\s*[)\]]?\s*(?:;|$)", re.I)
WS_FIELD = re.compile(r"^\s*\|?\s*(ÜBERSETZER|translator|traducteur|traductor|traduttore|tradutor)\s*=\s*([^|\n}]*)", re.I | re.M)
WS_ATTR = re.compile(r"\b(traducteur|translator)\s*=\s*\"([^\"]*)\"", re.I)
# Humboldt wrote in French and German. His larger works by the language of the original, matched on
# the title in any language; a work not listed counts as an original in French or German.
HUMBOLDT = [("fr", re.compile(r"equino[cx]|aequino[ck]|äquino|personal narrative|relation historique|travels and researches"
                              r"|reise in s[üu]damerika|travels and discoveries in south america|nouvelle[- ]espagne"
                              r"|neu[- ]?spanien|new spain|nueva espa|[iî]le de cuba|island of cuba|isla de cuba"
                              r"|zustand der insel cuba|vues des cordill|views of the cordill|vistas de las cordill|recueil d.observations|asie centrale|central[- ]?asien"
                              r"|examen critique|kritische untersuchungen|g[ée]ographie des plantes|geography of plants", re.I)),
            ("de", re.compile(r"ansichten der natur|views of nature|aspects of nature|tableaux de la nature"
                              r"|cuadros de la naturaleza|quadri della natura|kosmos|cosmos|physiognomik der gew", re.I))]
# Authors whose original language is known, matched on the first author: (pattern, languages, works)
AUTHORS = [(re.compile(r"\bdarwin\b(?!.*galton)(?=.*\bcharles\b)|\bcharles\b.*\bdarwin\b", re.I), ("en",), []),
           (re.compile(r"\bwallace\b(?=.*\balfred\b)|\balfred\b.*\bwallace\b", re.I), ("en",), []),
           (re.compile(r"\bhumboldt\b(?!.*\bwilhelm\b)", re.I), ("fr", "de"), HUMBOLDT)]


def by_author(r, m):
    """The original's language when the work is a translation of Darwin, Wallace or Humboldt, else None."""
    if r["src"] == "EHD":
        return None  # the edition of Humboldt's own manuscripts
    first = unicodedata.normalize("NFC", (r.get("a") or "").split(";")[0])
    for rx, langs, works in AUTHORS:
        if rx.search(first):
            title = unicodedata.normalize("NFC", m.get("t") or r["t"])
            orig = next((lang for lang, wrx in works if wrx.search(title)), None)
            origs = {orig} if orig else set(langs)
            if origs & set(r["l"]):
                return None
            return orig or (langs[0] if len(langs) == 1 else "?")
    return None


def from_text(text, own):
    """'?' or a language code when the text names a translation of this work, else None."""
    text = unicodedata.normalize("NFC", text)  # some records spell ç as c + combining cedilla
    for m in MARKER.finditer(text):
        after = list(SOURCE.finditer(text[m.end():m.end() + 70]))
        before = list(SOURCE.finditer(text[max(0, m.start() - 45):m.start()]))  # "aus dem Englischen übersetzt"
        hit = after[0] if after else before[-1] if before else None
        src = WORD[re.sub(r"\s+", " ", hit.group(1).lower())] if hit else None
        if src and src in own:
            continue  # "traduicte du françois au langage des peuples" in a French book
        return src or "?"
    return None


def bnf(cache):
    ns = {"m": "info:lc/xmlns/marcxchange-v2"}
    out = {}
    for f in sorted(glob.glob(str(cache / "bnf" / "*.xml"))):
        for rec in ET.parse(f).getroot().iter("{info:lc/xmlns/marcxchange-v2}record"):
            ark = rec.findtext("m:controlfield[@tag='003']", "", ns).rsplit("/", 1)[-1]
            f101 = rec.find("m:datafield[@tag='101']", ns)
            if f101 is None or f101.get("ind1") != "1":
                continue
            own = {s.text for s in f101.findall("m:subfield[@code='a']", ns)}
            orig = [s.text for s in f101.findall("m:subfield[@code='c']", ns) if s.text not in own]
            if orig or not f101.findall("m:subfield[@code='c']", ns):
                out[ark] = MARC.get(orig[0], orig[0]) if orig else "?"
    return out


def ia_creators(cache):
    out = {}
    path = cache / "ia" / "scrape.jsonl"
    if path.exists():
        for line in open(path, encoding="utf-8"):
            o = json.loads(line)
            c = o.get("creator") or []
            out[o["identifier"]] = [c] if isinstance(c, str) else c
    return out


def europeana(cache):
    out = {}
    for f in glob.glob(str(cache / "europeana" / "*.jsonl")):
        for line in open(f, encoding="utf-8"):
            o = json.loads(line)
            out[o["id"].strip("/")] = (o.get("dcCreator") or []) + (o.get("dcContributor") or []), " | ".join(o.get("dcDescription") or [])
    return out


def wikisource(rows, path):
    cache = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
    want = {}
    for r in rows:
        if r["src"] == "WS":
            for page in [r["id"]] + [e["id"] for e in r.get("ed", [])]:
                if f"{r['l'][0]}:{page}" not in cache:
                    want.setdefault(r["l"][0], []).append(page)
    if want:
        from wikisource_nature_travel import wikitext
        for lang, pages in want.items():
            print(f"  Wikisource {lang}: fetching {len(pages)} pages", file=sys.stderr)
            got = dict(wikitext(sorted(set(pages)), lang))
            for p in pages:
                text = got.get(p, "")
                names = [v for _, v in WS_FIELD.findall(text) + WS_ATTR.findall(text)]
                names = [re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]*)\]\]", r"\1", v).strip() for v in names]
                cache[f"{lang}:{p}"] = next((v for v in names if v and v not in ("?", "-", "—")), "")
        path.write_text(json.dumps(cache, ensure_ascii=False, indent=0), encoding="utf-8")
    return cache


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", default="overview/data.json")
    ap.add_argument("--cache", default=str(HERE / "cache"))
    ap.add_argument("--ws-cache", default=str(HERE / "translations_ws.json"))
    ap.add_argument("--show", action="store_true")
    args = ap.parse_args()
    cache = Path(args.cache)
    rows = json.load(open(args.data, encoding="utf-8"))
    ga, ia, eu = bnf(cache), ia_creators(cache), europeana(cache)
    ws = wikisource(rows, Path(args.ws_cache))

    def judge(r, m):
        """(language or '?', evidence) for one member m (the work or one of its volumes/editions) of row r."""
        own = set(r["l"])
        if r["src"] == "GA" and m["id"] in ga:
            return ga[m["id"]], "UNIMARC 101"
        if r["src"] == "DWO" and "en" not in own:
            return "en", "Darwin/Wallace in translation"
        lang = by_author(r, m)
        if lang:
            return lang, "author"
        if r["src"] == "WS" and ws.get(f"{r['l'][0]}:{m['id']}"):
            return from_text(m.get("t") or "", own) or "?", f"translator: {ws[r['l'][0] + ':' + m['id']]}"
        credits = []
        if r["src"] == "PG" and "[Translator]" in (r.get("a") or ""):
            credits.append("[Translator]")
        if r["src"] == "IA":
            credits += [c for c in ia.get(m["id"], []) if CREDIT.search(c)]
        if r["src"] in ("BNE", "UCM", "BNP") and m["id"] in eu:
            people, desc = eu[m["id"]]
            credits += [c for c in people if CREDIT.search(c)]
            hit = from_text(desc, own)
            if hit:
                return hit, "description"
        hit = from_text(m.get("t") or "", own)
        if hit:
            return hit, "title"
        if credits:
            return "?", "credit: " + credits[0]
        return None, None

    shown, evidence = Counter(), Counter()
    for r in rows:
        r.pop("tl", None)
        found = None
        for m in [r] + r.get("ed", []):
            lang, why = judge(r, m)
            if lang and (found is None or found[0] == "?"):
                found = (lang, why)
        if found is None:
            own = set(r["l"])
            for field in ("sub", "im", "sum"):
                text = r.get(field) or ""
                if field == "sub":
                    hit = "?" if any(SUBJECT.search(h) for h in text.split(" | ")) else None
                else:
                    hit = from_text(text, own)
                if hit and not (field == "sum" and r["src"] == "WS"):  # de summaries describe other editions
                    found = (hit, field)
                    break
        if found:
            r["tl"] = found[0]
            shown[r["src"]] += 1
            evidence[found[1].split(":")[0]] += 1
            if args.show:
                print(f"{r['src']:4} {found[0]:3} {found[1][:40]:40} {r['t'][:90]}")

    json.dump(rows, open(args.data, "w", encoding="utf-8"), ensure_ascii=False, separators=(",", ":"))
    print(f"{sum(shown.values())} of {len(rows)} works marked as translations: "
          + ", ".join(f"{s} {n}" for s, n in shown.most_common()) + "; evidence: "
          + ", ".join(f"{e} {n}" for e, n in evidence.most_common()), file=sys.stderr)


if __name__ == "__main__":
    main()
