Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions __tests__/lib/string-it-xunity-ai.test.ts
Original file line number Diff line number Diff line change
@@ -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<XUnityAiDeps> = {}) {
return {
readCaptured: vi.fn(async () => CAPTURED),
write: vi.fn(async () => 'C:/game/BepInEx/Translation/nl/Text/Game.txt'),
...over,
};
}

const NL: Record<string, string> = { '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') });
});
});
55 changes: 54 additions & 1 deletion components/game-detail-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 ?? '');
Expand All @@ -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') }]);
Expand Down
90 changes: 90 additions & 0 deletions docs/METODI-DI-TRADUZIONE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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="<file1>;<file2>;…" \
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
Expand Down
6 changes: 6 additions & 0 deletions lib/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 6 additions & 0 deletions lib/i18n/locales/el.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 6 additions & 0 deletions lib/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 6 additions & 0 deletions lib/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading