aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/regen.py
blob: 4158d129400e69b1aca5e0cd8770f8aa3e385b09 (plain)
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
45
46
# -*- coding: utf-8 -*-
"""Regenerates specific segments trying several seeds and keeping the best."""
import json, os, subprocess, sys, shutil
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from narration import SCRIPTS
from gen_audio import synth_safe, transcribe, dur, ROOT
from verify import norm
from difflib import SequenceMatcher

TRIES = 5


def main(name, idxs):
    outdir = os.path.join(ROOT, "audio", name)
    work = os.path.join(ROOT, "tmp", name + "_rg")
    os.makedirs(work, exist_ok=True)
    data = json.load(open(os.path.join(outdir, "segments.json"), encoding="utf-8"))
    segs = SCRIPTS[name]["segments"]

    for i in idxs:
        text = segs[i][0]
        cands = []
        for k in range(TRIES):
            c = os.path.join(work, f"{i:02d}_{k}.wav")
            synth_safe(text, c, 4242 + 977 * k, f"[{name}] {i:02d}")
            cands.append(c)
        tr = transcribe(cands, work)
        scored = sorted(((SequenceMatcher(None, norm(text, False),
                                          norm(tr[c], False)).ratio(), c) for c in cands),
                        reverse=True)
        for r, c in scored:
            print(f"  {i:02d} seed{cands.index(c)} r={r:.2f} {dur(c):.2f}s | {tr[c][:70]}")
        best_r, best = scored[0]
        shutil.copy(best, os.path.join(outdir, f"{i:02d}.wav"))
        data["segments"][i].update(tts=text, sub=segs[i][1],
                                   dur=round(dur(best), 3), score=round(best_r, 3))
        print(f"  -> {i:02d} elegido r={best_r:.2f}\n")

    data["total_audio"] = round(sum(s["dur"] for s in data["segments"]), 2)
    json.dump(data, open(os.path.join(outdir, "segments.json"), "w", encoding="utf-8"),
              ensure_ascii=False, indent=2)
    print(f"[{name}] actualizado, audio={data['total_audio']}s")


if __name__ == "__main__":
    main(sys.argv[1], [int(x) for x in sys.argv[2:]])