File size: 2,939 Bytes
7b6f2cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""Sequential paragraph translation with native PFML history and exact blank lines."""
import argparse,json,re
from pathlib import Path
from inference.run import TranslationEngine,InputBudgetError

def translate_document(engine,text,source,target,*,max_new_tokens=256,max_history_pairs=2,max_input_tokens=2048,context=None,glossary=None,form=None):
    if max_history_pairs<0:raise ValueError('History limit must be nonnegative')
    pieces=re.split(r'((?:\r?\n[ \t]*){2,})',text)
    output=[];history=[];records=[]
    for i,piece in enumerate(pieces):
        if i%2 or not piece.strip():output.append(piece);continue
        # Boundary whitespace belongs to the document, not to generated translation.
        prefix=piece[:len(piece)-len(piece.lstrip())]
        suffix=piece[len(piece.rstrip()):]
        content=piece.strip()
        usable=history[-max_history_pairs:] if max_history_pairs else []
        while True:
            try:
                report=engine.translate(content,source,target,max_new_tokens,history=usable,context=context,glossary=glossary,form=form,max_input_tokens=max_input_tokens)
                break
            except InputBudgetError:
                if not usable:raise
                usable=usable[1:]
        if report['truncated']:raise RuntimeError(f'Paragraph {len(records)+1} exhausted generation budget; no document returned')
        translation=report['translation'].strip()
        if not translation:raise RuntimeError('Empty paragraph translation; no document returned')
        output.append(prefix+translation+suffix)
        history.append((content,translation));records.append(report)
    return {'translation':''.join(output),'paragraphs':records,'source_lang':source,'target_lang':target,'history_limit':max_history_pairs}

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('input');p.add_argument('output');p.add_argument('--model',default='..')
    p.add_argument('--source',required=True);p.add_argument('--target',required=True);p.add_argument('--history',type=int,default=2)
    p.add_argument('--max-input-tokens',type=int,default=2048);p.add_argument('--max-new-tokens',type=int,default=256)
    p.add_argument('--glossary');p.add_argument('--context');p.add_argument('--form',choices=['polite','plain']);a=p.parse_args()
    engine=TranslationEngine(a.model)
    def read(file):
        if not file:return None
        with Path(file).open(newline='') as stream:return stream.read()
    glossary=json.loads(read(a.glossary)) if a.glossary else None
    result=translate_document(engine,read(a.input),a.source,a.target,max_new_tokens=a.max_new_tokens,max_history_pairs=a.history,max_input_tokens=a.max_input_tokens,context=read(a.context),glossary=glossary,form=a.form)
    with Path(a.output).open('x',newline='') as stream:stream.write(result['translation'])
    Path(a.output+'.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')