Skip to content
Closed
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
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ include __init__.py README.zh-CN.md
include NOTICE THIRD_PARTY_NOTICES.md CONTRIBUTING.md SECURITY.md CITATION.cff
recursive-include example_workflows *.json
recursive-include web *.js *.css
recursive-include web/locales *.json
include web/vendor/three/LICENSE
include web/assets/*.svg web/assets/*.png web/assets/*.webp
recursive-include web/assets/image *.webp
Expand Down
48 changes: 48 additions & 0 deletions docs/I18N.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Frontend internationalization (incremental migration)

FreeVideo historically embeds pairs of English and Chinese strings directly in
JavaScript. This change proposes a dependency-free catalog architecture that
keeps those existing translations working during migration.

## Locale selection
Use Settings > Appearance > Interface language, or the existing
`freevideo_lang` query parameter: `en`, `zh` or `pt-BR`. The explicit
selection takes priority over the browser locale. Unsupported locales fall back
to English. Changing the setting reloads the UI using the existing FreeVideo
mechanism; it does not restart the server.

## Adding UI text

1. Add a stable, contextual key to `web/locales/en.json`, `zh.json` and
`pt-BR.json`. Keep the same keys across the catalogs.
2. Import `translateKey` from `web/i18n.js`. For example:
```js
import { translateKey } from './i18n.js';
const label = translateKey('ui.generate_video');
const eta = translateKey('progress.estimate_minutes', undefined, {minutes: 18});
```
3. Run `node scripts/build_locales.mjs` to regenerate the bundled ES module.
The generated module is checked in to avoid runtime JSON requests or
dependency on import attributes in older browsers.
4. Run `node scripts/build_locales.mjs --check` and
`node --test scripts/test_i18n.mjs scripts/test_freevideo_entry.mjs`.

Existing bilingual calls use the transitional `translatePair(en, zh, chinese)`
adapter. It preserves existing English/Chinese wording and uses known catalog
entries for Portuguese, falling back to English for untranslated strings.
New code should use stable keys instead. Keep labels separate from protocol
identifiers, prompts, model names, persisted settings, and workflow data.

## Scope and limits

This first contribution centralizes locale selection and translation helpers,
migrates view navigation and primary video generation labels to keys, and
provides an initial Brazilian Portuguese catalog. Settings and common controls
can use the legacy bridge as their strings are migrated. Long tutorial and
release content, specialized editor controls, messages and more complex
pluralization still need dedicated migration and native-speaker review. This is
not a claim of complete Portuguese coverage. The Task Manager extension is
intentionally not part of this branch.

Browser acceptance testing of all locales, narrow layouts and live generation
continues to be required before upstream merge. Development used AI assistance.
19 changes: 19 additions & 0 deletions scripts/build_locales.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Keep JSON as the editable source of truth. Emit a synchronous browser ES module,
// avoiding a runtime network request or JSON import-attribute browser dependency.
import fs from 'node:fs';
import {fileURLToPath} from 'node:url';
const root = new URL('../web/locales/', import.meta.url);
const languages = ['en', 'zh', 'pt-BR'];
const catalogs = Object.fromEntries(languages.map(lang => [lang, JSON.parse(fs.readFileSync(new URL(lang+'.json', root), 'utf8'))]));
const keys = Object.keys(catalogs.en).sort();
for (const lang of languages) {
for (const [key, value] of Object.entries(catalogs[lang])) {
if (!Object.hasOwn(catalogs.en, key) || typeof value !== 'string' || !value.trim()) throw new Error(lang+': invalid entry '+key);
}
for (const key of keys) if (!Object.hasOwn(catalogs[lang], key)) throw new Error(lang+': missing '+key);
}
const source = '// Generated by scripts/build_locales.mjs. Edit locales/*.json instead.\nexport const catalogs = '+JSON.stringify(catalogs, null, 2)+';\n';
const output = fileURLToPath(new URL('catalogs.js', root));
if (process.argv.includes('--check')) {
if (fs.readFileSync(output, 'utf8').replace(/\r\n/g,'\n') !== source) throw new Error('Locale bundle is stale; run node scripts/build_locales.mjs');
} else fs.writeFileSync(output, source);
1 change: 1 addition & 0 deletions scripts/test_freevideo_entry.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ test('main browser entry registers both views and preserves node hooks', async t
source = source.replace("from './fv_player.js'", `from '${new URL('../web/fv_player.js', import.meta.url).href}'`);
source = source.replace("from './fv_select.js'", `from '${new URL('../web/fv_select.js', import.meta.url).href}'`);
source = source.replace("from './tip_words.js'", `from '${new URL('../web/tip_words.js', import.meta.url).href}'`);
source = source.replace("from './i18n.js'", `from '${new URL('../web/i18n.js', import.meta.url).href}'`);
source = source.replace("from './cut_tip.js'", `from '${new URL('../web/cut_tip.js', import.meta.url).href}'`);
source = source.replace("from './middle_frames.js'", `from '${new URL('../web/middle_frames.js', import.meta.url).href}'`);
source = source.replace("from './workflow_drafts.js'", `from '${new URL('../web/workflow_drafts.js', import.meta.url).href}'`);
Expand Down
60 changes: 60 additions & 0 deletions scripts/test_i18n.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {execFileSync} from 'node:child_process';
import {fileURLToPath} from 'node:url';
import { resolveLocale, translateKey, translatePair, nextLocale, SUPPORTED_LOCALES } from '../web/i18n.js';
import { catalogs } from '../web/locales/catalogs.js';

test('locale priority and regional aliases', () => {
assert.equal(resolveLocale('?freevideo_lang=pt-BR', 'zh-CN'), 'pt-BR');
assert.equal(resolveLocale('?freevideo_lang=en', 'pt-BR'), 'en');
assert.equal(resolveLocale('?freevideo_lang=zh', 'en-US'), 'zh');
assert.equal(resolveLocale('', 'pt-br'), 'pt-BR');
assert.equal(resolveLocale('', 'zh-TW'), 'zh');
assert.equal(resolveLocale('', 'fr-FR'), 'en');
assert.equal(resolveLocale('?freevideo_lang=invalid', 'en-US'), 'en');
});
test('catalogs agree with source and every translation is nonempty', () => {
const keySet = Object.keys(catalogs.en).sort();
assert.ok(keySet.length >= 140);
for (const language of SUPPORTED_LOCALES) {
assert.deepEqual(Object.keys(catalogs[language]).sort(), keySet);
assert.deepEqual(catalogs[language], JSON.parse(readFileSync(new URL('../web/locales/'+language+'.json', import.meta.url), 'utf8')));
for (const key of keySet) assert.ok(catalogs[language][key].trim());
}
execFileSync(process.execPath, [fileURLToPath(new URL('./build_locales.mjs', import.meta.url)), '--check']);
});
test('stable keys preserve native English and Chinese with Brazilian Portuguese', () => {
assert.equal(translateKey('nav.create', 'en'), 'Create');
assert.equal(translateKey('nav.create', 'zh'), '创作面板');
assert.equal(translateKey('nav.create', 'pt-BR'), 'Criar');
assert.equal(translateKey('ui.generate_video', 'pt-BR'), 'Gerar vídeo');
assert.equal(translateKey('ui.generate_video', 'unsupported'), 'Generate video');
assert.equal(translateKey('missing.key', 'pt-BR'), 'missing.key');
assert.equal(translateKey('toString', 'pt-BR'), 'toString');
assert.equal(translateKey('progress.estimate_minutes', 'pt-BR', {minutes: 18}), 'Cerca de 18 min');
});
test('legacy bridge preserves supplied English and Chinese and falls back for unknown Portuguese copy', () => {
const old = globalThis.location;
try {
globalThis.location = {search: '?freevideo_lang=en'};
assert.equal(translatePair('Settings','自定义',false), 'Settings');
globalThis.location.search = '?freevideo_lang=zh';
assert.equal(translatePair('Settings','自定义',true), '自定义');
globalThis.location.search = '?freevideo_lang=pt-BR';
assert.equal(translatePair('Settings','设置',false), 'Configurações');
assert.equal(translatePair('About 18 min','约 18 分钟',false), 'Cerca de 18 min');
assert.equal(translatePair('Generating 42%','正在生成 42%',false), 'Gerando 42%');
assert.equal(translatePair('Light','浅色',false), 'Claro');
assert.equal(translatePair('Light','光线',false), 'Luz');
assert.equal(translatePair('Light','轻量',false), 'Leve');
assert.equal(translatePair('Untranslated original','原文',false), 'Untranslated original');
assert.equal(translatePair('Settings','设置',true), '设置');
} finally { if (old === undefined) delete globalThis.location; else globalThis.location=old; }
});
test('all three locales are reachable from command palette', () => {
assert.equal(nextLocale('en'), 'zh');
assert.equal(nextLocale('zh'), 'pt-BR');
assert.equal(nextLocale('pt-BR'), 'en');
});
8 changes: 3 additions & 5 deletions web/autopilot.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { currentLocale, translatePair } from './i18n.js';
import {createLanAccess} from './lan_access.js';
// The Agent's own page, beside the studio and the editing view: the card that connects one, then the conversation with it.
import { api } from '../../scripts/api.js';
Expand All @@ -16,11 +17,8 @@ import { keepViewSwitchPlace } from './view_switch_place.js';
import { tip } from './autopilot_tips.js';
import { agentPost } from './agent_session.js';

const languageOverride = typeof location !== 'undefined'
? new URLSearchParams(location.search).get('freevideo_lang') : null;
const cn = languageOverride === 'zh' || (languageOverride !== 'en'
&& String(navigator.language || '').toLowerCase().startsWith('zh'));
const t = (en, zh) => cn ? zh : en;
const cn = currentLocale() === 'zh';
const t = (en, zh) => translatePair(en, zh, cn);
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };

let current = null, kept = null;
Expand Down
5 changes: 2 additions & 3 deletions web/comfy_templates.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { currentLocale } from './i18n.js';
// ComfyUI's own Templates window, shown over the Nodes view: FreeVideo says its search box and its first category in the
// interface language (ComfyUI's Chinese file reads the search box as "搜索占位符", and the category name is not translated),
// and comfy_templates.css brings the window into the light theme. The window is added to the page body when it opens.
const query = new URLSearchParams(globalThis.location?.search || '');
const asked = query.get('freevideo_lang');
export const chinese = asked === 'zh' || (asked !== 'en' && String(globalThis.navigator?.language || '').toLowerCase().startsWith('zh'));
export const chinese = currentLocale() === 'zh';

// English text of a ComfyUI-made label -> the Chinese FreeVideo shows in its place.
export const LABELS = {Popular: '热门'};
Expand Down
8 changes: 3 additions & 5 deletions web/compatibility.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { currentLocale, translatePair } from './i18n.js';
import { api } from '../../scripts/api.js';
import './fv_select.js';
import './glass/library.js';
Expand All @@ -9,11 +10,8 @@ const saveFailure = (error, tt) => { const text = userMessage(error, tt, tt('Cou
const readFailure = (error, tt) => { const text = userMessage(error, tt, tt('Could not read the setting. Try again.', '没能读取设置,请重试。'));
return text === String(error?.message ?? '').trim() ? tt('The setting could not be read: ', '无法读取设置:') + text : text; };

const languageOverride = typeof location !== 'undefined'
? new URLSearchParams(location.search).get('freevideo_lang') : null;
const cn = languageOverride === 'zh' || (languageOverride !== 'en'
&& String(navigator.language || '').toLowerCase().startsWith('zh'));
const t = (en, zh) => cn ? zh : en;
const cn = currentLocale() === 'zh';
const t = (en, zh) => translatePair(en, zh, cn);
const unavailable = () => t('Device information is unavailable; compatibility settings are off.', '无法获取设备信息,兼容性设置已关闭。');
let current;
const element = (tag, text) => { const node = document.createElement(tag); if (text) node.textContent = text; return node; };
Expand Down
9 changes: 4 additions & 5 deletions web/context_menu.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { currentLocale, translatePair } from './i18n.js';
// The one right-click menu of every FreeVideo view, and the small pieces the command layer shares (language,
// icons, how a shortcut is written). The library, the image view and the editor build their menus with it:
// attachContextMenu(element, event => items | null) right click, Shift+F10, the menu key, a long press on touch
Expand All @@ -10,12 +11,10 @@
import { isolateDialogKeys, listenDialogKey } from './dialog_keys.js';

const browser = typeof document !== 'undefined';
const query = browser ? new URLSearchParams(globalThis.location?.search || '') : new URLSearchParams();
const forced = query.get('freevideo_lang');
export const CN = forced === 'zh' || (forced !== 'en' && String(globalThis.navigator?.language || '').toLowerCase().startsWith('zh'));
export const t = (en, zh) => CN ? zh : en;
export const CN = currentLocale() === 'zh';
export const t = (en, zh) => translatePair(en, zh, CN);
// [en, zh] pairs, plain strings and functions returning either all read the same way.
export const words = (value, cn = CN) => typeof value === 'function' ? words(value(), cn) : Array.isArray(value) ? String(value[cn ? 1 : 0] ?? value[0] ?? '') : String(value ?? '');
export const words = (value, cn) => typeof value === 'function' ? words(value(), cn) : Array.isArray(value) ? String((cn === undefined ? translatePair(value[0], value[1] ?? value[0]) : value[cn ? 1 : 0]) ?? value[0] ?? '') : String(value ?? '');
export const MAC = /Mac|iPhone|iPad/.test(globalThis.navigator?.platform || globalThis.navigator?.userAgent || '');
// The compatibility view (Settings → 兼容界面, stored as freevideo.glass = solid): solid panels, fewer animations,
// and nothing plays until asked. It counts as reduced motion everywhere.
Expand Down
3 changes: 2 additions & 1 deletion web/editor.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { translatePair } from './i18n.js';
import './has_mirror.js';
import {createLanAccess} from './lan_access.js';
import {createEditorText} from './editor_text.js';
Expand Down Expand Up @@ -244,7 +245,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given
}
// The same language as the top bar and the other views, read once when the page opened (the app later drops the
// address's query, so reading it again when the editor opened fell back to the browser's language).
const t = (en, zh) => CN ? zh : en;
const t = (en, zh) => translatePair(en, zh, CN);
const returnFocus = document.activeElement;
const even = value => Math.max(2, Math.floor(value / 2) * 2);
// A new edit opens with an empty second sound track, where music is made.
Expand Down
5 changes: 3 additions & 2 deletions web/first_run_guide.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { translatePair } from './i18n.js';
import {SHOWCASE_TEXT, showcaseChapter, loadShowcaseImage} from './entry_showcase.js';
import './glass/library.js';
import {openAnchor} from './feature_tour_layer.js';
Expand Down Expand Up @@ -159,7 +160,7 @@ const ROW_ICONS = {flag: 'M4 13.5V3M4 3.5h7.5l-1.5 2.5 1.5 2.5H4', play: 'M5 3.2
const rowIcon = name => { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 16 16'); svg.setAttribute('aria-hidden', 'true');
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', ROW_ICONS[name]); svg.append(path); return svg; };
export function createGuideReplayEntry({dialog, cn, api, openWorkspace, replay = replayInFront}) {
const text = key => REPLAY_TEXT[key][cn ? 1 : 0], t = (en, zh) => cn ? zh : en;
const text = key => REPLAY_TEXT[key][cn ? 1 : 0], t = (en, zh) => translatePair(en, zh, cn);
const tipped = (node, name, use) => { node.dataset.fvTipName = name; node.dataset.fvTipUse = use; return node; };
const section = el('section', null, 'fv-guide-replay'), row = el('div', null, 'fv-guide-replay-row'), rows = el('div', null, 'fv-guide-rows');
const line = (icon, name, small, control) => { const item = el('div', null, 'fv-guide-row'), words = el('span'); words.append(el('b', name), el('small', small)); item.append(rowIcon(icon), words, control); return item; };
Expand Down Expand Up @@ -256,7 +257,7 @@ export function guideTarget(dialog, chapter, targets = {}) {
}

export function createFirstRunGuide({dialog, api, cn, isBusy = () => false, group = 'studio', targets = {}, onShowcaseTry = null}) {
const t = (en, zh) => cn ? zh : en;
const t = (en, zh) => translatePair(en, zh, cn);
const automatic = !attempted.has(group), editor = group === 'editor';
const chapters = chaptersFor(group);
if (!document.querySelector('link[data-fv-first-run-guide]')) {
Expand Down
8 changes: 3 additions & 5 deletions web/freevideo.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { currentLocale, translatePair } from './i18n.js';
import { setTip } from './tip_words.js';
import { cutTip } from './cut_tip.js';
import './has_mirror.js';
Expand Down Expand Up @@ -48,11 +49,8 @@ import { createPlayBar } from './fv_player.js';
import { userMessage } from './user_message.js';
import { AUDIO_USE, usesOriginal, checkOriginal, checkedLength, failureText, multipleText, createUseSwitch, originalBlocked, stuckText, liftBlock } from './audio_original.js';

const languageOverride = typeof location !== 'undefined'
? new URLSearchParams(location.search).get('freevideo_lang') : null;
const cn = languageOverride === 'zh' || (languageOverride !== 'en'
&& String(navigator.language || '').toLowerCase().startsWith('zh'));
const text = (en, zh) => cn ? zh : en;
const cn = currentLocale() === 'zh';
const text = (en, zh) => translatePair(en, zh, cn);
const style = document.createElement("style");
style.textContent = `
.fv-panel{box-sizing:border-box;width:100%;height:100%;padding:16px;background:var(--fv-card);color:var(--fv-ink);border:1px solid var(--fv-border);border-radius:var(--fv-r-md,12px);font:13px/1.6 var(--fv-font);overflow:auto;color-scheme:dark}
Expand Down
6 changes: 3 additions & 3 deletions web/health.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { currentLocale, translatePair } from './i18n.js';
// Checks that FreeVideo's page loaded completely and says what is wrong when
// it did not: which file, why, and what to do. It imports nothing at load and
// styles itself inline, so it still runs when every other FreeVideo file fails.
Expand All @@ -7,9 +8,8 @@
let extensionUI = null, errorUI = null;
const base = new URL('./', import.meta.url);
const query = new URLSearchParams(location.search);
const language = query.get('freevideo_lang');
const cn = language === 'zh' || (language !== 'en' && String(navigator.language || '').toLowerCase().startsWith('zh'));
const t = (en, zh) => cn ? zh : en;
const cn = currentLocale() === 'zh';
const t = (en, zh) => translatePair(en, zh, cn);
// launcher.js removes this flag during setup; read it before that.
const launchVisit = query.get('freevideo') === 'launch';
// Every script this folder ships; a test keeps the list in step with web/*.js.
Expand Down
Loading