diff --git a/docs/existing-python-runtime.md b/docs/existing-python-runtime.md new file mode 100644 index 000000000..379344b4a --- /dev/null +++ b/docs/existing-python-runtime.md @@ -0,0 +1,37 @@ +# Using an existing Python runtime + +VoiceStudio can use an existing local Python interpreter instead of installing its managed runtime. This is intended for development and for hosts that already have the required model dependencies. + +## Requirements + +- Python 3.11 or newer. +- The selected interpreter must be an executable file. +- The validation probe performs real imports (including FastAPI, Uvicorn, OmniVoice, Torch, and the speech engine dependencies). `find_spec` is not sufficient. +- Keep the environment in place. Searching and validation do not install packages. Dependency installation is a separate, explicitly confirmed action, limited to eligible virtual environments. + +## Selecting an interpreter + +On the first-run backend screen, choose **Choose interpreter**, or use **Settings → Performance → Python runtime**. Select the interpreter itself (for example, `.venv/bin/python` or `.venv\\Scripts\\python.exe`). VoiceStudio validates it before saving: + +1. It checks the path and Python version. +2. It runs the import probe with offline model/download settings. +3. It reports missing modules or the import that failed. +4. It shows a successful validation without changing the saved selection. Choose **Confirm use and continue** to revalidate, save the absolute path and restart the backend. + +If modules are missing, choose another interpreter or review the dependency installation plan. Only reviewed package specifications are offered; unknown imports do not become arbitrary pip arguments. The plan shows the exact interpreter and packages. Installation requires both UI consent and a native confirmation dialog, uses no sudo or system-package override, and is not offered for system/protected environments. Cancellation leaves the environment and saved selection unchanged. After installation, validation runs again and still requires **Confirm use and continue** before saving. Installation errors retain diagnostic output. Existing environments are not backed up automatically; use a dedicated virtual environment if other applications share your current one. + +Use **Use managed runtime** to remove the selection and restart with the bundled/managed environment. + +## Quick search + +First-run setup and Settings also provide **Quick search**. It searches common PATH/system installations, pyenv/Conda/uv locations and bounded project folders. It lists absolute interpreter paths and versions when environment metadata provides them. Discovery does not run Python or install packages; a listed interpreter is not yet known to be compatible. Click a result to validate it; the saved selection and backend remain unchanged until **Confirm use and continue**. + +The search is not a full-disk inventory. A four-second deadline, directory/depth limits and excluded dependency/cache folders keep it responsive. Results are marked potentially incomplete when access is denied, another filesystem error occurs or scan limits are reached. Missing optional search roots are not errors. For permission-denied locations, allow access in the operating system if appropriate, or use **Choose interpreter** to select the file directly. Manual selection remains available even when no candidates are found. + +Separate virtual environments are kept separate even when their Python executables link to the same base interpreter. Duplicate aliases within one environment are consolidated. Searching never changes the current saved selection. + +## Overrides and troubleshooting + +An `OMNIVOICE_BACKEND_CMD` override remains authoritative and is shown in Settings. It is not replaced by a selected interpreter. Clear the override if the selected interpreter is not being used. + +A Python 3.10 environment is rejected before backend imports. Install the missing dependencies into a separate Python 3.11+ environment rather than modifying a user environment that VoiceStudio did not create. If validation succeeds but startup fails, check the backend log for the import marker and restart after correcting the environment. diff --git a/electron/src/main/backend-launch.test.ts b/electron/src/main/backend-launch.test.ts index b039ea667..f17ebb869 100644 --- a/electron/src/main/backend-launch.test.ts +++ b/electron/src/main/backend-launch.test.ts @@ -1,7 +1,13 @@ // @vitest-environment node import { afterEach, expect, it, vi } from 'vitest'; import { join, resolve } from 'node:path'; -const state = vi.hoisted(() => ({ installed: true, packaged: false, ready: true, checkout: true })); +const state = vi.hoisted(() => ({ installed: true, packaged: false, ready: true, checkout: true, selected: null as string | null })); +const validateSelected = vi.hoisted(() => vi.fn(async (pythonPath: string, _cwd: string) => ({ ok: true, pythonPath }))); +vi.mock('./runtime-python-selection', async (importOriginal) => ({ + ...(await importOriginal()), + selectedPythonPath: () => state.selected, + validatePythonRuntime: validateSelected, +})); vi.mock('electron', () => ({ app: { get isPackaged() { @@ -48,8 +54,24 @@ afterEach(() => { state.ready = true; state.packaged = false; state.checkout = true; + state.selected = null; + validateSelected.mockClear(); vi.unstubAllEnvs(); }); +it('runs a selected interpreter against bundled resources, never the absent managed project', async () => { + vi.stubEnv('OMNIVOICE_BACKEND_CMD', ''); + state.packaged = true; + state.selected = '/existing/bin/python'; + const original = process.resourcesPath; + Object.defineProperty(process, 'resourcesPath', { configurable: true, value: '/packaged/resources' }); + try { + const plan = await resolveSpawnPlan(3912, '/missing/managed/project'); + expect(plan).toMatchObject({ cwd: '/packaged/resources' }); + expect(validateSelected).toHaveBeenCalledWith('/existing/bin/python', '/packaged/resources'); + } finally { + Object.defineProperty(process, 'resourcesPath', { configurable: true, value: original }); + } +}); it.each(['darwin', 'win32', 'linux'] as const)( 'leaves China downloads eligible for automatic failover on %s', (platform) => { diff --git a/electron/src/main/backend.ts b/electron/src/main/backend.ts index 182501168..cec3e7db9 100644 --- a/electron/src/main/backend.ts +++ b/electron/src/main/backend.ts @@ -2,6 +2,7 @@ import { decideMissingRuntime, runtimeWasInstalled } from './runtime-repair'; import { windowsRocmInstalled, windowsRocmRequested } from './runtime-windows-rocm'; import { runtimeProjectReady } from './runtime-readiness'; import { runRuntimeProbe } from './runtime-probe'; +import { selectedPythonPath, shouldBypassManagedRuntime, validatePythonRuntime } from './runtime-python-selection'; import { RuntimeLaunchRefusedError } from './runtime-launch-refusal'; import { pypiFilesHost } from './pypi-mirror'; import { @@ -490,6 +491,21 @@ export async function resolveSpawnPlan( const root = backendRoot(); const override = parseBackendCmdOverride(process.env.OMNIVOICE_BACKEND_CMD); if (override) return { argv: override, cwd: root }; + const selectedPython = selectedPythonPath(); + if (selectedPython) { + // The external interpreter uses bundled sources; no managed project exists yet. + const project = root; + const validation = await validatePythonRuntime(selectedPython, project); + if (!validation.ok) { + const missing = validation.missingModules?.length + ? ` Missing modules: ${validation.missingModules.join(', ')}.` + : ''; + return { + error: `The selected Python runtime is not compatible${validation.version ? ` (Python ${validation.version})` : ''}.${missing} ${validation.detail ?? 'Validation failed.'} Select another interpreter or return to the managed runtime.`, + }; + } + return { argv: [selectedPython, '-m', ...UVICORN_ARGS, '--port', String(port)], cwd: project }; + } if (app.isPackaged) { const project = packagedProject ?? join(defaultRuntimeRoot(), 'project'); // Heals runtimes installed before #1783 was fixed without a repair run. @@ -605,6 +621,7 @@ function childEnv( delete env.PYTHONPATH; env.PYTHONUNBUFFERED = '1'; env.PYTHONUTF8 = '1'; + env.PYTHONDONTWRITEBYTECODE = '1'; // Arms backend/core/parent_liveness.py: stdin EOF == "the shell is gone". env.OMNIVOICE_DESKTOP_CONTAINED = '1'; env.OMNIVOICE_PORT = String(port); @@ -1028,7 +1045,13 @@ export class BackendSupervisor extends EventEmitter<{ } } - if (app.isPackaged && !parseBackendCmdOverride(process.env.OMNIVOICE_BACKEND_CMD)) { + if ( + !shouldBypassManagedRuntime( + app.isPackaged, + selectedPythonPath(), + process.env.OMNIVOICE_BACKEND_CMD, + ) + ) { const { project, ready } = await this.resolveRuntimeProject(); if (!ready) { if (gen === this.generation) { diff --git a/electron/src/main/ipc-python-discovery-registration.test.ts b/electron/src/main/ipc-python-discovery-registration.test.ts new file mode 100644 index 000000000..ccea425fb --- /dev/null +++ b/electron/src/main/ipc-python-discovery-registration.test.ts @@ -0,0 +1,11 @@ +// @vitest-environment node +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { expect, it } from 'vitest'; + +it('registers each existing and discovery Python IPC handler exactly once', () => { + const source = readFileSync(resolve(__dirname, 'ipc.ts'), 'utf8'); + for (const name of ['backendGetPythonRuntime', 'backendChoosePythonRuntime', 'backendUseManagedPython', 'backendDiscoverPythonRuntimes', 'backendUseDiscoveredPythonRuntime']) { + expect(source.match(new RegExp(`ipcMain\\.handle\\(CHANNELS\\.${name}\\b`, 'g')) ?? [], name).toHaveLength(1); + } +}); diff --git a/electron/src/main/ipc.ts b/electron/src/main/ipc.ts index bd2f6a264..0d9865bb2 100644 --- a/electron/src/main/ipc.ts +++ b/electron/src/main/ipc.ts @@ -44,6 +44,17 @@ import { createUninstallPlan, scanUninstallTargets, type UninstallRoots } from ' import { scheduleUninstallCleanup } from './uninstall-cleanup'; import { sendToLiveWindow } from './window-safety'; import { securityScopedDialogOptions, withSecurityScopedBookmark } from './security-scoped-files'; +import { + clearPythonRuntimeSelection, + loadPythonRuntimeSelection, + savePythonRuntimeSelection, + validatePythonRuntime, + sanitizedPythonEnvironment, +} from './runtime-python-selection'; +import { backendRoot } from './backend'; +import { discoverPythonRuntimes, type PythonDiscoveryResult } from './python-runtime-discovery'; +import { createOpaqueToken, type PythonRepairPlan } from './runtime-python-selection'; +import { runRuntimeProbe } from './runtime-probe'; export const CHANNELS = { permissionsGetState: 'permissions:getState', @@ -59,6 +70,15 @@ export const CHANNELS = { backendSetRuntimeRegion: 'backend:setRuntimeRegion', backendChooseRuntimeLocation: 'backend:chooseRuntimeLocation', backendUseDefaultRuntimeLocation: 'backend:useDefaultRuntimeLocation', + backendGetPythonRuntime: 'backend:getPythonRuntime', + backendChoosePythonRuntime: 'backend:choosePythonRuntime', + backendUseManagedPython: 'backend:useManagedPython', + backendDiscoverPythonRuntimes: 'backend:discoverPythonRuntimes', + backendUseDiscoveredPythonRuntime: 'backend:useDiscoveredPythonRuntime', + backendConfirmPythonRuntime: 'backend:confirmPythonRuntime', + backendPlanPythonRepair: 'backend:planPythonRepair', + backendInstallPythonRepair: 'backend:installPythonRepair', + backendPythonRepairProgress: 'backend:pythonRepairProgress', backendGetConnection: 'backend:getConnection', backendHostSnapshot: 'backend:hostSnapshot', backendTestRemote: 'backend:testRemote', @@ -335,6 +355,34 @@ export function registerIpc( target: string; createdAt: number; } | null = null; + let discoveredPythonPaths = new Set(); + let discoveryInFlight: Promise | null = null; + const PYTHON_STAGE_TTL_MS = 10 * 60 * 1000; + const MAX_PYTHON_STAGES = 32; + const stagedPython = new Map(); + const stagedRepairs = new Map(); + const prunePythonStages = () => { + const now = Date.now(); + for (const [token, value] of stagedPython) if (now - value.createdAt > PYTHON_STAGE_TTL_MS) stagedPython.delete(token); + for (const [token, value] of stagedRepairs) if (now - value.createdAt > PYTHON_STAGE_TTL_MS) stagedRepairs.delete(token); + while (stagedPython.size > MAX_PYTHON_STAGES) stagedPython.delete(stagedPython.keys().next().value!); + while (stagedRepairs.size > MAX_PYTHON_STAGES) stagedRepairs.delete(stagedRepairs.keys().next().value!); + }; + const stagePython = (pythonPath: string, event: IpcMainInvokeEvent, validated: boolean) => { + prunePythonStages(); + const token = createOpaqueToken(); + stagedPython.set(token, { pythonPath, validated, senderId: event.sender.id, frameId: event.frameId, createdAt: Date.now() }); + return token; + }; + const consumeStage = (token: unknown, event: IpcMainInvokeEvent) => { + prunePythonStages(); + if (typeof token !== 'string') throw new Error('invalid_python_confirmation'); + const staged = stagedPython.get(token); + stagedPython.delete(token); + if (!staged || staged.senderId !== event.sender.id || staged.frameId !== event.frameId) throw new Error('python_confirmation_expired'); + if (!staged.validated) throw new Error('python_runtime_not_validated'); + return staged; + }; supervisor.subscribe((status: BackendStatus) => broadcast(CHANNELS.backendStatus, status)); ipcMain.handle(CHANNELS.permissionsGetState, (event) => { @@ -355,6 +403,103 @@ export function registerIpc( return supervisor.acknowledgeLastCrash(); }); ipcMain.handle(CHANNELS.backendGetConnection, () => supervisor.connection); + ipcMain.handle(CHANNELS.backendDiscoverPythonRuntimes, async (event) => { + const owner = getMainWindow(); + assertTrustedMainFrame(event, owner); + if (!discoveryInFlight) { + discoveryInFlight = discoverPythonRuntimes().then((result) => { + // The discovery result is informational. It is not a compatibility check. + discoveredPythonPaths = new Set( + result.candidates + .filter((candidate) => isAbsolute(candidate.pythonPath)) + .map((candidate) => resolve(candidate.pythonPath)), + ); + return result; + }).finally(() => { + discoveryInFlight = null; + }); + } + return discoveryInFlight; + }); + ipcMain.handle(CHANNELS.backendUseDiscoveredPythonRuntime, async (event, raw: unknown) => { + const owner = getMainWindow(); + assertTrustedMainFrame(event, owner); + if (typeof raw !== 'string' || !isAbsolute(raw)) throw new Error('Invalid Python runtime path'); + const pythonPath = resolve(raw); + if (!discoveredPythonPaths.has(pythonPath)) throw new Error('Python runtime was not discovered; search again'); + const validation = await validatePythonRuntime(pythonPath, backendRoot()); + return { ...validation, token: stagePython(pythonPath, event, validation.ok) }; + }); + ipcMain.handle(CHANNELS.backendConfirmPythonRuntime, async (event, raw: unknown) => { + const owner = getMainWindow(); + assertTrustedMainFrame(event, owner); + const staged = consumeStage(raw, event); + const validation = await validatePythonRuntime(staged.pythonPath, backendRoot()); + if (!validation.ok) return validation; + savePythonRuntimeSelection(validation.pythonPath); + await supervisor.restart(); + return validation; + }); + ipcMain.handle(CHANNELS.backendPlanPythonRepair, async (event, raw: unknown) => { + const owner = getMainWindow(); + assertTrustedMainFrame(event, owner); + if (typeof raw !== 'string') throw new Error('Python selection token is required'); + prunePythonStages(); + const staged = stagedPython.get(raw); + if (!staged || staged.senderId !== event.sender.id || staged.frameId !== event.frameId) throw new Error('python_selection_expired'); + const validation = await validatePythonRuntime(staged.pythonPath, backendRoot()); + if (!validation.repairPlan) return validation; + prunePythonStages(); + const repairToken = createOpaqueToken(); + stagedRepairs.set(repairToken, { plan: validation.repairPlan, senderId: event.sender.id, frameId: event.frameId, createdAt: Date.now() }); + return { ...validation, repairToken }; + }); + ipcMain.handle(CHANNELS.backendInstallPythonRepair, async (event, raw: unknown) => { + const owner = getMainWindow(); + assertTrustedMainFrame(event, owner); + if (!raw || typeof raw !== 'object') throw new Error('Invalid Python repair confirmation'); + const input = raw as { token?: unknown; pythonPath?: unknown; packages?: unknown }; + if (typeof input.token !== 'string' || typeof input.pythonPath !== 'string' || !Array.isArray(input.packages) || input.packages.some((p) => typeof p !== 'string')) + throw new Error('Explicit confirmation of the exact Python repair is required'); + prunePythonStages(); + const staged = stagedRepairs.get(input.token); + if (!staged || staged.senderId !== event.sender.id || staged.frameId !== event.frameId) throw new Error('python_repair_expired'); + if (resolve(input.pythonPath) !== staged.plan.interpreter || JSON.stringify(input.packages) !== JSON.stringify(staged.plan.packages)) throw new Error('python_repair_changed'); + const recheck = await validatePythonRuntime(staged.plan.interpreter, backendRoot()); + if (recheck.ok || !recheck.repairPlan || JSON.stringify(recheck.repairPlan) !== JSON.stringify(staged.plan)) throw new Error('python_repair_changed'); + const choice = await dialog.showMessageBox(owner, { + type: 'question', buttons: ['Install', 'Cancel'], defaultId: 0, cancelId: 1, + title: 'Install Python dependencies', + message: `Install dependencies into ${staged.plan.interpreter}?`, + detail: staged.plan.packages.join('\n'), + }); + if (choice.response !== 0) return { ...recheck, installed: false, canceled: true, token: stagePython(recheck.pythonPath, event, false) }; + if (maintenanceBusy) throw new Error('maintenance_busy'); + maintenanceBusy = true; + stagedRepairs.delete(input.token); + let output = ''; + let installError: unknown; + try { + const finalCheck = await validatePythonRuntime(staged.plan.interpreter, backendRoot()); + if (finalCheck.ok || !finalCheck.repairPlan || JSON.stringify(finalCheck.repairPlan) !== JSON.stringify(staged.plan)) throw new Error('python_repair_changed'); + try { + output = await runRuntimeProbe(staged.plan.interpreter, ['-m', 'pip', 'install', '--disable-pip-version-check', '--no-input', ...staged.plan.packages], backendRoot(), sanitizedPythonEnvironment(), { timeoutMs: 15 * 60 * 1000, captureStderr: true, onOutput: (text, stream) => sendToLiveWindow(owner, CHANNELS.backendPythonRepairProgress, { text, stream }) }); + } catch (error) { + installError = error; + const failure = error as { stdout?: unknown; stderr?: unknown; message?: unknown }; + output = `${String(failure.stdout ?? '')}\n${String(failure.stderr ?? '')}\n${String(failure.message ?? '')}`; + } + } finally { + maintenanceBusy = false; + } + const after = await validatePythonRuntime(staged.plan.interpreter, backendRoot()); + if (!after.ok && after.repairPlan) { + const repairToken = createOpaqueToken(); + stagedRepairs.set(repairToken, { plan: after.repairPlan, senderId: event.sender.id, frameId: event.frameId, createdAt: Date.now() }); + return { ...after, installed: false, repairToken, outputTail: output.slice(-4000) }; + } + return { ...after, installed: after.ok && !installError, token: after.ok && !installError ? stagePython(after.pythonPath, event, true) : undefined, outputTail: output.slice(-4000) }; + }); ipcMain.handle(CHANNELS.backendHostSnapshot, (event) => { const owner = getMainWindow(); assertTrustedMainFrame(event, owner); @@ -538,6 +683,33 @@ export function registerIpc( assertTrustedMainFrame(event, owner); return supervisor.setRuntimeLocation(null); }); + ipcMain.handle(CHANNELS.backendGetPythonRuntime, (event: IpcMainInvokeEvent) => { + const owner = getMainWindow(); + assertTrustedMainFrame(event, owner); + return { + selection: loadPythonRuntimeSelection(), + overrideActive: Boolean(String(process.env.OMNIVOICE_BACKEND_CMD ?? '').trim()), + }; + }); + ipcMain.handle(CHANNELS.backendChoosePythonRuntime, async (event: IpcMainInvokeEvent, rawTitle: unknown) => { + const owner = getMainWindow(); + assertTrustedMainFrame(event, owner); + const title = typeof rawTitle === 'string' && rawTitle.length <= 200 ? rawTitle : undefined; + const picked = await dialog.showOpenDialog(owner, { + ...(title ? { title } : {}), + properties: ['openFile'], + }); + if (picked.canceled || !picked.filePaths[0]) return { ok: false, canceled: true }; + const validation = await validatePythonRuntime(picked.filePaths[0], backendRoot()); + return { ...validation, token: stagePython(validation.pythonPath, event, validation.ok) }; + }); + ipcMain.handle(CHANNELS.backendUseManagedPython, async (event: IpcMainInvokeEvent) => { + const owner = getMainWindow(); + assertTrustedMainFrame(event, owner); + clearPythonRuntimeSelection(); + await supervisor.restart(); + return { ok: true }; + }); ipcMain.handle(CHANNELS.backendRestart, () => supervisor.restart()); ipcMain.handle(CHANNELS.filesExtractScript, (_event, input: unknown) => extractWordScript(input)); diff --git a/electron/src/main/python-runtime-discovery.test.ts b/electron/src/main/python-runtime-discovery.test.ts new file mode 100644 index 000000000..b06b7fcdd --- /dev/null +++ b/electron/src/main/python-runtime-discovery.test.ts @@ -0,0 +1,92 @@ +// @vitest-environment node +import { mkdtemp, mkdir, symlink, writeFile, rm, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve, win32 } from 'node:path'; +import { afterEach, describe, expect, test } from 'vitest'; +import { discoverPythonRuntimes, type PythonDiscoveryFileSystem } from './python-runtime-discovery'; +const cleanups: string[] = []; +afterEach(async () => { await Promise.all(cleanups.splice(0).map(p => rm(p, { recursive: true, force: true }))); }); +async function fixture() { const root = await mkdtemp(join(tmpdir(), 'python-discovery-')); cleanups.push(root); return root; } +async function makeVenv(root: string, name: string, version = '3.12.1') { + const env = join(root, name); await mkdir(join(env, 'bin'), { recursive: true }); + await writeFile(join(env, 'bin', 'python'), 'not executed'); + await writeFile(join(env, 'pyvenv.cfg'), `home = /base\nversion = ${version}\n`); return env; +} +const fakeFs = (overrides: Partial = {}): PythonDiscoveryFileSystem => ({ + readdir: async () => [], stat: async () => ({ isFile: () => false, isDirectory: () => true }), + lstat: async () => ({ isSymbolicLink: () => false, isDirectory: () => true }), realpath: async p => p, + readFile: async () => { throw Object.assign(new Error('missing'), {code:'ENOENT'}); }, ...overrides, +}); +describe('discoverPythonRuntimes', () => { + test('finds project venv metadata without executing the interpreter', async () => { + const root = await fixture(), env = await makeVenv(root, 'project/.venv'); + const result = await discoverPythonRuntimes({ roots: [root], homeDir: root, env: { PATH: '' } }); + expect(result.candidates).toContainEqual({ pythonPath: join(env, 'bin', 'python'), source: 'venv', version: '3.12.1' }); + expect(await readFile(join(env,'bin','python'),'utf8')).toBe('not executed'); + }); + test('deduplicates command aliases', async () => { + const root = await fixture(), bin = join(root,'bin'); await mkdir(bin); + await writeFile(join(bin,'python'),'not executed'); await symlink(join(bin,'python'),join(bin,'python3')); + const result = await discoverPythonRuntimes({roots:[],homeDir:root,env:{PATH:bin}}); + expect(result.candidates).toHaveLength(1); + }); + test('preserves separate PATH virtualenvs sharing one base Python and deduplicates each environment', async () => { + const root = await fixture(), a = await makeVenv(root,'a/.venv'), b = await makeVenv(root,'b/.venv'); + const base=join(root,'base');await writeFile(base,'not executed'); + for(const env of [a,b]) {await rm(join(env,'bin','python'));await symlink(base,join(env,'bin','python'));await symlink(base,join(env,'bin','python3'));} + const result=await discoverPythonRuntimes({roots:[root],homeDir:root,env:{PATH:[join(a,'bin'),join(b,'bin')].join(':')}}); + expect(result.candidates.map(x=>x.pythonPath)).toEqual([join(a,'bin','python'),join(b,'bin','python')]); + }); + test('reports EACCES and EPERM as partial, preserving readable results', async () => { + const root=await fixture();await makeVenv(root,'project/.venv'); + for(const code of ['EACCES','EPERM']) { + const result=await discoverPythonRuntimes({roots:[root,'/denied'],homeDir:root,env:{PATH:''},fs:{lstat:async p=>{if(p==='/denied')throw Object.assign(new Error('denied'),{code});return (await import('node:fs/promises')).lstat(p);}}}); + expect(result.candidates.length).toBeGreaterThan(0);expect(result.partial).toBe(true); + expect(result.warnings).toContainEqual({path:'/denied',reason:'permission_denied'}); + } + }); + test('does not label absent common locations as errors',async()=>{ + const root=await fixture();const result=await discoverPythonRuntimes({roots:[join(root,'absent')],homeDir:root,env:{PATH:''}}); + expect(result).toMatchObject({candidates:[],warnings:[],partial:false}); + }); + test('reports an actual directory budget cutoff',async()=>{ + const result=await discoverPythonRuntimes({roots:['/fixture'],homeDir:'/fixture',env:{PATH:''},maxDirs:1,fs:fakeFs({readdir:async p=>p==='/fixture'?['child']:[]})}); + expect(result.partial).toBe(true);expect(result.warnings.some(w=>w.reason==='scan_limit')).toBe(true); + }); + test('reports other filesystem failures as incomplete rather than silently empty',async()=>{ + const result=await discoverPythonRuntimes({roots:['/bad'],env:{PATH:''},fs:fakeFs({lstat:async()=>{throw Object.assign(new Error('io'),{code:'EIO'});}})}); + expect(result.partial).toBe(true);expect(result.warnings).toContainEqual({path:'/bad',reason:'read_error'}); + }); + test('supports Windows Scripts paths on a non-Windows test host',async()=>{ + const root=win32.join('C:\\','Work','app'),venv=win32.join(root,'venv'),exe=win32.join(venv,'Scripts','python.exe'); + const dirs=new Set([root,venv,win32.dirname(exe)]),cfg=win32.join(venv,'pyvenv.cfg'); + const missing=()=>{throw Object.assign(new Error('missing'),{code:'ENOENT'});}; + const fs=fakeFs({ + stat:async p=>p===exe?{isFile:()=>true,isDirectory:()=>false}:dirs.has(p)?{isFile:()=>false,isDirectory:()=>true}:missing(), + lstat:async p=>dirs.has(p)?{isSymbolicLink:()=>false,isDirectory:()=>true}:missing(), + readdir:async p=>p===root?['venv']:p===win32.dirname(exe)?['python.exe']:dirs.has(p)?[]:missing(), + readFile:async p=>p===cfg?'version = 3.14.1':missing(), + }); + const result=await discoverPythonRuntimes({platform:'win32',homeDir:win32.join('C:\\','Users','tester'),roots:[root],env:{PATH:''},fs}); + expect(result.candidates).toEqual([{pythonPath:exe,source:'venv',version:'3.14.1'}]); + }); + test('returns partial on a slow operation even if it is the final configured directory',async()=>{ + const result=await discoverPythonRuntimes({roots:['/slow'],homeDir:'/fixture',env:{PATH:''},timeoutMs:15,fs:fakeFs({readdir:async()=>new Promise(()=>{})})}); + expect(result.partial).toBe(true);expect(result.warnings.some(w=>w.reason==='scan_limit')).toBe(true); + }); + test('never follows directory symlink cycles or descends node_modules',async()=>{ + const root=await fixture();await makeVenv(root,'project/.venv');await mkdir(join(root,'node_modules','ignored'),{recursive:true}); + await symlink(root,join(root,'project','loop')); + const result=await discoverPythonRuntimes({roots:[root],homeDir:root,env:{PATH:''},maxDepth:2}); + expect(result.candidates).toHaveLength(1);expect(result.partial).toBe(false); + }); + test('discovers arbitrary pyenv release names without version hardcoding',async()=>{ + const home=await fixture(),root=join(home,'.pyenv','versions'),env=await makeVenv(root,'3.14.7'); + const result=await discoverPythonRuntimes({roots:[root],homeDir:home,env:{PATH:''}}); + expect(result.candidates).toContainEqual({pythonPath:join(env,'bin','python'),source:'pyenv',version:'3.12.1'}); + }); + test('has no subprocess execution dependency',async()=>{ + const source=await readFile(resolve(__dirname,'python-runtime-discovery.ts'),'utf8'); + expect(source).not.toMatch(/child_process|\bspawn\s*\(|\bexec(?:File|Sync)?\s*\(/); + }); +}); diff --git a/electron/src/main/python-runtime-discovery.ts b/electron/src/main/python-runtime-discovery.ts new file mode 100644 index 000000000..bb7c8eb4a --- /dev/null +++ b/electron/src/main/python-runtime-discovery.ts @@ -0,0 +1,136 @@ +import * as nativeFs from 'node:fs/promises'; +import { homedir } from 'node:os'; +import * as paths from 'node:path'; + +export interface PythonCandidate { pythonPath: string; source: string; version?: string } +export interface PythonDiscoveryWarning { path: string; reason: 'permission_denied' | 'scan_limit' | 'read_error' } +export interface PythonDiscoveryResult { candidates: PythonCandidate[]; warnings: PythonDiscoveryWarning[]; partial: boolean; scannedRoots: string[] } +export interface PythonDiscoveryFileSystem { + readdir(path: string): Promise; + stat(path: string): Promise<{ isFile(): boolean; isDirectory(): boolean }>; + lstat(path: string): Promise<{ isSymbolicLink(): boolean; isDirectory(): boolean }>; + realpath?(path: string): Promise; + readFile(path: string): Promise; +} +export interface PythonDiscoveryOptions { + fs?: Partial; env?: Record; + homeDir?: string; cwd?: string; platform?: 'darwin' | 'linux' | 'win32'; + pathSeparator?: string; roots?: string[]; maxDirs?: number; maxDepth?: number; timeoutMs?: number; +} +class ScanLimit extends Error { constructor(readonly path: string) { super('scan_limit'); } } +const SKIP = new Set(['node_modules', '.git', 'site-packages', '__pycache__', '.cache', '.cargo', '.rustup', 'target', 'dist', 'release', '.next', 'build']); +const PYTHON_NAME = /^python(?:\d+(?:\.\d+)*t?)?(?:\.exe)?$/i; + +/** Explicit, read-only common-location discovery. Finding a path is NOT validation. */ +export async function discoverPythonRuntimes(options: PythonDiscoveryOptions = {}): Promise { + const fs: PythonDiscoveryFileSystem = { + readdir: async p => nativeFs.readdir(p), stat: nativeFs.stat, lstat: nativeFs.lstat, + realpath: nativeFs.realpath, readFile: p => nativeFs.readFile(p, 'utf8'), ...options.fs, + }; + const windows = (options.platform ?? process.platform) === 'win32'; + const path = windows ? paths.win32 : paths.posix; + const env = options.env ?? process.env; + const home = path.resolve(options.homeDir ?? env.HOME ?? env.USERPROFILE ?? homedir()); + const cwd = options.cwd ?? process.cwd(); + const deadline = Date.now() + Math.max(1, options.timeoutMs ?? 4000); + const maxDirs = Math.max(1, options.maxDirs ?? 4000), maxDepth = Math.max(0, options.maxDepth ?? 4); + const result: PythonDiscoveryResult = { candidates: [], warnings: [], partial: false, scannedRoots: [] }; + const identities = new Set(), visited = new Set(); + let dirs = 0; + const key = (p: string) => windows ? p.toLowerCase() : p; + const warn = (p: string, reason: PythonDiscoveryWarning['reason']) => { + result.partial = true; + if (result.warnings.length < 100 && !result.warnings.some(w => w.path === p && w.reason === reason)) result.warnings.push({ path: p, reason }); + }; + async function read(p: string, fn: () => Promise): Promise { + const remaining = deadline - Date.now(); + if (remaining <= 0) throw new ScanLimit(p); + let timer: ReturnType | undefined; + try { + return await Promise.race([fn(), new Promise((_, reject) => { timer = setTimeout(() => reject(new ScanLimit(p)), remaining); })]); + } catch (error) { + if (error instanceof ScanLimit) throw error; + const code = (error as NodeJS.ErrnoException).code; + if (code !== 'ENOENT' && code !== 'ENOTDIR') warn(p, code === 'EACCES' || code === 'EPERM' ? 'permission_denied' : 'read_error'); + return undefined; + } finally { if (timer) clearTimeout(timer); } + } + const canonical = async (p: string) => key(path.normalize(fs.realpath ? await read(p, () => fs.realpath!(p)) ?? p : p)); + const source = (p: string) => { + const s = p.replaceAll('\\', '/').toLowerCase(); + return s.includes('/.pyenv/versions/') ? 'pyenv' : /\/(?:\.?conda|miniconda\d*|anaconda\d*)(?:\/|$)/.test(s) ? 'conda' : s.includes('/uv/python/') ? 'uv' : 'venv'; + }; + async function candidate(p: string, from: string) { + const info = await read(p, () => fs.stat(p)); + if (!info?.isFile()) return; + const root = path.dirname(path.dirname(p)); + const cfg = await read(path.join(root, 'pyvenv.cfg'), () => fs.readFile(path.join(root, 'pyvenv.cfg'))); + const conda = await read(path.join(root, 'conda-meta'), () => fs.stat(path.join(root, 'conda-meta'))); + const isEnvironment = cfg !== undefined || conda?.isDirectory() || ['venv', 'pyenv', 'conda', 'uv'].includes(from); + const identity = isEnvironment ? 'env:' + await canonical(root) : 'file:' + await canonical(p); + if (identities.has(identity)) return; + identities.add(identity); + const version = cfg?.match(/^version\s*=\s*([^\r\n]+)$/im)?.[1]?.trim(); + result.candidates.push({ pythonPath: path.normalize(p), source: from, ...(version ? { version } : {}) }); + if (result.candidates.length >= 256) throw new ScanLimit(p); + } + const commonNames = windows ? ['python.exe', 'python3.exe'] : ['python', 'python3']; + async function bin(p: string, from: string) { + for (const name of commonNames) await candidate(path.join(p, name), from); + // Include versioned installations without assuming a particular Python release. + const names = await read(p, () => fs.readdir(p)); + for (const name of (names ?? []).filter(n => PYTHON_NAME.test(n) && !commonNames.includes(n)).sort()) await candidate(path.join(p, name), from); + } + async function environment(p: string, from: string) { + // A venv symlink is safe to inspect directly; its directory is never traversed. + await bin(path.join(p, windows ? 'Scripts' : 'bin'), from); + if (windows) await candidate(path.join(p, 'python.exe'), from); // Conda on Windows. + } + try { + for (const p of (env.PATH ?? env.Path ?? '').split(options.pathSeparator ?? (windows ? ';' : ':')).filter(Boolean)) { + // Relative PATH entries are deliberately ignored, as their identity changes with cwd. + if (path.isAbsolute(p)) await bin(path.normalize(p), 'path'); + } + const systems = windows ? [path.join(env.LOCALAPPDATA ?? path.join(home, 'AppData', 'Local'), 'Programs', 'Python')] : ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/opt/local/bin']; + if (!options.roots && !windows) for (const p of systems) { + result.scannedRoots.push(p); await bin(p, 'system'); + } + const defaults = [ + path.join(home, '.pyenv', 'versions'), path.join(home, '.conda', 'envs'), + path.join(home, 'miniconda3'), path.join(home, 'anaconda3'), + path.join(home, '.local', 'share', 'uv', 'python'), + ...['Work', 'Tools', 'Projects', 'Developer'].map(p => path.join(home, p)), path.join(home, 'gopath', 'src'), + ...(windows ? [...systems, path.join(home, 'source', 'repos')] : ['/opt/miniconda3', '/opt/anaconda3', '/Library/Frameworks/Python.framework/Versions']), + ]; + for (const raw of options.roots ?? defaults) { + const root = path.isAbsolute(raw) ? path.normalize(raw) : path.resolve(cwd, raw); + result.scannedRoots.push(root); + const queue = [{ p: root, depth: 0 }]; + for (let i = 0; i < queue.length; i++) { + const { p, depth } = queue[i]; + if (dirs >= maxDirs) throw new ScanLimit(p); + const info = await read(p, () => fs.lstat(p)); + if (!info?.isDirectory() || info.isSymbolicLink()) continue; + const id = await canonical(p); + if (visited.has(id)) continue; + visited.add(id); dirs++; + await environment(p, source(p)); + const names = await read(p, () => fs.readdir(p)); + for (const name of names ?? []) { + const child = path.join(p, name), lower = name.toLowerCase(); + if (SKIP.has(lower)) continue; + if (lower === '.venv' || lower === 'venv') { await environment(child, 'venv'); continue; } + if (lower === 'bin' || lower === 'scripts' || lower === 'lib' || lower === 'lib64' || lower === 'include' || lower === 'conda-meta') continue; + const entry = await read(child, () => fs.lstat(child)); + if (!entry?.isDirectory() || entry.isSymbolicLink()) continue; + if (depth >= maxDepth) { warn(child, 'scan_limit'); continue; } + queue.push({ p: child, depth: depth + 1 }); + } + } + } + } catch (error) { + if (!(error instanceof ScanLimit)) throw error; + warn(error.path, 'scan_limit'); + } + return result; +} diff --git a/electron/src/main/runtime-import-probe.ts b/electron/src/main/runtime-import-probe.ts new file mode 100644 index 000000000..eab7d40ca --- /dev/null +++ b/electron/src/main/runtime-import-probe.ts @@ -0,0 +1,25 @@ +const RUNTIME_IMPORT_MODULES = [ + 'fastapi', + 'uvicorn', + 'omnivoice', + 'faster_whisper', + 'sentencepiece', + 'torch', + 'torchaudio', + 'torchvision', +] as const; +const IMPORT_MARKER = 'VOICESTUDIO_IMPORT='; + +/** Import every runtime dependency, announcing each one before import. */ +export const RUNTIME_IMPORT_PROBE = RUNTIME_IMPORT_MODULES.map( + (name) => `print('${IMPORT_MARKER}${name}', flush=True)\nimport ${name}`, +).join('\n'); + +/** The dependency an import probe was loading when its output stopped. */ +export function lastImportAttempted(output: unknown): string | null { + const marked = String(output ?? '') + .split(/\r?\n/) + .filter((line) => line.startsWith(IMPORT_MARKER)) + .at(-1); + return marked ? marked.slice(IMPORT_MARKER.length).trim() || null : null; +} diff --git a/electron/src/main/runtime-probe.ts b/electron/src/main/runtime-probe.ts index abc7645a4..9a2c91b52 100644 --- a/electron/src/main/runtime-probe.ts +++ b/electron/src/main/runtime-probe.ts @@ -9,6 +9,7 @@ export interface RuntimeProbeOptions { onClose?: (child: ChildProcess) => void; /** Resolve with stderr appended to stdout (uv writes its plan and debug log there). */ captureStderr?: boolean; + onOutput?: (text: string, stream: 'stdout' | 'stderr') => void; } /** Terminate the probe tree; its close event remains the cleanup/settlement gate. */ @@ -72,13 +73,17 @@ export function runRuntimeProbe( options.signal?.addEventListener('abort', abort, { once: true }); child.stdin?.on('error', () => {}); child.stdout?.on('data', (chunk: Buffer | string) => { - stdout = (stdout + chunk.toString()).slice(-65_536); + const text = chunk.toString(); + stdout = (stdout + text).slice(-65_536); + options.onOutput?.(text, 'stdout'); }); let stderr = ''; if (options.captureStderr) child.stderr?.on('data', (chunk: Buffer | string) => { + const text = chunk.toString(); // A verbose uv dry run lists hundreds of packages; keep enough for all of them. - stderr = (stderr + chunk.toString()).slice(-4_194_304); + stderr = (stderr + text).slice(-4_194_304); + options.onOutput?.(text, 'stderr'); }); child.once('error', (error) => { failure ??= error; @@ -93,6 +98,7 @@ export function runRuntimeProbe( reject( Object.assign(failure ?? new Error(`Runtime setup exited with code ${code}`), { stdout, + stderr, code: failure && 'code' in failure ? failure.code : code, }), ); diff --git a/electron/src/main/runtime-project.ts b/electron/src/main/runtime-project.ts index 27633fa90..8c621d650 100644 --- a/electron/src/main/runtime-project.ts +++ b/electron/src/main/runtime-project.ts @@ -7,6 +7,8 @@ export { nvidiaDriverPresent, cudaOnlyPackages } from '../../scripts/torch-varia import { inspectRuntimeInterpreter } from './runtime-interpreter'; import { RuntimeLaunchRefusedError, runtimeLaunchRefusal } from './runtime-launch-refusal'; import { WINDOWS_ROCM_IMPORT_TIMEOUT_MS } from './runtime-probe'; +import { RUNTIME_IMPORT_PROBE, lastImportAttempted } from './runtime-import-probe'; +export { RUNTIME_IMPORT_PROBE, lastImportAttempted } from './runtime-import-probe'; import { windowsRocmSelected, windowsRocmStamp, @@ -180,33 +182,6 @@ export const OUTDATED_SYSTEM_LIBRARY_CODE = 'OUTDATED_SYSTEM_LIBRARY'; export const MIN_MSVCP140_VERSION = [14, 40] as const; /** Windows exit status for an access violation, unsigned and signed. */ const ACCESS_VIOLATION_EXIT_CODES = new Set([3221225477, -1073741819]); -const RUNTIME_IMPORT_MODULES = [ - 'fastapi', - 'uvicorn', - 'omnivoice', - 'faster_whisper', - 'sentencepiece', - 'torch', - 'torchaudio', - 'torchvision', -] as const; -const IMPORT_MARKER = 'VOICESTUDIO_IMPORT='; -/** - * Imports every runtime module, announcing each one first. A native import that - * dies with an access violation (exit code 3221225477) leaves no traceback, so - * the last announcement is the only evidence of which module crashed (#3293). - */ -export const RUNTIME_IMPORT_PROBE = RUNTIME_IMPORT_MODULES.map( - (name) => `print('${IMPORT_MARKER}${name}', flush=True)\nimport ${name}`, -).join('\n'); -/** The module an import probe was loading when its output stopped, if it said. */ -export function lastImportAttempted(output: unknown): string | null { - const marked = String(output ?? '') - .split(/\r?\n/) - .filter((line) => line.startsWith(IMPORT_MARKER)) - .at(-1); - return marked ? marked.slice(IMPORT_MARKER.length).trim() || null : null; -} function importFailure(error: unknown): Error { const failure = error as { code?: unknown; message?: unknown; stdout?: unknown } | null; const module = lastImportAttempted(failure?.stdout); diff --git a/electron/src/main/runtime-python-selection.test.ts b/electron/src/main/runtime-python-selection.test.ts new file mode 100644 index 000000000..fdfe024b5 --- /dev/null +++ b/electron/src/main/runtime-python-selection.test.ts @@ -0,0 +1,86 @@ +// @vitest-environment node +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { SELECTED_RUNTIME_IMPORT_PROBE, buildPythonRepairPlan, isVenvInterpreter, createOpaqueToken, sanitizedPythonEnvironment } from './runtime-python-selection'; + +const userData = mkdtempSync(join(tmpdir(), 'voicestudio-runtime-test-')); +vi.mock('electron', () => ({ app: { getPath: () => userData } })); + +import { shouldBypassManagedRuntime, validatePythonRuntime, clearPythonRuntimeSelection, loadPythonRuntimeSelection, savePythonRuntimeSelection } from './runtime-python-selection'; + +describe('existing Python runtime selection', () => { + beforeEach(() => clearPythonRuntimeSelection()); + afterEach(() => clearPythonRuntimeSelection()); + + it('persists and reloads an absolute interpreter path', () => { + savePythonRuntimeSelection('/tmp/fixture/.venv/bin/python'); + expect(loadPythonRuntimeSelection()).toEqual({ pythonPath: '/tmp/fixture/.venv/bin/python' }); + }); + + it('rejects a missing interpreter without spawning it', async () => { + const result = await validatePythonRuntime('/tmp/does-not-exist/python', process.cwd()); + expect(result).toMatchObject({ ok: false, detail: 'interpreter_not_found' }); + }); + + it('bypasses managed readiness only for a packaged selected interpreter', () => { + expect(shouldBypassManagedRuntime(true, '/tmp/.venv/bin/python', undefined)).toBe(true); + expect(shouldBypassManagedRuntime(false, '/tmp/.venv/bin/python', undefined)).toBe(false); + expect(shouldBypassManagedRuntime(true, '/tmp/.venv/bin/python', 'custom-backend')).toBe(false); + }); + it('verifies the backend entry module, not only a dependency allowlist', () => { + expect(SELECTED_RUNTIME_IMPORT_PROBE).toContain("print('VOICESTUDIO_BACKEND_IMPORT=main'"); + expect(SELECTED_RUNTIME_IMPORT_PROBE).toContain('import main'); + expect(SELECTED_RUNTIME_IMPORT_PROBE).toContain('sys.version_info[:2] < (3, 11)'); + expect(SELECTED_RUNTIME_IMPORT_PROBE).not.toContain('sys.version_info[:2] < [3,11]'); + }); + + it('builds repair plans only from reviewed project requirements', () => { + const project = mkdtempSync(join(tmpdir(), 'voicestudio-manifest-')); + writeFileSync(join(project, 'pyproject.toml'), '[project]\ndependencies = [\n "torch>=2.4",\n "torchaudio>=2.4",\n "setuptools>=75,<80",\n]\n'); + expect(buildPythonRepairPlan('/tmp/requirements/project', ['torch'], project)).toEqual({ + interpreter: '/tmp/requirements/project', packages: ['torch>=2.4'], + }); + expect(buildPythonRepairPlan('/tmp/requirements/project', ['torch', 'NoSuchModule'], project)).toBeNull(); + expect(buildPythonRepairPlan('/tmp/requirements/project', ['torchaudio'], project)?.packages).toEqual(['torchaudio>=2.4']); + }); + + it('does not inherit Python or pip installation overrides', () => { + const env = sanitizedPythonEnvironment({ PYTHONPATH: '/tmp/evil', PIP_TARGET: '/tmp/evil', PIP_PREFIX: '/tmp/evil', PIP_USER: '1', PIP_INDEX_URL: 'https://evil.invalid' }); + expect(env.PYTHONPATH).toBeUndefined(); + expect(env.PIP_TARGET).toBeUndefined(); + expect(env.PIP_PREFIX).toBeUndefined(); + expect(env.PIP_USER).toBeUndefined(); + expect(env.PIP_CONFIG_FILE).toBeTruthy(); + }); + + it('rejects system interpreters as repair targets', () => { + expect(isVenvInterpreter('/usr/bin/python3', '/tmp/project')).toBe(false); + }); + + it('creates unguessable opaque tokens', () => { + const token = createOpaqueToken(); + expect(token).toMatch(/^[A-Za-z0-9_-]{32,}$/); + expect(createOpaqueToken()).not.toBe(token); + }); + + it('accepts the isolated verification interpreter when requested', async () => { + const python = process.env.VOICESTUDIO_REAL_TEST_PYTHON; + if (!python) return; + const result = await validatePythonRuntime(python, process.cwd().endsWith('/electron') ? resolve(process.cwd(), '..') : process.cwd()); + expect(result).toMatchObject({ ok: true, pythonPath: python }); + expect(result.version).toMatch(/^\d+\.\d+(?:\.\d+)?$/); + }, 180_000); + + it('runs a real fixture interpreter and reports missing imports', async () => { + const dir = mkdtempSync(join(tmpdir(), 'voicestudio-python-fixture-')); + const fixture = join(dir, 'python'); + const realPython = process.env.VOICESTUDIO_TEST_PYTHON || '/usr/bin/python3'; + writeFileSync(fixture, `#!${realPython}\n`); + chmodSync(fixture, 0o755); + const result = await validatePythonRuntime(fixture, process.cwd()); + expect(result.ok).toBe(false); + expect(result.detail || result.missingModules?.length || result.version).toBeTruthy(); + }, 30_000); +}); diff --git a/electron/src/main/runtime-python-selection.ts b/electron/src/main/runtime-python-selection.ts new file mode 100644 index 000000000..253914304 --- /dev/null +++ b/electron/src/main/runtime-python-selection.ts @@ -0,0 +1,183 @@ +import { app } from 'electron'; +import { existsSync, readFileSync, statSync, writeFileSync, mkdirSync, rmSync, mkdtempSync } from 'node:fs'; +import { dirname, isAbsolute, resolve, join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { randomBytes } from 'node:crypto'; +import { runRuntimeProbe } from './runtime-probe'; +import { RUNTIME_IMPORT_PROBE, lastImportAttempted } from './runtime-import-probe'; + +const FILE = 'python-runtime-selection.json'; +const MIN_PYTHON = [3, 11] as const; +const PROBE_TIMEOUT_MS = 180_000; +const VERSION_PREFIX = 'VOICESTUDIO_PYTHON='; + +export interface PythonRuntimeSelection { pythonPath: string; } +export interface PythonRuntimeValidation { + ok: boolean; + pythonPath: string; + version?: string; + missingModules?: string[]; + unsupportedModules?: string[]; + detail?: string; + repairPlan?: PythonRepairPlan; +} +export interface PythonRepairPlan { interpreter: string; packages: string[]; } + +/** Import names which differ from the package names in the reviewed manifest. */ +const IMPORT_PACKAGE_ALIAS: Record = { + faster_whisper: 'faster-whisper', + pkg_resources: 'setuptools', + PIL: 'pillow', +}; + +export function createOpaqueToken(): string { return randomBytes(32).toString('base64url'); } + +/** Only package specs reviewed in the repository may be emitted for repair. */ +export function buildPythonRepairPlan(interpreter: string, missingModules: string[], cwd = process.cwd()): PythonRepairPlan | null { + let source: string; + try { source = readFileSync(join(cwd, 'pyproject.toml'), 'utf8'); } catch { return null; } + const dependencyBlock = source.match(/^dependencies\s*=\s*\[(.*?)^\s*\]/ms)?.[1]; + if (!dependencyBlock) return null; + const reviewed = new Map(); + for (const match of dependencyBlock.matchAll(/^[ \t]*["']([A-Za-z0-9_.-]+(?:\s*(?:[<>=!~].*|@\s*https?:\/\/.*))?)["'][,]?/gm)) { + const spec = match[1].trim(); + const name = spec.split(/[<>=!~@\s]/, 1)[0].toLowerCase().replaceAll('_', '-'); + reviewed.set(name, spec); + } + const packages: string[] = []; + for (const module of [...new Set(missingModules)]) { + const root = module.split('.')[0]; + const packageName = (IMPORT_PACKAGE_ALIAS[root] ?? root).toLowerCase().replaceAll('_', '-'); + const spec = reviewed.get(packageName); + if (!spec) return null; + packages.push(spec); + } + return packages.length ? { interpreter: resolve(interpreter), packages: [...new Set(packages)].sort() } : null; +} + +/** Environment for probes and pip: no user-controlled Python or pip config. */ +export function sanitizedPythonEnvironment(extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { + const env = { ...process.env, ...extra }; + for (const key of ['PYTHONPATH', 'PYTHONHOME', 'PYTHONSTARTUP', 'PYTHONINSPECT']) delete env[key]; + for (const key of Object.keys(env)) if (key.startsWith('PIP_')) delete env[key]; + env.PYTHONDONTWRITEBYTECODE = '1'; + env.PYTHONNOUSERSITE = '1'; + env.PIP_CONFIG_FILE = process.platform === 'win32' ? 'NUL' : '/dev/null'; + return env; +} + +export function isVenvInterpreter(pythonPath: string, _cwd = process.cwd()): boolean { + const normalized = resolve(pythonPath); + if (/^(?:\/usr\/|\/System\/|C:\\Windows\\|C:\\Program Files\\)/i.test(normalized)) return false; + const bin = dirname(normalized); + const root = dirname(bin); + try { return existsSync(join(root, 'pyvenv.cfg')); } catch { return false; } +} + +function selectionFile(): string { return join(app.getPath('userData'), FILE); } + +export function loadPythonRuntimeSelection(): PythonRuntimeSelection | null { + try { + const parsed = JSON.parse(readFileSync(selectionFile(), 'utf8')) as { pythonPath?: unknown }; + if (typeof parsed.pythonPath !== 'string' || !isAbsolute(parsed.pythonPath)) return null; + return { pythonPath: resolve(parsed.pythonPath) }; + } catch { return null; } +} + +export function savePythonRuntimeSelection(pythonPath: string): PythonRuntimeSelection { + const normalized = resolve(pythonPath); + mkdirSync(dirname(selectionFile()), { recursive: true }); + writeFileSync(selectionFile(), JSON.stringify({ pythonPath: normalized }, null, 2), 'utf8'); + return { pythonPath: normalized }; +} + +export function clearPythonRuntimeSelection(): void { rmSync(selectionFile(), { force: true }); } + +export function selectedPythonPath(): string | null { return loadPythonRuntimeSelection()?.pythonPath ?? null; } + +/** A saved interpreter must skip packaged managed-runtime readiness checks. */ +export function shouldBypassManagedRuntime( + packaged: boolean, + selected: string | null, + override: string | undefined, +): boolean { + return packaged && Boolean(selected) && !override?.trim(); +} + +export const BACKEND_IMPORT_MARKER = 'VOICESTUDIO_BACKEND_IMPORT=main'; +export const SELECTED_RUNTIME_IMPORT_PROBE = [ + 'import json, os, sys', + `sys.path.insert(0, os.path.join(os.getcwd(), 'backend'))`, + `print(${JSON.stringify(VERSION_PREFIX)} + sys.version.split()[0], flush=True)`, + `print('VOICESTUDIO_VENV=' + ('1' if sys.prefix != sys.base_prefix else '0'), flush=True)`, + `print('VOICESTUDIO_EXTERNALLY_MANAGED=' + ('1' if sys.prefix == sys.base_prefix and __import__('os').path.exists(__import__('sysconfig').get_path('stdlib') + '/EXTERNALLY-MANAGED') else '0'), flush=True)`, + `if sys.version_info[:2] < (${MIN_PYTHON[0]}, ${MIN_PYTHON[1]}): raise SystemExit('python_version_unsupported')`, + RUNTIME_IMPORT_PROBE, + `print('${BACKEND_IMPORT_MARKER}', flush=True)`, + 'import main', +].join('\n'); + +export async function validatePythonRuntime(pythonPath: string, cwd: string): Promise { + const normalized = resolve(pythonPath); + if (!isAbsolute(pythonPath) || !existsSync(normalized)) + return { ok: false, pythonPath: normalized, detail: 'interpreter_not_found' }; + try { + if (!statSync(normalized).isFile()) return { ok: false, pythonPath: normalized, detail: 'interpreter_not_file' }; + } catch { return { ok: false, pythonPath: normalized, detail: 'interpreter_not_readable' }; } + const sandbox = mkdtempSync(join(tmpdir(), 'voicestudio-runtime-probe-')); + try { + const output = await runRuntimeProbe(normalized, ['-c', SELECTED_RUNTIME_IMPORT_PROBE], cwd, { + ...sanitizedPythonEnvironment(), + PYTHONDONTWRITEBYTECODE: '1', + PYTHONNOUSERSITE: '1', + HF_HUB_OFFLINE: '1', + TRANSFORMERS_OFFLINE: '1', + OMNIVOICE_DATA_DIR: join(sandbox, 'data'), + OMNIVOICE_CACHE_DIR: join(sandbox, 'models'), + HF_HOME: join(sandbox, 'models'), + HF_HUB_CACHE: join(sandbox, 'models'), + TORCH_HOME: join(sandbox, 'models'), + OMNIVOICE_DISABLE_FILE_LOG: '1', + TMPDIR: join(sandbox, 'tmp'), + TMP: join(sandbox, 'tmp'), + TEMP: join(sandbox, 'tmp'), + }, { timeoutMs: PROBE_TIMEOUT_MS, captureStderr: true }); + const version = output.split(/\r?\n/).find((line) => line.startsWith(VERSION_PREFIX))?.slice(VERSION_PREFIX.length); + if (!version) return { ok: false, pythonPath: normalized, detail: 'version_unavailable' }; + const [major, minor] = version.split('.').map(Number); + if (major < MIN_PYTHON[0] || (major === MIN_PYTHON[0] && minor < MIN_PYTHON[1])) + return { ok: false, pythonPath: normalized, version, detail: 'python_version_unsupported' }; + if (!isVenvInterpreter(normalized, cwd) || !output.includes('VOICESTUDIO_VENV=1')) + return { ok: false, pythonPath: normalized, version, detail: 'venv_required' }; + if (output.includes('VOICESTUDIO_EXTERNALLY_MANAGED=1')) + return { ok: false, pythonPath: normalized, version, detail: 'externally_managed' }; + return { ok: true, pythonPath: normalized, version }; + } catch (error) { + const failure = error as { stdout?: unknown; stderr?: unknown; message?: unknown }; + const text = `${String(failure.stdout ?? '')}\n${String(failure.stderr ?? '')}`; + const version = text.match(/VOICESTUDIO_PYTHON=([0-9]+\.[0-9]+(?:\.[0-9]+)?)/)?.[1]; + const attempted = text.includes(BACKEND_IMPORT_MARKER) + ? 'main' + : lastImportAttempted(text); + const missing: string[] = [...text.matchAll(/No module named ['\"]([^'\"]+)['\"]/g)].map((m) => m[1]); + const detail = version && (() => { + const [major, minor] = version.split('.').map(Number); + return major < MIN_PYTHON[0] || (major === MIN_PYTHON[0] && minor < MIN_PYTHON[1]); + })() + ? 'python_version_unsupported' + : attempted + ? `missing_or_failed:${attempted}` + : String(failure.message ?? 'probe_failed').split('\n')[0]; + const uniqueMissing = [...new Set(missing)]; + const canRepair = isVenvInterpreter(normalized, cwd) && text.includes('VOICESTUDIO_VENV=1') && !text.includes('VOICESTUDIO_EXTERNALLY_MANAGED=1'); + const repairPlan = canRepair && uniqueMissing.length ? buildPythonRepairPlan(normalized, uniqueMissing, cwd) : undefined; + return { + ok: false, pythonPath: normalized, version, + missingModules: uniqueMissing, detail, + ...(uniqueMissing.length && !repairPlan ? { unsupportedModules: uniqueMissing } : {}), + ...(repairPlan ? { repairPlan } : {}), + }; + } finally { + rmSync(sandbox, { recursive: true, force: true }); + } +} diff --git a/electron/src/preload/index.d.ts b/electron/src/preload/index.d.ts index 9045f9175..e9ab2525f 100644 --- a/electron/src/preload/index.d.ts +++ b/electron/src/preload/index.d.ts @@ -105,6 +105,23 @@ export interface RuntimeLocation { custom: boolean; } +export interface PythonRuntimeCandidate { + pythonPath: string; + source: string; + version?: string; +} +export interface PythonRuntimeDiscoveryWarning { + path: string; + reason: 'permission_denied' | 'scan_limit' | 'read_error'; +} +export interface PythonDiscoveryResult { + candidates: PythonRuntimeCandidate[]; + warnings: PythonRuntimeDiscoveryWarning[]; + partial: boolean; + scannedRoots: string[]; +} +export interface PythonRepairPlan { interpreter: string; packages: string[]; } + export interface BackendConnection { remote: boolean; url: string; @@ -429,6 +446,65 @@ export interface VoiceStudioBridge { setRuntimeRegion(region: RuntimeRegion): Promise; chooseRuntimeLocation(title: string): Promise; useDefaultRuntimeLocation(): Promise; + getPythonRuntime(): Promise<{ + selection: { pythonPath: string } | null; + overrideActive: boolean; + }>; + choosePythonRuntime(title?: string): Promise<{ + ok: boolean; + canceled?: boolean; + pythonPath?: string; + version?: string; + missingModules?: string[]; + detail?: string; + token?: string; + repairPlan?: PythonRepairPlan; + }>; + confirmPythonRuntime(token: string): Promise<{ + ok: boolean; + pythonPath: string; + version?: string; + missingModules?: string[]; + detail?: string; + repairPlan?: PythonRepairPlan; + }>; + planPythonRepair(selectionToken: string): Promise<{ + ok: boolean; + pythonPath: string; + version?: string; + missingModules?: string[]; + detail?: string; + repairToken?: string; + repairPlan?: PythonRepairPlan; + }>; + installPythonRepair(request: { + token: string; + pythonPath: string; + packages: string[]; + }): Promise<{ + ok: boolean; + pythonPath: string; + version?: string; + missingModules?: string[]; + detail?: string; + installed: boolean; + canceled?: boolean; + token?: string; + repairToken?: string; + outputTail?: string; + }>; + onPythonRepairProgress(callback: (event: { text: string; stream: 'stdout' | 'stderr' }) => void): () => void; + useManagedPython(): Promise<{ ok: boolean }>; + discoverPythonRuntimes(): Promise; + useDiscoveredPythonRuntime(pythonPath: string): Promise<{ + ok: boolean; + pythonPath: string; + version?: string; + missingModules?: string[]; + detail?: string; + token?: string; + repairPlan?: PythonRepairPlan; + }>; getConnection(): Promise; getHostSnapshot(): Promise; testRemote(input: { url: string; apiKey: string }): Promise; diff --git a/electron/src/preload/index.ts b/electron/src/preload/index.ts index d56374546..808e830f8 100644 --- a/electron/src/preload/index.ts +++ b/electron/src/preload/index.ts @@ -9,6 +9,7 @@ import type { VoiceStudioBridge, RepairAgentEvent, AccountPublicState, + PythonDiscoveryResult, } from './index.d'; function subscribe(channel: string, cb: (payload: T) => void): () => void { @@ -104,6 +105,19 @@ const bridge: VoiceStudioBridge = { setRuntimeRegion: (region) => ipcRenderer.invoke('backend:setRuntimeRegion', region), chooseRuntimeLocation: (title) => ipcRenderer.invoke('backend:chooseRuntimeLocation', title), useDefaultRuntimeLocation: () => ipcRenderer.invoke('backend:useDefaultRuntimeLocation'), + getPythonRuntime: () => ipcRenderer.invoke('backend:getPythonRuntime') as Promise<{ + selection: { pythonPath: string } | null; + overrideActive: boolean; + }>, + choosePythonRuntime: (title) => ipcRenderer.invoke('backend:choosePythonRuntime', title), + confirmPythonRuntime: (token) => ipcRenderer.invoke('backend:confirmPythonRuntime', token), + planPythonRepair: (pythonPath) => ipcRenderer.invoke('backend:planPythonRepair', pythonPath), + installPythonRepair: (request) => ipcRenderer.invoke('backend:installPythonRepair', request), + onPythonRepairProgress: (callback) => subscribe('backend:pythonRepairProgress', callback), + useManagedPython: () => ipcRenderer.invoke('backend:useManagedPython'), + discoverPythonRuntimes: () => ipcRenderer.invoke('backend:discoverPythonRuntimes') as Promise, + useDiscoveredPythonRuntime: (pythonPath) => + ipcRenderer.invoke('backend:useDiscoveredPythonRuntime', pythonPath), restart: () => ipcRenderer.invoke('backend:restart') as Promise, getConnection: () => ipcRenderer.invoke('backend:getConnection'), getHostSnapshot: () => ipcRenderer.invoke('backend:hostSnapshot'), diff --git a/electron/src/renderer/src/components/backend-gate.tsx b/electron/src/renderer/src/components/backend-gate.tsx index a2266833b..f7667ca16 100644 --- a/electron/src/renderer/src/components/backend-gate.tsx +++ b/electron/src/renderer/src/components/backend-gate.tsx @@ -32,6 +32,7 @@ import { import { Spinner } from '@/components/ui/spinner'; import { ConfirmDialog } from '@/features/clone/confirm-dialog'; import { RemoteBackendSettings } from '@/features/settings/remote-backend-settings'; +import { ExistingPythonSettings } from '@/features/settings/existing-python-settings'; import { useBackendStatus } from '@/hooks/use-backend-status'; import { isBackendBusy } from '@shared/utils/backendStage'; import { @@ -305,6 +306,7 @@ export function BackendGate({ children, repairDock }: BackendGateProps) { {setup ? ( <>

