Repository navigation
Expand file tree
/
Copy pathsconstruct
More file actions
580 lines (463 loc) · 18.9 KB
/
Copy pathsconstruct
File metadata and controls
580 lines (463 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# NVDA add-on template SCONSTRUCT file
# Copyright (C) 2012-2021 Rui Batista, Noelia Martinez, Joseph Lee
# This file is covered by the GNU General Public License.
# See the file COPYING.txt for more details.
import codecs
import gettext
import os
import os.path
import zipfile
import sys
# While names imported below are available by default in every SConscript
# Linters aren't aware about them.
# To avoid Flake8 F821 warnings about them they are imported explicitly.
# When using other Scons functions please add them to the line below.
from SCons.Script import BoolVariable, Builder, Copy, Environment, Variables
sys.dont_write_bytecode = True
# Bytecode should not be written for build vars module to keep the repository root folder clean.
import buildVars # NOQA: E402
def md2html(source, dest):
import markdown
# Use extensions if defined.
mdExtensions = buildVars.markdownExtensions
lang = os.path.basename(os.path.dirname(source)).replace('_', '-')
localeLang = os.path.basename(os.path.dirname(source))
try:
_ = gettext.translation("nvda", localedir=os.path.join("addon", "locale"), languages=[localeLang]).gettext
summary = _(buildVars.addon_info["addon_summary"])
except Exception:
summary = buildVars.addon_info["addon_summary"]
title = "{addonSummary} {addonVersion}".format(
addonSummary=summary, addonVersion=buildVars.addon_info["addon_version"]
)
headerDic = {
"[[!meta title=\"": "# ",
"\"]]": " #",
}
with codecs.open(source, "r", "utf-8") as f:
mdText = f.read()
for k, v in headerDic.items():
mdText = mdText.replace(k, v, 1)
htmlText = markdown.markdown(mdText, extensions=mdExtensions)
# Optimization: build resulting HTML text in one go instead of writing parts separately.
docText = "\n".join([
"<!DOCTYPE html>",
"<html lang=\"%s\">" % lang,
"<head>",
"<meta charset=\"UTF-8\">"
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">",
"<link rel=\"stylesheet\" type=\"text/css\" href=\"../style.css\" media=\"screen\">",
"<title>%s</title>" % title,
"</head>\n<body>",
htmlText,
"</body>\n</html>"
])
with codecs.open(dest, "w", "utf-8") as f:
f.write(docText)
def mdTool(env):
mdAction = env.Action(
lambda target, source, env: md2html(source[0].path, target[0].path),
lambda target, source, env: 'Generating % s' % target[0],
)
mdBuilder = env.Builder(
action=mdAction,
suffix='.html',
src_suffix='.md',
)
env['BUILDERS']['markdown'] = mdBuilder
vars = Variables()
vars.Add("version", "The version of this build", buildVars.addon_info["addon_version"])
vars.Add(BoolVariable("dev", "Whether this is a daily development version", False))
vars.Add("channel", "Update channel for this build", buildVars.addon_info["addon_updateChannel"])
env = Environment(variables=vars, ENV=os.environ, tools=['gettexttool', mdTool])
env.Append(**buildVars.addon_info)
if env["dev"]:
import datetime
buildDate = datetime.datetime.now()
year, month, day = str(buildDate.year), str(buildDate.month), str(buildDate.day)
env["addon_version"] = "".join([year, month.zfill(2), day.zfill(2), "-dev"])
env["channel"] = "dev"
elif env["version"] is not None:
env["addon_version"] = env["version"]
if "channel" in env and env["channel"] is not None:
env["addon_updateChannel"] = env["channel"]
buildVars.addon_info["addon_version"] = env["addon_version"]
buildVars.addon_info["addon_updateChannel"] = env["addon_updateChannel"]
addonFile = env.File("output/${addon_name}-${addon_version}.nvda-addon")
def addonGenerator(target, source, env, for_signature):
action = env.Action(
lambda target, source, env: createAddonBundleFromPath(source[0].abspath, target[0].abspath) and None,
lambda target, source, env: "Generating Addon %s" % target[0]
)
return action
def manifestGenerator(target, source, env, for_signature):
action = env.Action(
lambda target, source, env: generateManifest(source[0].abspath, target[0].abspath) and None,
lambda target, source, env: "Generating manifest %s" % target[0]
)
return action
def translatedManifestGenerator(target, source, env, for_signature):
dir = os.path.abspath(os.path.join(os.path.dirname(str(source[0])), ".."))
lang = os.path.basename(dir)
action = env.Action(
lambda target, source, env: generateTranslatedManifest(source[1].abspath, lang, target[0].abspath) and None,
lambda target, source, env: "Generating translated manifest %s" % target[0]
)
return action
env['BUILDERS']['NVDAAddon'] = Builder(generator=addonGenerator)
env['BUILDERS']['NVDAManifest'] = Builder(generator=manifestGenerator)
env['BUILDERS']['NVDATranslatedManifest'] = Builder(generator=translatedManifestGenerator)
def createAddonHelp(dir):
docsDir = os.path.join(dir, "doc")
if os.path.isfile("style.css"):
cssPath = os.path.join(docsDir, "style.css")
cssTarget = env.Command(cssPath, "style.css", Copy("$TARGET", "$SOURCE"))
env.Depends(addon, cssTarget)
def createAddonBundleFromPath(path, dest):
""" Creates a bundle from a directory that contains an addon manifest file."""
basedir = os.path.abspath(path)
with zipfile.ZipFile(dest, 'w', zipfile.ZIP_DEFLATED) as z:
# FIXME: the include/exclude feature may or may not be useful. Also python files can be pre-compiled.
for dir, dirnames, filenames in os.walk(basedir):
relativePath = os.path.relpath(dir, basedir)
for filename in filenames:
pathInBundle = os.path.join(relativePath, filename)
absPath = os.path.join(dir, filename)
if pathInBundle not in buildVars.excludedFiles:
z.write(absPath, pathInBundle)
return dest
def generateManifest(source, dest):
addon_info = buildVars.addon_info
with codecs.open(source, "r", "utf-8") as f:
manifest_template = f.read()
manifest = manifest_template.format(**addon_info)
with codecs.open(dest, "w", "utf-8") as f:
f.write(manifest)
def generateTranslatedManifest(source, language, out):
_ = gettext.translation("nvda", localedir=os.path.join("addon", "locale"), languages=[language]).gettext
vars = {}
for var in ("addon_summary", "addon_description"):
vars[var] = _(buildVars.addon_info[var])
with codecs.open(source, "r", "utf-8") as f:
manifest_template = f.read()
result = manifest_template.format(**vars)
with codecs.open(out, "w", "utf-8") as f:
f.write(result)
def expandGlobs(files):
return [f for pattern in files for f in env.Glob(pattern)]
def _rmtree(path):
"""Remove directory tree, handling Windows read-only and locked files."""
import shutil
import stat
import time
def _on_error(func, p, exc_info):
try:
os.chmod(p, stat.S_IWRITE)
func(p)
except OSError:
time.sleep(1)
try:
func(p)
except Exception:
pass
try:
shutil.rmtree(path, onerror=_on_error)
except Exception as e:
print(f"Warning: could not clean up {path}: {e}")
VOICEVOX_CORE_VERSION = "0.17.1"
VVM_VERSION = "0.17.0"
def _readCoreVersion(target_dir):
"""ダウンロード済みの voicevox_core.dll のバージョン(記録ファイル)を返す"""
version_file = target_dir / "c_api" / "VERSION"
if not version_file.exists():
return None
return version_file.read_text(encoding="utf-8").strip()
def _readVvmFormatVersion(vvm_path):
"""VVM内の manifest.json から vvm_format_version を読む"""
import json
import zipfile
try:
with zipfile.ZipFile(vvm_path) as z:
manifest = json.loads(z.read("manifest.json").decode("utf-8"))
return int(manifest.get("vvm_format_version", 1))
except Exception as e:
print(f"Warning: could not read vvm_format_version of {vvm_path}: {e}")
return 0
def downloadVoicevoxCore():
"""Download and extract VOICEVOX Core files to addon directory"""
import shutil
import urllib.request
import zipfile
import tarfile
from pathlib import Path
target_dir = Path("addon") / "voicevox_core"
# Check if all required files exist
dll_path = target_dir / "c_api" / "lib" / "voicevox_core.dll"
onnx_path = target_dir / "onnxruntime" / "lib" / "voicevox_onnxruntime.dll"
dml_path = target_dir / "onnxruntime" / "lib" / "DirectML.dll"
dict_path = target_dir / "dict" / "open_jtalk_dic_utf_8-1.11"
vvm_path = target_dir / "models" / "vvms" / "0.vvm"
# 古いバージョンのDLLや旧形式VVMが残っている場合は取り直す(ストリーミング合成に必要)
core_ok = dll_path.exists() and _readCoreVersion(target_dir) == VOICEVOX_CORE_VERSION
onnx_ok = onnx_path.exists()
dml_ok = dml_path.exists()
dict_ok = dict_path.exists()
vvm_ok = vvm_path.exists() and _readVvmFormatVersion(vvm_path) >= 2
if core_ok and onnx_ok and dml_ok and dict_ok and vvm_ok:
print("VOICEVOX Core files already exist, skipping download")
return True
target_dir.mkdir(parents=True, exist_ok=True)
try:
# 1. Download voicevox_core.dll
if not core_ok:
print(f"Downloading voicevox_core.dll {VOICEVOX_CORE_VERSION}...")
downloadVoicevoxCoreDLL(target_dir)
# 2. Download voicevox_onnxruntime.dll (DirectML build)
if not onnx_ok:
print("Downloading voicevox_onnxruntime.dll (DirectML)...")
downloadOnnxRuntime(target_dir)
# 3. Download DirectML.dll
if not dml_ok:
print("Downloading DirectML.dll...")
downloadDirectML(target_dir)
# 5. Download Open JTalk dictionary
if not dict_ok:
print("Downloading Open JTalk dictionary...")
downloadOpenJTalkDict(target_dir)
# 6. Download voice model (0.vvm)
if not vvm_ok:
print(f"Downloading voice model 0.vvm {VVM_VERSION}...")
downloadVoiceModel(target_dir, 0)
print("VOICEVOX Core files prepared successfully")
return True
except Exception as e:
print(f"Error preparing VOICEVOX Core: {e}")
print("Trying to use local file if available...")
local_source = Path(r"C:\Users\yuki\Downloads\voicevox\voicevox_core")
if local_source.exists():
return copyVoicevoxCoreFromLocal(local_source, target_dir)
return False
def downloadVoicevoxCoreDLL(target_dir):
"""Download voicevox_core.dll from GitHub releases"""
import urllib.request
import zipfile
import shutil
from pathlib import Path
version = VOICEVOX_CORE_VERSION
zip_filename = f"voicevox_core-windows-x64-{version}.zip"
download_url = f"https://github.com/VOICEVOX/voicevox_core/releases/download/{version}/{zip_filename}"
zip_path = Path(zip_filename)
temp_dir = Path("temp_core_dll")
try:
urllib.request.urlretrieve(download_url, zip_path)
print(f"Downloaded: {zip_filename}")
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(temp_dir)
# Find the DLL in the extracted directory
extracted_dirs = list(temp_dir.glob("*/"))
source_dir = extracted_dirs[0] if extracted_dirs else temp_dir
# Copy voicevox_core.dll
dll_src = source_dir / "lib" / "voicevox_core.dll"
dll_dst = target_dir / "c_api" / "lib"
dll_dst.mkdir(parents=True, exist_ok=True)
if dll_src.exists():
shutil.copy2(dll_src, dll_dst / "voicevox_core.dll")
(target_dir / "c_api" / "VERSION").write_text(version, encoding="utf-8")
print("Copied: voicevox_core.dll")
else:
raise FileNotFoundError(f"voicevox_core.dll not found in {source_dir}")
finally:
if zip_path.exists():
zip_path.unlink()
if temp_dir.exists():
_rmtree(temp_dir)
def downloadOnnxRuntime(target_dir):
"""Download voicevox_onnxruntime.dll from onnxruntime-builder releases"""
import urllib.request
import tarfile
import shutil
from pathlib import Path
# VOICEVOX Core 0.17系の推奨は1.23.2だが、1.17.3も対応範囲内(>=1.17)。
# 実測(i7-13700F / RTX 4060 Ti)では1.23.2の方がCPUで約1.4倍、DirectMLで1〜2割、
# CUDAで3〜4倍遅かったため1.17.3のままにしている。
# 1.23.2に上げる場合はDirectMLを1.15.4(additional_libraries 0.3.0)に揃え、CUDA版は
# cuDNN 9に合わせて cuda_installer.py と _voicevox_wrapper.py のDLLプリロード一覧も直すこと。
version = "1.17.3"
tgz_filename = f"voicevox_onnxruntime-win-x64-dml-{version}.tgz"
tag_name = f"voicevox_onnxruntime-{version}"
download_url = f"https://github.com/VOICEVOX/onnxruntime-builder/releases/download/{tag_name}/{tgz_filename}"
tgz_path = Path(tgz_filename)
temp_dir = Path("temp_onnx")
try:
urllib.request.urlretrieve(download_url, tgz_path)
print(f"Downloaded: {tgz_filename}")
with tarfile.open(tgz_path, 'r:gz') as tar_ref:
tar_ref.extractall(temp_dir)
dll_dst = target_dir / "onnxruntime" / "lib"
dll_dst.mkdir(parents=True, exist_ok=True)
dll_src = temp_dir / f"voicevox_onnxruntime-win-x64-dml-{version}" / "lib" / "voicevox_onnxruntime.dll"
if not dll_src.exists():
dll_files = list(temp_dir.glob("**/voicevox_onnxruntime.dll"))
if dll_files:
dll_src = dll_files[0]
if dll_src.exists():
shutil.copy2(dll_src, dll_dst / "voicevox_onnxruntime.dll")
print("Copied: voicevox_onnxruntime.dll")
else:
raise FileNotFoundError(f"voicevox_onnxruntime.dll not found in archive")
finally:
if tgz_path.exists():
tgz_path.unlink()
if temp_dir.exists():
_rmtree(temp_dir)
def downloadDirectML(target_dir):
"""Download DirectML.dll from voicevox_additional_libraries"""
import urllib.request
import zipfile
import shutil
from pathlib import Path
url = "https://github.com/VOICEVOX/voicevox_additional_libraries/releases/download/0.2.1/DirectML-windows-x64.zip"
zip_filename = "DirectML-windows-x64.zip"
zip_path = Path(zip_filename)
temp_dir = Path("temp_directml")
try:
urllib.request.urlretrieve(url, zip_path)
print(f"Downloaded: {zip_filename}")
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(temp_dir)
dll_dst = target_dir / "onnxruntime" / "lib"
dll_dst.mkdir(parents=True, exist_ok=True)
dll_src = temp_dir / "DirectML-windows-x64" / "DirectML.dll"
if dll_src.exists():
shutil.copy2(dll_src, dll_dst / "DirectML.dll")
print("Copied: DirectML.dll")
else:
raise FileNotFoundError(f"DirectML.dll not found in {temp_dir}")
finally:
if zip_path.exists():
zip_path.unlink()
if temp_dir.exists():
_rmtree(temp_dir)
def downloadOpenJTalkDict(target_dir):
"""Download Open JTalk dictionary from SourceForge"""
import urllib.request
import tarfile
import shutil
from pathlib import Path
dict_version = "1.11"
tgz_filename = f"open_jtalk_dic_utf_8-{dict_version}.tar.gz"
download_url = f"https://sourceforge.net/projects/open-jtalk/files/Dictionary/open_jtalk_dic-{dict_version}/{tgz_filename}/download"
tgz_path = Path(tgz_filename)
temp_dir = Path("temp_dict")
try:
print(f"Downloading from SourceForge (this may take a while)...")
urllib.request.urlretrieve(download_url, tgz_path)
print(f"Downloaded: {tgz_filename}")
with tarfile.open(tgz_path, 'r:gz') as tar_ref:
tar_ref.extractall(temp_dir)
# Find the dictionary directory
dict_src = temp_dir / f"open_jtalk_dic_utf_8-{dict_version}"
if not dict_src.exists():
# Try searching for it
dict_dirs = list(temp_dir.glob("open_jtalk_dic_utf_8-*"))
if dict_dirs:
dict_src = dict_dirs[0]
dict_dst = target_dir / "dict" / f"open_jtalk_dic_utf_8-{dict_version}"
if dict_src.exists():
shutil.copytree(dict_src, dict_dst, dirs_exist_ok=True)
print(f"Copied: Open JTalk dictionary")
else:
raise FileNotFoundError(f"Dictionary directory not found in {temp_dir}")
finally:
if tgz_path.exists():
tgz_path.unlink()
if temp_dir.exists():
_rmtree(temp_dir)
def copyVoicevoxCoreFromLocal(source_dir, target_dir):
"""Fallback: Copy VOICEVOX Core from local directory"""
import shutil
print(f"Copying VOICEVOX Core from local directory: {source_dir}")
# Create target directory
target_dir.mkdir(parents=True, exist_ok=True)
# Copy DLL files
c_api_lib_src = source_dir / "c_api" / "lib"
c_api_lib_dst = target_dir / "c_api" / "lib"
c_api_lib_dst.mkdir(parents=True, exist_ok=True)
shutil.copy2(c_api_lib_src / "voicevox_core.dll", c_api_lib_dst / "voicevox_core.dll")
print(f"Copied: voicevox_core.dll")
onnx_lib_src = source_dir / "onnxruntime" / "lib"
onnx_lib_dst = target_dir / "onnxruntime" / "lib"
onnx_lib_dst.mkdir(parents=True, exist_ok=True)
for dll in onnx_lib_src.glob("*.dll"):
shutil.copy2(dll, onnx_lib_dst / dll.name)
print(f"Copied: {dll.name}")
# Copy dictionary
dict_src = source_dir / "dict" / "open_jtalk_dic_utf_8-1.11"
dict_dst = target_dir / "dict" / "open_jtalk_dic_utf_8-1.11"
if dict_src.exists():
shutil.copytree(dict_src, dict_dst, dirs_exist_ok=True)
print(f"Copied: Open JTalk dictionary")
# Copy voice model 0.vvm (contains Zundamon and Tsumugi)
models_src = source_dir / "models" / "vvms"
models_dst = target_dir / "models" / "vvms"
models_dst.mkdir(parents=True, exist_ok=True)
shutil.copy2(models_src / "0.vvm", models_dst / "0.vvm")
print(f"Copied: 0.vvm (Zundamon & Tsumugi)")
print("VOICEVOX Core files copied successfully")
return True
def downloadVoiceModel(target_dir, model_id):
"""Download voice model file (vvm) from voicevox_vvm releases"""
import urllib.request
from pathlib import Path
models_dst = target_dir / "models" / "vvms"
models_dst.mkdir(parents=True, exist_ok=True)
vvm_path = models_dst / f"{model_id}.vvm"
url = f"https://github.com/VOICEVOX/voicevox_vvm/releases/download/{VVM_VERSION}/{model_id}.vvm"
urllib.request.urlretrieve(url, vvm_path)
print(f"Downloaded: {model_id}.vvm")
# Download/prepare VOICEVOX Core files before building
print("Preparing VOICEVOX Core files...")
downloadVoicevoxCore()
addon = env.NVDAAddon(addonFile, env.Dir('addon'))
langDirs = [f for f in env.Glob(os.path.join("addon", "locale", "*"))]
# Allow all NVDA's gettext po files to be compiled in source/locale, and manifest files to be generated
for dir in langDirs:
poFile = dir.File(os.path.join("LC_MESSAGES", "nvda.po"))
moFile = env.gettextMoFile(poFile)
env.Depends(moFile, poFile)
translatedManifest = env.NVDATranslatedManifest(
dir.File("manifest.ini"),
[moFile, os.path.join("manifest-translated.ini.tpl")]
)
env.Depends(translatedManifest, ["buildVars.py"])
env.Depends(addon, [translatedManifest, moFile])
pythonFiles = expandGlobs(buildVars.pythonSources)
for file in pythonFiles:
env.Depends(addon, file)
# Convert markdown files to html
# We need at least doc in English and should enable the Help button for the add-on in Add-ons Manager
createAddonHelp("addon")
for mdFile in env.Glob(os.path.join('addon', 'doc', '*', '*.md')):
htmlFile = env.markdown(mdFile)
env.Depends(htmlFile, mdFile)
env.Depends(addon, htmlFile)
# Pot target
i18nFiles = expandGlobs(buildVars.i18nSources)
gettextvars = {
'gettext_package_bugs_address': 'nvda-translations@groups.io',
'gettext_package_name': buildVars.addon_info['addon_name'],
'gettext_package_version': buildVars.addon_info['addon_version']
}
pot = env.gettextPotFile("${addon_name}.pot", i18nFiles, **gettextvars)
env.Alias('pot', pot)
env.Depends(pot, i18nFiles)
mergePot = env.gettextMergePotFile("${addon_name}-merge.pot", i18nFiles, **gettextvars)
env.Alias('mergePot', mergePot)
env.Depends(mergePot, i18nFiles)
# Generate Manifest path
manifest = env.NVDAManifest(os.path.join("addon", "manifest.ini"), os.path.join("manifest.ini.tpl"))
# Ensure manifest is rebuilt if buildVars is updated.
env.Depends(manifest, "buildVars.py")
env.Depends(addon, manifest)
env.Default(addon)
env.Clean(addon, ['.sconsign.dblite', 'addon/doc/' + buildVars.baseLanguage + '/'])