import json, re, time, urllib.parse, urllib.request
from pathlib import Path

src = Path('/home/spazio/kingdom_calls/out/королевство 3_transcript.txt')
dst = Path('/home/spazio/kingdom_calls/final/Королевство 3 — полный перевод на русский.txt')
lines = src.read_text(encoding='utf-8').splitlines()
pat = re.compile(r'^(\[\d\d:\d\d:\d\d–\d\d:\d\d:\d\d\]) (.*)$')

# Preserve established Access Consciousness terminology and names from machine mistranslation.
replacements = {
    'СуперСлив.биз': 'SuperSliv.biz',
    'SuperSleeve.biz': 'SuperSliv.biz',
    'сознание доступа': 'Access Consciousness',
    'доступ к сознанию': 'Access Consciousness',
    'доступ': 'Access',
}

def translate(text):
    if not text:
        return ''
    data = urllib.parse.urlencode({'client':'gtx','sl':'en','tl':'ru','dt':'t','q':text}).encode()
    req = urllib.request.Request('https://translate.googleapis.com/translate_a/single', data=data,
                                 headers={'User-Agent':'Mozilla/5.0'})
    for attempt in range(7):
        try:
            with urllib.request.urlopen(req, timeout=30) as r:
                obj=json.loads(r.read().decode('utf-8'))
            out=''.join(x[0] for x in obj[0] if x and x[0])
            for a,b in replacements.items():
                out=out.replace(a,b).replace(a.capitalize(),b)
            return out
        except Exception as e:
            if attempt == 6: raise
            time.sleep(1.5*(attempt+1))

out=[]
for i,line in enumerate(lines):
    if i == 0:
        out.append('Транскрибация аудио: королевство 3.mp3')
    elif i == 1:
        out.append('Язык перевода: русский (исходный язык: английский)')
    elif i == 2:
        out.append('Модель транскрибации: faster-whisper small / cpu int8')
    elif not line:
        out.append('')
    else:
        m=pat.match(line)
        if not m:
            out.append(translate(line))
        else:
            out.append(m.group(1)+' '+translate(m.group(2)))
    if i % 25 == 0:
        print(f'{i+1}/{len(lines)}', flush=True)
        dst.parent.mkdir(parents=True, exist_ok=True)
        dst.write_text('\n'.join(out), encoding='utf-8')
dst.write_text('\n'.join(out), encoding='utf-8')
print('DONE',len(out),dst)