{t('backend.setup_hint')}

+ {!unsupportedPlatform && !wrongArchitecture ? : null} {wrongArchitecture ? (

{t('backend.setup_wrong_architecture')} diff --git a/electron/src/renderer/src/features/settings/existing-python-settings.test.tsx b/electron/src/renderer/src/features/settings/existing-python-settings.test.tsx new file mode 100644 index 000000000..b5c61e0e3 --- /dev/null +++ b/electron/src/renderer/src/features/settings/existing-python-settings.test.tsx @@ -0,0 +1,226 @@ +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { ExistingPythonSettings } from './existing-python-settings'; +const backend = vi.hoisted(() => ({ + getPythonRuntime: vi.fn(), discoverPythonRuntimes: vi.fn(), + useDiscoveredPythonRuntime: vi.fn(), choosePythonRuntime: vi.fn(), useManagedPython: vi.fn(), + confirmPythonRuntime: vi.fn(), planPythonRepair: vi.fn(), installPythonRepair: vi.fn(), +})); +vi.mock('@/components/bridge', () => ({ getBridge: () => ({ backend }) })); +vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) })); +const candidate = { pythonPath: '/fixture/.venv/bin/python', source: 'venv', version: '3.14.3' }; +const found = { candidates: [candidate], warnings: [], partial: false, scannedRoots: ['/fixture'] }; +afterEach(cleanup); +beforeEach(() => { + vi.resetAllMocks(); + backend.getPythonRuntime.mockResolvedValue({ selection: null, overrideActive: false }); + backend.discoverPythonRuntimes.mockResolvedValue(found); + backend.useDiscoveredPythonRuntime.mockResolvedValue({ ok: true, token: 'selection-token', pythonPath: candidate.pythonPath, version: '3.14.3' }); + backend.confirmPythonRuntime.mockResolvedValue({ ok: true, pythonPath: candidate.pythonPath, version: '3.14.3' }); + backend.choosePythonRuntime.mockResolvedValue({ canceled: true, ok: false }); +}); +async function search() { + render(); + await waitFor(() => expect(backend.getPythonRuntime).toHaveBeenCalled()); + fireEvent.click(screen.getByTestId('python-runtime-quick-search')); +} +it('lists paths and metadata without selecting, while retaining manual selection', async () => { + await search(); + expect(await screen.findByText(candidate.pythonPath)).toBeVisible(); + expect(screen.getByText('3.14.3')).toBeVisible(); + expect(screen.getByText('settings.python_runtime_search_scope')).toBeVisible(); + expect(screen.getByRole('button', { name: 'settings.python_runtime_choose' })).toBeEnabled(); + expect(backend.useDiscoveredPythonRuntime).not.toHaveBeenCalled(); +}); +it('shows permission and incomplete-result warnings alongside readable candidates', async () => { + backend.discoverPythonRuntimes.mockResolvedValue({ ...found, partial: true, warnings: [{ path: '/denied', reason: 'permission_denied' }] }); + await search(); + expect(await screen.findByText('settings.python_runtime_permission_warning')).toBeVisible(); + // The permission-specific warning already states that results may be incomplete. + expect(screen.queryByText('settings.python_runtime_partial_warning')).toBeNull(); + expect(screen.getByText(candidate.pythonPath)).toBeVisible(); +}); +it('shows the limit warning even if some environments were found', async () => { + backend.discoverPythonRuntimes.mockResolvedValue({ ...found, partial: true, warnings: [{ path: '/large', reason: 'scan_limit' }] }); + await search(); + expect(await screen.findByText('settings.python_runtime_partial_warning')).toBeVisible(); + expect(screen.queryByText('settings.python_runtime_permission_warning')).toBeNull(); +}); +it('shows empty results without removing the manual picker', async () => { + backend.discoverPythonRuntimes.mockResolvedValue({ ...found, candidates: [] }); + await search(); + expect(await screen.findByText('settings.python_runtime_empty')).toBeVisible(); + expect(screen.getByRole('button', { name: 'settings.python_runtime_choose' })).toBeEnabled(); +}); +it('reports scan errors and restores enabled controls', async () => { + backend.discoverPythonRuntimes.mockRejectedValue(new Error('scan_failed')); + await search(); + expect(await screen.findByText('scan_failed')).toBeVisible(); + expect(screen.getByTestId('python-runtime-quick-search')).toBeEnabled(); +}); +it('does not allow repeated scans or manual choices while scanning', async () => { + let finish!: (result: typeof found) => void; + backend.discoverPythonRuntimes.mockReturnValue(new Promise(resolve => { finish = resolve; })); + await search(); + expect(screen.getByTestId('python-runtime-quick-search')).toBeDisabled(); + expect(screen.getByRole('button', { name: 'settings.python_runtime_choose' })).toBeDisabled(); + fireEvent.click(screen.getByTestId('python-runtime-quick-search')); + expect(backend.discoverPythonRuntimes).toHaveBeenCalledTimes(1); + await act(async () => finish(found)); +}); +it('stages a validated discovery result without refreshing or saving selection', async () => { + await search(); + fireEvent.click(await screen.findByTestId('python-runtime-candidate')); + expect(await screen.findByRole('button', { name: 'settings.python_runtime_confirm' })).toBeEnabled(); + expect(screen.getByText('settings.python_runtime_ready')).toBeVisible(); + expect(backend.useDiscoveredPythonRuntime).toHaveBeenCalledWith(candidate.pythonPath); + expect(backend.getPythonRuntime).toHaveBeenCalledTimes(1); + expect(backend.choosePythonRuntime).not.toHaveBeenCalled(); +}); +it('stages the native picker result without changing the previously saved selection', async () => { + backend.getPythonRuntime.mockResolvedValue({ selection: { pythonPath: '/previous/bin/python' }, overrideActive: false }); + backend.choosePythonRuntime.mockResolvedValue({ ok: true, token: 'manual-token', pythonPath: candidate.pythonPath, version: '3.14.3' }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'settings.python_runtime_choose' })); + expect(await screen.findByRole('button', { name: 'settings.python_runtime_confirm' })).toBeEnabled(); + expect(screen.getByText('/previous/bin/python')).toBeVisible(); + expect(screen.getByText(candidate.pythonPath)).toBeVisible(); + expect(backend.getPythonRuntime).toHaveBeenCalledTimes(1); +}); +it('reports missing dependencies instead of treating discovery as compatibility', async () => { + backend.useDiscoveredPythonRuntime.mockResolvedValue({ ok: false, missingModules: ['torch'] }); + await search(); + fireEvent.click(await screen.findByTestId('python-runtime-candidate')); + expect(await screen.findByText('settings.python_runtime_missing')).toBeVisible(); + expect(backend.getPythonRuntime).toHaveBeenCalledTimes(1); +}); +it('requires a reviewed plan before any install and allows choosing another interpreter', async () => { + backend.useDiscoveredPythonRuntime.mockResolvedValue({ ok: false, pythonPath: candidate.pythonPath, version: '3.14.3', missingModules: ['torch'], repairPlan: { interpreter: candidate.pythonPath, packages: ['torch>=2.10.0'] } }); + await search(); + fireEvent.click(await screen.findByTestId('python-runtime-candidate')); + expect(await screen.findByRole('button', { name: 'settings.python_runtime_review_install' })).toBeEnabled(); + expect(screen.getByRole('button', { name: 'settings.python_runtime_choose_another' })).toBeEnabled(); + expect(backend.planPythonRepair).not.toHaveBeenCalled(); + expect(backend.installPythonRepair).not.toHaveBeenCalled(); + expect(backend.confirmPythonRuntime).not.toHaveBeenCalled(); + expect(screen.queryByRole('button', { name: 'settings.python_runtime_confirm' })).toBeNull(); +}); +it('does not offer package installation when no reviewed dependency mapping exists', async () => { + backend.useDiscoveredPythonRuntime.mockResolvedValue({ ok: false, pythonPath: candidate.pythonPath, missingModules: ['unreviewed_import'] }); + await search(); + fireEvent.click(await screen.findByTestId('python-runtime-candidate')); + expect(await screen.findByText('settings.python_runtime_repair_blocked')).toBeVisible(); + expect(screen.queryByRole('button', { name: 'settings.python_runtime_review_install' })).toBeNull(); + expect(backend.installPythonRepair).not.toHaveBeenCalled(); +}); +const repairPlan = { interpreter: candidate.pythonPath, packages: ['torch>=2.10.0'] }; +const missing = { ok: false, token: 'candidate-token', pythonPath: candidate.pythonPath, version: '3.14.3', missingModules: ['torch'], repairPlan }; +async function reviewRepair() { + backend.useDiscoveredPythonRuntime.mockResolvedValue(missing); + backend.planPythonRepair.mockResolvedValue({ ...missing, repairToken: 'repair-token' }); + await search(); + fireEvent.click(await screen.findByTestId('python-runtime-candidate')); + fireEvent.click(await screen.findByRole('button', { name: 'settings.python_runtime_review_install' })); + await screen.findByRole('checkbox', { name: 'settings.python_runtime_install_consent' }); +} +it('reviews exact target and packages, and denial never starts installation', async () => { + await reviewRepair(); + expect(backend.planPythonRepair).toHaveBeenCalledWith('candidate-token'); + expect(screen.getByTestId('python-runtime-repair-plan')).toHaveTextContent(candidate.pythonPath); + expect(screen.getByTestId('python-runtime-repair-plan')).toHaveTextContent('torch>=2.10.0'); + expect(screen.getByRole('button', { name: 'settings.python_runtime_install_confirm' })).toBeDisabled(); + fireEvent.click(screen.getByRole('button', { name: 'common.cancel' })); + expect(screen.queryByRole('checkbox')).toBeNull(); + expect(backend.installPythonRepair).not.toHaveBeenCalled(); + expect(backend.confirmPythonRuntime).not.toHaveBeenCalled(); + expect(backend.getPythonRuntime).toHaveBeenCalledTimes(1); +}); +it('installs only the confirmed reviewed target and packages, then still waits for selection confirmation', async () => { + backend.installPythonRepair.mockResolvedValue({ ok: true, pythonPath: candidate.pythonPath, version: '3.14.3', token: 'revalidated-token', installed: true }); + await reviewRepair(); + fireEvent.click(screen.getByRole('checkbox', { name: 'settings.python_runtime_install_consent' })); + fireEvent.click(screen.getByRole('button', { name: 'settings.python_runtime_install_confirm' })); + expect(await screen.findByText('settings.python_runtime_ready')).toBeVisible(); + expect(backend.installPythonRepair).toHaveBeenCalledWith({ token: 'repair-token', pythonPath: candidate.pythonPath, packages: repairPlan.packages }); + expect(backend.confirmPythonRuntime).not.toHaveBeenCalled(); + expect(backend.getPythonRuntime).toHaveBeenCalledTimes(1); + fireEvent.click(screen.getByRole('button', { name: 'settings.python_runtime_confirm' })); + await waitFor(() => expect(backend.confirmPythonRuntime).toHaveBeenCalledWith('revalidated-token')); +}); +it.each([ + ['rejected', new Error('pip_failed')], + ['failed revalidation', { ...missing, installed: true }], + ['canceled', { ...missing, canceled: true, installed: false }], +])('keeps the saved selection unchanged after %s installation', async (_label, outcome) => { + backend.getPythonRuntime.mockResolvedValue({ selection: { pythonPath: '/previous/bin/python' }, overrideActive: false }); + if (outcome instanceof Error) backend.installPythonRepair.mockRejectedValue(outcome); + else backend.installPythonRepair.mockResolvedValue(outcome); + await reviewRepair(); + fireEvent.click(screen.getByRole('checkbox', { name: 'settings.python_runtime_install_consent' })); + fireEvent.click(screen.getByRole('button', { name: 'settings.python_runtime_install_confirm' })); + await waitFor(() => expect(screen.getByRole('button', { name: 'settings.python_runtime_choose_another' })).toBeEnabled()); + if (_label !== 'canceled') expect(await screen.findByText(/python_runtime_repair_failed/)).toBeVisible(); + else expect(screen.queryByText(/python_runtime_repair_failed/)).toBeNull(); + if (outcome instanceof Error) expect(screen.getByText(/pip_failed/)).toBeVisible(); + expect(screen.getByText('/previous/bin/python')).toBeVisible(); + expect(backend.confirmPythonRuntime).not.toHaveBeenCalled(); + expect(backend.getPythonRuntime).toHaveBeenCalledTimes(1); + expect(screen.queryByRole('checkbox')).toBeNull(); + expect(screen.queryByRole('button', { name: 'settings.python_runtime_confirm' })).toBeNull(); + expect(screen.getByRole('button', { name: 'settings.python_runtime_choose_another' })).toBeEnabled(); +}); +it('blocks all selection controls while installation is running and does not save on completion', async () => { + let finish!: (result: unknown) => void; + backend.installPythonRepair.mockReturnValue(new Promise(resolve => { finish = resolve; })); + await reviewRepair(); + fireEvent.click(screen.getByRole('checkbox', { name: 'settings.python_runtime_install_consent' })); + fireEvent.click(screen.getByRole('button', { name: 'settings.python_runtime_install_confirm' })); + expect(await screen.findByText('settings.python_runtime_installing')).toBeVisible(); + expect(screen.getByTestId('python-runtime-quick-search')).toBeDisabled(); + expect(screen.getByRole('button', { name: 'settings.python_runtime_choose' })).toBeDisabled(); + expect(screen.getByTestId('python-runtime-candidate')).toBeDisabled(); + expect(screen.getByRole('button', { name: 'settings.python_runtime_choose_another' })).toBeDisabled(); + expect(backend.installPythonRepair).toHaveBeenCalledTimes(1); + await act(async () => finish({ ok: true, pythonPath: candidate.pythonPath, token: 'repaired-token' })); + expect(screen.getByRole('button', { name: 'settings.python_runtime_confirm' })).toBeEnabled(); + expect(backend.confirmPythonRuntime).not.toHaveBeenCalled(); +}); +it('handles a blocked main repair plan without exposing an install confirmation', async () => { + backend.useDiscoveredPythonRuntime.mockResolvedValue(missing); + backend.planPythonRepair.mockResolvedValue({ ...missing, repairPlan: undefined, detail: 'externally_managed' }); + await search(); + fireEvent.click(await screen.findByTestId('python-runtime-candidate')); + fireEvent.click(await screen.findByRole('button', { name: 'settings.python_runtime_review_install' })); + await waitFor(() => expect(backend.planPythonRepair).toHaveBeenCalled()); + expect(screen.queryByRole('checkbox')).toBeNull(); + expect(screen.getAllByText('settings.python_runtime_repair_blocked').length).toBeGreaterThan(0); + expect(backend.installPythonRepair).not.toHaveBeenCalled(); +}); +it('clears a consumed selection token after failed confirmation while keeping the previous saved selection', async () => { + backend.getPythonRuntime.mockResolvedValue({ selection: { pythonPath: '/previous/bin/python' }, overrideActive: false }); + backend.confirmPythonRuntime.mockRejectedValue(new Error('python_confirmation_expired')); + await search(); + fireEvent.click(await screen.findByTestId('python-runtime-candidate')); + fireEvent.click(await screen.findByRole('button', { name: 'settings.python_runtime_confirm' })); + expect(await screen.findByText('python_confirmation_expired')).toBeVisible(); + expect(screen.getByText('/previous/bin/python')).toBeVisible(); + expect(screen.queryByTestId('python-runtime-staged')).toBeNull(); + expect(backend.getPythonRuntime).toHaveBeenCalledTimes(1); +}); +it('commits the main-owned selection token only on explicit confirmation', async () => { + await search(); + fireEvent.click(await screen.findByTestId('python-runtime-candidate')); + const confirm = await screen.findByRole('button', { name: 'settings.python_runtime_confirm' }); + expect(backend.confirmPythonRuntime).not.toHaveBeenCalled(); + fireEvent.click(confirm); + await waitFor(() => expect(backend.confirmPythonRuntime).toHaveBeenCalledWith('selection-token')); + expect(await screen.findByText('settings.python_runtime_saved')).toBeVisible(); + expect(backend.getPythonRuntime).toHaveBeenCalledTimes(2); + expect(screen.queryByTestId('python-runtime-staged')).toBeNull(); +}); +it('cancelling the manual picker adds no validation error', async () => { + render(); + fireEvent.click(screen.getByRole('button', { name: 'settings.python_runtime_choose' })); + await waitFor(() => expect(backend.choosePythonRuntime).toHaveBeenCalled()); + expect(screen.queryByText('settings.python_runtime_invalid')).toBeNull(); +}); diff --git a/electron/src/renderer/src/features/settings/existing-python-settings.tsx b/electron/src/renderer/src/features/settings/existing-python-settings.tsx new file mode 100644 index 000000000..32e17c0f4 --- /dev/null +++ b/electron/src/renderer/src/features/settings/existing-python-settings.tsx @@ -0,0 +1,278 @@ +import { useEffect, useState } from 'react'; +import { CheckCircle2Icon, FolderOpenIcon, Loader2Icon, RotateCcwIcon, SearchIcon, TerminalIcon } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { Button } from '@/components/ui/button'; +import { getBridge } from '@/components/bridge'; +import { SettingsRow, SettingsSection } from './settings-layout'; + +type DiscoveryResult = Awaited>['backend']['discoverPythonRuntimes']>>; +type Candidate = DiscoveryResult['candidates'][number]; +type Validation = Awaited>['backend']['choosePythonRuntime']>>; +type RepairReview = Awaited>['backend']['planPythonRepair']>>; + +export function ExistingPythonSettings() { + const { t } = useTranslation(); + const [selection, setSelection] = useState<{ pythonPath: string } | null>(null); + const [overrideActive, setOverrideActive] = useState(false); + const [staged, setStaged] = useState(null); + const [repair, setRepair] = useState(null); + const [installConsent, setInstallConsent] = useState(false); + const [installing, setInstalling] = useState(false); + const [message, setMessage] = useState(null); + const [busy, setBusy] = useState(false); + const [searching, setSearching] = useState(false); + const [discovery, setDiscovery] = useState(null); + + const refresh = async () => { + const backend = getBridge()?.backend; + if (!backend) return; + const result = await backend.getPythonRuntime(); + setSelection(result.selection); + setOverrideActive(result.overrideActive); + }; + useEffect(() => { void refresh(); }, []); + + const stage = (result: Validation) => { + setRepair(null); + setInstallConsent(false); + setStaged(result.pythonPath ? result : null); + setMessage(result.ok + ? t('settings.python_runtime_ready') + : result.missingModules?.length + ? t('settings.python_runtime_missing', { modules: result.missingModules.join(', ') }) + : t('settings.python_runtime_invalid', { detail: result.detail ?? '' })); + }; + + const reviewInstall = async () => { + const backend = getBridge()?.backend; + if (!backend || !staged?.pythonPath || busy || searching) return; + setBusy(true); + setMessage(null); + setInstallConsent(false); + setRepair(null); + try { + if (!staged.token) throw new Error('Python runtime selection expired; choose it again'); + const result = await backend.planPythonRepair(staged.token); + if (result.ok) { + stage(result); + } else if (result.repairToken && result.repairPlan?.packages.length) { + setRepair(result); + } else { + stage(result); + setMessage(t('settings.python_runtime_repair_blocked')); + } + } catch (error) { + setMessage(error instanceof Error ? error.message : String(error)); + } finally { + setBusy(false); + } + }; + + const install = async () => { + const backend = getBridge()?.backend; + if (!backend || !repair?.repairToken || !repair.repairPlan || !installConsent || busy || searching) return; + setBusy(true); + setInstalling(true); + setMessage(null); + const { repairToken, repairPlan } = repair; + setRepair(null); + setInstallConsent(false); + try { + const result = await backend.installPythonRepair({ + token: repairToken, pythonPath: repairPlan.interpreter, packages: [...repairPlan.packages], + }); + stage(result); + if (!result.ok && !result.canceled) setMessage(`${t('settings.python_runtime_repair_failed')}${result.outputTail ? `\n${result.outputTail}` : ''}`); + } catch (error) { + setMessage(`${t('settings.python_runtime_repair_failed')}\n${error instanceof Error ? error.message : String(error)}`); + } finally { + setInstalling(false); + setBusy(false); + } + }; + + const search = async () => { + if (busy || searching) return; + const backend = getBridge()?.backend; + if (!backend) return; + setMessage(null); + setSearching(true); + setDiscovery(null); + setStaged(null); + setRepair(null); + setInstallConsent(false); + try { + setDiscovery(await backend.discoverPythonRuntimes()); + } catch (error) { + setMessage(error instanceof Error ? error.message : String(error)); + } finally { + setSearching(false); + } + }; + + const useCandidate = async (candidate: Candidate) => { + if (busy || searching) return; + const backend = getBridge()?.backend; + if (!backend) return; + setMessage(null); + setStaged(null); + setRepair(null); + setInstallConsent(false); + setBusy(true); + try { + const result = await backend.useDiscoveredPythonRuntime(candidate.pythonPath); + stage({ ...result, pythonPath: result.pythonPath ?? candidate.pythonPath, version: result.version ?? candidate.version }); + } catch (error) { + setMessage(error instanceof Error && /not discovered|search again/i.test(error.message) + ? t('settings.python_runtime_search_again') + : error instanceof Error ? error.message : String(error)); + } finally { + setBusy(false); + } + }; + + const choose = async () => { + if (busy || searching) return; + setMessage(null); + const backend = getBridge()?.backend; + if (!backend) return; + setBusy(true); + setStaged(null); + setRepair(null); + setInstallConsent(false); + try { + const result = await backend.choosePythonRuntime(t('settings.python_runtime_path_title')); + if (result.canceled) return; + stage(result); + } catch (error) { + setMessage(error instanceof Error ? error.message : String(error)); + } finally { + setBusy(false); + } + }; + + const confirm = async () => { + const backend = getBridge()?.backend; + if (!backend || !staged?.ok || !staged.token || busy || searching) return; + setBusy(true); + setMessage(null); + try { + const result = await backend.confirmPythonRuntime(staged.token); + if (!result.ok) { + setStaged(null); + setMessage(t('settings.python_runtime_invalid', { detail: result.detail ?? '' })); + return; + } + setStaged(null); + await refresh(); + setMessage(t('settings.python_runtime_saved', { version: result.version ?? staged.version ?? '' })); + } catch (error) { + setStaged(null); + setMessage(error instanceof Error ? error.message : String(error)); + } finally { + setBusy(false); + } + }; + + const reset = async () => { + if (busy || searching) return; + const backend = getBridge()?.backend; + if (!backend) return; + setBusy(true); + try { + await backend.useManagedPython(); + setSelection(null); + setStaged(null); + setMessage(t('settings.python_runtime_managed_saved')); + } catch (error) { + setMessage(error instanceof Error ? error.message : String(error)); + } finally { + setBusy(false); + } + }; + + const warningText = discovery?.warnings.some((warning) => warning.reason === 'permission_denied') + ? t('settings.python_runtime_permission_warning') + : discovery?.partial ? t('settings.python_runtime_partial_warning') : null; + + return ( + + {overrideActive && ( + + {t('settings.python_runtime_override_active')} + + )} + +

+ {selection && } + + + {selection && } +
+ +
{t('settings.python_runtime_search_scope')}
+ {searching &&
{t('settings.python_runtime_searching')}
} + {discovery && ( +
+ {warningText &&

{warningText}

} + {discovery.partial && !warningText &&

{t('settings.python_runtime_partial_warning')}

} + {discovery.candidates.length === 0 ? ( +

{t('settings.python_runtime_empty')}

+ ) : ( +
+ {discovery.candidates.map((candidate) => ( + + ))} +
+ )} +
+ )} + {staged && ( +
+

{staged.pythonPath}

+ {staged.version &&

{staged.version}

} + {staged.ok && } + {!staged.ok && staged.missingModules?.length ? ( + staged.repairPlan ? + :

{t('settings.python_runtime_repair_blocked')}

+ ) : null} + +
+ )} + {repair?.repairPlan && ( +
+

{repair.repairPlan.interpreter}

+
    {repair.repairPlan.packages.map((pkg) =>
  • {pkg}
  • )}
+ +
+ + +
+
+ )} + {busy &&
{installing ? t('settings.python_runtime_installing') : t('settings.python_runtime_validating')}
} + {message &&
{message}
} + + ); +} diff --git a/electron/src/renderer/src/features/settings/settings-page.tsx b/electron/src/renderer/src/features/settings/settings-page.tsx index 1a271b9c6..5a12e9b91 100644 --- a/electron/src/renderer/src/features/settings/settings-page.tsx +++ b/electron/src/renderer/src/features/settings/settings-page.tsx @@ -44,9 +44,18 @@ import { cn } from '@/lib/utils'; import { SettingsContent, SettingsPageTitleContext } from './settings-layout'; import { SettingsNav, type SettingsLocation } from './settings-nav'; import { AppearanceResetButton, AppearanceSettings, GeneralSettings } from './settings-preferences'; +import { ExistingPythonSettings } from './existing-python-settings'; import { rememberSettingsRoute } from '@/lib/settings-route'; -// Pause fill (#3611) sits with the pronunciation dictionary: both shape how +function PerformanceAndPythonSettings() { + return ( + <> + + + + ); +} + // the generated speech sounds. function SpeechOutputSettings() { return ( @@ -130,7 +139,7 @@ const extraSettings = [ to: '/settings/performance', label: 'settings.perf_title', Icon: CpuIcon, - Component: PerformanceSettings, + Component: PerformanceAndPythonSettings, fields: [ 'settings.perf_title', 'settings.compute_device_title', diff --git a/electron/src/renderer/src/i18n/locales/ar.json b/electron/src/renderer/src/i18n/locales/ar.json index 72f77b0a1..434a966d7 100644 --- a/electron/src/renderer/src/i18n/locales/ar.json +++ b/electron/src/renderer/src/i18n/locales/ar.json @@ -1550,7 +1550,37 @@ "gpu_report_engine_no_family_path": "CPU: لا يوجد مسار لنوع GPU لديك", "gpu_report_engine_no_gpu": "CPU: لا يتوفر GPU", "gpu_report_engine_needs_accelerator": "يحتاج إلى GPU ({{needs}}) غير موجود في هذا الجهاز", - "models_dir_desc": "تُخزَّن النماذج المنزّلة هنا. اختر قرصًا به مساحة أكبر إذا امتلأ هذا القرص." + "models_dir_desc": "تُخزَّن النماذج المنزّلة هنا. اختر قرصًا به مساحة أكبر إذا امتلأ هذا القرص.", + "python_runtime_title": "بيئة Python", + "python_runtime_override_title": "التجاوز نشط", + "python_runtime_override_help": "تجاوز أمر الواجهة الخلفية المتقدم نشط وله الأولوية.", + "python_runtime_override_active": "التجاوز نشط", + "python_runtime_path_title": "مفسر Python", + "python_runtime_managed_help": "استخدام بيئة VoiceStudio المُدارة", + "python_runtime_valid": "مفسر صالح", + "python_runtime_choose": "اختيار المفسر", + "python_runtime_use_managed": "استخدام البيئة المُدارة", + "python_runtime_missing": "وحدات Python مفقودة: {{modules}}", + "python_runtime_invalid": "المفسر غير صالح: {{detail}}", + "python_runtime_saved": "تم حفظ Python {{version}}. إعادة تشغيل الواجهة الخلفية.", + "python_runtime_managed_saved": "تم اختيار البيئة المُدارة. إعادة التشغيل.", + "python_runtime_quick_search": "بحث سريع", + "python_runtime_searching": "جارٍ البحث…", + "python_runtime_search_scope": "يبحث فقط في المواقع الشائعة؛ يظل الاختيار اليدوي متاحًا.", + "python_runtime_empty": "لم يتم العثور على مفسرات Python في المواقع التي تم البحث فيها.", + "python_runtime_partial_warning": "قد تكون النتائج غير مكتملة بسبب تعذر قراءة بعض المواقع أو بلوغ حدود البحث. يمكنك اختيار المفسر يدويًا.", + "python_runtime_permission_warning": "تم تخطي بعض المواقع لرفض الإذن. اسمح بالوصول من إعدادات النظام أو اختر المفسر يدويًا.", + "python_runtime_validating": "جارٍ التحقق من المفسر…", + "python_runtime_search_again": "ابحث مرة أخرى؛ لم تعد هذه النتيجة متاحة.", + "python_runtime_confirm": "تأكيد الاستخدام والمتابعة", + "python_runtime_ready": "نجح التحقق. راجع المفسّر ثم أكّد للحفظ وإعادة التشغيل.", + "python_runtime_choose_another": "اختيار مفسّر آخر", + "python_runtime_review_install": "مراجعة خطة تثبيت الاعتماديات", + "python_runtime_install_consent": "أوافق على تثبيت الحزم المدرجة في المفسّر الموضّح أعلاه.", + "python_runtime_install_confirm": "تأكيد وتثبيت الحزم", + "python_runtime_installing": "جارٍ تثبيت الاعتماديات…", + "python_runtime_repair_failed": "لم يكتمل التثبيت. لم يتغير المفسّر المحفوظ.", + "python_runtime_repair_blocked": "التثبيت التلقائي غير متاح لهذا المفسّر. اختر بيئة أخرى." }, "gallery": { "title": "VoiceStudio معرض", diff --git a/electron/src/renderer/src/i18n/locales/de.json b/electron/src/renderer/src/i18n/locales/de.json index e0c35ad8d..8fe87f4a7 100644 --- a/electron/src/renderer/src/i18n/locales/de.json +++ b/electron/src/renderer/src/i18n/locales/de.json @@ -1522,7 +1522,37 @@ "gpu_report_engine_no_family_path": "CPU: kein Pfad für Ihren GPU-Typ", "gpu_report_engine_no_gpu": "CPU: keine GPU verfügbar", "gpu_report_engine_needs_accelerator": "Benötigt eine GPU ({{needs}}), die dieser Rechner nicht hat", - "models_dir_desc": "Hier werden heruntergeladene Modelle gespeichert. Wählen Sie ein Laufwerk mit mehr freiem Speicher, wenn dieses voll wird." + "models_dir_desc": "Hier werden heruntergeladene Modelle gespeichert. Wählen Sie ein Laufwerk mit mehr freiem Speicher, wenn dieses voll wird.", + "python_runtime_title": "Python-Laufzeit", + "python_runtime_override_title": "Override aktiv", + "python_runtime_override_help": "Ein erweiterter Backend-Befehls-Override ist aktiv. Er hat Vorrang vor dieser Auswahl.", + "python_runtime_override_active": "Override aktiv", + "python_runtime_path_title": "Python-Interpreter", + "python_runtime_managed_help": "Verwaltete VoiceStudio-Laufzeit verwenden", + "python_runtime_valid": "Gültiger Interpreter", + "python_runtime_choose": "Interpreter auswählen", + "python_runtime_use_managed": "Verwaltete Laufzeit verwenden", + "python_runtime_missing": "Fehlende Python-Module: {{modules}}", + "python_runtime_invalid": "Ausgewählter Interpreter ist ungültig: {{detail}}", + "python_runtime_saved": "Python {{version}} gespeichert. Backend wird neu gestartet.", + "python_runtime_managed_saved": "Verwaltete Laufzeit ausgewählt. Backend wird neu gestartet.", + "python_runtime_quick_search": "Schnellsuche", + "python_runtime_searching": "Suche läuft…", + "python_runtime_search_scope": "Durchsucht nur häufige Speicherorte; die manuelle Auswahl bleibt verfügbar.", + "python_runtime_empty": "An den durchsuchten Orten wurden keine Python-Interpreter gefunden.", + "python_runtime_partial_warning": "Die Ergebnisse können wegen unlesbarer Speicherorte oder Suchlimits unvollständig sein. Wählen Sie bei Bedarf den Interpreter manuell.", + "python_runtime_permission_warning": "Einige Speicherorte wurden wegen fehlender Berechtigung übersprungen. Erlauben Sie den Zugriff in den Systemeinstellungen oder wählen Sie den Interpreter manuell.", + "python_runtime_validating": "Interpreter wird überprüft…", + "python_runtime_search_again": "Bitte erneut suchen; dieses Ergebnis ist nicht mehr verfügbar.", + "python_runtime_confirm": "Verwendung bestätigen und fortfahren", + "python_runtime_ready": "Prüfung erfolgreich. Prüfen Sie den Interpreter; erst nach Bestätigung wird gespeichert und neu gestartet.", + "python_runtime_choose_another": "Anderen Interpreter wählen", + "python_runtime_review_install": "Installation der Abhängigkeiten prüfen", + "python_runtime_install_consent": "Ich genehmige die Installation der aufgeführten Pakete in den oben angezeigten Interpreter.", + "python_runtime_install_confirm": "Bestätigen und Pakete installieren", + "python_runtime_installing": "Abhängigkeiten werden installiert…", + "python_runtime_repair_failed": "Installation nicht abgeschlossen. Ihr gespeicherter Interpreter bleibt unverändert.", + "python_runtime_repair_blocked": "Für diesen Interpreter ist keine automatische Installation möglich. Wählen Sie eine andere Umgebung." }, "gallery": { "title": "VoiceStudio Galerie", diff --git a/electron/src/renderer/src/i18n/locales/en.json b/electron/src/renderer/src/i18n/locales/en.json index 622744019..387990beb 100644 --- a/electron/src/renderer/src/i18n/locales/en.json +++ b/electron/src/renderer/src/i18n/locales/en.json @@ -1690,7 +1690,37 @@ "gpu_report_engine_no_family_path": "CPU: no path for your GPU type", "gpu_report_engine_no_gpu": "CPU: no GPU available", "gpu_report_engine_needs_accelerator": "Needs a GPU ({{needs}}) this machine does not have", - "models_dir_desc": "Downloaded models are stored here. Choose a drive with more free space if this one fills up." + "models_dir_desc": "Downloaded models are stored here. Choose a drive with more free space if this one fills up.", + "python_runtime_title": "Python runtime", + "python_runtime_override_title": "Override active", + "python_runtime_override_help": "An advanced backend command override is active. It takes precedence over this selection.", + "python_runtime_override_active": "Override active", + "python_runtime_path_title": "Python interpreter", + "python_runtime_managed_help": "Use the managed VoiceStudio runtime", + "python_runtime_valid": "Valid interpreter", + "python_runtime_choose": "Choose interpreter", + "python_runtime_use_managed": "Use managed runtime", + "python_runtime_missing": "Missing Python modules: {{modules}}", + "python_runtime_invalid": "Selected interpreter is invalid: {{detail}}", + "python_runtime_saved": "Python {{version}} saved. Restarting backend.", + "python_runtime_managed_saved": "Managed runtime selected. Restarting backend.", + "python_runtime_quick_search": "Quick search", + "python_runtime_searching": "Searching…", + "python_runtime_search_scope": "Search common locations only; manual selection remains available.", + "python_runtime_empty": "No Python interpreters found in the searched locations.", + "python_runtime_partial_warning": "Search results may be incomplete because some locations could not be read or scan limits were reached. You can select an interpreter manually.", + "python_runtime_permission_warning": "Some locations were skipped because permission was denied. Allow access in system settings or select an interpreter manually.", + "python_runtime_validating": "Validating interpreter…", + "python_runtime_search_again": "Search again; this result is no longer available.", + "python_runtime_confirm": "Confirm use and continue", + "python_runtime_ready": "Validation succeeded. Review this interpreter, then confirm to save and restart.", + "python_runtime_choose_another": "Choose another interpreter", + "python_runtime_review_install": "Review dependency installation", + "python_runtime_install_consent": "I approve installing the listed packages into the interpreter shown above.", + "python_runtime_install_confirm": "Confirm and install packages", + "python_runtime_installing": "Installing dependencies…", + "python_runtime_repair_failed": "Installation did not complete. Your saved interpreter is unchanged.", + "python_runtime_repair_blocked": "Automatic installation is unavailable for this interpreter. Choose another environment." }, "gallery": { "title": "VoiceStudio Gallery", diff --git a/electron/src/renderer/src/i18n/locales/es.json b/electron/src/renderer/src/i18n/locales/es.json index 2e8d871af..cad412167 100644 --- a/electron/src/renderer/src/i18n/locales/es.json +++ b/electron/src/renderer/src/i18n/locales/es.json @@ -1524,7 +1524,37 @@ "gpu_report_engine_no_family_path": "CPU: sin ruta para tu tipo de GPU", "gpu_report_engine_no_gpu": "CPU: no hay GPU disponible", "gpu_report_engine_needs_accelerator": "Necesita una GPU ({{needs}}) que este equipo no tiene", - "models_dir_desc": "Aquí se guardan los modelos descargados. Elige una unidad con más espacio libre si esta se llena." + "models_dir_desc": "Aquí se guardan los modelos descargados. Elige una unidad con más espacio libre si esta se llena.", + "python_runtime_title": "Entorno de Python", + "python_runtime_override_title": "Anulación activa", + "python_runtime_override_help": "Hay una anulación avanzada del backend activa y prioritaria.", + "python_runtime_override_active": "Anulación activa", + "python_runtime_path_title": "Intérprete de Python", + "python_runtime_managed_help": "Usar el entorno administrado de VoiceStudio", + "python_runtime_valid": "Intérprete válido", + "python_runtime_choose": "Elegir intérprete", + "python_runtime_use_managed": "Usar entorno administrado", + "python_runtime_missing": "Módulos de Python faltantes: {{modules}}", + "python_runtime_invalid": "Intérprete no válido: {{detail}}", + "python_runtime_saved": "Python {{version}} guardado. Reiniciando el backend.", + "python_runtime_managed_saved": "Entorno administrado seleccionado. Reiniciando.", + "python_runtime_quick_search": "Búsqueda rápida", + "python_runtime_searching": "Buscando…", + "python_runtime_search_scope": "Solo busca en ubicaciones habituales; la selección manual sigue disponible.", + "python_runtime_empty": "No se encontraron intérpretes de Python en las ubicaciones buscadas.", + "python_runtime_partial_warning": "Los resultados pueden estar incompletos por ubicaciones inaccesibles o límites de búsqueda. Puede seleccionar el intérprete manualmente.", + "python_runtime_permission_warning": "Se omitieron algunas ubicaciones por falta de permisos. Autorice el acceso en los ajustes del sistema o seleccione el intérprete manualmente.", + "python_runtime_validating": "Validando el intérprete…", + "python_runtime_search_again": "Busca de nuevo; este resultado ya no está disponible.", + "python_runtime_confirm": "Confirmar uso y continuar", + "python_runtime_ready": "Validación correcta. Revise el intérprete y confirme para guardar y reiniciar.", + "python_runtime_choose_another": "Elegir otro intérprete", + "python_runtime_review_install": "Revisar la instalación de dependencias", + "python_runtime_install_consent": "Autorizo instalar los paquetes indicados en el intérprete mostrado arriba.", + "python_runtime_install_confirm": "Confirmar e instalar paquetes", + "python_runtime_installing": "Instalando dependencias…", + "python_runtime_repair_failed": "La instalación no se completó. El intérprete guardado no ha cambiado.", + "python_runtime_repair_blocked": "La instalación automática no está disponible para este intérprete. Elija otro entorno." }, "gallery": { "title": "VoiceStudio Galería", diff --git a/electron/src/renderer/src/i18n/locales/fr.json b/electron/src/renderer/src/i18n/locales/fr.json index 9926336c5..e678efd2c 100644 --- a/electron/src/renderer/src/i18n/locales/fr.json +++ b/electron/src/renderer/src/i18n/locales/fr.json @@ -1524,7 +1524,37 @@ "gpu_report_engine_no_family_path": "CPU : aucun chemin pour votre type de GPU", "gpu_report_engine_no_gpu": "CPU : aucun GPU disponible", "gpu_report_engine_needs_accelerator": "Nécessite un GPU ({{needs}}) que cette machine n'a pas", - "models_dir_desc": "Les modèles téléchargés sont stockés ici. Choisissez un disque avec plus d'espace libre si celui-ci se remplit." + "models_dir_desc": "Les modèles téléchargés sont stockés ici. Choisissez un disque avec plus d'espace libre si celui-ci se remplit.", + "python_runtime_title": "Environnement Python", + "python_runtime_override_title": "Surcharge active", + "python_runtime_override_help": "Une commande backend avancée est active et prioritaire.", + "python_runtime_override_active": "Surcharge active", + "python_runtime_path_title": "Interpréteur Python", + "python_runtime_managed_help": "Utiliser l’environnement VoiceStudio géré", + "python_runtime_valid": "Interpréteur valide", + "python_runtime_choose": "Choisir un interpréteur", + "python_runtime_use_managed": "Utiliser l’environnement géré", + "python_runtime_missing": "Modules Python manquants : {{modules}}", + "python_runtime_invalid": "Interpréteur invalide : {{detail}}", + "python_runtime_saved": "Python {{version}} enregistré. Redémarrage du backend.", + "python_runtime_managed_saved": "Environnement géré sélectionné. Redémarrage.", + "python_runtime_quick_search": "Recherche rapide", + "python_runtime_searching": "Recherche en cours…", + "python_runtime_search_scope": "Recherche uniquement dans les emplacements courants ; la sélection manuelle reste disponible.", + "python_runtime_empty": "Aucun interpréteur Python trouvé dans les emplacements recherchés.", + "python_runtime_partial_warning": "Les résultats peuvent être incomplets en raison de dossiers illisibles ou des limites de recherche. Vous pouvez choisir un interpréteur manuellement.", + "python_runtime_permission_warning": "Certains dossiers ont été ignorés faute de permission. Autorisez leur accès dans les réglages système ou choisissez un interpréteur manuellement.", + "python_runtime_validating": "Validation de l’interpréteur…", + "python_runtime_search_again": "Relancez la recherche ; ce résultat n’est plus disponible.", + "python_runtime_confirm": "Confirmer et continuer", + "python_runtime_ready": "Validation réussie. Vérifiez cet interpréteur, puis confirmez pour enregistrer et redémarrer.", + "python_runtime_choose_another": "Choisir un autre interpréteur", + "python_runtime_review_install": "Vérifier le plan d’installation", + "python_runtime_install_consent": "J’autorise l’installation des paquets indiqués dans l’interpréteur affiché ci-dessus.", + "python_runtime_install_confirm": "Confirmer et installer les paquets", + "python_runtime_installing": "Installation des dépendances…", + "python_runtime_repair_failed": "L’installation n’a pas abouti. Votre interpréteur enregistré reste inchangé.", + "python_runtime_repair_blocked": "L’installation automatique est indisponible pour cet interpréteur. Choisissez un autre environnement." }, "gallery": { "title": "VoiceStudio Galerie", diff --git a/electron/src/renderer/src/i18n/locales/gl.json b/electron/src/renderer/src/i18n/locales/gl.json index b82b882c3..0348b41aa 100644 --- a/electron/src/renderer/src/i18n/locales/gl.json +++ b/electron/src/renderer/src/i18n/locales/gl.json @@ -1690,7 +1690,37 @@ "gpu_report_engine_no_family_path": "CPU: non hai camiño para o teu tipo de GPU", "gpu_report_engine_no_gpu": "CPU: non hai GPU dispoñible", "gpu_report_engine_needs_accelerator": "Necesita unha GPU ({{needs}}) que esta máquina non ten", - "models_dir_desc": "Os modelos descargados almacénanse aquí. Escolle unha unidade con máis espazo libre se esta se enche." + "models_dir_desc": "Os modelos descargados almacénanse aquí. Escolle unha unidade con máis espazo libre se esta se enche.", + "python_runtime_title": "Tempo de execución de Python", + "python_runtime_override_title": "Substitución activa", + "python_runtime_override_help": "A substitución avanzada do backend está activa e ten prioridade.", + "python_runtime_override_active": "Substitución activa", + "python_runtime_path_title": "Intérprete de Python", + "python_runtime_managed_help": "Usar o tempo xestionado de VoiceStudio", + "python_runtime_valid": "Intérprete válido", + "python_runtime_choose": "Escoller intérprete", + "python_runtime_use_managed": "Usar tempo xestionado", + "python_runtime_missing": "Módulos de Python que faltan: {{modules}}", + "python_runtime_invalid": "Intérprete non válido: {{detail}}", + "python_runtime_saved": "Python {{version}} gardado. Reiniciando o backend.", + "python_runtime_managed_saved": "Tempo xestionado seleccionado. Reiniciando.", + "python_runtime_quick_search": "Busca rápida", + "python_runtime_searching": "Buscando…", + "python_runtime_search_scope": "Busca só en localizacións comúns; a selección manual segue dispoñible.", + "python_runtime_empty": "Non se atoparon intérpretes de Python nas localizacións buscadas.", + "python_runtime_partial_warning": "Os resultados poden estar incompletos por localizacións inaccesibles ou límites de busca. Pode seleccionar o intérprete manualmente.", + "python_runtime_permission_warning": "Omitíronse algunhas localizacións por falta de permisos. Autorice o acceso nos axustes do sistema ou seleccione o intérprete manualmente.", + "python_runtime_validating": "Validando o intérprete…", + "python_runtime_search_again": "Busca de novo; este resultado xa non está dispoñible.", + "python_runtime_confirm": "Confirmar uso e continuar", + "python_runtime_ready": "Validación correcta. Revisa o intérprete e confirma para gardar e reiniciar.", + "python_runtime_choose_another": "Escoller outro intérprete", + "python_runtime_review_install": "Revisar a instalación de dependencias", + "python_runtime_install_consent": "Autorizo a instalación dos paquetes indicados no intérprete mostrado arriba.", + "python_runtime_install_confirm": "Confirmar e instalar paquetes", + "python_runtime_installing": "Instalando dependencias…", + "python_runtime_repair_failed": "A instalación non se completou. O intérprete gardado non cambiou.", + "python_runtime_repair_blocked": "A instalación automática non está dispoñible para este intérprete. Escolle outro contorno." }, "gallery": { "title": "Galería VoiceStudio", diff --git a/electron/src/renderer/src/i18n/locales/hi.json b/electron/src/renderer/src/i18n/locales/hi.json index ffb431509..6453e6877 100644 --- a/electron/src/renderer/src/i18n/locales/hi.json +++ b/electron/src/renderer/src/i18n/locales/hi.json @@ -1522,7 +1522,37 @@ "gpu_report_engine_no_family_path": "CPU: आपके GPU प्रकार के लिए रास्ता नहीं", "gpu_report_engine_no_gpu": "CPU: कोई GPU उपलब्ध नहीं", "gpu_report_engine_needs_accelerator": "ऐसे GPU ({{needs}}) की ज़रूरत है जो इस मशीन में नहीं है", - "models_dir_desc": "डाउनलोड किए गए मॉडल यहाँ रखे जाते हैं। यह ड्राइव भर जाए तो ज़्यादा खाली जगह वाली ड्राइव चुनें।" + "models_dir_desc": "डाउनलोड किए गए मॉडल यहाँ रखे जाते हैं। यह ड्राइव भर जाए तो ज़्यादा खाली जगह वाली ड्राइव चुनें।", + "python_runtime_title": "Python रनटाइम", + "python_runtime_override_title": "ओवरराइड सक्रिय", + "python_runtime_override_help": "उन्नत बैकएंड कमांड ओवरराइड सक्रिय है और प्राथमिकता रखता है।", + "python_runtime_override_active": "ओवरराइड सक्रिय", + "python_runtime_path_title": "Python इंटरप्रेटर", + "python_runtime_managed_help": "प्रबंधित VoiceStudio रनटाइम उपयोग करें", + "python_runtime_valid": "मान्य इंटरप्रेटर", + "python_runtime_choose": "इंटरप्रेटर चुनें", + "python_runtime_use_managed": "प्रबंधित रनटाइम उपयोग करें", + "python_runtime_missing": "अनुपलब्ध Python मॉड्यूल: {{modules}}", + "python_runtime_invalid": "इंटरप्रेटर अमान्य है: {{detail}}", + "python_runtime_saved": "Python {{version}} सहेजा गया। बैकएंड पुनः आरंभ हो रहा है।", + "python_runtime_managed_saved": "प्रबंधित रनटाइम चुना गया। पुनः आरंभ हो रहा है।", + "python_runtime_quick_search": "त्वरित खोज", + "python_runtime_searching": "खोज जारी है…", + "python_runtime_search_scope": "केवल सामान्य स्थानों में खोजता है; मैन्युअल चयन उपलब्ध रहता है।", + "python_runtime_empty": "खोजे गए स्थानों में कोई Python इंटरप्रेटर नहीं मिला।", + "python_runtime_partial_warning": "कुछ स्थान पढ़े नहीं जा सके या खोज सीमा पूरी हुई; परिणाम अधूरे हो सकते हैं। इंटरप्रेटर मैन्युअल रूप से चुन सकते हैं।", + "python_runtime_permission_warning": "अनुमति न मिलने के कारण कुछ स्थान छोड़ दिए गए। सिस्टम सेटिंग में पहुँच दें या इंटरप्रेटर मैन्युअल रूप से चुनें।", + "python_runtime_validating": "इंटरप्रेटर का सत्यापन हो रहा है…", + "python_runtime_search_again": "फिर से खोजें; यह परिणाम अब उपलब्ध नहीं है।", + "python_runtime_confirm": "उपयोग की पुष्टि करें और जारी रखें", + "python_runtime_ready": "सत्यापन सफल हुआ। इंटरप्रेटर जाँचें, फिर सहेजने और पुनः शुरू करने की पुष्टि करें।", + "python_runtime_choose_another": "दूसरा इंटरप्रेटर चुनें", + "python_runtime_review_install": "निर्भरताओं की स्थापना योजना देखें", + "python_runtime_install_consent": "मैं ऊपर दिखाए गए इंटरप्रेटर में सूचीबद्ध पैकेज स्थापित करने की अनुमति देता हूँ।", + "python_runtime_install_confirm": "पुष्टि करें और पैकेज स्थापित करें", + "python_runtime_installing": "निर्भरताएँ स्थापित हो रही हैं…", + "python_runtime_repair_failed": "स्थापना पूरी नहीं हुई। सहेजा गया इंटरप्रेटर अपरिवर्तित है।", + "python_runtime_repair_blocked": "इस इंटरप्रेटर के लिए स्वचालित स्थापना उपलब्ध नहीं है। दूसरा परिवेश चुनें।" }, "gallery": { "title": "VoiceStudio गैलरी", diff --git a/electron/src/renderer/src/i18n/locales/id.json b/electron/src/renderer/src/i18n/locales/id.json index b011d515b..f1135f4f0 100644 --- a/electron/src/renderer/src/i18n/locales/id.json +++ b/electron/src/renderer/src/i18n/locales/id.json @@ -1522,7 +1522,37 @@ "gpu_report_engine_no_family_path": "CPU: tidak ada jalur untuk jenis GPU Anda", "gpu_report_engine_no_gpu": "CPU: tidak ada GPU", "gpu_report_engine_needs_accelerator": "Memerlukan GPU ({{needs}}) yang tidak dimiliki komputer ini", - "models_dir_desc": "Model yang diunduh disimpan di sini. Pilih drive dengan ruang kosong lebih besar jika drive ini penuh." + "models_dir_desc": "Model yang diunduh disimpan di sini. Pilih drive dengan ruang kosong lebih besar jika drive ini penuh.", + "python_runtime_title": "Runtime Python", + "python_runtime_override_title": "Penggantian aktif", + "python_runtime_override_help": "Penggantian perintah backend lanjutan aktif dan diprioritaskan.", + "python_runtime_override_active": "Penggantian aktif", + "python_runtime_path_title": "Interpreter Python", + "python_runtime_managed_help": "Gunakan runtime VoiceStudio terkelola", + "python_runtime_valid": "Interpreter valid", + "python_runtime_choose": "Pilih interpreter", + "python_runtime_use_managed": "Gunakan runtime terkelola", + "python_runtime_missing": "Modul Python hilang: {{modules}}", + "python_runtime_invalid": "Interpreter tidak valid: {{detail}}", + "python_runtime_saved": "Python {{version}} disimpan. Memulai ulang backend.", + "python_runtime_managed_saved": "Runtime terkelola dipilih. Memulai ulang.", + "python_runtime_quick_search": "Pencarian cepat", + "python_runtime_searching": "Mencari…", + "python_runtime_search_scope": "Hanya mencari lokasi umum; pemilihan manual tetap tersedia.", + "python_runtime_empty": "Tidak ada interpreter Python di lokasi yang dicari.", + "python_runtime_partial_warning": "Hasil mungkin tidak lengkap karena lokasi tidak dapat dibaca atau batas pencarian tercapai. Anda dapat memilih interpreter secara manual.", + "python_runtime_permission_warning": "Beberapa lokasi dilewati karena izin ditolak. Izinkan akses di pengaturan sistem atau pilih interpreter secara manual.", + "python_runtime_validating": "Memvalidasi interpreter…", + "python_runtime_search_again": "Cari lagi; hasil ini tidak lagi tersedia.", + "python_runtime_confirm": "Konfirmasi penggunaan dan lanjutkan", + "python_runtime_ready": "Validasi berhasil. Tinjau interpreter, lalu konfirmasi untuk menyimpan dan memulai ulang.", + "python_runtime_choose_another": "Pilih interpreter lain", + "python_runtime_review_install": "Tinjau pemasangan dependensi", + "python_runtime_install_consent": "Saya menyetujui pemasangan paket yang tercantum ke interpreter yang ditampilkan di atas.", + "python_runtime_install_confirm": "Konfirmasi dan pasang paket", + "python_runtime_installing": "Memasang dependensi…", + "python_runtime_repair_failed": "Pemasangan tidak selesai. Interpreter tersimpan tidak berubah.", + "python_runtime_repair_blocked": "Pemasangan otomatis tidak tersedia untuk interpreter ini. Pilih lingkungan lain." }, "gallery": { "title": "VoiceStudio Galeri", diff --git a/electron/src/renderer/src/i18n/locales/it.json b/electron/src/renderer/src/i18n/locales/it.json index 146ba4aeb..12bf48aaf 100644 --- a/electron/src/renderer/src/i18n/locales/it.json +++ b/electron/src/renderer/src/i18n/locales/it.json @@ -1524,7 +1524,37 @@ "gpu_report_engine_no_family_path": "CPU: nessun percorso per il tuo tipo di GPU", "gpu_report_engine_no_gpu": "CPU: nessuna GPU disponibile", "gpu_report_engine_needs_accelerator": "Richiede una GPU ({{needs}}) che questo computer non ha", - "models_dir_desc": "Qui vengono salvati i modelli scaricati. Scegli un disco con più spazio libero se questo si riempie." + "models_dir_desc": "Qui vengono salvati i modelli scaricati. Scegli un disco con più spazio libero se questo si riempie.", + "python_runtime_title": "Runtime Python", + "python_runtime_override_title": "Override attivo", + "python_runtime_override_help": "È attivo un override avanzato del backend, prioritario.", + "python_runtime_override_active": "Override attivo", + "python_runtime_path_title": "Interprete Python", + "python_runtime_managed_help": "Usa il runtime VoiceStudio gestito", + "python_runtime_valid": "Interprete valido", + "python_runtime_choose": "Scegli interprete", + "python_runtime_use_managed": "Usa runtime gestito", + "python_runtime_missing": "Moduli Python mancanti: {{modules}}", + "python_runtime_invalid": "Interprete non valido: {{detail}}", + "python_runtime_saved": "Python {{version}} salvato. Riavvio del backend.", + "python_runtime_managed_saved": "Runtime gestito selezionato. Riavvio.", + "python_runtime_quick_search": "Ricerca rapida", + "python_runtime_searching": "Ricerca in corso…", + "python_runtime_search_scope": "Cerca solo nelle posizioni comuni; la selezione manual resta disponibile.", + "python_runtime_empty": "Nessun interprete Python trovato nelle posizioni cercate.", + "python_runtime_partial_warning": "I risultati potrebbero essere incompleti per percorsi illeggibili o limiti di ricerca. Puoi selezionare un interprete manualmente.", + "python_runtime_permission_warning": "Alcuni percorsi sono stati ignorati per mancanza di autorizzazione. Consenti l’accesso nelle impostazioni di sistema o seleziona un interprete manualmente.", + "python_runtime_validating": "Convalida dell’interprete…", + "python_runtime_search_again": "Cerca di nuovo; questo risultato non è più disponibile.", + "python_runtime_confirm": "Conferma utilizzo e continua", + "python_runtime_ready": "Convalida riuscita. Controlla l’interprete, poi conferma per salvare e riavviare.", + "python_runtime_choose_another": "Scegli un altro interprete", + "python_runtime_review_install": "Verifica l’installazione delle dipendenze", + "python_runtime_install_consent": "Autorizzo l’installazione dei pacchetti elencati nell’interprete mostrato sopra.", + "python_runtime_install_confirm": "Conferma e installa i pacchetti", + "python_runtime_installing": "Installazione delle dipendenze…", + "python_runtime_repair_failed": "Installazione non completata. L’interprete salvato non è stato modificato.", + "python_runtime_repair_blocked": "L’installazione automatica non è disponibile per questo interprete. Scegli un altro ambiente." }, "gallery": { "title": "VoiceStudio Galleria", diff --git a/electron/src/renderer/src/i18n/locales/ja.json b/electron/src/renderer/src/i18n/locales/ja.json index 62890d70f..f11ea813a 100644 --- a/electron/src/renderer/src/i18n/locales/ja.json +++ b/electron/src/renderer/src/i18n/locales/ja.json @@ -1522,7 +1522,37 @@ "gpu_report_engine_no_family_path": "CPU:お使いの GPU の種類に対応する経路がありません", "gpu_report_engine_no_gpu": "CPU:GPU がありません", "gpu_report_engine_needs_accelerator": "このマシンにない GPU({{needs}})が必要です", - "models_dir_desc": "ダウンロードしたモデルはここに保存されます。空き容量が足りなくなったら、より空きのあるドライブを選んでください。" + "models_dir_desc": "ダウンロードしたモデルはここに保存されます。空き容量が足りなくなったら、より空きのあるドライブを選んでください。", + "python_runtime_title": "Python ランタイム", + "python_runtime_override_title": "上書きが有効", + "python_runtime_override_help": "高度なバックエンドコマンドの上書きが有効で、優先されます。", + "python_runtime_override_active": "上書きが有効", + "python_runtime_path_title": "Python インタープリター", + "python_runtime_managed_help": "管理された VoiceStudio ランタイムを使用", + "python_runtime_valid": "有効なインタープリター", + "python_runtime_choose": "インタープリターを選択", + "python_runtime_use_managed": "管理ランタイムを使用", + "python_runtime_missing": "不足している Python モジュール: {{modules}}", + "python_runtime_invalid": "選択したインタープリターは無効です: {{detail}}", + "python_runtime_saved": "Python {{version}} を保存。バックエンドを再起動します。", + "python_runtime_managed_saved": "管理ランタイムを選択。再起動します。", + "python_runtime_quick_search": "クイック検索", + "python_runtime_searching": "検索中…", + "python_runtime_search_scope": "一般的な場所のみを検索します。手動選択も利用できます。", + "python_runtime_empty": "検索した場所に Python インタープリターが見つかりません。", + "python_runtime_partial_warning": "読み取れない場所や検索範囲の制限により、結果が不完全な場合があります。インタープリターは手動でも選択できます。", + "python_runtime_permission_warning": "アクセス権限がない場所をスキップしました。システム設定でアクセスを許可するか、インタープリターを手動で選択してください。", + "python_runtime_validating": "インタープリターを検証中…", + "python_runtime_search_again": "もう一度検索してください。この結果は利用できません。", + "python_runtime_confirm": "使用を確定して続行", + "python_runtime_ready": "検証に成功しました。インタープリターを確認してください。確定後に保存して再起動します。", + "python_runtime_choose_another": "別のインタープリターを選択", + "python_runtime_review_install": "依存パッケージのインストールを確認", + "python_runtime_install_consent": "上に表示されたインタープリター環境に、一覧のパッケージをインストールすることを承認します。", + "python_runtime_install_confirm": "確定してパッケージをインストール", + "python_runtime_installing": "依存パッケージをインストール中…", + "python_runtime_repair_failed": "インストールは完了しませんでした。保存済みのインタープリターは変更されていません。", + "python_runtime_repair_blocked": "このインタープリターには自動インストールできません。別の環境を選択してください。" }, "gallery": { "title": "VoiceStudio ギャラリー", diff --git a/electron/src/renderer/src/i18n/locales/ko.json b/electron/src/renderer/src/i18n/locales/ko.json index 08d748bd2..d7228e0a1 100644 --- a/electron/src/renderer/src/i18n/locales/ko.json +++ b/electron/src/renderer/src/i18n/locales/ko.json @@ -1522,7 +1522,37 @@ "usage_empty": "아직 생성한 항목이 없습니다. 무언가 만들면 여기에 표시됩니다.", "usage_since": "{{date}}부터", "usage_starred": "별표 표시한 테이크", - "usage_takes": "생성한 테이크" + "usage_takes": "생성한 테이크", + "python_runtime_title": "Python 런타임", + "python_runtime_override_title": "재정의 활성화", + "python_runtime_override_help": "고급 백엔드 명령 재정의가 활성화되어 우선 적용됩니다.", + "python_runtime_override_active": "재정의 활성화", + "python_runtime_path_title": "Python 인터프리터", + "python_runtime_managed_help": "관리되는 VoiceStudio 런타임 사용", + "python_runtime_valid": "유효한 인터프리터", + "python_runtime_choose": "인터프리터 선택", + "python_runtime_use_managed": "관리 런타임 사용", + "python_runtime_missing": "누락된 Python 모듈: {{modules}}", + "python_runtime_invalid": "선택한 인터프리터가 올바르지 않음: {{detail}}", + "python_runtime_saved": "Python {{version}} 저장됨. 백엔드를 다시 시작합니다.", + "python_runtime_managed_saved": "관리 런타임 선택됨. 다시 시작합니다.", + "python_runtime_quick_search": "빠른 검색", + "python_runtime_searching": "검색 중…", + "python_runtime_search_scope": "일반적인 위치만 검색하며 수동 선택도 사용할 수 있습니다.", + "python_runtime_empty": "검색한 위치에서 Python 인터프리터를 찾지 못했습니다.", + "python_runtime_partial_warning": "읽을 수 없는 위치 또는 검색 제한으로 결과가 불완전할 수 있습니다. 인터프리터를 수동으로 선택할 수 있습니다.", + "python_runtime_permission_warning": "권한이 없어 일부 위치를 건너뛰었습니다. 시스템 설정에서 접근을 허용하거나 인터프리터를 수동으로 선택하세요.", + "python_runtime_validating": "인터프리터 확인 중…", + "python_runtime_search_again": "다시 검색하세요. 이 결과는 더 이상 사용할 수 없습니다.", + "python_runtime_confirm": "사용 확인 후 계속", + "python_runtime_ready": "검증에 성공했습니다. 인터프리터를 검토하고 확인하면 저장 후 다시 시작합니다.", + "python_runtime_choose_another": "다른 인터프리터 선택", + "python_runtime_review_install": "의존성 설치 계획 검토", + "python_runtime_install_consent": "위에 표시된 인터프리터 환경에 나열된 패키지를 설치하는 데 동의합니다.", + "python_runtime_install_confirm": "확인 후 패키지 설치", + "python_runtime_installing": "의존성 설치 중…", + "python_runtime_repair_failed": "설치가 완료되지 않았습니다. 저장된 인터프리터는 변경되지 않았습니다.", + "python_runtime_repair_blocked": "이 인터프리터에는 자동 설치할 수 없습니다. 다른 환경을 선택하세요." }, "gallery": { "title": "VoiceStudio 갤러리", diff --git a/electron/src/renderer/src/i18n/locales/nl.json b/electron/src/renderer/src/i18n/locales/nl.json index 7d57fa1a8..426441bfc 100644 --- a/electron/src/renderer/src/i18n/locales/nl.json +++ b/electron/src/renderer/src/i18n/locales/nl.json @@ -1522,7 +1522,37 @@ "gpu_report_engine_no_family_path": "CPU: geen pad voor uw GPU-type", "gpu_report_engine_no_gpu": "CPU: geen GPU beschikbaar", "gpu_report_engine_needs_accelerator": "Heeft een GPU ({{needs}}) nodig die deze computer niet heeft", - "models_dir_desc": "Gedownloade modellen worden hier opgeslagen. Kies een schijf met meer vrije ruimte als deze volraakt." + "models_dir_desc": "Gedownloade modellen worden hier opgeslagen. Kies een schijf met meer vrije ruimte als deze volraakt.", + "python_runtime_title": "Python-runtime", + "python_runtime_override_title": "Overschrijving actief", + "python_runtime_override_help": "Een geavanceerde backend-overschrijving is actief en heeft voorrang.", + "python_runtime_override_active": "Overschrijving actief", + "python_runtime_path_title": "Python-interpreter", + "python_runtime_managed_help": "Beheerde VoiceStudio-runtime gebruiken", + "python_runtime_valid": "Geldige interpreter", + "python_runtime_choose": "Interpreter kiezen", + "python_runtime_use_managed": "Beheerde runtime gebruiken", + "python_runtime_missing": "Ontbrekende Python-modules: {{modules}}", + "python_runtime_invalid": "Interpreter ongeldig: {{detail}}", + "python_runtime_saved": "Python {{version}} opgeslagen. Backend herstart.", + "python_runtime_managed_saved": "Beheerde runtime geselecteerd. Herstart.", + "python_runtime_quick_search": "Snel zoeken", + "python_runtime_searching": "Bezig met zoeken…", + "python_runtime_search_scope": "Zoekt alleen op gebruikelijke locaties; handmatige selectie blijft beschikbaar.", + "python_runtime_empty": "Geen Python-interpreters gevonden op de doorzochte locaties.", + "python_runtime_partial_warning": "De resultaten kunnen onvolledig zijn door onleesbare locaties of zoeklimieten. U kunt een interpreter handmatig kiezen.", + "python_runtime_permission_warning": "Sommige locaties zijn overgeslagen wegens ontbrekende toestemming. Sta toegang toe in de systeeminstellingen of kies handmatig een interpreter.", + "python_runtime_validating": "Interpreter wordt gevalideerd…", + "python_runtime_search_again": "Zoek opnieuw; dit resultaat is niet meer beschikbaar.", + "python_runtime_confirm": "Gebruik bevestigen en doorgaan", + "python_runtime_ready": "Validatie geslaagd. Controleer deze interpreter en bevestig om op te slaan en opnieuw te starten.", + "python_runtime_choose_another": "Andere interpreter kiezen", + "python_runtime_review_install": "Installatie van afhankelijkheden bekijken", + "python_runtime_install_consent": "Ik geef toestemming om de vermelde pakketten in de hierboven getoonde interpreter te installeren.", + "python_runtime_install_confirm": "Bevestigen en pakketten installeren", + "python_runtime_installing": "Afhankelijkheden installeren…", + "python_runtime_repair_failed": "De installatie is niet voltooid. Uw opgeslagen interpreter is niet gewijzigd.", + "python_runtime_repair_blocked": "Automatische installatie is niet beschikbaar voor deze interpreter. Kies een andere omgeving." }, "gallery": { "title": "VoiceStudio Galerij", diff --git a/electron/src/renderer/src/i18n/locales/pl.json b/electron/src/renderer/src/i18n/locales/pl.json index 7b3f32253..1903ab3db 100644 --- a/electron/src/renderer/src/i18n/locales/pl.json +++ b/electron/src/renderer/src/i18n/locales/pl.json @@ -1536,7 +1536,37 @@ "gpu_report_engine_no_family_path": "CPU: brak ścieżki dla Twojego typu GPU", "gpu_report_engine_no_gpu": "CPU: brak dostępnego GPU", "gpu_report_engine_needs_accelerator": "Wymaga GPU ({{needs}}), którego ten komputer nie ma", - "models_dir_desc": "Tu są przechowywane pobrane modele. Jeśli ten dysk się zapełni, wybierz dysk z większą ilością wolnego miejsca." + "models_dir_desc": "Tu są przechowywane pobrane modele. Jeśli ten dysk się zapełni, wybierz dysk z większą ilością wolnego miejsca.", + "python_runtime_title": "Środowisko Python", + "python_runtime_override_title": "Nadpisanie aktywne", + "python_runtime_override_help": "Aktywne nadpisanie polecenia backendu ma pierwszeństwo.", + "python_runtime_override_active": "Nadpisanie aktywne", + "python_runtime_path_title": "Interpreter Pythona", + "python_runtime_managed_help": "Użyj zarządzanego środowiska VoiceStudio", + "python_runtime_valid": "Prawidłowy interpreter", + "python_runtime_choose": "Wybierz interpreter", + "python_runtime_use_managed": "Użyj zarządzanego środowiska", + "python_runtime_missing": "Brakujące moduły Pythona: {{modules}}", + "python_runtime_invalid": "Interpreter jest nieprawidłowy: {{detail}}", + "python_runtime_saved": "Python {{version}} zapisany. Restart backendu.", + "python_runtime_managed_saved": "Wybrano zarządzane środowisko. Restart.", + "python_runtime_quick_search": "Szybkie wyszukiwanie", + "python_runtime_searching": "Wyszukiwanie…", + "python_runtime_search_scope": "Przeszukuje tylko typowe lokalizacje; wybór ręczny pozostaje dostępny.", + "python_runtime_empty": "Nie znaleziono interpreterów Pythona w przeszukanych lokalizacjach.", + "python_runtime_partial_warning": "Wyniki mogą być niepełne z powodu niedostępnych lokalizacji lub limitów wyszukiwania. Możesz wybrać interpreter ręcznie.", + "python_runtime_permission_warning": "Niektóre lokalizacje pominięto z powodu braku uprawnień. Zezwól na dostęp w ustawieniach systemu lub wybierz interpreter ręcznie.", + "python_runtime_validating": "Sprawdzanie interpretera…", + "python_runtime_search_again": "Wyszukaj ponownie; ten wynik nie jest już dostępny.", + "python_runtime_confirm": "Potwierdź użycie i kontynuuj", + "python_runtime_ready": "Weryfikacja powiodła się. Sprawdź interpreter, a następnie potwierdź zapis i ponowne uruchomienie.", + "python_runtime_choose_another": "Wybierz inny interpreter", + "python_runtime_review_install": "Sprawdź plan instalacji zależności", + "python_runtime_install_consent": "Zgadzam się na instalację wymienionych pakietów w interpreterze pokazanym powyżej.", + "python_runtime_install_confirm": "Potwierdź i zainstaluj pakiety", + "python_runtime_installing": "Instalowanie zależności…", + "python_runtime_repair_failed": "Instalacja nie została ukończona. Zapisany interpreter pozostaje bez zmian.", + "python_runtime_repair_blocked": "Automatyczna instalacja jest niedostępna dla tego interpretera. Wybierz inne środowisko." }, "gallery": { "title": "VoiceStudio Galeria", diff --git a/electron/src/renderer/src/i18n/locales/pt.json b/electron/src/renderer/src/i18n/locales/pt.json index 6ef92aa88..08d6adfc9 100644 --- a/electron/src/renderer/src/i18n/locales/pt.json +++ b/electron/src/renderer/src/i18n/locales/pt.json @@ -1524,7 +1524,37 @@ "gpu_report_engine_no_family_path": "CPU: sem caminho para o seu tipo de GPU", "gpu_report_engine_no_gpu": "CPU: nenhuma GPU disponível", "gpu_report_engine_needs_accelerator": "Precisa de uma GPU ({{needs}}) que esta máquina não tem", - "models_dir_desc": "Os modelos baixados ficam aqui. Escolha uma unidade com mais espaço livre se esta encher." + "models_dir_desc": "Os modelos baixados ficam aqui. Escolha uma unidade com mais espaço livre se esta encher.", + "python_runtime_title": "Ambiente Python", + "python_runtime_override_title": "Substituição ativa", + "python_runtime_override_help": "Uma substituição avançada do backend está ativa e tem prioridade.", + "python_runtime_override_active": "Substituição ativa", + "python_runtime_path_title": "Interpretador Python", + "python_runtime_managed_help": "Usar o ambiente gerenciado do VoiceStudio", + "python_runtime_valid": "Interpretador válido", + "python_runtime_choose": "Escolher interpretador", + "python_runtime_use_managed": "Usar ambiente gerenciado", + "python_runtime_missing": "Módulos Python ausentes: {{modules}}", + "python_runtime_invalid": "Interpretador inválido: {{detail}}", + "python_runtime_saved": "Python {{version}} salvo. Reiniciando o backend.", + "python_runtime_managed_saved": "Ambiente gerenciado selecionado. Reiniciando.", + "python_runtime_quick_search": "Pesquisa rápida", + "python_runtime_searching": "A pesquisar…", + "python_runtime_search_scope": "Pesquisa apenas locais comuns; a seleção manual continua disponível.", + "python_runtime_empty": "Não foram encontrados interpretadores Python nos locais pesquisados.", + "python_runtime_partial_warning": "Os resultados podem estar incompletos devido a locais inacessíveis ou limites de pesquisa. Pode selecionar o interpretador manualmente.", + "python_runtime_permission_warning": "Alguns locais foram ignorados por falta de permissão. Autorize o acesso nas definições do sistema ou selecione o interpretador manualmente.", + "python_runtime_validating": "A validar o interpretador…", + "python_runtime_search_again": "Pesquise novamente; este resultado já não está disponível.", + "python_runtime_confirm": "Confirmar uso e continuar", + "python_runtime_ready": "Validação concluída. Revise o interpretador e confirme para salvar e reiniciar.", + "python_runtime_choose_another": "Escolher outro interpretador", + "python_runtime_review_install": "Revisar a instalação de dependências", + "python_runtime_install_consent": "Autorizo a instalação dos pacotes listados no interpretador mostrado acima.", + "python_runtime_install_confirm": "Confirmar e instalar pacotes", + "python_runtime_installing": "Instalando dependências…", + "python_runtime_repair_failed": "A instalação não foi concluída. O interpretador salvo não foi alterado.", + "python_runtime_repair_blocked": "A instalação automática não está disponível para este interpretador. Escolha outro ambiente." }, "gallery": { "title": "VoiceStudio Galeria", diff --git a/electron/src/renderer/src/i18n/locales/ru.json b/electron/src/renderer/src/i18n/locales/ru.json index a4a1a3703..4a066af29 100644 --- a/electron/src/renderer/src/i18n/locales/ru.json +++ b/electron/src/renderer/src/i18n/locales/ru.json @@ -1536,7 +1536,37 @@ "gpu_report_engine_no_family_path": "CPU: нет пути для вашего типа GPU", "gpu_report_engine_no_gpu": "CPU: GPU недоступен", "gpu_report_engine_needs_accelerator": "Требуется GPU ({{needs}}), которого нет на этом компьютере", - "models_dir_desc": "Здесь хранятся загруженные модели. Если диск заполнится, выберите диск с большим свободным местом." + "models_dir_desc": "Здесь хранятся загруженные модели. Если диск заполнится, выберите диск с большим свободным местом.", + "python_runtime_title": "Среда Python", + "python_runtime_override_title": "Переопределение включено", + "python_runtime_override_help": "Расширенное переопределение команды backend активно и имеет приоритет.", + "python_runtime_override_active": "Переопределение включено", + "python_runtime_path_title": "Интерпретатор Python", + "python_runtime_managed_help": "Использовать управляемую среду VoiceStudio", + "python_runtime_valid": "Рабочий интерпретатор", + "python_runtime_choose": "Выбрать интерпретатор", + "python_runtime_use_managed": "Использовать управляемую среду", + "python_runtime_missing": "Отсутствуют модули Python: {{modules}}", + "python_runtime_invalid": "Интерпретатор недействителен: {{detail}}", + "python_runtime_saved": "Python {{version}} сохранён. Перезапуск backend.", + "python_runtime_managed_saved": "Управляемая среда выбрана. Перезапуск.", + "python_runtime_quick_search": "Быстрый поиск", + "python_runtime_searching": "Поиск…", + "python_runtime_search_scope": "Поиск выполняется только в распространённых местах; ручной выбор доступен.", + "python_runtime_empty": "В проверенных местах интерпретаторы Python не найдены.", + "python_runtime_partial_warning": "Результаты могут быть неполными из-за недоступных папок или ограничений поиска. Интерпретатор можно выбрать вручную.", + "python_runtime_permission_warning": "Некоторые папки пропущены из-за отсутствия разрешения. Разрешите доступ в настройках системы или выберите интерпретатор вручную.", + "python_runtime_validating": "Проверка интерпретатора…", + "python_runtime_search_again": "Выполните поиск ещё раз: этот результат больше недоступен.", + "python_runtime_confirm": "Подтвердить выбор и продолжить", + "python_runtime_ready": "Проверка пройдена. Проверьте интерпретатор и подтвердите сохранение и перезапуск.", + "python_runtime_choose_another": "Выбрать другой интерпретатор", + "python_runtime_review_install": "Проверить план установки зависимостей", + "python_runtime_install_consent": "Я разрешаю установку перечисленных пакетов в указанный выше интерпретатор.", + "python_runtime_install_confirm": "Подтвердить и установить пакеты", + "python_runtime_installing": "Установка зависимостей…", + "python_runtime_repair_failed": "Установка не завершена. Сохранённый интерпретатор не изменён.", + "python_runtime_repair_blocked": "Автоматическая установка для этого интерпретатора недоступна. Выберите другое окружение." }, "gallery": { "title": "VoiceStudio Галерея", diff --git a/electron/src/renderer/src/i18n/locales/sv.json b/electron/src/renderer/src/i18n/locales/sv.json index 1d74148dc..1a3aa5f9f 100644 --- a/electron/src/renderer/src/i18n/locales/sv.json +++ b/electron/src/renderer/src/i18n/locales/sv.json @@ -1522,7 +1522,37 @@ "gpu_report_engine_no_family_path": "CPU: ingen väg för din GPU-typ", "gpu_report_engine_no_gpu": "CPU: ingen GPU tillgänglig", "gpu_report_engine_needs_accelerator": "Kräver en GPU ({{needs}}) som den här datorn inte har", - "models_dir_desc": "Nedladdade modeller lagras här. Välj en enhet med mer ledigt utrymme om den här blir full." + "models_dir_desc": "Nedladdade modeller lagras här. Välj en enhet med mer ledigt utrymme om den här blir full.", + "python_runtime_title": "Pythonkörning", + "python_runtime_override_title": "Åsidosättning aktiv", + "python_runtime_override_help": "En avancerad åsidosättning är aktiv och har företräde.", + "python_runtime_override_active": "Åsidosättning aktiv", + "python_runtime_path_title": "Python-tolk", + "python_runtime_managed_help": "Använd VoiceStudios hanterade körning", + "python_runtime_valid": "Giltig tolk", + "python_runtime_choose": "Välj tolk", + "python_runtime_use_managed": "Använd hanterad körning", + "python_runtime_missing": "Saknade Python-moduler: {{modules}}", + "python_runtime_invalid": "Vald tolk är ogiltig: {{detail}}", + "python_runtime_saved": "Python {{version}} sparad. Startar om backend.", + "python_runtime_managed_saved": "Hanterad körning vald. Startar om.", + "python_runtime_quick_search": "Snabbsökning", + "python_runtime_searching": "Söker…", + "python_runtime_search_scope": "Söker bara på vanliga platser; manuellt val är fortfarande tillgängligt.", + "python_runtime_empty": "Inga Python-tolkar hittades på de genomsökta platserna.", + "python_runtime_partial_warning": "Resultaten kan vara ofullständiga på grund av oläsbara platser eller sökgränser. Du kan välja en tolk manuellt.", + "python_runtime_permission_warning": "Vissa platser hoppades över eftersom behörighet saknas. Tillåt åtkomst i systeminställningarna eller välj en tolk manuellt.", + "python_runtime_validating": "Validerar tolk…", + "python_runtime_search_again": "Sök igen; resultatet är inte längre tillgängligt.", + "python_runtime_confirm": "Bekräfta användning och fortsätt", + "python_runtime_ready": "Valideringen lyckades. Granska tolken och bekräfta för att spara och starta om.", + "python_runtime_choose_another": "Välj en annan tolk", + "python_runtime_review_install": "Granska installation av beroenden", + "python_runtime_install_consent": "Jag godkänner att de angivna paketen installeras i tolken som visas ovan.", + "python_runtime_install_confirm": "Bekräfta och installera paket", + "python_runtime_installing": "Installerar beroenden…", + "python_runtime_repair_failed": "Installationen slutfördes inte. Din sparade tolk är oförändrad.", + "python_runtime_repair_blocked": "Automatisk installation är inte tillgänglig för den här tolken. Välj en annan miljö." }, "gallery": { "title": "VoiceStudio Galleri", diff --git a/electron/src/renderer/src/i18n/locales/th.json b/electron/src/renderer/src/i18n/locales/th.json index c07a0d103..f29d5743a 100644 --- a/electron/src/renderer/src/i18n/locales/th.json +++ b/electron/src/renderer/src/i18n/locales/th.json @@ -1522,7 +1522,37 @@ "gpu_report_engine_no_family_path": "CPU: ไม่มีเส้นทางสำหรับ GPU ประเภทของคุณ", "gpu_report_engine_no_gpu": "CPU: ไม่มี GPU ให้ใช้", "gpu_report_engine_needs_accelerator": "ต้องใช้ GPU ({{needs}}) ซึ่งเครื่องนี้ไม่มี", - "models_dir_desc": "โมเดลที่ดาวน์โหลดจะเก็บไว้ที่นี่ หากไดรฟ์นี้เต็ม ให้เลือกไดรฟ์ที่มีพื้นที่ว่างมากกว่า" + "models_dir_desc": "โมเดลที่ดาวน์โหลดจะเก็บไว้ที่นี่ หากไดรฟ์นี้เต็ม ให้เลือกไดรฟ์ที่มีพื้นที่ว่างมากกว่า", + "python_runtime_title": "รันไทม์ Python", + "python_runtime_override_title": "เปิดใช้การแทนที่", + "python_runtime_override_help": "เปิดใช้การแทนที่คำสั่งแบ็กเอนด์ขั้นสูงและมีลำดับความสำคัญ", + "python_runtime_override_active": "เปิดใช้การแทนที่", + "python_runtime_path_title": "ตัวแปลภาษา Python", + "python_runtime_managed_help": "ใช้รันไทม์ VoiceStudio ที่จัดการให้", + "python_runtime_valid": "ตัวแปลภาษาถูกต้อง", + "python_runtime_choose": "เลือกตัวแปลภาษา", + "python_runtime_use_managed": "ใช้รันไทม์ที่จัดการให้", + "python_runtime_missing": "โมดูล Python ที่ขาดหาย: {{modules}}", + "python_runtime_invalid": "ตัวแปลภาษาไม่ถูกต้อง: {{detail}}", + "python_runtime_saved": "บันทึก Python {{version}} แล้ว กำลังเริ่มใหม่", + "python_runtime_managed_saved": "เลือกรันไทม์ที่จัดการแล้ว กำลังเริ่มใหม่", + "python_runtime_quick_search": "ค้นหาอย่างรวดเร็ว", + "python_runtime_searching": "กำลังค้นหา…", + "python_runtime_search_scope": "ค้นหาเฉพาะตำแหน่งทั่วไป และยังเลือกด้วยตนเองได้", + "python_runtime_empty": "ไม่พบตัวแปลภาษา Python ในตำแหน่งที่ค้นหา", + "python_runtime_partial_warning": "ผลลัพธ์อาจไม่ครบถ้วนเนื่องจากอ่านบางตำแหน่งไม่ได้หรือถึงขีดจำกัดการค้นหา คุณสามารถเลือกตัวแปลภาษาเองได้", + "python_runtime_permission_warning": "ข้ามบางตำแหน่งเนื่องจากไม่มีสิทธิ์เข้าถึง โปรดอนุญาตในการตั้งค่าระบบหรือเลือกตัวแปลภาษาเอง", + "python_runtime_validating": "กำลังตรวจสอบตัวแปลภาษา…", + "python_runtime_search_again": "ค้นหาอีกครั้ง ผลลัพธ์นี้ไม่พร้อมใช้งานแล้ว", + "python_runtime_confirm": "ยืนยันการใช้และดำเนินการต่อ", + "python_runtime_ready": "ตรวจสอบสำเร็จ โปรดตรวจทานตัวแปลภาษา แล้วยืนยันเพื่อบันทึกและเริ่มใหม่", + "python_runtime_choose_another": "เลือกตัวแปลภาษาอื่น", + "python_runtime_review_install": "ตรวจทานแผนการติดตั้งส่วนที่จำเป็น", + "python_runtime_install_consent": "ฉันยินยอมให้ติดตั้งแพ็กเกจที่ระบุลงในตัวแปลภาษาที่แสดงด้านบน", + "python_runtime_install_confirm": "ยืนยันและติดตั้งแพ็กเกจ", + "python_runtime_installing": "กำลังติดตั้งส่วนที่จำเป็น…", + "python_runtime_repair_failed": "การติดตั้งไม่เสร็จสมบูรณ์ ตัวแปลภาษาที่บันทึกไว้ไม่เปลี่ยนแปลง", + "python_runtime_repair_blocked": "ตัวแปลภาษานี้ไม่รองรับการติดตั้งอัตโนมัติ โปรดเลือกสภาพแวดล้อมอื่น" }, "gallery": { "title": "VoiceStudio แกลเลอรี่", diff --git a/electron/src/renderer/src/i18n/locales/tr.json b/electron/src/renderer/src/i18n/locales/tr.json index fcaac4f78..e393e8803 100644 --- a/electron/src/renderer/src/i18n/locales/tr.json +++ b/electron/src/renderer/src/i18n/locales/tr.json @@ -1522,7 +1522,37 @@ "gpu_report_engine_no_family_path": "CPU: GPU türünüz için yol yok", "gpu_report_engine_no_gpu": "CPU: kullanılabilir GPU yok", "gpu_report_engine_needs_accelerator": "Bu bilgisayarda olmayan bir GPU ({{needs}}) gerekir", - "models_dir_desc": "İndirilen modeller burada saklanır. Bu sürücü dolarsa daha fazla boş alanı olan bir sürücü seçin." + "models_dir_desc": "İndirilen modeller burada saklanır. Bu sürücü dolarsa daha fazla boş alanı olan bir sürücü seçin.", + "python_runtime_title": "Python çalışma zamanı", + "python_runtime_override_title": "Geçersiz kılma etkin", + "python_runtime_override_help": "Gelişmiş backend komut geçersiz kılması etkin ve önceliklidir.", + "python_runtime_override_active": "Geçersiz kılma etkin", + "python_runtime_path_title": "Python yorumlayıcısı", + "python_runtime_managed_help": "Yönetilen VoiceStudio çalışma zamanını kullan", + "python_runtime_valid": "Geçerli yorumlayıcı", + "python_runtime_choose": "Yorumlayıcı seç", + "python_runtime_use_managed": "Yönetilen çalışma zamanını kullan", + "python_runtime_missing": "Eksik Python modülleri: {{modules}}", + "python_runtime_invalid": "Yorumlayıcı geçersiz: {{detail}}", + "python_runtime_saved": "Python {{version}} kaydedildi. Backend yeniden başlıyor.", + "python_runtime_managed_saved": "Yönetilen çalışma zamanı seçildi. Yeniden başlıyor.", + "python_runtime_quick_search": "Hızlı arama", + "python_runtime_searching": "Aranıyor…", + "python_runtime_search_scope": "Yalnızca yaygın konumlarda arar; manuel seçim kullanılabilir.", + "python_runtime_empty": "Aranan konumlarda Python yorumlayıcısı bulunamadı.", + "python_runtime_partial_warning": "Okunamayan konumlar veya arama sınırları nedeniyle sonuçlar eksik olabilir. Yorumlayıcıyı elle seçebilirsiniz.", + "python_runtime_permission_warning": "İzin verilmediği için bazı konumlar atlandı. Sistem ayarlarından erişime izin verin veya yorumlayıcıyı elle seçin.", + "python_runtime_validating": "Yorumlayıcı doğrulanıyor…", + "python_runtime_search_again": "Tekrar arayın; bu sonuç artık kullanılamıyor.", + "python_runtime_confirm": "Kullanımı onayla ve devam et", + "python_runtime_ready": "Doğrulama başarılı. Yorumlayıcıyı inceleyin, ardından kaydetmek ve yeniden başlatmak için onaylayın.", + "python_runtime_choose_another": "Başka bir yorumlayıcı seç", + "python_runtime_review_install": "Bağımlılık kurulumunu incele", + "python_runtime_install_consent": "Listelenen paketlerin yukarıda gösterilen yorumlayıcıya kurulmasını onaylıyorum.", + "python_runtime_install_confirm": "Onayla ve paketleri kur", + "python_runtime_installing": "Bağımlılıklar kuruluyor…", + "python_runtime_repair_failed": "Kurulum tamamlanmadı. Kayıtlı yorumlayıcınız değişmedi.", + "python_runtime_repair_blocked": "Bu yorumlayıcı için otomatik kurulum kullanılamıyor. Başka bir ortam seçin." }, "gallery": { "title": "VoiceStudio Galeri", diff --git a/electron/src/renderer/src/i18n/locales/uk.json b/electron/src/renderer/src/i18n/locales/uk.json index 1277f66fe..3d35acb6d 100644 --- a/electron/src/renderer/src/i18n/locales/uk.json +++ b/electron/src/renderer/src/i18n/locales/uk.json @@ -1536,7 +1536,37 @@ "gpu_report_engine_no_family_path": "CPU: немає шляху для вашого типу GPU", "gpu_report_engine_no_gpu": "CPU: GPU недоступний", "gpu_report_engine_needs_accelerator": "Потрібен GPU ({{needs}}), якого немає на цьому комп'ютері", - "models_dir_desc": "Тут зберігаються завантажені моделі. Якщо диск заповниться, виберіть диск із більшим вільним місцем." + "models_dir_desc": "Тут зберігаються завантажені моделі. Якщо диск заповниться, виберіть диск із більшим вільним місцем.", + "python_runtime_title": "Середовище Python", + "python_runtime_override_title": "Перевизначення активне", + "python_runtime_override_help": "Розширене перевизначення команди backend активне й має пріоритет.", + "python_runtime_override_active": "Перевизначення активне", + "python_runtime_path_title": "Інтерпретатор Python", + "python_runtime_managed_help": "Використовувати кероване середовище VoiceStudio", + "python_runtime_valid": "Дійсний інтерпретатор", + "python_runtime_choose": "Вибрати інтерпретатор", + "python_runtime_use_managed": "Використовувати кероване середовище", + "python_runtime_missing": "Відсутні модулі Python: {{modules}}", + "python_runtime_invalid": "Інтерпретатор недійсний: {{detail}}", + "python_runtime_saved": "Python {{version}} збережено. Перезапуск backend.", + "python_runtime_managed_saved": "Кероване середовище вибрано. Перезапуск.", + "python_runtime_quick_search": "Швидкий пошук", + "python_runtime_searching": "Пошук…", + "python_runtime_search_scope": "Пошук лише в поширених місцях; ручний вибір доступний.", + "python_runtime_empty": "У перевірених місцях інтерпретаторів Python не знайдено.", + "python_runtime_partial_warning": "Результати можуть бути неповними через недоступні папки або обмеження пошуку. Інтерпретатор можна вибрати вручну.", + "python_runtime_permission_warning": "Деякі папки пропущено через відсутність дозволу. Надайте доступ у налаштуваннях системи або виберіть інтерпретатор вручну.", + "python_runtime_validating": "Перевірка інтерпретатора…", + "python_runtime_search_again": "Виконайте пошук ще раз: цей результат більше недоступний.", + "python_runtime_confirm": "Підтвердити вибір і продовжити", + "python_runtime_ready": "Перевірка успішна. Перегляньте інтерпретатор і підтвердьте збереження та перезапуск.", + "python_runtime_choose_another": "Вибрати інший інтерпретатор", + "python_runtime_review_install": "Переглянути план установлення залежностей", + "python_runtime_install_consent": "Я дозволяю встановити перелічені пакети в показаний вище інтерпретатор.", + "python_runtime_install_confirm": "Підтвердити та встановити пакети", + "python_runtime_installing": "Установлення залежностей…", + "python_runtime_repair_failed": "Установлення не завершено. Збережений інтерпретатор не змінено.", + "python_runtime_repair_blocked": "Автоматичне встановлення для цього інтерпретатора недоступне. Виберіть інше середовище." }, "gallery": { "title": "VoiceStudio Галерея", diff --git a/electron/src/renderer/src/i18n/locales/vi.json b/electron/src/renderer/src/i18n/locales/vi.json index ccb4f1b65..8c3ab70b3 100644 --- a/electron/src/renderer/src/i18n/locales/vi.json +++ b/electron/src/renderer/src/i18n/locales/vi.json @@ -1522,7 +1522,37 @@ "gpu_report_engine_no_family_path": "CPU: không có đường chạy cho loại GPU của bạn", "gpu_report_engine_no_gpu": "CPU: không có GPU", "gpu_report_engine_needs_accelerator": "Cần GPU ({{needs}}) mà máy này không có", - "models_dir_desc": "Các mô hình đã tải được lưu ở đây. Hãy chọn ổ có nhiều dung lượng trống hơn nếu ổ này đầy." + "models_dir_desc": "Các mô hình đã tải được lưu ở đây. Hãy chọn ổ có nhiều dung lượng trống hơn nếu ổ này đầy.", + "python_runtime_title": "Môi trường Python", + "python_runtime_override_title": "Ghi đè đang bật", + "python_runtime_override_help": "Ghi đè lệnh backend nâng cao đang bật và được ưu tiên.", + "python_runtime_override_active": "Ghi đè đang bật", + "python_runtime_path_title": "Trình thông dịch Python", + "python_runtime_managed_help": "Dùng môi trường VoiceStudio được quản lý", + "python_runtime_valid": "Trình thông dịch hợp lệ", + "python_runtime_choose": "Chọn trình thông dịch", + "python_runtime_use_managed": "Dùng môi trường được quản lý", + "python_runtime_missing": "Thiếu mô-đun Python: {{modules}}", + "python_runtime_invalid": "Trình thông dịch không hợp lệ: {{detail}}", + "python_runtime_saved": "Đã lưu Python {{version}}. Đang khởi động lại.", + "python_runtime_managed_saved": "Đã chọn môi trường quản lý. Đang khởi động lại.", + "python_runtime_quick_search": "Tìm kiếm nhanh", + "python_runtime_searching": "Đang tìm…", + "python_runtime_search_scope": "Chỉ tìm ở các vị trí phổ biến; bạn vẫn có thể chọn thủ công.", + "python_runtime_empty": "Không tìm thấy trình thông dịch Python ở các vị trí đã tìm.", + "python_runtime_partial_warning": "Kết quả có thể chưa đầy đủ do một số vị trí không đọc được hoặc đã chạm giới hạn tìm kiếm. Bạn có thể chọn trình thông dịch thủ công.", + "python_runtime_permission_warning": "Một số vị trí bị bỏ qua do thiếu quyền. Hãy cấp quyền trong cài đặt hệ thống hoặc chọn trình thông dịch thủ công.", + "python_runtime_validating": "Đang xác thực trình thông dịch…", + "python_runtime_search_again": "Hãy tìm lại; kết quả này không còn khả dụng.", + "python_runtime_confirm": "Xác nhận sử dụng và tiếp tục", + "python_runtime_ready": "Xác thực thành công. Kiểm tra trình thông dịch rồi xác nhận để lưu và khởi động lại.", + "python_runtime_choose_another": "Chọn trình thông dịch khác", + "python_runtime_review_install": "Xem kế hoạch cài đặt phụ thuộc", + "python_runtime_install_consent": "Tôi đồng ý cài các gói được liệt kê vào trình thông dịch hiển thị ở trên.", + "python_runtime_install_confirm": "Xác nhận và cài các gói", + "python_runtime_installing": "Đang cài đặt phụ thuộc…", + "python_runtime_repair_failed": "Cài đặt chưa hoàn tất. Trình thông dịch đã lưu không thay đổi.", + "python_runtime_repair_blocked": "Không thể cài đặt tự động cho trình thông dịch này. Hãy chọn môi trường khác." }, "gallery": { "title": "VoiceStudio Thư viện ảnh", diff --git a/electron/src/renderer/src/i18n/locales/zh-CN.json b/electron/src/renderer/src/i18n/locales/zh-CN.json index 455f9ffbd..bfff1e1a0 100644 --- a/electron/src/renderer/src/i18n/locales/zh-CN.json +++ b/electron/src/renderer/src/i18n/locales/zh-CN.json @@ -1522,7 +1522,37 @@ "review_mode": "审核模式", "review_mode_off": "直接执行到底", "translate_cinematic": "影视级", - "translate_quality_desc": "快速模式直译且速度快;影视级模式使用 LLM 生成自然表达。" + "translate_quality_desc": "快速模式直译且速度快;影视级模式使用 LLM 生成自然表达。", + "python_runtime_title": "Python 运行环境", + "python_runtime_override_title": "覆盖已启用", + "python_runtime_override_help": "高级后端命令覆盖已启用,优先于此选择。", + "python_runtime_override_active": "覆盖已启用", + "python_runtime_path_title": "Python 解释器", + "python_runtime_managed_help": "使用 VoiceStudio 托管运行环境", + "python_runtime_valid": "解释器有效", + "python_runtime_choose": "选择解释器", + "python_runtime_use_managed": "使用托管运行环境", + "python_runtime_missing": "缺少 Python 模块:{{modules}}", + "python_runtime_invalid": "所选解释器无效:{{detail}}", + "python_runtime_saved": "已保存 Python {{version}}。正在重启后端。", + "python_runtime_managed_saved": "已选择托管运行环境。正在重启后端。", + "python_runtime_quick_search": "快速搜索", + "python_runtime_searching": "正在搜索…", + "python_runtime_search_scope": "仅搜索常见位置;仍可手动选择。", + "python_runtime_empty": "在搜索的位置中未找到 Python 解释器。", + "python_runtime_partial_warning": "部分位置无法读取或已达到扫描限制,搜索结果可能不完整。仍可手动选择解释器。", + "python_runtime_permission_warning": "部分位置因权限不足无法读取,搜索结果可能不完整。可在系统设置中授权,或手动选择解释器。", + "python_runtime_validating": "正在验证解释器…", + "python_runtime_search_again": "请重新搜索;此结果已不可用。", + "python_runtime_confirm": "确认使用并继续", + "python_runtime_ready": "验证成功。请核对解释器,确认后才会保存并重启。", + "python_runtime_choose_another": "选择其他解释器", + "python_runtime_review_install": "查看依赖安装计划", + "python_runtime_install_consent": "我同意将列出的软件包安装到上方显示的解释器环境中。", + "python_runtime_install_confirm": "确认并安装软件包", + "python_runtime_installing": "正在安装依赖…", + "python_runtime_repair_failed": "安装未完成。已保存的解释器保持不变。", + "python_runtime_repair_blocked": "此解释器不支持自动安装。请选择其他环境。" }, "gallery": { "title": "VoiceStudio 音色库", diff --git a/electron/src/renderer/src/i18n/locales/zh-TW.json b/electron/src/renderer/src/i18n/locales/zh-TW.json index bc730c0a0..a1545ef35 100644 --- a/electron/src/renderer/src/i18n/locales/zh-TW.json +++ b/electron/src/renderer/src/i18n/locales/zh-TW.json @@ -1522,7 +1522,37 @@ "gpu_report_engine_no_family_path": "CPU:沒有適用於你的 GPU 類型的路徑", "gpu_report_engine_no_gpu": "CPU:沒有可用的 GPU", "gpu_report_engine_needs_accelerator": "需要這台電腦沒有的 GPU({{needs}})", - "models_dir_desc": "下載的模型存放在這裡。如果此磁碟空間不足,請選擇剩餘空間更多的磁碟。" + "models_dir_desc": "下載的模型存放在這裡。如果此磁碟空間不足,請選擇剩餘空間更多的磁碟。", + "python_runtime_title": "Python 執行環境", + "python_runtime_override_title": "覆寫已啟用", + "python_runtime_override_help": "進階後端命令覆寫已啟用,優先於此選擇。", + "python_runtime_override_active": "覆寫已啟用", + "python_runtime_path_title": "Python 直譯器", + "python_runtime_managed_help": "使用 VoiceStudio 管理的執行環境", + "python_runtime_valid": "直譯器有效", + "python_runtime_choose": "選擇直譯器", + "python_runtime_use_managed": "使用管理的執行環境", + "python_runtime_missing": "缺少 Python 模組:{{modules}}", + "python_runtime_invalid": "所選直譯器無效:{{detail}}", + "python_runtime_saved": "已儲存 Python {{version}}。正在重新啟動後端。", + "python_runtime_managed_saved": "已選擇管理的執行環境。正在重新啟動。", + "python_runtime_quick_search": "快速搜尋", + "python_runtime_searching": "搜尋中…", + "python_runtime_search_scope": "僅搜尋常見位置;仍可手動選擇。", + "python_runtime_empty": "在搜尋的位置中找不到 Python 直譯器。", + "python_runtime_partial_warning": "部分位置無法讀取或已達掃描限制,搜尋結果可能不完整。仍可手動選擇直譯器。", + "python_runtime_permission_warning": "部分位置因權限不足無法讀取,搜尋結果可能不完整。可在系統設定中授權,或手動選擇直譯器。", + "python_runtime_validating": "正在驗證直譯器…", + "python_runtime_search_again": "請重新搜尋;此結果已不可用。", + "python_runtime_confirm": "確認使用並繼續", + "python_runtime_ready": "驗證成功。請核對直譯器,確認後才會儲存並重新啟動。", + "python_runtime_choose_another": "選擇其他直譯器", + "python_runtime_review_install": "檢視相依套件安裝計畫", + "python_runtime_install_consent": "我同意將列出的套件安裝至上方顯示的直譯器環境。", + "python_runtime_install_confirm": "確認並安裝套件", + "python_runtime_installing": "正在安裝相依套件…", + "python_runtime_repair_failed": "安裝未完成。已儲存的直譯器維持不變。", + "python_runtime_repair_blocked": "此直譯器不支援自動安裝。請選擇其他環境。" }, "gallery": { "title": "VoiceStudio 畫廊",