egatari 0.6.22-rc.2 → 0.6.23-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,24 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
8
8
 
9
9
  <!-- Unreleased changes are fragments in changes/*.md (see CONTRIBUTING.md "Changelog"); node tools/changelog.mjs --release X.Y.Z moves them here. -->
10
10
 
11
+ ## [0.6.22] - 2026-11-28
12
+
13
+ ### Added
14
+
15
+ - Viewer: notes in the learner's own words, one per slide (typed in the memo area under the slide, with handwriting over it; `m` or 「メモ」) and one per section of the book (opened from a button at the section's end, written in the page, never in the file's frame). Kept on the device only, never on a shared device.
16
+ - Viewer: quotes — 「メモ」 in the window for selected words quotes them into the note (a dotted underline marks them; no highlight, so 暗記 does not hide them), with ↗ back to the place. With the book on screen, 「メモ」 opens the note of the section being read. Highlights and 暗記 now work on the slides' text too, so Markup shows for files without a book.
17
+ - Viewer: export of notes as a PDF handout (each slide with its memo area; the page draws the notes and prints, the file's frames never print), as Markdown, and as a backup (`.ega-notes.json`, with highlights and handwriting) that another device can read in for the same file.
18
+
19
+ ### Changed
20
+
21
+ - Format spec copy (`vendor/egatari-spec`): the snapshot **wd-2026-11-28** (egatari-spec af53dcf). Studio follows Egatari 1.0 WD 2026-11-28, including the annotations (the Note record, `target.slide`, the `.ega-notes.json` exchange file, notes never entering a frame of the file, printing included) that the Viewer's notes implement. The other changes since wd-2026-11-22 (§8.4 declared questions, Player P8 `prefs`, Appendix A 14) do not change what Studio does.
22
+
23
+ ### Fixed
24
+
25
+ - Editor: a **Copy** button could still grow by a few pixels when it said “✓ Copied” for the first time: if the font for those characters started loading only after the width was measured, the width came from the fallback font. The buttons are measured again whenever fonts finish loading
26
+ - Editor: **⌘S / Ctrl+S** saves the file also when the focus is in the slide preview. After an edit the preview reloads and takes the focus, so the shortcut pressed then reached the preview and did not save (in Chrome it could open the browser's own Save page). The preview now passes the shortcut to the editor, which saves under the same rules as elsewhere (handoff #80)
27
+ - Editor: **Request a part…** could not send from the published editor: after about 20 seconds the dialog said the check frame could not be loaded. The relay's deploy (Wrangler, esbuild `keepNames`) wrapped functions of the frame's script in `__name(…)`, a helper the frame did not have, so the script stopped before it said it was ready. The relay now deploys without `keepNames` and the frame's script defines the helper itself; a test bundles the relay as a deploy does and checks that the frame says ready. Only the relay at request.egatari.org is deployed again (handoff #35)
28
+
11
29
  ## [0.6.21] - 2026-11-27
12
30
 
13
31
  ### Added
@@ -1768,7 +1786,8 @@ First public release.
1768
1786
  - Docs: README (English and Japanese), the contract (`docs/contract.md`), a reference of every option, syntax and key (`docs/reference.md`, `docs/reference.ja.md`), guides for the dev server and video, CONTRIBUTING, SECURITY, issue forms
1769
1787
  - Tests (`npm test`) and GitHub Actions running them on Node 22 and 24, plus a TTS dry-run through video export
1770
1788
 
1771
- [Unreleased]: https://github.com/egatari/egatari-studio/compare/v0.6.21...HEAD
1789
+ [Unreleased]: https://github.com/egatari/egatari-studio/compare/v0.6.22...HEAD
1790
+ [0.6.22]: https://github.com/egatari/egatari-studio/compare/v0.6.21...v0.6.22
1772
1791
  [0.6.21]: https://github.com/egatari/egatari-studio/compare/v0.6.20...v0.6.21
1773
1792
  [0.6.20]: https://github.com/egatari/egatari-studio/compare/v0.6.19...v0.6.20
1774
1793
  [0.6.19]: https://github.com/egatari/egatari-studio/compare/v0.6.18...v0.6.19
@@ -159,6 +159,10 @@ export const MESSAGES = {
159
159
  ja: (a) => `参照音声「${a.path}」(voice.json の声の元の録音)が${{ slides: 'スライドで使われている:Egatari ファイルには参照音声を含めないので、Egatari ファイル(.ega.html)へのエクスポートは断る。スライドから削除する', audio: ' audio/manifest.json でステップの音声になっている:Egatari ファイル(.ega.html)には含めない(そのステップは音声なし)。その声で作った音声に置き換える', attachments: '添付の場所(attachments/)にある:Egatari ファイル(.ega.html)には含めない', folder: '作業フォルダの中にある:Egatari ファイル(.ega.html)には含めないが、作業フォルダごと人に渡すと一緒に渡る' }[a.where]}。録音は作業フォルダの外に置き、voice.json にはその場所か名前を書く(Egatari ファイルには、その声で作った音声だけが含まれる)`,
160
160
  en: (a) => `the reference voice “${a.path}” (the recording a voice in voice.json imitates) ${{ slides: 'is used by the slides: an Egatari file does not carry reference voices, so export to an Egatari file (.ega.html) is refused. Remove it from the slides', audio: 'is a step\'s audio in audio/manifest.json: it is left out of the Egatari file (.ega.html) and that step has no audio. Replace it with audio made with the voice', attachments: 'is in the attachments folder (attachments/): it is left out of the Egatari file (.ega.html)', folder: 'is inside the working folder: it is left out of the Egatari file (.ega.html), but goes along if you share the whole working folder' }[a.where]}. Keep the recording outside the working folder and give its location or name in voice.json (an Egatari file carries only the audio made with the voice)`,
161
161
  },
162
+ keyLike: {
163
+ ja: (a) => `${a.file} ${a.line} 行目に API キーらしい文字があります`,
164
+ en: (a) => `${a.file} line ${a.line} may contain an API key`,
165
+ },
162
166
  // ---------------------------------------------------------------- 添付(attachments/。format spec §3.8)
163
167
  extensionVersion: { ja: (a) => `拡張 ${a.name} の v${a.v} には未対応(対応は v${a.supported}):拡張を使わず、そのまま保持する。使うには対応するバージョンで開く`, en: (a) => `extension ${a.name} v${a.v} is not supported (implements v${a.supported}): ignore and preserve it; open in a supporting version to use it` },
164
168
  attachBadConfig: { ja: (a) => `egatari.json の attachments が読めない(${a.why}):[{"path": "attachments/…", "role": "pdf", "title": "…"}] の形にする`, en: (a) => `attachments in egatari.json cannot be read (${a.why}): use [{"path": "attachments/…", "role": "pdf", "title": "…"}]` },
package/kit/check.mjs CHANGED
@@ -144,7 +144,7 @@ catch (e) {
144
144
  await new Promise((resolve) => process.stdout.write('', resolve));
145
145
  process.exit(1);
146
146
  }
147
- console.error('ビルド失敗: ' + e.message); process.exit(1);
147
+ console.error('ビルド失敗: ' + (e instanceof SyntaxError ? '書式を確認してください / invalid syntax' : e.message)); process.exit(1);
148
148
  }
149
149
  // 言語:<html lang> が ja か、lang が無ければ日本語の規則。それ以外(英語など)は英語の規則
150
150
  const lang = built.html.match(/<html[^>]*\slang="([^"]*)"/)?.[1] || '';
@@ -248,7 +248,7 @@ if (extraMissing.length) report(null, 'error', 'fontsExtraMissing', { fonts: ext
248
248
  const aDir = path.join(deckDir, FORMAT.ATTACH_DIR);
249
249
  let conf = null;
250
250
  const cfgPath = path.join(deckDir, FORMAT.CONFIG_FILE);
251
- try { if (fs.existsSync(cfgPath)) conf = JSON.parse(readRegular(cfgPath, { max: READ_LIMITS.json }).toString('utf8')); } catch (e) { report(null, 'warn', 'attachBadConfig', { why: `${FORMAT.CONFIG_FILE}: ${e.message}` }); }
251
+ try { if (fs.existsSync(cfgPath)) conf = JSON.parse(readRegular(cfgPath, { max: READ_LIMITS.json }).toString('utf8')); } catch (e) { report(null, 'warn', 'attachBadConfig', { why: `${FORMAT.CONFIG_FILE}: ${e instanceof SyntaxError ? 'invalid JSON' : e.message}` }); }
252
252
  for (const name of ['live', 'embed']) {
253
253
  const v = conf?.extensions?.[name]?.v;
254
254
  if (Number.isInteger(v) && v > 1) report(null, 'info', 'extensionVersion', { name, v, supported: 1 });
@@ -314,6 +314,22 @@ if (extraMissing.length) report(null, 'error', 'fontsExtraMissing', { fonts: ext
314
314
  }
315
315
  }
316
316
 
317
+ // 作業フォルダ直下の設定。鍵らしい文字がある行だけを知らせる。
318
+ {
319
+ const deckDir = path.dirname(path.resolve(src));
320
+ const keyLike = /\b(?:sk-[\w-]{20,}|AIza[\w-]{35}(?![\w-])|[Bb][Ee][Aa][Rr][Ee][Rr]\s+[\w.~+/=-]{20,}|gh[pousr]_[A-Za-z0-9]{36,})/;
321
+ for (const entry of fs.readdirSync(deckDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
322
+ const file = entry.name;
323
+ if (!entry.isFile() || (file !== '.env' && !file.toLowerCase().endsWith('.json'))) continue;
324
+ let text;
325
+ try { text = readRegular(path.join(deckDir, file), { max: READ_LIMITS.json }).toString('utf8'); }
326
+ catch { continue; }
327
+ for (const [i, line] of text.split(/\r?\n/).entries()) {
328
+ if (keyLike.test(line)) report(null, 'warn', 'keyLike', { file, line: i + 1 });
329
+ }
330
+ }
331
+ }
332
+
317
333
  // 出力に使うもの(ブラウザの検査が埋める。--no-browser では組み立てのスライドの一覧から)
318
334
  let meta = [], compErrors = [], narrText = '';
319
335
  // コンソールのエラーとページの例外は、読み込み直後だけでなく検査の全体(後の seek・再現性の確認・開き直し)を通して集め、最後にまとめて報告する
@@ -49,6 +49,7 @@ export const CLI_ONLY = Object.freeze({
49
49
  linkFileMissing: 'needs the filesystem: checks that a linked file exists next to the deck',
50
50
  fontsExtraMissing: 'needs the @egatari/fonts-extra npm package on disk; the editor bundles its fonts',
51
51
  extensionVersion: 'info; reads extension versions from egatari.json on disk',
52
+ keyLike: 'scans configuration files on disk for possible API keys',
52
53
  'component-requires-missing': 'the build stops; the editor shows the same message as a build error',
53
54
  'component-not-in-catalogue': 'the build stops; the editor shows the same message (catalogueMessage) as a build error',
54
55
  });
@@ -79,6 +79,7 @@ export const RULES = Object.freeze([
79
79
  { id: 'C-font', kind: 'checker', phase: 'A 体裁', codes: ['themeMetricsDrift', 'metricsFontLoad', 'themeMetricsInvalid', 'fontsExtraMissing', 'fontNotCovered', 'fontNotEmbedded'] },
80
80
  { id: 'C-links', kind: 'checker', phase: 'J リンク', codes: ['linkFileMissing', 'linkEmpty', 'linkUnknown', 'linkNumberRange', 'linkNoConcl', 'linkStepRange', 'linkBadStep', 'linkNumber', 'linkNoId', 'linkCount'], applies: needs('links', 'noLinks') },
81
81
  { id: 'C-audio', kind: 'checker', phase: '読み込み', codes: ['audioStale', 'refVoice'], applies: needs('audio', 'noAudio') },
82
+ { id: 'C-keys', kind: 'checker', phase: '読み込み', codes: ['keyLike'] },
82
83
  { id: 'C-attach', kind: 'checker', phase: '読み込み', codes: ATTACH, applies: needs('attachments', 'noAttachments') },
83
84
  { id: 'C-book', kind: 'checker', phase: 'M 本文', codes: ARTICLE, applies: needs('book', 'noBook') },
84
85
  { id: 'C-a11y', kind: 'checker', phase: 'H 読み上げ', codes: ['imgAlt', 'svgName', 'compName'] },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "egatari",
3
- "version": "0.6.22-rc.2",
3
+ "version": "0.6.23-rc.1",
4
4
  "license": "MIT",
5
5
  "homepage": "https://studio.egatari.org/",
6
6
  "repository": {
package/tts/core.py CHANGED
@@ -12,7 +12,9 @@ marp2mp4(main_irodori.py)の関数を移したもの。ffmpeg のフィル
12
12
 
13
13
  from __future__ import annotations
14
14
 
15
+ from dataclasses import dataclass, field
15
16
  import hashlib
17
+ from ipaddress import ip_address
16
18
  import json
17
19
  import os
18
20
  import re
@@ -54,8 +56,22 @@ def ref_dir(cli: str | None = None) -> Path:
54
56
  return Path(d).expanduser() if d else DEFAULT_REF_DIR
55
57
 
56
58
 
57
- def server_is_local() -> bool:
58
- return urlparse(IRODORI_URL).hostname in ("localhost", "127.0.0.1", "::1")
59
+ def plain_http_warning(url: str, api_key: str) -> str | None:
60
+ """API キーを localhost 以外へ http(TLS なし)で送るときの警告。送らないなら None。"""
61
+ if not api_key or urlparse(url).scheme != "http" or server_is_local(url):
62
+ return None
63
+ return (f"⚠ API キーを暗号化しない通信(http)で {urlparse(url).hostname} へ送ります。"
64
+ "https の URL にできるか確かめてください")
65
+
66
+
67
+ def server_is_local(url: str = IRODORI_URL) -> bool:
68
+ host = urlparse(url).hostname
69
+ if host in ("localhost", "localhost."):
70
+ return True
71
+ try:
72
+ return ip_address(host).is_loopback
73
+ except ValueError:
74
+ return False
59
75
 
60
76
 
61
77
  def _default_refs(refs: Path) -> bool:
@@ -71,22 +87,24 @@ def voice_available(name: str, refs: Path) -> bool:
71
87
  return (refs / f"{name}.wav").exists() or (_default_refs(refs) and R.is_default(f"{name}.wav"))
72
88
 
73
89
 
74
- def resolve_voice(voice: str, refs: Path, base: Path | None = None) -> Path:
90
+ def resolve_voice(voice: str, refs: Path, base: Path | None = None, *, local: bool | None = None) -> Path:
75
91
  """声の指定 → 参照音声のパス。名前(bob)なら <refs>/<名前>.wav、
76
92
  パス(/ を含むか .wav で終わる)ならそのファイル(相対なら base から)。
77
93
  既定のフォルダ(tts/voices)にない既定の声は、取り寄せたキャッシュのパス(refvoices.default_voice。取り寄せられなければ VoiceFetchError)。
78
94
 
79
95
  サーバーが別のマシンのときはパスはサーバー側のものなので、有無を確かめない。
80
96
  """
97
+ if local is None:
98
+ local = server_is_local()
81
99
  if "/" in voice or voice.endswith(".wav"):
82
100
  p = Path(voice).expanduser()
83
101
  if not p.is_absolute() and base is not None:
84
102
  p = base / p
85
103
  else:
86
104
  p = refs / f"{voice}.wav"
87
- if server_is_local() and not p.exists() and _default_refs(refs) and R.is_default(p.name):
105
+ if local and not p.exists() and _default_refs(refs) and R.is_default(p.name):
88
106
  return R.default_voice(p.name)
89
- if server_is_local() and not p.exists():
107
+ if local and not p.exists():
90
108
  raise FileNotFoundError(f"参照音声が見つかりません: {p}"
91
109
  "(IRODORI_REF_DIR か --ref-dir、または voice.json にパスで書く)")
92
110
  return p
@@ -95,13 +113,15 @@ def resolve_voice(voice: str, refs: Path, base: Path | None = None) -> Path:
95
113
  REF_RATE = 48000 # TTS のモデル(Irodori・VoxCPM2)が前提にする参照音声のサンプリング周波数
96
114
 
97
115
 
98
- def ref_at_model_rate(path: Path, cache_dir: Path) -> Path:
116
+ def ref_at_model_rate(path: Path, cache_dir: Path, *, local: bool | None = None) -> Path:
99
117
  """参照音声が 48 kHz・モノラルでなければ、変換したものを cache_dir に作ってそのパスを返す。
100
118
 
101
119
  16 kHz のまま渡すと、mlx のサーバーでは読む速さが変わった(ブラウザ版より 2〜4 割速い)。
102
120
  サーバーが別のマシンのときはパスが向こうのものなので、何もしない。
103
121
  """
104
- if not server_is_local() or not path.exists():
122
+ if local is None:
123
+ local = server_is_local()
124
+ if not local or not path.exists():
105
125
  return path
106
126
  info = subprocess.run(
107
127
  ["ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=sample_rate,channels",
@@ -120,36 +140,70 @@ def ref_at_model_rate(path: Path, cache_dir: Path) -> Path:
120
140
  return out
121
141
 
122
142
 
123
- def ping(timeout: float = 5):
124
- requests.get(f"{IRODORI_URL}/v1/models", timeout=timeout).raise_for_status()
143
+ @dataclass(frozen=True)
144
+ class SpeechServer:
145
+ url: str = IRODORI_URL
146
+ model: str = TTS_MODEL
147
+ voice_by: str = "ref"
148
+ api_key: str = field(default="", repr=False)
149
+ configured: bool = False
150
+
151
+ def authorize(self, request):
152
+ if self.api_key:
153
+ request.headers["Authorization"] = f"Bearer {self.api_key}"
154
+ return request
125
155
 
156
+ def request(self, method: str, endpoint: str, timeout: float, **kwargs):
157
+ # HTTP の例外に入る URL・ヘッダー・応答の本文や理由は表示しない。
158
+ try:
159
+ resp = requests.request(
160
+ method, f"{self.url}{endpoint}", timeout=timeout,
161
+ auth=self.authorize if self.configured else None,
162
+ allow_redirects=not self.configured, **kwargs)
163
+ except requests.RequestException as e:
164
+ raise RuntimeError(f"{method} {endpoint}: {type(e).__name__}") from None
165
+ if not 200 <= resp.status_code < 300:
166
+ raise RuntimeError(f"{method} {endpoint}: HTTP {resp.status_code}")
167
+ return resp
126
168
 
127
- def synthesize_line(text: str, ref: Path, out_path: Path, retries: int = 2, model: str = TTS_MODEL):
169
+ def ping(self, timeout: float = 5):
170
+ self.request("GET", "/v1/models", timeout)
171
+
172
+
173
+ def synthesize_line(text: str, voice: Path | str, out_path: Path, server: SpeechServer):
128
174
  """1 行を合成して WAV に保存する。
129
175
 
130
176
  response_format="wav" の明示は必須(省略すると mp3 が返り、拡張子と中身が食い違う)。
131
177
  """
132
178
  payload = {
133
- "model": model,
179
+ "model": server.model,
134
180
  "input": text,
135
- "ref_audio": str(ref),
181
+ "ref_audio" if server.voice_by == "ref" else "voice": str(voice),
136
182
  "response_format": "wav",
137
183
  }
138
- last_err = None
184
+ retries = 0 if server.configured else 2
139
185
  for attempt in range(retries + 1):
140
186
  try:
141
- resp = requests.post(f"{IRODORI_URL}/v1/audio/speech", json=payload, timeout=600)
142
- resp.raise_for_status()
143
- out_path.write_bytes(resp.content)
144
- return
145
- except Exception as e:
146
- last_err = e
147
- if attempt < retries:
148
- time.sleep(2 * (attempt + 1))
149
- raise RuntimeError(f"TTS合成に失敗しました: {last_err}")
150
-
151
-
152
- def trim_silence(path: Path):
187
+ resp = server.request("POST", "/v1/audio/speech", 600, json=payload)
188
+ except RuntimeError:
189
+ if attempt == retries:
190
+ raise
191
+ time.sleep(2 * (attempt + 1))
192
+ else:
193
+ break
194
+ audio = resp.content
195
+ if audio.startswith(b"RIFF") and audio[8:12] == b"WAVE":
196
+ out_path.write_bytes(audio)
197
+ else:
198
+ result = subprocess.run(
199
+ ["ffmpeg", "-y", "-loglevel", "error", "-protocol_whitelist", "pipe", "-i", "pipe:0",
200
+ "-map", "0:a:0", "-map_metadata", "-1", "-c:a", "pcm_s16le", str(out_path)],
201
+ input=audio, capture_output=True)
202
+ if result.returncode != 0:
203
+ raise RuntimeError("応答の音声を WAV に変換できません")
204
+
205
+
206
+ def trim_silence(path: Path, detail: bool = True):
153
207
  """先頭・末尾の無音を削る(インプレース)。発話の途中の間は削らない。
154
208
 
155
209
  残すと「TTS 由来の無音 + 意図した無音」が二重に乗り、段階の切り替わりが間延びする。
@@ -164,13 +218,13 @@ def trim_silence(path: Path):
164
218
  capture_output=True,
165
219
  )
166
220
  if result.returncode != 0:
167
- print(f" ⚠ 無音除去に失敗(元の音声を使用): {result.stderr.decode()[-500:]}")
221
+ print(" ⚠ 無音除去に失敗(元の音声を使用)" + (f": {result.stderr.decode(errors='replace')[-500:]}" if detail else ""))
168
222
  tmp_out.unlink(missing_ok=True)
169
223
  return
170
224
  tmp_out.replace(path)
171
225
 
172
226
 
173
- def normalize_level(path: Path):
227
+ def normalize_level(path: Path, detail: bool = True):
174
228
  """1 行の音声を TARGET_LUFS に揃える(インプレース)。
175
229
 
176
230
  1 パス目で測り、2 パス目は linear=true の一律のゲインで当てる(行の中の抑揚は保つ)。
@@ -199,13 +253,13 @@ def normalize_level(path: Path):
199
253
  ["ffmpeg", "-y", "-i", str(path), "-af", af, "-ar", "44100", str(tmp_out)],
200
254
  capture_output=True)
201
255
  if result.returncode != 0:
202
- print(f" ⚠ 音量調整に失敗(元の音声を使用): {result.stderr.decode()[-300:]}")
256
+ print(" ⚠ 音量調整に失敗(元の音声を使用)" + (f": {result.stderr.decode(errors='replace')[-300:]}" if detail else ""))
203
257
  tmp_out.unlink(missing_ok=True)
204
258
  return
205
259
  tmp_out.replace(path)
206
260
 
207
261
 
208
- def concat_audio_with_pauses(seg_paths: list[Path], out_path: Path, pause_ms: int = PAUSE_MS):
262
+ def concat_audio_with_pauses(seg_paths: list[Path], out_path: Path, pause_ms: int = PAUSE_MS, detail: bool = True):
209
263
  """複数の WAV を、行間に無音を挟んで 1 本に結合する。
210
264
 
211
265
  サンプルレートが違っても繋がるよう、concat demuxer ではなく concat フィルタを使う。
@@ -247,7 +301,8 @@ def concat_audio_with_pauses(seg_paths: list[Path], out_path: Path, pause_ms: in
247
301
  ]
248
302
  result = subprocess.run(cmd, capture_output=True)
249
303
  if result.returncode != 0:
250
- print(f" ⚠ 音声結合エラー:\n{result.stderr.decode()[-2000:]}")
304
+ if detail: # 追加したエンジン(configured)では出さない:応答の中身が混ざりうるため
305
+ print(f" ⚠ 音声結合エラー:\n{result.stderr.decode(errors='replace')[-2000:]}")
251
306
  result.check_returncode()
252
307
 
253
308
 
@@ -0,0 +1,106 @@
1
+ """作成者の端末で使う CLI の TTS 設定。作業フォルダには置かない。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ from pathlib import Path
9
+
10
+
11
+ def outside_deck(path: Path, deckdir: Path, label: str) -> Path:
12
+ try:
13
+ path = path.expanduser().resolve()
14
+ except (OSError, RuntimeError, ValueError):
15
+ raise SystemExit(f"{label} の場所を確認できません") from None
16
+ if path.is_relative_to(deckdir):
17
+ raise SystemExit(f"{label} は作業フォルダの外に置いてください")
18
+ return path
19
+
20
+
21
+ def engine_definitions(deckdir: Path) -> tuple[Path, dict]:
22
+ override = os.environ.get("EGATARI_TTS_CONFIG")
23
+ if os.name == "nt":
24
+ base = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming")
25
+ else:
26
+ base = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
27
+ path = outside_deck(Path(override) if override else base / "egatari" / "tts.json", deckdir, "tts.json")
28
+ try:
29
+ data = json.loads(path.read_text(encoding="utf-8-sig"))
30
+ except FileNotFoundError:
31
+ if not override:
32
+ return path, {}
33
+ raise SystemExit("EGATARI_TTS_CONFIG のファイルがありません") from None
34
+ except (OSError, ValueError):
35
+ raise SystemExit("tts.json を JSON として読めません") from None
36
+ engines = data.get("engines") if isinstance(data, dict) else None
37
+ if not isinstance(engines, dict) or any(not name.strip() or not isinstance(cfg, dict) for name, cfg in engines.items()):
38
+ raise SystemExit("tts.json の engines に名前と設定を書いてください")
39
+ return path, engines
40
+
41
+
42
+ def dotenv_value(text: str, name: str | None) -> str:
43
+ """変数の展開はせず、指定した代入か、1 行だけの鍵を読む。"""
44
+ lines = [line.strip() for line in text.splitlines() if line.strip() and not line.lstrip().startswith("#")]
45
+ if name:
46
+ assignment = re.compile(rf"(?:export\s+)?{re.escape(name)}\s*=\s*(.*)")
47
+ for line in reversed(lines):
48
+ match = assignment.fullmatch(line)
49
+ if not match:
50
+ continue
51
+ value = match[1]
52
+ if value.startswith(("'", '"')):
53
+ quoted = re.fullmatch(r"""(['"])(.*?)\1\s*(?:#.*)?""", value)
54
+ return quoted[2] if quoted else ""
55
+ return "" if value.startswith("#") else re.split(r"\s+#", value, maxsplit=1)[0].rstrip()
56
+ if len(lines) == 1:
57
+ bare = re.split(r"\s+#", lines[0], maxsplit=1)[0].rstrip()
58
+ if name and re.match(r"[A-Za-z_]\w*=", bare):
59
+ return ""
60
+ if re.fullmatch(r"[^=\s]+={0,2}", bare):
61
+ return bare
62
+ return ""
63
+
64
+
65
+ def api_key(cfg: dict, config_path: Path, deckdir: Path, *, dry_run: bool) -> str:
66
+ name, file = cfg.get("apiKeyEnv"), cfg.get("apiKeyFile")
67
+ path = None
68
+ if file:
69
+ path = outside_deck(config_path.parent / file, deckdir, "apiKeyFile")
70
+ if dry_run:
71
+ return ""
72
+ key = ""
73
+ if path is not None:
74
+ try:
75
+ key = dotenv_value(path.read_text(encoding="utf-8-sig"), name)
76
+ except (OSError, ValueError):
77
+ raise SystemExit("apiKeyFile を読めません") from None
78
+ elif name:
79
+ key = os.environ.get(name, "").strip()
80
+ if (file or name) and not re.fullmatch(r"[!-~][ -~]*", key):
81
+ raise SystemExit("tts.json で指定した API キーを読み取れません")
82
+ return key
83
+
84
+
85
+ def read_voice_config(deckdir: Path) -> dict:
86
+ path = deckdir / "voice.json"
87
+ try:
88
+ if not path.resolve().is_relative_to(deckdir):
89
+ raise SystemExit("voice.json は作業フォルダの中に置いてください")
90
+ cfg = json.loads(path.read_text(encoding="utf-8-sig"))
91
+ except FileNotFoundError:
92
+ return {}
93
+ except (OSError, RuntimeError, ValueError):
94
+ raise SystemExit("voice.json を JSON として読めません") from None
95
+ if not isinstance(cfg, dict):
96
+ raise SystemExit("voice.json に声の設定を書いてください")
97
+ pending = [cfg]
98
+ while pending:
99
+ item = pending.pop()
100
+ if isinstance(item, dict):
101
+ if any(k.lower() in {"apikey", "key", "token", "authorization"} for k in item):
102
+ raise SystemExit("voice.json の API キーの設定は作業フォルダの外の tts.json に移してください")
103
+ pending.extend(item.values())
104
+ elif isinstance(item, list):
105
+ pending.extend(item)
106
+ return cfg
package/tts/synth.py CHANGED
@@ -15,7 +15,7 @@
15
15
  名前は <参照音声のフォルダ>/<名前>.wav(--ref-dir > IRODORI_REF_DIR > tts/voices)、パスも書ける。
16
16
  既定の声(tts/voices.json)が tts/voices/ になければ(npm の包み)、初めて使うときに取り寄せる(refvoices.py)
17
17
  - 読み辞書:--yomi > MOTION_YOMI > tts/yomi.yaml
18
- - サーバー:IRODORI_URL(既定 http://localhost:8882)
18
+ - サーバー:tts.json(作業フォルダの外)。既定のエンジンは IRODORI_URL(既定 http://localhost:8882)
19
19
  - 録音・取り込みの音声(manifest の kind が recorded か imported。編集アプリの音声の板が書く)は作り直さず、そのまま残す
20
20
  (--replace-recorded で TTS に替える)。manifest の各段階には kind と inputHash(その段階の口述原稿の hash。format spec §5.4)も書く
21
21
  """
@@ -33,16 +33,17 @@ import sys
33
33
  import tempfile
34
34
  import wave
35
35
  from pathlib import Path
36
+ from urllib.parse import urlparse
36
37
 
37
38
  TTS_DIR = Path(__file__).resolve().parent
38
39
  sys.path.insert(0, str(TTS_DIR))
39
40
 
40
41
  import core as M # noqa: E402 (synthesize_line, trim_silence, normalize_level, …)
42
+ from engine_config import api_key, engine_definitions, read_voice_config # noqa: E402
41
43
  import yomi as Y # noqa: E402
42
44
 
43
45
  REPO = TTS_DIR.parent
44
46
  CHARS_PER_SEC = 7.5
45
- MODEL = M.TTS_MODEL # main() でエンジンに合わせて決める
46
47
  SR = 44100
47
48
  ROLE_LABEL = {"expert": "Expert", "novice": "Novice"}
48
49
 
@@ -52,28 +53,30 @@ def parse_args():
52
53
  p.add_argument("deckdir")
53
54
  p.add_argument("--voices", default=None, help="expert=bob,novice=alice")
54
55
  p.add_argument("--ref-dir", default=None, help="参照音声(<名前>.wav)のフォルダ(既定 IRODORI_REF_DIR か tts/voices)")
55
- p.add_argument("--engine", default=None, choices=sorted(M.ENGINES), help="TTS のエンジン(既定:英語のデッキは voxcpm2、それ以外は irodori)")
56
+ p.add_argument("--engine", help="TTS のエンジン(irodori、voxcpm2、または tts.json の名前)")
57
+ p.add_argument("--tts-url", help="今回だけ使う TTS サーバーの URL")
58
+ p.add_argument("--tts-model", help="今回だけ使う TTS モデルの名前")
56
59
  p.add_argument("--yomi", default=None, help="読み辞書(既定 MOTION_YOMI か tts/yomi.yaml)")
57
60
  p.add_argument("--only", default=None, help="この鍵(slideKey:stepKey)の段階だけ作る。カンマ区切り")
58
61
  p.add_argument("--dry-run", action="store_true", help="TTS を呼ばず、推定の長さの無音を作る")
59
62
  p.add_argument("--force", action="store_true", help="キャッシュを無視して作り直す")
60
63
  p.add_argument("--replace-recorded", action="store_true", help="録音・取り込みの音声(kind が recorded か imported)も TTS で作り直す")
61
- return p.parse_args()
64
+ return p, p.parse_args()
62
65
 
63
66
 
64
67
  DEFAULT_VOICES = {"expert": "bob", "novice": "alice"}
65
68
 
66
69
 
67
- def resolve_voices(deckdir: Path, cli: str | None) -> tuple[dict[str, str], list[str], dict[str, str]]:
68
- """{role: 声の名前}, 既定を使った role, どこから来たか。"""
70
+ def resolve_voices(config: dict, cli: str | None) -> tuple[dict[str, str], dict[str, str]]:
71
+ """{role: 声の名前}, どこから来たか。"""
69
72
  src: dict[str, str] = {}
70
73
  voices: dict[str, str] = {}
71
- vj = deckdir / "voice.json"
72
- if vj.exists():
73
- for k, v in json.loads(vj.read_text(encoding="utf-8")).items():
74
- if k.lower() in ROLE_LABEL and v:
75
- voices[k.lower()] = v
76
- src[k.lower()] = "voice.json"
74
+ for k, v in config.items():
75
+ if k.lower() in ROLE_LABEL and v:
76
+ if not isinstance(v, str):
77
+ sys.exit("voice.json の expert と novice には声の名前を書いてください")
78
+ voices[k.lower()] = v
79
+ src[k.lower()] = "voice.json"
77
80
  if cli:
78
81
  for item in cli.split(","):
79
82
  if not item.strip():
@@ -81,24 +84,70 @@ def resolve_voices(deckdir: Path, cli: str | None) -> tuple[dict[str, str], list
81
84
  k, _, v = item.partition("=")
82
85
  k = k.strip().lower()
83
86
  if k not in ROLE_LABEL or not v.strip():
84
- sys.exit(f"--voices の書式が不正です: {item!r}(例: expert=bob,novice=alice)")
87
+ sys.exit("--voices の書式が不正です(例: expert=bob,novice=alice)")
85
88
  if k in voices and voices[k] != v.strip():
86
- print(f" --voices が voice.json を上書き: {k} {voices[k]} → {v.strip()}")
89
+ print(f" --voices が voice.json を上書き: {k}")
87
90
  voices[k] = v.strip()
88
91
  src[k] = "--voices"
89
92
  # 既定の声:1 人モードは bob、掛け合いは bob(Expert)× alice(Novice)。
90
93
  # 既定を使っても警告はしない(既定は決まった声で、尺が黙ってずれることはない)
91
- defaulted = []
92
94
  for role in ROLE_LABEL:
93
95
  if role not in voices:
94
96
  voices[role] = DEFAULT_VOICES[role]
95
97
  src[role] = "既定"
96
- return voices, defaulted, src
98
+ return voices, src
97
99
 
98
100
 
99
101
  def voice_file(v: str) -> str:
100
102
  """digest と表示に使う参照音声のファイル名(名前なら <名前>.wav、パスならファイル名)。"""
101
- return Path(v).name if ("/" in v or v.endswith(".wav")) else v + ".wav"
103
+ return re.split(r"[/\\]", v)[-1] if ("/" in v or "\\" in v or v.endswith(".wav")) else v + ".wav"
104
+
105
+
106
+ def select_server(args, engine: str, cfg: dict | None, config_path: Path, deckdir: Path) -> M.SpeechServer:
107
+ if cfg is None:
108
+ cfg = {"url": M.IRODORI_URL, "model": M.ENGINES[engine], "voiceBy": "ref"}
109
+ configured = False
110
+ else:
111
+ configured = True
112
+ for field in ("url", "model", "voiceBy", "apiKeyEnv", "apiKeyFile"):
113
+ if field in ("url", "model", "voiceBy") or field in cfg:
114
+ if not isinstance(cfg.get(field), str) or not cfg[field].strip():
115
+ sys.exit(f"tts.json の {field} には文字列を書いてください")
116
+ if cfg["voiceBy"] not in ("ref", "name"):
117
+ sys.exit('tts.json の voiceBy には "ref" か "name" を書いてください')
118
+ if "yomi" in cfg and not isinstance(cfg["yomi"], bool):
119
+ sys.exit("tts.json の yomi には true か false を書いてください")
120
+ url = (args.tts_url if args.tts_url is not None else cfg["url"]).rstrip("/")
121
+ model = args.tts_model if args.tts_model is not None else cfg["model"]
122
+ if not model.strip():
123
+ sys.exit("--tts-model にモデルの名前を書いてください")
124
+ try:
125
+ parsed = urlparse(url)
126
+ valid = (parsed.scheme in ("http", "https") and parsed.hostname and parsed.username is None
127
+ and not parsed.query and not parsed.fragment and not parsed.params
128
+ and not any(c.isspace() or ord(c) < 32 for c in url))
129
+ parsed.port # ポート番号の書式も確かめる
130
+ except ValueError:
131
+ valid = False
132
+ if not valid:
133
+ sys.exit("TTS サーバーの URL には HTTP(S) のベース URL を指定してください")
134
+ if configured or args.tts_url is not None:
135
+ url = url.removesuffix("/v1") if parsed.path.endswith("/v1") else url
136
+ return M.SpeechServer(url, model, cfg["voiceBy"], api_key(cfg, config_path, deckdir, dry_run=args.dry_run), configured)
137
+
138
+
139
+ def recipe_of(voice: dict) -> dict:
140
+ # Egatari の recipe には公開の声の名前だけを書く(kit/core/portable.mjs の voiceName と同じ書式)。
141
+ names = {}
142
+ for role in ROLE_LABEL:
143
+ name = voice[role]
144
+ if voice.get("voiceBy", "ref") == "ref" and name.lower().endswith(".wav"):
145
+ name = name[:-4]
146
+ if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}", name):
147
+ names[role] = name
148
+ return {"engine": voice["engine"], "model": voice["model"], "voice": names,
149
+ "seed": None, "dictionary": voice["yomi"],
150
+ "processing": f"trim={voice['trim']};norm={voice['norm']};pause_ms={voice['pause_ms']}"}
102
151
 
103
152
 
104
153
  def file_hash(*paths: Path) -> str:
@@ -183,7 +232,8 @@ def plan(seg: dict, terms, watch_kanji, watch, stats) -> list[list[str]]:
183
232
  return turns
184
233
 
185
234
 
186
- def synth_segment(seg: dict, turns: list[list[str]], out: Path, dry: bool, refs: dict[str, Path]) -> tuple[float, list[float]]:
235
+ def synth_segment(seg: dict, turns: list[list[str]], out: Path, dry: bool,
236
+ voices: dict[str, Path | str], server: M.SpeechServer) -> tuple[float, list[float]]:
187
237
  """1 段階分を合成して out に書く。(長さ, cues) を返す。"""
188
238
  pause_s = M.PAUSE_MS / 1000.0
189
239
  if dry:
@@ -206,7 +256,7 @@ def synth_segment(seg: dict, turns: list[list[str]], out: Path, dry: bool, refs:
206
256
  cues: list[float] = []
207
257
  t = 0.0
208
258
  for ti, parts in enumerate(turns):
209
- ref = refs.get(seg["turns"][ti]["role"])
259
+ voice = voices[seg["turns"][ti]["role"]]
210
260
  if ti > 0 and pause_s > 0:
211
261
  pieces.append(sil)
212
262
  t += pause_s
@@ -216,23 +266,23 @@ def synth_segment(seg: dict, turns: list[list[str]], out: Path, dry: bool, refs:
216
266
  if not p.strip():
217
267
  continue
218
268
  f = tmp / f"t{ti:02d}_p{pi:02d}.wav"
219
- M.synthesize_line(p, ref, f, model=MODEL)
269
+ M.synthesize_line(p, voice, f, server)
220
270
  if M.TRIM_SILENCE:
221
- M.trim_silence(f)
222
- M.normalize_level(f)
271
+ M.trim_silence(f, detail=not server.configured)
272
+ M.normalize_level(f, detail=not server.configured)
223
273
  pieces.append(f)
224
274
  t += M.media_duration(f)
225
275
  if not pieces:
226
276
  write_silence(out, 0.0)
227
277
  return 0.0, cues
228
278
  # 行間の無音は pieces に入れてあるので、ここでは間を足さない
229
- M.concat_audio_with_pauses(pieces, out, pause_ms=0)
279
+ M.concat_audio_with_pauses(pieces, out, pause_ms=0, detail=not server.configured)
230
280
  dur = M.media_duration(out)
231
281
  return round(dur, 3), cues
232
282
 
233
283
 
234
284
  def main():
235
- args = parse_args()
285
+ parser, args = parse_args()
236
286
  deckdir = Path(args.deckdir).resolve()
237
287
  deck_html = None
238
288
  if deckdir.is_file(): # <deck>/foo.html を渡してもよい
@@ -242,65 +292,88 @@ def main():
242
292
  else:
243
293
  cands = sorted(p for p in deckdir.glob("*.html"))
244
294
  deck_html = cands[0] if len(cands) == 1 else None
295
+ vjson = read_voice_config(deckdir)
296
+ config_path, engines = engine_definitions(deckdir)
297
+ choices = sorted(M.ENGINES.keys() | engines.keys())
298
+ if args.engine is not None and args.engine not in choices:
299
+ parser.error("--engine には次の名前を使えます: " + ", ".join(choices))
245
300
  narr = deckdir / "narration.md"
246
301
  if not narr.exists():
247
302
  sys.exit(f"narration.md がありません: {narr}")
248
- audio_dir = no_link(deckdir, deckdir / "audio")
249
- audio_dir.mkdir(exist_ok=True)
250
-
251
- voices, _, src = resolve_voices(deckdir, args.voices)
252
- # 言語とエンジン:--engine > voice.json の "engine" > デッキの <html lang>(en なら voxcpm2)
253
- global MODEL
254
- vjson = json.loads((deckdir / "voice.json").read_text(encoding="utf-8")) if (deckdir / "voice.json").exists() else {}
255
- m_lang = re.search(r'<html[^>]*\blang="([^"]+)"', deck_html.read_text(encoding="utf-8")) if deck_html else None
256
- lang = (vjson.get("lang") or (m_lang.group(1) if m_lang else "ja")).lower()
303
+ voices, src = resolve_voices(vjson, args.voices)
304
+ # --engine > voice.json の "engine" > 台本の言語(既定はデッキの <html lang>)。
305
+ m_lang = re.search(r"""<html\b[^>]*\slang=(["'])([^"']+)\1""",
306
+ deck_html.read_text(encoding="utf-8"), re.IGNORECASE) if deck_html else None
307
+ deck_lang = (m_lang.group(2) if m_lang else "ja").lower()
308
+ lang = vjson.get("lang") or deck_lang
309
+ if not isinstance(lang, str):
310
+ sys.exit("voice.json の lang には言語を書いてください")
311
+ lang = lang.lower()
257
312
  engine = args.engine or vjson.get("engine") or ("irodori" if lang.startswith("ja") else "voxcpm2")
258
- MODEL = M.ENGINES[engine]
259
- use_yomi = lang.startswith("ja")
260
- ref_dir = M.ref_dir(args.ref_dir)
313
+ if not isinstance(engine, str) or engine not in choices:
314
+ sys.exit("voice.json の engine には次の名前を使えます: " + ", ".join(choices))
315
+ cfg = engines.get(engine)
316
+ server = select_server(args, engine, cfg, config_path, deckdir)
317
+ use_yomi = lang.startswith("ja") and (cfg or {}).get("yomi", engine in M.ENGINES)
318
+ ref_dir = M.ref_dir(args.ref_dir) if server.voice_by == "ref" else None
261
319
  yomi_src = args.yomi or os.environ.get("MOTION_YOMI")
262
320
  yomi_path = Path(yomi_src).expanduser().resolve() if yomi_src else TTS_DIR / "yomi.yaml"
263
- if yomi_src and not yomi_path.exists():
321
+ if use_yomi and yomi_src and not yomi_path.exists():
264
322
  sys.exit(f"読み辞書がありません: {yomi_path}")
265
323
  # 日本語以外のデッキでは、名前で指定した声に <名前>_<言語>.wav(例:alice_en.wav)があればそちらを使う
266
324
  # (日本語の参照音声で英語を読ませると訛りが出るため。ファイルの有無はこの PC の参照音声のフォルダで見る)
267
- if not lang.startswith("ja"):
325
+ if ref_dir is not None and not lang.startswith("ja"):
268
326
  suffix = "_" + lang.split("-")[0]
269
327
  for r, v in list(voices.items()):
270
- if not ("/" in v or v.endswith(".wav")) and M.voice_available(v + suffix, ref_dir):
328
+ if not ("/" in v or "\\" in v or v.endswith(".wav")) and M.voice_available(v + suffix, ref_dir):
271
329
  voices[r] = v + suffix
330
+ if ref_dir is None and any("/" in v or "\\" in v for v in voices.values()):
331
+ sys.exit('voiceBy が "name" のエンジンには声の名前を指定してください')
332
+ # expert・novice の順に並べる(digest は JSON の並びで変わる。今までの音声の digest を保つ)
333
+ display_voices = {r: (voice_file(voices[r]) if ref_dir is not None else voices[r]) for r in ROLE_LABEL}
272
334
  voice = {
273
335
  "engine": "dry-run" if args.dry_run else engine,
274
- "model": MODEL,
275
- "expert": voice_file(voices["expert"]),
276
- "novice": voice_file(voices["novice"]),
336
+ "model": server.model,
337
+ # voiceBy は "name" のときだけ入れる("ref" で入れると、今までの音声の digest がすべて替わり作り直しになる)
338
+ **({"voiceBy": "name"} if server.voice_by == "name" else {}),
339
+ **display_voices,
277
340
  "norm": f"{M.TARGET_LUFS}/{M.TARGET_TP_DB}/{M.TARGET_LRA}",
278
341
  "pause_ms": M.PAUSE_MS,
279
342
  "trim": f"{M.TRIM_SILENCE}/{M.TRIM_THRESHOLD}/{M.TRIM_KEEP_S}",
280
343
  # 実際に使う読み辞書と適用規則(yomi.py)が変われば作り直す
281
344
  "yomi": file_hash(yomi_path, TTS_DIR / "yomi.py") if use_yomi else None,
282
345
  }
346
+ if args.dry_run:
347
+ voice["selectedEngine"] = engine
348
+ recipe = recipe_of(voice)
349
+ audio_dir = no_link(deckdir, deckdir / "audio")
350
+ audio_dir.mkdir(exist_ok=True)
283
351
  segs = narration_json(narr, voice)
284
352
  used_roles = sorted({t["role"] for s in segs for t in s["turns"]})
285
353
  print(f"口述原稿: {len(segs)} 段階 / {sum(len(s['turns']) for s in segs)} ターン"
286
354
  f"({'dry-run' if args.dry_run else engine}・言語 {lang})")
287
355
  for r in used_roles:
288
- print(f" {ROLE_LABEL[r]} → {voice_file(voices[r])}({src[r]})")
289
- print(f" 読み辞書の場所: {yomi_path}" if use_yomi else " 読み辞書:使わない(日本語以外)")
356
+ print(f" {ROLE_LABEL[r]} → {display_voices[r]}({src[r]})")
357
+ print(f" 読み辞書の場所: {yomi_path}" if use_yomi else " 読み辞書:使わない")
290
358
 
291
- refs: dict[str, Path] = {}
359
+ speech_voices: dict[str, Path | str] = dict(voices)
360
+ local = M.server_is_local(server.url)
292
361
  if not args.dry_run:
293
362
  try:
294
- M.ping()
295
- except Exception as e:
296
- sys.exit(f"⚠ TTS のサーバーに接続できません: {M.IRODORI_URL} ({e})\n"
297
- " サーバーを起動するか IRODORI_URL を確かめてください(オフラインで流れを試すなら --dry-run)")
298
- for r in used_roles:
299
- try:
300
- refs[r] = M.resolve_voice(voices[r], ref_dir, deckdir) # 参照音声が無ければここで止める
301
- refs[r] = M.ref_at_model_rate(refs[r], no_link(deckdir, deckdir / ".cache" / "voices")) # 48 kHz・モノラルにそろえる
302
- except (FileNotFoundError, PermissionError, M.VoiceFetchError) as e:
303
- sys.exit(f"⚠ {e}")
363
+ server.ping()
364
+ except RuntimeError as e:
365
+ if server.configured:
366
+ print(f"⚠ TTS の起動を確認できません({e})。音声の合成を試します", file=sys.stderr)
367
+ else:
368
+ sys.exit(f"⚠ TTS のサーバーに接続できません({e})\n"
369
+ " サーバーを起動するか IRODORI_URL または --tts-url を確かめてください(オフラインで流れを試すなら --dry-run)")
370
+ if ref_dir is not None:
371
+ for r in used_roles:
372
+ try:
373
+ ref = M.resolve_voice(voices[r], ref_dir, deckdir, local=local)
374
+ speech_voices[r] = M.ref_at_model_rate(ref, no_link(deckdir, deckdir / ".cache" / "voices"), local=local)
375
+ except (FileNotFoundError, PermissionError, M.VoiceFetchError) as e:
376
+ sys.exit(f"⚠ {e}")
304
377
 
305
378
  only = set(k.strip() for k in args.only.split(",")) if args.only else None
306
379
  if only:
@@ -328,6 +401,9 @@ def main():
328
401
 
329
402
  made = cached = kept = 0
330
403
  failed: list[tuple[str, str]] = []
404
+ announce_host = not local and not args.dry_run
405
+ if not args.dry_run and (warning := M.plain_http_warning(server.url, server.api_key)):
406
+ print(warning, file=sys.stderr)
331
407
  for n, seg in enumerate(segs):
332
408
  key = seg["key"]
333
409
  if only and key not in only:
@@ -346,16 +422,21 @@ def main():
346
422
  cached += 1
347
423
  print(f" [{n+1}/{len(segs)}] {key}: キャッシュ使用 ({fname}, {info['dur']:.2f}s)")
348
424
  else:
425
+ if announce_host and any(part.strip() for parts in turns for part in parts):
426
+ print(f"原稿の文を {urlparse(server.url).hostname} へ送ります", flush=True)
427
+ announce_host = False
349
428
  print(f" [{n+1}/{len(segs)}] {key}: {len(turns)} ターン合成中…", end="")
350
429
  tmp_out = no_link(deckdir, out.with_suffix(".tmp.wav"))
351
430
  try:
352
- dur, cues = synth_segment(seg, turns, tmp_out, args.dry_run, refs)
431
+ dur, cues = synth_segment(seg, turns, tmp_out, args.dry_run, speech_voices, server)
353
432
  except Exception as e:
354
433
  tmp_out.unlink(missing_ok=True)
355
434
  print(f"\n ✗ 合成に失敗: {e}")
356
435
  failed.append((key, str(e)))
357
436
  # 前の版の音声(違う原稿・声のもの)を使い続けないよう、manifest から外す
358
437
  manifest["segments"].pop(key, None)
438
+ if server.configured:
439
+ break
359
440
  continue
360
441
  tmp_out.replace(out)
361
442
  info = {"dur": dur, "cues": cues, "voice": voice, "tts": turns}
@@ -363,7 +444,7 @@ def main():
363
444
  made += 1
364
445
  print(f" {dur:.2f}s" + (f", cues {cues}" if cues else ""))
365
446
  manifest["segments"][key] = {"file": fname, "dur": info["dur"], "cues": info["cues"], "digest": seg["digest"],
366
- "engine": info.get("voice", {}).get("engine", voice["engine"]),
447
+ "engine": voice["engine"], "recipe": recipe,
367
448
  "kind": "tts", "inputHash": seg.get("inputHash")}
368
449
 
369
450
  # 原稿の順に並べ直して書く
@@ -385,8 +466,9 @@ def main():
385
466
  print(f"✗ 失敗 {len(failed)} 段階(新規 {made} / キャッシュ {cached} / 録音を残した {kept})→ {man_path}", file=sys.stderr)
386
467
  for k, e in failed:
387
468
  print(f" {k}: {e}", file=sys.stderr)
388
- print(" 失敗した段階は manifest から外した(音声なしになる)。サーバーを確かめて、"
389
- f"--only {','.join(k for k, _ in failed)} でやり直すこと", file=sys.stderr)
469
+ retry = "同じコマンド" if server.configured else f"--only {','.join(k for k, _ in failed)}"
470
+ print(f" 失敗した段階は manifest から外した(音声なしになる)。サーバーを確かめて、{retry} でやり直すこと",
471
+ file=sys.stderr)
390
472
  sys.exit(1)
391
473
  print(f"完了: 新規 {made} / キャッシュ {cached}" + (f" / 録音を残した {kept}" if kept else "") + f" → {man_path}")
392
474
  # egatari コマンドから呼ばれたら(EGATARI_CLI)そのコマンドの形で
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "repository": "https://github.com/egatari/egatari-spec",
3
- "commit": "af53dcf54dd80717c2bc2630af0e677eb5de36d7",
4
- "snapshot": "wd-2026-11-28",
3
+ "commit": "737c4ffa426e4ce923a98ea0a8cbf520ac9290a3",
4
+ "snapshot": "wd-2026-11-30",
5
5
  "files": 238,
6
6
  "note": "Copied by tools/sync-spec.mjs. Do not edit; change the spec repository and sync again."
7
7
  }