diff --git a/__tests__/lib/string-it-xunity-ai.test.ts b/__tests__/lib/string-it-xunity-ai.test.ts new file mode 100644 index 000000000..c0ee076be --- /dev/null +++ b/__tests__/lib/string-it-xunity-ai.test.ts @@ -0,0 +1,77 @@ +import { describe, it, expect, vi } from 'vitest'; + +import { runXUnityAiTranslation, type XUnityAiDeps, type XUnityEntry } from '@/lib/string-it/xunity-ai'; + +const CAPTURED: XUnityEntry[] = [ + { original: 'New Game', translated: 'Nieuw spel', line_number: 1 }, + { original: 'Options', translated: '', line_number: 2 }, + { original: 'Quit', translated: 'Quit', line_number: 3 }, + { original: 'New Game', translated: 'Nieuw spel', line_number: 4 }, + { original: ' ', translated: '', line_number: 5 }, +]; + +function deps(over: Partial = {}) { + return { + readCaptured: vi.fn(async () => CAPTURED), + write: vi.fn(async () => 'C:/game/BepInEx/Translation/nl/Text/Game.txt'), + ...over, + }; +} + +const NL: Record = { 'New Game': 'Nieuw spel (AI)', Options: 'Opties', Quit: 'Afsluiten' }; +const translateAll = async (texts: string[]) => texts.map(t => NL[t] ?? null); + +const base = { gamePath: 'C:/game', lang: 'nl', gameName: 'Game' }; + +describe('ritraduzione AI dei testi catturati da XUnity', () => { + it('ritraduce ogni testo una volta, anche quelli già tradotti da Google', async () => { + const d = deps(); + const translate = vi.fn(translateAll); + const out = await runXUnityAiTranslation({ ...base, translate, deps: d }); + + expect(translate).toHaveBeenCalledWith(['New Game', 'Options', 'Quit']); + expect(d.write).toHaveBeenCalledWith('C:/game', 'nl', 'Game', [ + { original: 'New Game', translated: 'Nieuw spel (AI)', line_number: 0 }, + { original: 'Options', translated: 'Opties', line_number: 0 }, + { original: 'Quit', translated: 'Afsluiten', line_number: 0 }, + ]); + expect(out).toMatchObject({ status: 'done', changed: 3, failed: 0, total: 3 }); + }); + + it('non scrive le traduzioni mancanti o uguali all\'originale, e le conta', async () => { + const d = deps(); + const out = await runXUnityAiTranslation({ + ...base, + translate: async texts => texts.map(t => (t === 'Options' ? 'Opties' : t === 'Quit' ? ' Quit ' : null)), + deps: d, + }); + expect(d.write.mock.calls[0][3]).toEqual([{ original: 'Options', translated: 'Opties', line_number: 0 }]); + expect(out).toMatchObject({ status: 'done', changed: 1, failed: 2, total: 3 }); + }); + + it('senza nemmeno una traduzione non tocca il gioco', async () => { + const d = deps(); + const out = await runXUnityAiTranslation({ ...base, translate: async texts => texts.map(() => null), deps: d }); + expect(out.status).toBe('failed'); + expect(d.write).not.toHaveBeenCalled(); + }); + + it('senza testi catturati, o senza file, chiede di giocare prima', async () => { + const translate = vi.fn(translateAll); + expect(await runXUnityAiTranslation({ ...base, translate, deps: deps({ readCaptured: async () => [] }) })) + .toEqual({ status: 'no-captures' }); + expect(await runXUnityAiTranslation({ + ...base, translate, deps: deps({ readCaptured: async () => { throw new Error('File traduzioni non trovato'); } }), + })).toEqual({ status: 'no-captures' }); + expect(translate).not.toHaveBeenCalled(); + }); + + it('un errore della traduzione o della scrittura è un fallimento, non un successo', async () => { + expect(await runXUnityAiTranslation({ + ...base, translate: async () => { throw new Error('rate limit'); }, deps: deps(), + })).toMatchObject({ status: 'failed', reason: expect.stringContaining('rate limit') }); + expect(await runXUnityAiTranslation({ + ...base, translate: translateAll, deps: deps({ write: async () => { throw new Error('disco pieno'); } }), + })).toMatchObject({ status: 'failed', reason: expect.stringContaining('disco pieno') }); + }); +}); diff --git a/components/game-detail-client.tsx b/components/game-detail-client.tsx index 08fc20d23..e6b839ecb 100644 --- a/components/game-detail-client.tsx +++ b/components/game-detail-client.tsx @@ -34,6 +34,7 @@ import { GameMakerTranslator } from '@/components/gamemaker-translator'; import { clientLogger } from '@/lib/client-logger'; import { translateWithFallback, translateWithFallbackBatched, getChainFailureSince } from '@/lib/ai/ai-translate-direct'; import { runUnityStaticTranslation } from '@/lib/string-it/unity-static'; +import { runXUnityAiTranslation } from '@/lib/string-it/xunity-ai'; import { projectService } from '@/lib/services/translation-projects'; import { gamePathKey } from '@/lib/game-path'; import { runHendrixTranslation } from '@/lib/hendrix-translate'; @@ -2887,6 +2888,58 @@ export default function GameDetailPage() { clientLogger.info(`[StringIt] metodo statico Unity ${outcome.status}: ${outcome.reason}`); toast.info(t('stringItPlan.unityStaticFallback').replace('{reason}', outcome.reason.slice(0, 160))); } + // Secondo passo di XUnity: se è già installato per questa lingua, i + // testi che ha catturato giocando (tradotti da Google) si ritraducono + // con la catena AI dell'app, in un file che XUnity preferisce al suo. + // Stessa lingua e stesso nome file di handleInstallUnityPatch e di + // «Migliora con AI», così i tre passi parlano dello stesso file. + const xuLang = targetLang || language || 'it'; + const xuGameName = game.title || game.name || 'Game'; + const xuStatus = await invoke<{ bepinex_installed: boolean; translation_dir_exists: boolean; captured_strings: number }>( + 'get_translation_status', { gamePath: game.installPath, lang: xuLang, gameName: xuGameName }, + ).catch(() => null); + if (xuStatus?.bepinex_installed && xuStatus.translation_dir_exists) { + const stepLabel = `🧠 ${t('stringItPlan.xunityAiStep')}`; + setAutoTranslateSteps([{ label: stepLabel, status: 'running' }]); + const outcome = await runXUnityAiTranslation({ + gamePath: game.installPath, + lang: xuLang, + gameName: xuGameName, + translate: async texts => { + const res = await translateWithFallbackBatched( + { texts, targetLanguage: tgt, sourceLanguage: 'en', gameId: game.id || game.appid?.toString() || gameId }, + 20, + (done, total) => setAutoTranslateSteps([{ + label: stepLabel, status: 'running', + detail: t('stringItPlan.unityStaticTranslating').replace('{done}', String(done)).replace('{total}', String(total)), + }]), + ); + return res.success ? res.translations : texts.map(() => null); + }, + }); + if (outcome.status === 'done') { + const done = t('stringItPlan.xunityAiDone').replace('{changed}', String(outcome.changed)); + const detail = outcome.failed > 0 + ? `${done} ${t('stringItPlan.xunityAiFailedPart').replace('{failed}', String(outcome.failed))}` + : done; + setAutoTranslateSteps([{ label: stepLabel, status: 'done', detail }]); + toast.success(done, { description: detail === done ? undefined : detail, duration: 20000 }); + void activityHistory.trackPatch(game.name || game.title || '', game.appid?.toString(), detail); + } else if (outcome.status === 'no-captures') { + const msg = t('stringItPlan.xunityAiNoCaptures'); + setAutoTranslateSteps([{ label: stepLabel, status: 'done', detail: msg }]); + toast.info(msg, { duration: 20000 }); + } else { + const msg = t('stringItPlan.xunityAiFailed').replace('{reason}', outcome.reason.slice(0, 160)); + setAutoTranslateSteps([{ label: stepLabel, status: 'error', detail: msg }]); + setAutoTranslateError(msg); + toast.error(msg); + } + setAutoTranslateBusy(false); + setAutoTranslateProgress(''); + autoTranslateRunningRef.current = false; + return; + } // Anti-cheat: XUnity inietta un loader nel gioco, quindi non si installa. if (findMethod(translationPlanRef.current, 'unity-xunity')?.blocked_by) { const blockedMsg = t('stringItPlan.injectionBlocked').replace('{name}', translationPlanRef.current?.anti_cheat ?? ''); @@ -2901,7 +2954,7 @@ export default function GameDetailPage() { try { const ok = await handleInstallUnityPatch(); if (ok) { - setAutoTranslateSteps([{ label: `🩹 ${t('heroJob.unityRouteStep')}`, status: 'done', detail: t('heroJob.unityRouteDone') }]); + setAutoTranslateSteps([{ label: `🩹 ${t('heroJob.unityRouteStep')}`, status: 'done', detail: `${t('heroJob.unityRouteDone')} ${t('stringItPlan.xunityAiNext')}` }]); toast.success(t('heroJob.unityRouteDone')); } else { setAutoTranslateSteps([{ label: `🩹 ${t('heroJob.unityRouteStep')}`, status: 'error', detail: t('heroJob.unityRouteFail') }]); diff --git a/docs/METODI-DI-TRADUZIONE.md b/docs/METODI-DI-TRADUZIONE.md index f114f2b1c..681021fb4 100644 --- a/docs/METODI-DI-TRADUZIONE.md +++ b/docs/METODI-DI-TRADUZIONE.md @@ -895,6 +895,96 @@ lingue da un'altra fonte e per Lost Host Demo diceva «Manca italiano». `components/game-detail-client.tsx`; `translation_plan.rs` mette `unity-loc-tables` prima di `unity-xunity`. +### XUnity con la catena AI dell'app: String it in due passi (25/11/2026) + +**Il fatto.** Sui giochi Unity senza tabelle di localizzazione String it +installa BepInEx + XUnity, e XUnity traduce con **Google**, non con la catena +AI dell'app (niente memoria, glossario, profilo). Ora il pulsante lavora in due +passi: + +1. **Primo clic**: installa XUnity come prima. Si gioca un po': XUnity cattura + i testi che il gioco mostra e li traduce con Google in + `BepInEx/Translation/{lang}/Text/_AutoGeneratedTranslations.txt`. +2. **Secondo clic** sullo stesso gioco e lingua: XUnity c'è già, quindi non si + reinstalla nulla. Si leggono **tutti** i testi catturati, si ritraducono a + blocchi con la catena AI e si scrivono in `{lang}/Text/{Gioco}.txt`. XUnity + lo preferisce al suo file: dal README, l'OutputFile «will always have the + lowest priority when reading translations». Un testo che l'AI non traduce + resta con la traduzione di Google. + +Al secondo clic senza testi catturati il pulsante dice di giocare prima. Una +lingua diversa da quella installata (cartella `{lang}` assente) reinstalla, +come prima. + +**Perché non il ponte dal vivo.** `xunity_bridge.rs` fa rispondere l'app a +XUnity mentre si gioca (`Endpoint=CustomTranslate`), ma oggi solo con Ollama. +Collegarlo alla catena AI avrebbe un difetto di fondo. XUnity manda **una +richiesta alla volta, un testo per richiesta** (README: «never send out more +than 1 request at a time»; `CustomTranslateEndpoint.cs` non ha batching), quindi +una schermata con 20 scritte aspetta 20 risposte AI in fila. Inoltre XUnity si +spegne dopo cinque risposte vuote di fila, e un fornitore gratuito che limita le +richieste ci arriva presto. In due passi l'AI lavora a blocchi da 20 e l'app non +deve restare aperta mentre si gioca. + +**Perché non leggere i testi dai file prima di giocare.** Mouthwashing tiene i +dialoghi in `Mouthwashing_Data/Languages/*.dat`, caricati dal gioco mentre +gira: nelle scene non ci sono. I testi veri li vede solo XUnity. + +**Il formato dei file XUnity, che prima leggevamo male.** Dal sorgente +(`TextHelper.Encode`, `TextTranslationCache.ReadTranslationLineAndDecode`): `\` +→ `\\`, `=` → `\=`, a capo → `\n` / `\r`, `//` → `\/\/`. La riga si divide al +primo `=` non preceduto da `\`, un secondo `=` libero la scarta, un `//` libero +apre un commento. Un escape sconosciuto resta com'è (`\/` resta `\/`). +`read_captured_translations` tagliava al primo `=` qualunque e passava all'AI il +testo ancora codificato (`Line one\nLine two` con il backslash vero), e +`write_translation_file` scriveva senza codificare: un a capo nella traduzione +spezzava la riga. Ora entrambi usano `xunity_decode_line` / `xunity_encode`. + +**Misura.** Sola lettura, su tutti i file di cattura XUnity rimasti sul disco +(11/2026): + +```bash +cd src-tauri && GS_XUNITY_FILES=";;…" \ + cargo test --bin gamestringer real_xunity_files -- --ignored --nocapture +``` + +| File | Righe | Con escape | Chiavi su più righe | Lette | Riscritte identiche | +|---|---|---|---|---|---| +| Fran Bow (`it`) | 11.599 | 561 | 4 | 11.599 | 11.599 | +| The Seance of Blake Manor | 179 | 23 | 8 | 179 | 179 | +| Blue Prince (`it`) | 142 | 29 | 24 | 142 | 142 | +| Mouthwashing (`it`) | 223 | 8 | 7 | 223 | 223 | +| Restory (`it`) | 135 | 16 | 1 | 135 | 135 | +| Uncanny Tales The Watcher (DEMO) | 31 | 6 | 1 | 31 | 31 | +| 9 Childs St | 21 | 3 | 1 | 21 | 21 | + +12.330 righe in tutto, nessuna scartata, tutte riscritte byte per byte. 46 +testi stanno su più righe: con la lettura vecchia arrivavano all'AI con `\n` +letterali. + +**Cosa NON è provato.** + +- Il percorso intero dal pulsante (due clic, AI vera) e che **in gioco** + compaia il testo del nostro file al posto di quello di Google. La priorità + viene dal README di XUnity, non da una prova. +- Giochi IL2CPP (BepInEx 6): stessa cartella `Translation`, non provato. + +**Trappole.** + +1. **«Migliora con AI» non sostituiva Google.** Ritraduceva solo i testi + rimasti uguali all'originale, quindi quelli già tradotti da Google + restavano di Google. Il secondo passo di String it ritraduce tutto. Il + pulsante «Migliora con AI» fa ancora come prima. +2. **Un file di cattura può avere valori vuoti.** In quello di Fran Bow ci + sono righe `testo=` senza traduzione (XUnity senza endpoint cattura e + basta). Si leggono solo le chiavi, quindi vanno bene lo stesso. + +**Nel codice.** `src-tauri/src/commands/unity_patcher.rs` — `xunity_encode`, +`xunity_decode_line`, `read_captured_translations`, `write_translation_file`, +test `real_xunity_files_round_trip`; `lib/string-it/xunity-ai.ts` — +`runXUnityAiTranslation`; ramo Unity di `startAutoTranslate` in +`components/game-detail-client.tsx`. + ## GameMaker ### Un `%` a metà frase è un codice anche se il controllo non lo conta diff --git a/lib/i18n/locales/de.json b/lib/i18n/locales/de.json index 98f3b5c8c..31f954c7e 100644 --- a/lib/i18n/locales/de.json +++ b/lib/i18n/locales/de.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "Die Spieldateien lassen sich nicht direkt übersetzen ({reason}). Weiter mit XUnity.", "unityStaticHint": "Lokalisierungstabellen gefunden: Die Texte werden in die Spieldateien geschrieben. XUnity nur, wenn das nicht reicht.", "alreadyHasLanguage": "Das Spiel hat {lang} bereits unter seinen Sprachen: Wähle sie in den Spieloptionen. Es gibt nichts zu übersetzen.", + "xunityAiStep": "Von XUnity erfasste Texte, mit deiner KI neu übersetzt", + "xunityAiDone": "{changed} Texte mit deiner KI neu übersetzt. Starte das Spiel neu, um sie zu sehen.", + "xunityAiFailedPart": "{failed} nicht übersetzte Texte bleiben so, wie XUnity sie übersetzt hatte.", + "xunityAiNoCaptures": "XUnity ist installiert, hat aber noch keine Texte erfasst. Starte das Spiel, spiele eine Weile, schließe es und drücke erneut String it.", + "xunityAiFailed": "Deine KI hat die erfassten Texte nicht übersetzt ({reason}). Das Spiel bleibt unverändert.", + "xunityAiNext": "Nachdem du eine Weile gespielt hast, schließe das Spiel und drücke erneut String it: Die erfassten Texte werden mit deiner KI neu übersetzt.", "ocrOffer": "Nächste Methode: Bildschirm-OCR", "ocrOfferDesc": "Ins Spiel konnte nichts geschrieben werden. Die OCR liest den Bildschirm und funktioniert mit jeder Engine.", "openOcr": "OCR öffnen", diff --git a/lib/i18n/locales/el.json b/lib/i18n/locales/el.json index c949229d0..c63870949 100644 --- a/lib/i18n/locales/el.json +++ b/lib/i18n/locales/el.json @@ -7266,6 +7266,12 @@ "unityStaticFallback": "Τα αρχεία του παιχνιδιού δεν μεταφράζονται απευθείας ({reason}). Συνέχεια με XUnity.", "unityStaticHint": "Βρέθηκαν πίνακες τοπικοποίησης: τα κείμενα γράφονται στα αρχεία του παιχνιδιού. XUnity μόνο αν δεν αρκεί.", "alreadyHasLanguage": "Το παιχνίδι έχει ήδη {lang} στις γλώσσες του: επιλέξτε τη στις ρυθμίσεις του παιχνιδιού. Δεν υπάρχει τίποτα για μετάφραση.", + "xunityAiStep": "Κείμενα που κατέγραψε το XUnity, επαναμεταφρασμένα με το AI σου", + "xunityAiDone": "{changed} κείμενα επαναμεταφράστηκαν με το AI σου. Επανεκκίνησε το παιχνίδι για να τα δεις.", + "xunityAiFailedPart": "{failed} μη μεταφρασμένα κείμενα μένουν όπως τα είχε μεταφράσει το XUnity.", + "xunityAiNoCaptures": "Το XUnity είναι εγκατεστημένο αλλά δεν έχει καταγράψει ακόμη κείμενα. Ξεκίνησε το παιχνίδι, παίξε λίγο, κλείσ' το και πάτησε ξανά String it.", + "xunityAiFailed": "Το AI σου δεν μετέφρασε τα καταγεγραμμένα κείμενα ({reason}). Το παιχνίδι μένει όπως ήταν.", + "xunityAiNext": "Αφού παίξεις λίγο, κλείσε το παιχνίδι και πάτησε ξανά String it: τα καταγεγραμμένα κείμενα θα επαναμεταφραστούν με το AI σου.", "ocrOffer": "Επόμενη μέθοδος: OCR οθόνης", "ocrOfferDesc": "Δεν ήταν δυνατή η εγγραφή στο παιχνίδι. Το OCR διαβάζει την οθόνη και λειτουργεί με κάθε μηχανή.", "openOcr": "Άνοιγμα OCR", diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index d74c63bc8..3c03320d9 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "The game files cannot be translated directly ({reason}). Moving on to XUnity.", "unityStaticHint": "Localization tables found: texts are written into the game files. XUnity only if that is not enough.", "alreadyHasLanguage": "The game already has {lang} among its languages: pick it in the game options. There is nothing to translate.", + "xunityAiStep": "Texts captured by XUnity, retranslated with your AI", + "xunityAiDone": "{changed} texts retranslated with your AI. Restart the game to see them.", + "xunityAiFailedPart": "{failed} untranslated texts stay as XUnity had translated them.", + "xunityAiNoCaptures": "XUnity is installed but has not captured any text yet. Launch the game, play for a while, close it and press String it again.", + "xunityAiFailed": "Your AI did not translate the captured texts ({reason}). The game is unchanged.", + "xunityAiNext": "After playing for a while, close the game and press String it again: the captured texts will be retranslated with your AI.", "ocrOffer": "Next method: on-screen OCR", "ocrOfferDesc": "Nothing could be written into the game. OCR reads the screen and works with any engine.", "openOcr": "Open OCR", diff --git a/lib/i18n/locales/es.json b/lib/i18n/locales/es.json index a483f9579..ee29b79dc 100644 --- a/lib/i18n/locales/es.json +++ b/lib/i18n/locales/es.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "Los archivos del juego no se pueden traducir directamente ({reason}). Paso a XUnity.", "unityStaticHint": "Tablas de localización encontradas: los textos se escriben en los archivos del juego. XUnity solo si no basta.", "alreadyHasLanguage": "El juego ya tiene {lang} entre sus idiomas: elígelo en las opciones del juego. No hay nada que traducir.", + "xunityAiStep": "Textos capturados por XUnity, retraducidos con tu IA", + "xunityAiDone": "{changed} textos retraducidos con tu IA. Reinicia el juego para verlos.", + "xunityAiFailedPart": "{failed} textos sin traducir se quedan como los había traducido XUnity.", + "xunityAiNoCaptures": "XUnity está instalado pero aún no ha capturado textos. Inicia el juego, juega un rato, ciérralo y vuelve a pulsar String it.", + "xunityAiFailed": "Tu IA no tradujo los textos capturados ({reason}). El juego queda como estaba.", + "xunityAiNext": "Después de jugar un rato, cierra el juego y vuelve a pulsar String it: los textos capturados se retraducirán con tu IA.", "ocrOffer": "Siguiente método: OCR en pantalla", "ocrOfferDesc": "No se pudo escribir nada en el juego. El OCR lee la pantalla y funciona con cualquier motor.", "openOcr": "Abrir OCR", diff --git a/lib/i18n/locales/fr.json b/lib/i18n/locales/fr.json index f5472e870..3c2f3ebb0 100644 --- a/lib/i18n/locales/fr.json +++ b/lib/i18n/locales/fr.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "Les fichiers du jeu ne peuvent pas être traduits directement ({reason}). Passage à XUnity.", "unityStaticHint": "Tables de localisation trouvées : les textes sont écrits dans les fichiers du jeu. XUnity seulement si cela ne suffit pas.", "alreadyHasLanguage": "Le jeu a déjà {lang} parmi ses langues : choisissez-la dans les options du jeu. Il n'y a rien à traduire.", + "xunityAiStep": "Textes capturés par XUnity, retraduits avec ton IA", + "xunityAiDone": "{changed} textes retraduits avec ton IA. Relance le jeu pour les voir.", + "xunityAiFailedPart": "{failed} textes non traduits restent tels que XUnity les avait traduits.", + "xunityAiNoCaptures": "XUnity est installé mais n'a encore capturé aucun texte. Lance le jeu, joue un moment, ferme-le et appuie de nouveau sur String it.", + "xunityAiFailed": "Ton IA n'a pas traduit les textes capturés ({reason}). Le jeu reste inchangé.", + "xunityAiNext": "Après avoir joué un moment, ferme le jeu et appuie de nouveau sur String it : les textes capturés seront retraduits avec ton IA.", "ocrOffer": "Méthode suivante : OCR à l'écran", "ocrOfferDesc": "Rien n'a pu être écrit dans le jeu. L'OCR lit l'écran et fonctionne avec n'importe quel moteur.", "openOcr": "Ouvrir l'OCR", diff --git a/lib/i18n/locales/it.json b/lib/i18n/locales/it.json index 324a156ef..fd148043c 100644 --- a/lib/i18n/locales/it.json +++ b/lib/i18n/locales/it.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "I file del gioco non si possono tradurre direttamente ({reason}). Passo a XUnity.", "unityStaticHint": "Tabelle di localizzazione trovate: i testi si scrivono nei file del gioco. XUnity solo se non basta.", "alreadyHasLanguage": "Il gioco ha già {lang} fra le sue lingue: sceglila nelle opzioni del gioco. Non c'è nulla da tradurre.", + "xunityAiStep": "Testi catturati da XUnity, ritradotti con la tua AI", + "xunityAiDone": "{changed} testi ritradotti con la tua AI. Riavvia il gioco per vederli.", + "xunityAiFailedPart": "{failed} testi non tradotti restano come li aveva tradotti XUnity.", + "xunityAiNoCaptures": "XUnity è installato ma non ha ancora catturato testi. Avvia il gioco, gioca un po', chiudilo e premi di nuovo String it.", + "xunityAiFailed": "La tua AI non ha tradotto i testi catturati ({reason}). Il gioco resta com'era.", + "xunityAiNext": "Dopo aver giocato un po', chiudi il gioco e premi di nuovo String it: i testi catturati verranno ritradotti con la tua AI.", "ocrOffer": "Metodo successivo: OCR a schermo", "ocrOfferDesc": "Nel gioco non è stato possibile scrivere nulla. L'OCR legge lo schermo e funziona con qualsiasi motore.", "openOcr": "Apri OCR", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index e048407f4..9183023de 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "ゲームのファイルは直接翻訳できません({reason})。XUnity に切り替えます。", "unityStaticHint": "ローカライズ表が見つかりました。テキストはゲームのファイルに書き込みます。足りない場合のみ XUnity を使います。", "alreadyHasLanguage": "このゲームにはすでに {lang} があります。ゲームのオプションで選んでください。翻訳するものはありません。", + "xunityAiStep": "XUnity が取得したテキストを AI で再翻訳", + "xunityAiDone": "{changed} 件のテキストを AI で再翻訳しました。ゲームを再起動すると反映されます。", + "xunityAiFailedPart": "翻訳できなかった {failed} 件は XUnity の翻訳のままです。", + "xunityAiNoCaptures": "XUnity はインストール済みですが、まだテキストを取得していません。ゲームを起動してしばらく遊び、終了してからもう一度 String it を押してください。", + "xunityAiFailed": "AI が取得したテキストを翻訳できませんでした ({reason})。ゲームは変更されていません。", + "xunityAiNext": "しばらく遊んだらゲームを終了し、もう一度 String it を押してください。取得したテキストが AI で再翻訳されます。", "ocrOffer": "次の方法:画面OCR", "ocrOfferDesc": "ゲームには何も書き込めませんでした。OCRは画面を読み取るため、どのエンジンでも使えます。", "openOcr": "OCRを開く", diff --git a/lib/i18n/locales/ko.json b/lib/i18n/locales/ko.json index bc7fe8f3d..647a917e2 100644 --- a/lib/i18n/locales/ko.json +++ b/lib/i18n/locales/ko.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "게임 파일을 직접 번역할 수 없습니다({reason}). XUnity로 넘어갑니다.", "unityStaticHint": "현지화 표를 찾았습니다. 텍스트를 게임 파일에 기록합니다. 부족할 때만 XUnity를 사용합니다.", "alreadyHasLanguage": "이 게임에는 이미 {lang}이(가) 있습니다. 게임 옵션에서 선택하세요. 번역할 내용이 없습니다.", + "xunityAiStep": "XUnity가 수집한 텍스트를 AI로 재번역", + "xunityAiDone": "{changed}개 텍스트를 AI로 재번역했습니다. 게임을 다시 시작하면 보입니다.", + "xunityAiFailedPart": "번역되지 않은 {failed}개 텍스트는 XUnity 번역 그대로 남습니다.", + "xunityAiNoCaptures": "XUnity가 설치되어 있지만 아직 수집한 텍스트가 없습니다. 게임을 실행해 잠시 플레이한 뒤 종료하고 String it을 다시 누르세요.", + "xunityAiFailed": "AI가 수집된 텍스트를 번역하지 못했습니다 ({reason}). 게임은 변경되지 않았습니다.", + "xunityAiNext": "잠시 플레이한 뒤 게임을 종료하고 String it을 다시 누르세요. 수집된 텍스트가 AI로 재번역됩니다.", "ocrOffer": "다음 방법: 화면 OCR", "ocrOfferDesc": "게임에 아무것도 쓸 수 없었습니다. OCR은 화면을 읽으므로 어떤 엔진에서도 동작합니다.", "openOcr": "OCR 열기", diff --git a/lib/i18n/locales/pl.json b/lib/i18n/locales/pl.json index cb3609ac2..25d7a0d1c 100644 --- a/lib/i18n/locales/pl.json +++ b/lib/i18n/locales/pl.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "Plików gry nie da się przetłumaczyć bezpośrednio ({reason}). Przechodzę do XUnity.", "unityStaticHint": "Znaleziono tabele lokalizacji: teksty są zapisywane w plikach gry. XUnity tylko wtedy, gdy to nie wystarczy.", "alreadyHasLanguage": "Gra ma już {lang} wśród swoich języków: wybierz go w opcjach gry. Nie ma nic do tłumaczenia.", + "xunityAiStep": "Teksty przechwycone przez XUnity, przetłumaczone ponownie twoją AI", + "xunityAiDone": "Przetłumaczono ponownie {changed} tekstów twoją AI. Uruchom grę ponownie, aby je zobaczyć.", + "xunityAiFailedPart": "{failed} nieprzetłumaczonych tekstów zostaje tak, jak przetłumaczyło je XUnity.", + "xunityAiNoCaptures": "XUnity jest zainstalowane, ale nie przechwyciło jeszcze tekstów. Uruchom grę, pograj chwilę, zamknij ją i ponownie naciśnij String it.", + "xunityAiFailed": "Twoja AI nie przetłumaczyła przechwyconych tekstów ({reason}). Gra pozostaje bez zmian.", + "xunityAiNext": "Po chwili gry zamknij ją i ponownie naciśnij String it: przechwycone teksty zostaną przetłumaczone ponownie twoją AI.", "ocrOffer": "Następna metoda: OCR ekranu", "ocrOfferDesc": "Nie udało się niczego zapisać w grze. OCR czyta ekran i działa z każdym silnikiem.", "openOcr": "Otwórz OCR", diff --git a/lib/i18n/locales/pt.json b/lib/i18n/locales/pt.json index 365bff37e..1cffc5574 100644 --- a/lib/i18n/locales/pt.json +++ b/lib/i18n/locales/pt.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "Os ficheiros do jogo não podem ser traduzidos diretamente ({reason}). A passar para o XUnity.", "unityStaticHint": "Tabelas de localização encontradas: os textos são escritos nos arquivos do jogo. XUnity só se não bastar.", "alreadyHasLanguage": "O jogo já tem {lang} entre os seus idiomas: escolha-o nas opções do jogo. Não há nada para traduzir.", + "xunityAiStep": "Textos capturados pelo XUnity, retraduzidos com a tua IA", + "xunityAiDone": "{changed} textos retraduzidos com a tua IA. Reinicia o jogo para os veres.", + "xunityAiFailedPart": "{failed} textos não traduzidos ficam como o XUnity os tinha traduzido.", + "xunityAiNoCaptures": "O XUnity está instalado mas ainda não capturou textos. Inicia o jogo, joga um pouco, fecha-o e prime String it novamente.", + "xunityAiFailed": "A tua IA não traduziu os textos capturados ({reason}). O jogo fica como estava.", + "xunityAiNext": "Depois de jogar um pouco, fecha o jogo e prime String it novamente: os textos capturados serão retraduzidos com a tua IA.", "ocrOffer": "Método seguinte: OCR no ecrã", "ocrOfferDesc": "Não foi possível escrever nada no jogo. O OCR lê o ecrã e funciona com qualquer motor.", "openOcr": "Abrir OCR", diff --git a/lib/i18n/locales/ru.json b/lib/i18n/locales/ru.json index 3d75943ca..a2424ade7 100644 --- a/lib/i18n/locales/ru.json +++ b/lib/i18n/locales/ru.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "Файлы игры нельзя перевести напрямую ({reason}). Перехожу к XUnity.", "unityStaticHint": "Найдены таблицы локализации: тексты записываются в файлы игры. XUnity — только если этого недостаточно.", "alreadyHasLanguage": "В игре уже есть {lang} среди языков: выберите его в настройках игры. Переводить нечего.", + "xunityAiStep": "Тексты, собранные XUnity, переведены заново твоим ИИ", + "xunityAiDone": "Переведено заново твоим ИИ: {changed} текстов. Перезапусти игру, чтобы их увидеть.", + "xunityAiFailedPart": "Непереведённые тексты ({failed}) остаются в переводе XUnity.", + "xunityAiNoCaptures": "XUnity установлен, но ещё не собрал тексты. Запусти игру, поиграй немного, закрой её и снова нажми String it.", + "xunityAiFailed": "Твой ИИ не перевёл собранные тексты ({reason}). Игра не изменилась.", + "xunityAiNext": "Поиграв немного, закрой игру и снова нажми String it: собранные тексты будут переведены заново твоим ИИ.", "ocrOffer": "Следующий метод: экранный OCR", "ocrOfferDesc": "В игру ничего не удалось записать. OCR читает экран и работает с любым движком.", "openOcr": "Открыть OCR", diff --git a/lib/i18n/locales/zh.json b/lib/i18n/locales/zh.json index 1ff72e720..c0ca54d41 100644 --- a/lib/i18n/locales/zh.json +++ b/lib/i18n/locales/zh.json @@ -7291,6 +7291,12 @@ "unityStaticFallback": "无法直接翻译游戏文件({reason})。改用 XUnity。", "unityStaticHint": "已找到本地化表:文本将写入游戏文件。仅在不够时才使用 XUnity。", "alreadyHasLanguage": "游戏已包含 {lang}:请在游戏选项中选择它。没有需要翻译的内容。", + "xunityAiStep": "XUnity 捕获的文本,用你的 AI 重新翻译", + "xunityAiDone": "已用你的 AI 重新翻译 {changed} 条文本。重启游戏即可看到。", + "xunityAiFailedPart": "{failed} 条未翻译的文本保留 XUnity 的翻译。", + "xunityAiNoCaptures": "XUnity 已安装,但还没有捕获到文本。启动游戏玩一会儿,关闭后再次点击 String it。", + "xunityAiFailed": "你的 AI 未能翻译捕获的文本({reason})。游戏保持不变。", + "xunityAiNext": "玩一会儿后关闭游戏,再次点击 String it:捕获的文本将用你的 AI 重新翻译。", "ocrOffer": "下一种方法:屏幕 OCR", "ocrOfferDesc": "无法向游戏写入任何内容。OCR 读取屏幕,适用于任何引擎。", "openOcr": "打开 OCR", diff --git a/lib/string-it/xunity-ai.ts b/lib/string-it/xunity-ai.ts new file mode 100644 index 000000000..2d5cd0c8d --- /dev/null +++ b/lib/string-it/xunity-ai.ts @@ -0,0 +1,89 @@ +/** + * Secondo passo di String it su Unity con XUnity: i testi che XUnity ha + * catturato giocando si ritraducono TUTTI con la catena AI dell'app (memoria, + * glossario, profilo), e si scrivono in un file di traduzione che XUnity + * preferisce al suo `_AutoGeneratedTranslations.txt` (quello di Google). + * + * Il lavoro sui file lo fa Rust (`read_captured_translations`, + * `write_translation_file` in unity_patcher.rs); qui ci sono l'ordine dei + * passi e le regole su cosa conta come traduzione. Le dipendenze sono + * iniettate, così la regola si prova senza Tauri né AI. + */ +import { invoke } from '@/lib/tauri-api'; + +export interface XUnityEntry { + original: string; + translated: string; + line_number: number; +} + +export type XUnityAiOutcome = + | { status: 'done'; changed: number; failed: number; total: number; path: string } + /** XUnity non ha ancora catturato niente: serve giocare prima. */ + | { status: 'no-captures' } + /** Nessun testo tradotto, o scrittura fallita: nel gioco non è cambiato nulla. */ + | { status: 'failed'; reason: string }; + +export interface XUnityAiDeps { + readCaptured: (gamePath: string, lang: string) => Promise; + write: (gamePath: string, lang: string, gameName: string, entries: XUnityEntry[]) => Promise; +} + +const tauriDeps: XUnityAiDeps = { + readCaptured: (gamePath, lang) => invoke('read_captured_translations', { gamePath, lang }), + write: (gamePath, lang, gameName, entries) => + invoke('write_translation_file', { gamePath, lang, gameName, entries }), +}; + +export interface XUnityAiOptions { + gamePath: string; + /** La lingua come la usa XUnity (`Translation/{lang}/Text`). */ + lang: string; + gameName: string; + /** Restituisce un array lungo quanto l'ingresso, con `null` dove la traduzione non è arrivata. */ + translate: (texts: string[]) => Promise<(string | null)[]>; + deps?: XUnityAiDeps; +} + +export async function runXUnityAiTranslation(options: XUnityAiOptions): Promise { + const { gamePath, lang, gameName, translate, deps = tauriDeps } = options; + + let captured: XUnityEntry[]; + try { + captured = await deps.readCaptured(gamePath, lang); + } catch { + // Il comando fallisce quando il file non c'è ancora: il gioco non è stato avviato. + return { status: 'no-captures' }; + } + + // Si ritraduce anche ciò che Google ha già tradotto: è il motivo del passo. + const texts = Array.from(new Set(captured.map(e => e.original).filter(t => t.trim() !== ''))); + if (texts.length === 0) return { status: 'no-captures' }; + + let results: (string | null)[]; + try { + results = await translate(texts); + } catch (e: unknown) { + return { status: 'failed', reason: String(e) }; + } + + // Una traduzione uguale all'originale non è una traduzione: scriverla + // coprirebbe quella di Google con l'inglese. + const entries: XUnityEntry[] = []; + texts.forEach((original, i) => { + const translated = results[i]?.trim(); + if (translated && translated !== original.trim()) { + entries.push({ original, translated, line_number: 0 }); + } + }); + if (entries.length === 0) { + return { status: 'failed', reason: `0 testi tradotti su ${texts.length}` }; + } + + try { + const path = await deps.write(gamePath, lang, gameName, entries); + return { status: 'done', changed: entries.length, failed: texts.length - entries.length, total: texts.length, path }; + } catch (e: unknown) { + return { status: 'failed', reason: String(e) }; + } +} diff --git a/src-tauri/src/commands/unity_patcher.rs b/src-tauri/src/commands/unity_patcher.rs index 2225d489d..665506f69 100644 --- a/src-tauri/src/commands/unity_patcher.rs +++ b/src-tauri/src/commands/unity_patcher.rs @@ -2853,6 +2853,88 @@ pub async fn save_xunity_translation(game_path: String, original: String, new_tr Ok(()) } +/// Codifica un testo per un file di traduzione XUnity, come `TextHelper.Encode` +/// di XUnity: `\` → `\\`, `=` → `\=`, a capo → `\n` / `\r`, e `//` → `\/\/` +/// (altrimenti XUnity lo leggerebbe come l'inizio di un commento). +pub(crate) fn xunity_encode(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 8); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '/' if chars.peek() == Some(&'/') => { + chars.next(); + out.push_str("\\/\\/"); + } + '\\' => out.push_str("\\\\"), + '=' => out.push_str("\\="), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + _ => out.push(c), + } + } + out +} + +/// Legge una riga `chiave=valore` di un file XUnity come la legge XUnity +/// (`ReadTranslationLineAndDecode`): divide al primo `=` non preceduto da `\`, +/// toglie gli escape, si ferma a un `//` non preceduto da `\` (commento). +/// Una riga con due `=` liberi, o senza `=`, per XUnity non esiste: `None`. +/// +/// Come in XUnity, un escape che non conosce resta com'è: `\/` resta `\/`. +/// Così la chiave che si rilegge qui è la stessa che XUnity tiene in memoria. +pub(crate) fn xunity_decode_line(line: &str) -> Option<(String, String)> { + let chars: Vec = line.chars().collect(); + let mut parts = vec![String::new()]; + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + let cur = parts.last_mut().expect("almeno una parte"); + if c == '\\' { + match chars.get(i + 1) { + Some('=') => cur.push('='), + Some('\\') => cur.push('\\'), + Some('n') => cur.push('\n'), + Some('r') => cur.push('\r'), + Some('u') => { + let hex: String = chars.iter().skip(i + 2).take(4).collect(); + match u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) { + Some(ch) if hex.len() == 4 => { + cur.push(ch); + i += 6; + continue; + } + _ => cur.push_str("\\u"), + } + } + Some(&other) => { + cur.push('\\'); + cur.push(other); + } + None => cur.push('\\'), + } + i += 2; + continue; + } + if c == '=' { + if parts.len() > 1 { + return None; + } + parts.push(String::new()); + } else if c == '/' && chars.get(i + 1) == Some(&'/') { + break; + } else { + cur.push(c); + } + i += 1; + } + if parts.len() != 2 { + return None; + } + let value = parts.pop().unwrap_or_default(); + let key = parts.pop().unwrap_or_default(); + Some((key, value)) +} + /// Legge le stringhe catturate da XUnity dal percorso corretto per la lingua specificata #[command] pub async fn read_captured_translations(game_path: String, lang: String) -> Result, String> { @@ -2872,17 +2954,19 @@ pub async fn read_captured_translations(game_path: String, lang: String) -> Resu let content = fs::read_to_string(&file_to_read) .map_err(|e| format!("Errore lettura: {}", e))?; + // Le righe si decodificano come le legge XUnity: un testo con un a capo + // sta su una riga sola come `\n`, e un `=` dentro il testo è `\=`. Prima si + // tagliava al primo `=` e si passava all'AI il testo ancora codificato. let entries = content.lines().enumerate() - .filter(|(_, l)| { let l = l.trim(); !l.is_empty() && !l.starts_with('#') && !l.starts_with(';') && l.contains('=') }) + .filter(|(_, l)| { let l = l.trim(); !l.is_empty() && !l.starts_with('#') && !l.starts_with(';') }) .filter_map(|(i, line)| { - let line = line.trim(); - line.find('=').map(|pos| TranslationEntry { - original: line[..pos].to_string(), - translated: line[pos + 1..].to_string(), + xunity_decode_line(line).map(|(original, translated)| TranslationEntry { + original, + translated, line_number: i + 1, }) }) - .filter(|e| !e.original.is_empty()) + .filter(|e| !e.original.trim().is_empty()) .collect(); Ok(entries) @@ -2911,9 +2995,9 @@ pub async fn write_translation_file( let mut written = 0usize; for e in &entries { if !e.original.is_empty() && !e.translated.is_empty() && e.original != e.translated { - content.push_str(&e.original); + content.push_str(&xunity_encode(&e.original)); content.push('='); - content.push_str(&e.translated); + content.push_str(&xunity_encode(&e.translated)); content.push('\n'); written += 1; } @@ -3750,6 +3834,106 @@ pub(crate) fn detect_anti_cheat_files(game_path: &str) -> (Option, Optio #[cfg(test)] mod tests { use super::*; + + #[test] + fn xunity_line_splits_at_first_unescaped_equals() { + assert_eq!( + xunity_decode_line("New Game=Nieuw spel"), + Some(("New Game".to_string(), "Nieuw spel".to_string())) + ); + assert_eq!( + xunity_decode_line(r"a\=b=c"), + Some(("a=b".to_string(), "c".to_string())) + ); + // Due `=` liberi o nessuno: XUnity scarta la riga. + assert_eq!(xunity_decode_line("a=b=c"), None); + assert_eq!(xunity_decode_line("solo testo"), None); + } + + #[test] + fn xunity_line_decodes_escapes_and_stops_at_comment() { + assert_eq!( + xunity_decode_line(r"Line one\nLine two=Riga uno\nRiga due"), + Some(("Line one\nLine two".to_string(), "Riga uno\nRiga due".to_string())) + ); + assert_eq!( + xunity_decode_line(r"C:\\dir=x"), + Some((r"C:\dir".to_string(), "x".to_string())) + ); + assert_eq!( + xunity_decode_line(r"\u00e8=e"), + Some(("è".to_string(), "e".to_string())) + ); + assert_eq!( + xunity_decode_line("Hi=Ciao // nota"), + Some(("Hi".to_string(), "Ciao ".to_string())) + ); + assert_eq!(xunity_decode_line("// commento=no"), None); + // Escape sconosciuto: resta com'è, come in XUnity. + assert_eq!( + xunity_decode_line(r"a\/\/b=x"), + Some((r"a\/\/b".to_string(), "x".to_string())) + ); + } + + #[test] + fn xunity_encode_round_trips_through_decode() { + for text in ["Play", "a=b", "Riga uno\nRiga due", "C:\\dir", "x\r\ny", "50% = metà"] { + let line = format!("{}={}", xunity_encode(text), xunity_encode(text)); + assert_eq!( + xunity_decode_line(&line), + Some((text.to_string(), text.to_string())), + "{text:?}" + ); + } + // `//` va scritto in modo che XUnity non lo prenda per un commento. + assert_eq!(xunity_encode("http://x"), r"http:\/\/x"); + assert!(xunity_decode_line(&format!("k={}", xunity_encode("a//b"))).is_some()); + } + + /// Sui file che XUnity ha scritto davvero: ogni riga si legge, e + /// riscriverla dà gli stessi byte. Sola lettura. + /// `GS_XUNITY_FILES="a.txt;b.txt" cargo test --bin gamestringer real_xunity_files -- --ignored --nocapture` + #[test] + #[ignore] + fn real_xunity_files_round_trip() { + let files = std::env::var("GS_XUNITY_FILES").expect("GS_XUNITY_FILES"); + for file in files.split(';').filter(|f| !f.trim().is_empty()) { + let content = std::fs::read_to_string(file).expect(file); + let (mut lines, mut read, mut escaped, mut multiline, mut same) = (0, 0, 0, 0, 0); + let mut dropped = Vec::new(); + for line in content.lines() { + if line.trim().is_empty() || line.trim_start().starts_with('#') { + continue; + } + lines += 1; + if line.contains('\\') { + escaped += 1; + } + match xunity_decode_line(line) { + Some((k, v)) => { + read += 1; + if k.contains('\n') { + multiline += 1; + } + if format!("{}={}", xunity_encode(&k), xunity_encode(&v)) == line { + same += 1; + } + } + None => dropped.push(line.to_string()), + } + } + println!( + "{file}: {lines} righe, {read} lette, {escaped} con escape, {multiline} chiavi su più righe, \ + {same} riscritte identiche, {} scartate", + dropped.len() + ); + for d in dropped.iter().take(5) { + println!(" scartata: {d}"); + } + assert_eq!(read + dropped.len(), lines); + } + } use tempfile::TempDir; // ========================================================================