, one per line given, '' for an empty line), `task` (settles with `result`, or the error). */ final class LyricsTranslator { public const MYMEMORY = 'https://api.mymemory.translated.net/get'; private const BLOCK = 450; public string $state = 'idle'; public float $progress = 0.0; public string $engine = ''; public string $error = ''; /** @var list */ public array $result = []; public Task $task; /** the song being translated (WinZik's) */ public string $song = ''; public string $lang = ''; private ?Process $job = null; /** @var list the lines given */ private array $lines = []; /** @var list the different lines with words, sent to MyMemory */ private array $unique = []; /** @var array line => its translation */ private array $done = []; /** @var list> the blocks left for MyMemory */ private array $blocks = []; private int $blockCount = 0; private string $from = ''; /** @var array what was translated already (from|to|line => translation): a chorus or a song played again */ private static array $cache = []; /** * @param (\Closure(list): Process)|null $runner how `claude -p` is started (tests: a fake) * @param ?string $claude Claude Code's program, null = MyMemory only */ public function __construct(private ?Http $http, private ?\Closure $runner = null, private ?string $claude = null, private string $logDir = '') { $this->task = new Task(); } public function busy(): bool { return $this->state === 'translating'; } /** @param list $lines @param string $from the language of the lyrics ('' = unknown) */ public function start(array $lines, string $from, string $to): Task { $this->task = new Task(); $this->lines = array_map(fn ($l) => trim((string)preg_replace('/\s+/u', ' ', (string)$l)), $lines); $this->from = $from; $this->lang = $to; $this->state = 'translating'; $this->progress = 0.0; $this->error = ''; $this->result = []; $this->done = []; $this->unique = array_values(array_unique(array_filter($this->lines, fn (string $l) => $l !== ''))); foreach ($this->unique as $line) { $cached = self::$cache["$from|$to|$line"] ?? null; if ($cached !== null) { $this->done[$line] = $cached; } } if ($this->unique === [] || count($this->done) === count($this->unique)) { $this->engine = $this->engine ?: 'cache'; $this->complete(); return $this->task; } if ($this->claude !== null) { $this->askClaude(); } else { $this->myMemory(); } return $this->task; } private function askClaude(): void { $this->engine = 'claude'; $numbered = []; foreach ($this->unique as $i => $line) { $numbered[] = ($i + 1) . '|' . $line; } $names = \App\Model\Language::NAMES; $to = mb_strtolower($names[$this->lang] ?? $this->lang); $from = $this->from !== '' ? ' (en ' . mb_strtolower($names[$this->from] ?? $this->from) . ')' : ''; $prompt = "Traduis en $to, ligne par ligne, les paroles de chanson ci-dessous$from (numéro|texte). Une traduction naturelle et fidèle " . "de chaque ligne, sans fusionner ni couper de lignes, sans commentaire. Réponds UNIQUEMENT avec exactement " . count($numbered) . " lignes au même format numéro|traduction, rien d'autre.\n\n" . implode("\n", $numbered); $command = [(string)$this->claude, '-p', $prompt, '--tools', '', '--strict-mcp-config']; try { $this->job = $this->runner !== null ? ($this->runner)($command) : Process::start($command, $this->logDir !== '' ? $this->logDir : sys_get_temp_dir() . '/winzik-logs'); $this->progress = 0.1; } catch (\Throwable) { $this->myMemory(); } } /** Each frame: Claude's answer. */ public function poll(): void { if ($this->job === null) { if ($this->busy() && $this->engine === 'claude' && $this->progress < 0.9) { $this->progress += 0.002; } return; } $this->job->poll(); if (!$this->job->done()) { $this->progress = min(0.9, $this->progress + 0.002); return; } $job = $this->job; $this->job = null; $texts = $job->ok() ? Transcriber::correctedLines($job->output(), count($this->unique)) : null; $job->cleanup(); if ($texts === null) { // Claude did not answer every line: the translation API instead $this->myMemory(); return; } foreach ($this->unique as $i => $line) { $this->keep($line, $texts[$i]); } $this->complete(); } private function myMemory(): void { $this->engine = 'mymemory'; if ($this->http === null) { $this->fail('pas de réseau ici'); return; } $this->blocks = []; $block = []; $size = 0; foreach ($this->unique as $line) { if (isset($this->done[$line])) { continue; } $line = mb_strcut($line, 0, self::BLOCK); if ($block !== [] && $size + strlen($line) + 1 > self::BLOCK) { $this->blocks[] = $block; [$block, $size] = [[], 0]; } $block[] = $line; $size += strlen($line) + 1; } if ($block !== []) { $this->blocks[] = $block; } $this->blockCount = max(1, count($this->blocks)); $this->nextBlock(); } private function nextBlock(): void { if ($this->state !== 'translating') { return; } $block = array_shift($this->blocks); if ($block === null) { $this->complete(); return; } $this->progress = 1 - (count($this->blocks) + 1) / ($this->blockCount + 1); $pair = ($this->from !== '' ? $this->from : 'en') . '|' . $this->lang; $url = self::MYMEMORY . '?' . http_build_query(['q' => implode("\n", $block), 'langpair' => $pair]); $this->http?->request('GET', $url, null, ['Accept' => 'application/json', 'User-Agent' => 'WinZik'], 30)->then(function (HttpResponse $r) use ($block): void { $data = $r->ok() ? $r->json() : null; if (!is_array($data) || !empty($data['quotaFinished']) || (int)($data['responseStatus'] ?? 200) === 429 || $r->status === 429) { $this->fail(is_array($data) && (!empty($data['quotaFinished']) || (int)($data['responseStatus'] ?? 0) === 429) || $r->status === 429 ? 'quota de traduction gratuite atteint pour aujourd\'hui (MyMemory) : réessayez demain' : 'le service de traduction ne répond pas (HTTP ' . $r->status . ')'); return; } if ((int)($data['responseStatus'] ?? 200) !== 200) { $this->fail('traduction refusée : ' . mb_substr((string)($data['responseDetails'] ?? ''), 0, 120)); return; } $text = html_entity_decode((string)($data['responseData']['translatedText'] ?? ''), ENT_QUOTES | ENT_HTML5, 'UTF-8'); $rows = preg_split('/\r\n|\r|\n/', trim($text)) ?: []; if (count($rows) === count($block)) { foreach ($block as $i => $line) { $this->keep($line, $rows[$i]); } } elseif (count($block) > 1) { // the lines came back merged or cut: each one on its own foreach (array_reverse($block) as $line) { array_unshift($this->blocks, [$line]); } $this->blockCount += count($block); } else { $this->keep($block[0], $text); } $this->nextBlock(); }, fn (\Throwable $e) => $this->fail('le service de traduction est injoignable')); } private function keep(string $line, string $translation): void { $translation = trim((string)preg_replace('/\s+/u', ' ', $translation)); $this->done[$line] = $translation; self::$cache["$this->from|$this->lang|$line"] = $translation; } private function complete(): void { $this->result = array_map(fn (string $l) => $l === '' ? '' : ($this->done[$l] ?? $this->done[mb_strcut($l, 0, self::BLOCK)] ?? ''), $this->lines); $this->state = 'done'; $this->progress = 1.0; $this->task->settle($this->result); } private function fail(string $why): void { $this->state = 'error'; $this->error = $why; $this->blocks = []; $this->task->settle(null, new \RuntimeException($why)); } /** Quitting: Claude ended now. */ public function stop(): void { if ($this->job !== null) { $this->job->stop(); $this->job->cleanup(); $this->job = null; } if ($this->busy()) { $this->fail('arrêté'); } } /** Tests: nothing remembered from a test before. */ public static function forgetCache(): void { self::$cache = []; } /** One line for the screens. */ public function describe(): string { return match ($this->state) { 'translating' => ($this->engine === 'claude' ? 'Claude Code traduit les paroles' : 'Traduction des paroles') . '... ' . (int)round($this->progress * 100) . ' %', 'done' => 'Paroles traduites' . ($this->engine === 'claude' ? ' (Claude)' : ($this->engine === 'mymemory' ? ' (MyMemory)' : '')), 'error' => 'Traduction impossible : ' . $this->error, default => '', }; } }