sisyo 1.6.8 → 1.7.0

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.
Files changed (42) hide show
  1. package/README.md +5 -1
  2. package/bin/known-hashes.json +95 -7
  3. package/bin/sisyo.js +285 -285
  4. package/package.json +30 -30
  5. package/templates/.claude/rules/agents-and-tests.md +24 -0
  6. package/templates/.claude/skills/g6-style/SKILL.md +125 -0
  7. package/templates/.claude/skills/g6-style/references/checks.md +58 -0
  8. package/templates/.claude/skills/g6-style/references/imagery.md +103 -0
  9. package/templates/.claude/skills/g6-style/references/motion.md +121 -0
  10. package/templates/.claude/skills/g6-style/references/sections.md +263 -0
  11. package/templates/.claude/skills/g6-style/references/tokens.md +197 -0
  12. package/templates/.claude/skills/hindsight/SKILL.md +13 -10
  13. package/templates/.claude/skills/i18n-multilang/SKILL.md +153 -0
  14. package/templates/.claude/skills/i18n-multilang/assets/languages.json +47 -0
  15. package/templates/.claude/skills/i18n-multilang/assets/plural-vectors.json +46 -0
  16. package/templates/.claude/skills/i18n-multilang/assets/project/README.md +17 -0
  17. package/templates/.claude/skills/i18n-multilang/assets/project/gitattributes.txt +6 -0
  18. package/templates/.claude/skills/i18n-multilang/assets/project/gitignore.txt +4 -0
  19. package/templates/.claude/skills/i18n-multilang/assets/project/glossary.json +6 -0
  20. package/templates/.claude/skills/i18n-multilang/assets/project/i18n.config.json +22 -0
  21. package/templates/.claude/skills/i18n-multilang/assets/project/locales/__source__/common.json +10 -0
  22. package/templates/.claude/skills/i18n-multilang/assets/project/notes/common.json +5 -0
  23. package/templates/.claude/skills/i18n-multilang/assets/project/style.md +20 -0
  24. package/templates/.claude/skills/i18n-multilang/references/format.md +100 -0
  25. package/templates/.claude/skills/i18n-multilang/references/languages.md +97 -0
  26. package/templates/.claude/skills/i18n-multilang/references/layout-and-versioning.md +256 -0
  27. package/templates/.claude/skills/i18n-multilang/references/numbers.md +161 -0
  28. package/templates/.claude/skills/i18n-multilang/references/platform-unity.md +142 -0
  29. package/templates/.claude/skills/i18n-multilang/references/platform-web.md +107 -0
  30. package/templates/.claude/skills/i18n-multilang/references/translation.md +143 -0
  31. package/templates/.claude/skills/i18n-multilang/references/voice.md +271 -0
  32. package/templates/.claude/skills/i18n-multilang/scripts/i18n.py +1041 -0
  33. package/templates/.claude/skills/i18n-multilang/scripts/numwords.py +1013 -0
  34. package/templates/.claude/skills/i18n-multilang/scripts/voice.py +478 -0
  35. package/templates/.claude/skills/neon-game-ui-ux-skill/COMPONENTS.md +490 -490
  36. package/templates/.claude/skills/neon-game-ui-ux-skill/GAMIFICATION.md +246 -246
  37. package/templates/.claude/skills/neon-game-ui-ux-skill/ICONS.md +249 -249
  38. package/templates/.claude/skills/neon-game-ui-ux-skill/LAYOUT-NAV.md +362 -362
  39. package/templates/.claude/skills/neon-game-ui-ux-skill/MOTION-A11Y.md +168 -168
  40. package/templates/.claude/skills/neon-game-ui-ux-skill/SKILL.md +137 -137
  41. package/templates/.claude/skills/neon-game-ui-ux-skill/TOKENS.md +323 -323
  42. package/templates/SISYO.md +1 -1
@@ -0,0 +1,478 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """voice.py - the optional voice side of the i18n-multilang skill (stdlib only, Python 3.8+).
4
+
5
+ Most products have text only and never run this tool. Voice exists only for the languages and the sets of lines
6
+ named in i18n.config.json -> "voice".
7
+
8
+ python voice.py plan per language and set: ready, behind, new, stale, blocked
9
+ python voice.py plan --lang vi --out todo.vi.json the lines to synthesise: id, text, speak (numbers in words), numbers
10
+ python voice.py say --lang ja --id game:say.reward "ほしを せんごひゃっこ もらったよ!"
11
+ write the spoken text of a line by hand (tied to its shown text)
12
+ python voice.py keep --lang vi --id game:say.hello --why "same greeting, one word added"
13
+ the text changed a little: keep playing the old clip until it is remade
14
+ python voice.py add --lang vi --map clips.json register finished clips: {"ns:key": {"file": "a.mp3", "speakHash": "…"}}
15
+ python voice.py pack build the CDN sets + voice manifest, bump voice versions
16
+
17
+ Text and voice have their own versions ("i18n.py versions" shows both). This tool never talks to the voice server:
18
+ making the audio with the project's voice backend and checking it is the project's own voice tool, under the rules
19
+ of references/voice.md. Number reading: numwords.py, references/numbers.md.
20
+ """
21
+ import argparse
22
+ import datetime
23
+ import hashlib
24
+ import json
25
+ import re
26
+ import shutil
27
+ import sys
28
+ import unicodedata
29
+ from pathlib import Path
30
+
31
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
32
+ import i18n as core # noqa: E402
33
+ import numwords # noqa: E402
34
+
35
+ CONTENT_TYPE = {'mp3': 'audio/mpeg', 'ogg': 'audio/ogg', 'wav': 'audio/wav', 'm4a': 'audio/mp4', 'flac': 'audio/flac'}
36
+ STATES = ('ok', 'behind', 'missing', 'stale', 'blocked', 'untranslated')
37
+
38
+
39
+ def nfc(text):
40
+ return unicodedata.normalize('NFC', text)
41
+
42
+
43
+ class Voice:
44
+ def __init__(self, project):
45
+ self.p = project
46
+ self.cfg = project.cfg['voice']
47
+ self.dir = project.root / 'voice'
48
+ for lang in self.cfg['languages']:
49
+ entry = project.registry.get(lang)
50
+ if not entry or not entry.get('voice'):
51
+ core.die('%s is not a voice language ("voice": true in the language registry: %s)'
52
+ % (lang, ' '.join(c for c, e in project.registry.items() if e.get('voice'))))
53
+ if lang not in project.enabled():
54
+ core.die('voice language %s is not one of the project\'s text languages' % lang)
55
+
56
+ def on(self):
57
+ return bool(self.cfg['languages'] and self.cfg['sets'])
58
+
59
+ def need_lang(self, lang):
60
+ if lang not in self.cfg['languages']:
61
+ core.die('%s is not in voice.languages of this project' % lang)
62
+
63
+ def voice_name(self, lang):
64
+ """The backend's voice name for a language: voice.voices[lang], else voice.voicePattern with {lang} filled in."""
65
+ return self.cfg['voices'].get(lang) or self.cfg['voicePattern'].replace('{lang}', lang)
66
+
67
+ def overrides_path(self, lang):
68
+ return self.dir / 'speak' / (lang + '.json')
69
+
70
+ def overrides(self, lang):
71
+ path = self.overrides_path(lang)
72
+ return core.read_json(path) if path.is_file() else {}
73
+
74
+ def manifest_path(self, lang):
75
+ return self.dir / lang / 'manifest.json'
76
+
77
+ def manifest(self, lang):
78
+ path = self.manifest_path(lang)
79
+ data = core.read_json(path) if path.is_file() else {}
80
+ data.setdefault('schema', core.SCHEMA)
81
+ data.setdefault('lang', lang)
82
+ data.setdefault('lines', {})
83
+ return data
84
+
85
+ def save_manifest(self, lang, manifest):
86
+ manifest['voice'] = self.voice_name(lang)
87
+ manifest['lines'] = dict(sorted(manifest['lines'].items()))
88
+ core.write_json(self.manifest_path(lang), manifest)
89
+
90
+ def cache(self, lang):
91
+ return self.dir / '_audio' / lang
92
+
93
+ def spoken(self, lang, uid, text, override, style):
94
+ """(speak, numbers, issues) of one line: from its override when it has one, else from the shown text."""
95
+ if override is None:
96
+ speak, numbers, issues = numwords.speak(text, lang, style)
97
+ if '{{' in text:
98
+ issues.append({'kind': 'placeholder', 'at': text, 'why': 'a text with a placeholder cannot be one fixed clip: '
99
+ 'write its spoken text with "voice.py say", or leave the line out of the set'})
100
+ return speak, numbers, issues
101
+ if not isinstance(override, dict) or not isinstance(override.get('speak'), str) or not isinstance(override.get('text'), str):
102
+ return '', [], [{'kind': 'override', 'at': uid, 'why': 'a spoken-text override is {"text": <the shown text it was '
103
+ 'written for>, "speak": <what is said>}: write it with "voice.py say"'}]
104
+ speak, issues = override['speak'], []
105
+ numbers = override['numbers'] if 'numbers' in override else numwords.numbers_in(text, lang, style)
106
+ if nfc(override['text']) != nfc(text):
107
+ issues.append({'kind': 'override-outdated', 'at': override['text'],
108
+ 'why': 'the shown text changed since this spoken text was written: write it again for the new text'})
109
+ if any(ch.isdigit() for ch in speak):
110
+ issues.append({'kind': 'digits', 'at': speak, 'why': 'the spoken text still holds digits: write every number in words'})
111
+ elif numbers:
112
+ ok, detail = numwords.heard(numbers, speak, lang)
113
+ if not ok:
114
+ lost = ', '.join(str(d['number']) for d in detail if d['heard'] is None)
115
+ issues.append({'kind': 'override-numbers', 'at': speak, 'why': 'the spoken text does not say %s, which the shown text '
116
+ 'holds. Fix the words; or, if the reading is right and unusual, list the numbers in "numbers"' % lost})
117
+ return speak, numbers, issues
118
+
119
+ def plan(self, lang):
120
+ """One row per selected line. state:
121
+ ok a clip matches the current spoken text (or says the same words: only punctuation or case changed)
122
+ behind the text changed, someone decided the old clip may keep playing ("keep"); to be made again
123
+ stale the text changed and nobody decided: the line is left out (silent) until "keep" or a new clip
124
+ missing no clip yet blocked the spoken text is unsettled untranslated no current text
125
+ """
126
+ lines, skipped = core.voice_lines(self.p)
127
+ report = self.p.report(lang)
128
+ target = self.p.load(lang)
129
+ overrides = self.overrides(lang)
130
+ manifest = self.manifest(lang)
131
+ style = self.cfg['numberStyle'].get(lang, {})
132
+ voice = self.voice_name(lang)
133
+ rows = []
134
+ for set_name, uid, unit in lines:
135
+ ns, _, key = uid.partition(':')
136
+ row = {'id': uid, 'set': set_name}
137
+ if report['states'][uid] not in ('ok', 'untracked'):
138
+ row.update(state='untranslated', why='the %s text is %s' % (lang, report['states'][uid]))
139
+ rows.append(row)
140
+ continue
141
+ text = unit['forms'][''] if lang == self.p.source else target[ns][key]
142
+ speak, numbers, issues = self.spoken(lang, uid, text, overrides.get(uid), style)
143
+ row.update(text=text, speak=speak, numbers=numbers)
144
+ if issues:
145
+ row.update(state='blocked', issues=issues)
146
+ rows.append(row)
147
+ continue
148
+ row['speakHash'] = core.short_hash(voice + '\n' + speak, 16)
149
+ row['textHash'] = core.short_hash(text)
150
+ row['voice'] = voice
151
+ have = manifest['lines'].get(uid)
152
+ if not have:
153
+ row['state'] = 'missing'
154
+ elif have.get('speakHash') == row['speakHash']:
155
+ row['state'] = 'ok'
156
+ elif have.get('voice') == voice and numwords.canon(have.get('speak', ''), lang) == numwords.canon(speak, lang):
157
+ row['state'] = 'ok' # the same words: only punctuation, case or spacing changed
158
+ elif have.get('keptFor', {}).get('speakHash') == row['speakHash']:
159
+ row.update(state='behind', recorded=have.get('speak'))
160
+ else:
161
+ row.update(state='stale', recorded=have.get('speak'))
162
+ rows.append(row)
163
+ return rows, skipped
164
+
165
+
166
+ def cmd_plan(v, a):
167
+ langs = [a.lang] if a.lang else v.cfg['languages']
168
+ if not langs:
169
+ print('no voice languages in i18n.config.json -> voice.languages: voice is off for this project')
170
+ return 0
171
+ if not v.cfg['sets']:
172
+ print('no voice sets in i18n.config.json -> voice.sets: no line is selected for voice')
173
+ return 0
174
+ for lang in langs:
175
+ v.need_lang(lang)
176
+ rows, skipped = v.plan(lang)
177
+ if a.out and a.lang:
178
+ todo = [r for r in rows if a.all or r['state'] in ('missing', 'stale', 'behind')]
179
+ if a.set:
180
+ todo = [r for r in todo if r['set'] == a.set]
181
+ if a.limit:
182
+ todo = todo[:a.limit]
183
+ core.write_json(a.out, {'lang': lang, 'voice': v.voice_name(lang), 'format': v.cfg['format'], 'lines': todo,
184
+ 'answer': {'<id>': {'file': '<path of the finished clip>', 'speakHash': '<as given here>',
185
+ 'checked': '<what the clip passed>'}}})
186
+ print('%s: %d lines written to %s' % (lang, len(todo), a.out))
187
+ by_set = {}
188
+ for r in rows:
189
+ c = by_set.setdefault(r['set'], {s: 0 for s in STATES})
190
+ c[r['state']] += 1
191
+ print('%s (%s)' % (lang, v.voice_name(lang)))
192
+ print(' %-18s %6s %6s %6s %6s %6s %8s %12s' % ('set', 'lines', 'ready', 'behind', 'new', 'stale', 'blocked', 'untranslated'))
193
+ for name, c in by_set.items():
194
+ print(' %-18s %6d %6d %6d %6d %6d %8d %12d' % (name, sum(c.values()), c['ok'], c['behind'], c['missing'], c['stale'],
195
+ c['blocked'], c['untranslated']))
196
+ for r in rows:
197
+ if r['state'] == 'blocked':
198
+ for i in r['issues']:
199
+ print(' blocked %s: %s (%s)' % (r['id'], i['why'], i['at']))
200
+ elif r['state'] in ('stale', 'behind'):
201
+ print(' %s %s\n clip says: %s\n text now : %s' % (r['state'], r['id'], r.get('recorded'), r['speak']))
202
+ if any(r['state'] == 'stale' for r in rows):
203
+ print(' stale = the text changed and the old clip no longer plays. Remake it, or if the old words still fit: voice.py keep')
204
+ if skipped:
205
+ print(' skipped %d plural keys (a plural text cannot be one clip): %s' % (len(skipped), ', '.join(skipped[:4])))
206
+ return 0
207
+
208
+
209
+ def cmd_say(v, a):
210
+ lang = a.lang
211
+ v.need_lang(lang)
212
+ rows = {r['id']: r for r in v.plan(lang)[0]}
213
+ row = rows.get(a.id)
214
+ if row is None:
215
+ core.die('%s is not a line of a voice set (i18n.config.json -> voice.sets)' % a.id)
216
+ if row['state'] == 'untranslated':
217
+ core.die('%s: %s. Translate it first' % (a.id, row['why']))
218
+ entry = {'text': row['text'], 'speak': nfc(a.speak.strip())}
219
+ if a.numbers is not None:
220
+ entry['numbers'] = [int(x) if re.fullmatch(r'-?\d+', x) and not (len(x) > 1 and x.startswith('0')) else x
221
+ for x in a.numbers.split(',') if x]
222
+ overrides = v.overrides(lang)
223
+ overrides[a.id] = entry
224
+ core.write_json(v.overrides_path(lang), dict(sorted(overrides.items())))
225
+ speak, numbers, issues = v.spoken(lang, a.id, row['text'], entry, v.cfg['numberStyle'].get(lang, {}))
226
+ print('%s %s' % (lang, a.id))
227
+ print(' shown : %s' % row['text'])
228
+ print(' spoken: %s' % speak)
229
+ print(' numbers to hear: %s' % (numbers or 'none'))
230
+ for i in issues:
231
+ print(' still blocked: %s (%s)' % (i['why'], i['at']))
232
+ return 1 if issues else 0
233
+
234
+
235
+ def cmd_keep(v, a):
236
+ """The text of a voiced line changed a little and its clip is not remade yet: let the old clip keep playing."""
237
+ lang = a.lang
238
+ v.need_lang(lang)
239
+ rows = {r['id']: r for r in v.plan(lang)[0]}
240
+ manifest = v.manifest(lang)
241
+ done, refused = 0, []
242
+ for uid in a.id:
243
+ row, have = rows.get(uid), manifest['lines'].get(uid)
244
+ if row is None or have is None:
245
+ refused.append((uid, 'no clip is registered for this line'))
246
+ continue
247
+ if a.undo:
248
+ if have.pop('keptFor', None) is not None:
249
+ done += 1
250
+ continue
251
+ if row['state'] in ('ok', 'behind'):
252
+ refused.append((uid, 'nothing to decide: the line is %s' % row['state']))
253
+ continue
254
+ if row['state'] != 'stale':
255
+ refused.append((uid, 'the line is %s' % row['state']))
256
+ continue
257
+ if have.get('numbers', []) != row['numbers']:
258
+ refused.append((uid, 'the numbers changed (clip says %s, text now holds %s): a clip that says another number is never kept'
259
+ % (have.get('numbers', []) or 'none', row['numbers'] or 'none')))
260
+ continue
261
+ have['keptFor'] = {'speakHash': row['speakHash'], 'textHash': row['textHash'], 'speak': row['speak'],
262
+ 'at': datetime.date.today().isoformat()}
263
+ if a.why:
264
+ have['keptFor']['why'] = a.why
265
+ done += 1
266
+ print('%s %s: the old clip keeps playing (behind)\n clip says: %s\n text now : %s' % (lang, uid, have.get('speak'), row['speak']))
267
+ if done:
268
+ v.save_manifest(lang, manifest)
269
+ print('%s: %d lines %s, %d refused' % (lang, done, 'released' if a.undo else 'kept', len(refused)))
270
+ for uid, why in refused:
271
+ print(' refused %s: %s' % (uid, why))
272
+ return 1 if refused else 0
273
+
274
+
275
+ def cmd_add(v, a):
276
+ lang = a.lang
277
+ v.need_lang(lang)
278
+ if a.map:
279
+ base = Path(a.map).resolve().parent
280
+ entries = core.read_json(a.map)
281
+ entries = entries.get('lines', entries) if isinstance(entries, dict) and isinstance(entries.get('lines'), dict) else entries
282
+ elif a.id and a.file:
283
+ base, entries = Path.cwd(), {a.id: {'file': a.file, 'speakHash': a.speak_hash}}
284
+ else:
285
+ core.die('pass --map FILE, or --id and --file')
286
+ rows = {r['id']: r for r in v.plan(lang)[0]}
287
+ manifest = v.manifest(lang)
288
+ cache = v.cache(lang)
289
+ text_manifest = v.p.root / 'manifest.json'
290
+ text_version = (core.read_json(text_manifest).get('languages', {}).get(lang, {}).get('version')
291
+ if text_manifest.is_file() else None)
292
+ added, rejected = 0, []
293
+ for uid, value in entries.items():
294
+ value = {'file': value} if isinstance(value, str) else value
295
+ row = rows.get(uid)
296
+ if row is None:
297
+ rejected.append((uid, 'not a line of a voice set'))
298
+ continue
299
+ if row['state'] in ('blocked', 'untranslated'):
300
+ rejected.append((uid, 'the line is %s' % row['state']))
301
+ continue
302
+ if value.get('speakHash') and value['speakHash'] != row['speakHash']:
303
+ rejected.append((uid, 'the spoken text changed since the plan (speakHash %s, now %s): make the clip again' % (value['speakHash'], row['speakHash'])))
304
+ continue
305
+ src = Path(value['file'])
306
+ src = src if src.is_absolute() else base / src
307
+ if not src.is_file() or src.stat().st_size == 0:
308
+ rejected.append((uid, 'no audio at %s' % src))
309
+ continue
310
+ ext = src.suffix.lstrip('.').lower()
311
+ if ext != v.cfg['format']:
312
+ rejected.append((uid, 'the project\'s voice format is %s, the file is .%s' % (v.cfg['format'], ext)))
313
+ continue
314
+ data = src.read_bytes()
315
+ sha = hashlib.sha256(data).hexdigest()
316
+ cache.mkdir(parents=True, exist_ok=True)
317
+ (cache / ('%s.%s' % (sha[:16], ext))).write_bytes(data)
318
+ line = {'speak': row['speak'], 'speakHash': row['speakHash'], 'textHash': row['textHash'], 'voice': row['voice'],
319
+ 'sha256': sha, 'file': '%s.%s' % (sha[:16], ext), 'bytes': len(data), 'at': datetime.date.today().isoformat()}
320
+ if text_version is not None:
321
+ line['textVersion'] = text_version # the language's text version when the clip was made
322
+ if row['numbers']:
323
+ line['numbers'] = row['numbers']
324
+ if value.get('checked'):
325
+ line['checked'] = value['checked']
326
+ manifest['lines'][uid] = line # a new clip replaces the old one and any "keep" decision
327
+ added += 1
328
+ if added:
329
+ v.save_manifest(lang, manifest)
330
+ print('%s: %d clips registered, %d rejected' % (lang, added, len(rejected)))
331
+ for uid, why in rejected:
332
+ print(' rejected %s: %s' % (uid, why))
333
+ return 1 if rejected else 0
334
+
335
+
336
+ def cmd_pack(v, a):
337
+ p = v.p
338
+ if not v.on():
339
+ print('voice is off for this project (voice.languages / voice.sets are empty): nothing to pack')
340
+ return 0
341
+ text_manifest_path = p.root / 'manifest.json'
342
+ text_manifest = core.read_json(text_manifest_path) if text_manifest_path.is_file() else {}
343
+ manifest_path = v.dir / 'manifest.json'
344
+ prev = core.read_json(manifest_path) if manifest_path.is_file() else {}
345
+ prev_langs = prev.get('languages', {}) if prev.get('compat') == p.cfg['compat'] else {}
346
+ prefix = p.cfg['cdn']['voicePrefix'].strip('/')
347
+ sets_prefix = '%s/c%d' % (prefix, p.cfg['compat'])
348
+ dist = p.root / p.cfg['dist']
349
+ for lang in v.cfg['languages']: # the voice sets are built against one known text version
350
+ entry = text_manifest.get('languages', {}).get(lang)
351
+ if not entry or entry['hash'] != core.pack_body(p, lang)[3]:
352
+ core.die('the %s text changed since the last text pack: run "i18n.py pack" first, then "voice.py pack"' % lang)
353
+ out = dist / sets_prefix
354
+ if out.is_dir():
355
+ shutil.rmtree(out)
356
+ plan, languages, changed, absent, behind_all, silent_all = [], {}, False, 0, [], []
357
+ for lang in v.cfg['languages']:
358
+ rows, _ = v.plan(lang)
359
+ manifest = v.manifest(lang)
360
+ cache = v.cache(lang)
361
+ sets = {}
362
+ for name in v.cfg['sets']:
363
+ mine = [r for r in rows if r['set'] == name]
364
+ clips, total, behind = {}, 0, 0
365
+ for r in mine:
366
+ if r['state'] not in ('ok', 'behind'):
367
+ silent_all.append('%s %s (%s)' % (lang, r['id'], r['state']))
368
+ continue
369
+ line = manifest['lines'][r['id']]
370
+ # the texts this clip may be played with: the one shown now, and the one it was recorded for
371
+ texts = list(dict.fromkeys([r['textHash']] + ([line['textHash']] if line.get('textHash') else [])))
372
+ clips[r['id']] = {'file': line['file'], 'bytes': line['bytes'], 'text': texts}
373
+ total += line['bytes']
374
+ if r['state'] == 'behind':
375
+ behind += 1
376
+ behind_all.append('%s %s' % (lang, r['id']))
377
+ src = cache / line['file']
378
+ if src.is_file():
379
+ dest = dist / prefix / 'clips' / lang / line['file']
380
+ dest.parent.mkdir(parents=True, exist_ok=True)
381
+ if not dest.is_file():
382
+ shutil.copyfile(src, dest)
383
+ key = '%s/clips/%s/%s' % (prefix, lang, line['file'])
384
+ plan.append({'file': key, 'key': key, 'contentType': CONTENT_TYPE.get(v.cfg['format'], 'application/octet-stream'),
385
+ 'cacheControl': 'public, max-age=31536000, immutable'})
386
+ else:
387
+ absent += 1
388
+ if not clips:
389
+ continue
390
+ body = json.dumps({'schema': core.SCHEMA, 'lang': lang, 'set': name, 'voice': v.voice_name(lang), 'clips': clips},
391
+ ensure_ascii=False, separators=(',', ':'), sort_keys=True).encode('utf-8')
392
+ sha = hashlib.sha256(body).hexdigest()
393
+ old = prev_langs.get(lang, {}).get('sets', {}).get(name)
394
+ rel = '%s/%s.%s.json' % (lang, name, sha[:12])
395
+ (out / rel).parent.mkdir(parents=True, exist_ok=True)
396
+ (out / rel).write_bytes(body)
397
+ sets[name] = {'version': (old['version'] + (0 if old.get('hash') == sha else 1)) if old else 1,
398
+ 'hash': sha, 'file': rel, 'lines': len(mine), 'clips': len(clips), 'behind': behind,
399
+ 'silent': len(mine) - len(clips), 'bytes': total, 'complete': len(clips) == len(mine)}
400
+ if not old or old.get('hash') != sha:
401
+ changed = True
402
+ key = sets_prefix + '/' + rel
403
+ plan.append({'file': key, 'key': key, 'contentType': 'application/json; charset=utf-8',
404
+ 'cacheControl': 'public, max-age=31536000, immutable'})
405
+ if sets:
406
+ languages[lang] = {'voice': v.voice_name(lang), 'textVersion': text_manifest['languages'][lang]['version'], 'sets': sets}
407
+ if set(languages) != set(prev_langs) or any(set(languages[l]['sets']) != set(prev_langs[l].get('sets', {})) for l in languages):
408
+ changed = True
409
+ manifest = {
410
+ 'schema': core.SCHEMA, 'product': p.cfg['product'], 'compat': p.cfg['compat'],
411
+ 'revision': prev.get('revision', 0) + 1 if changed or not prev else prev['revision'],
412
+ 'updatedAt': datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') if changed or not prev else prev.get('updatedAt'),
413
+ 'format': v.cfg['format'], 'fallback': v.cfg['fallback'], 'clipsBase': prefix + '/clips',
414
+ 'languages': languages,
415
+ }
416
+ core.write_json(manifest_path, manifest)
417
+ core.write_json(out / 'manifest.json', manifest)
418
+ seen, unique = set(), []
419
+ for item in plan:
420
+ if item['key'] not in seen:
421
+ seen.add(item['key'])
422
+ unique.append(item)
423
+ unique.append({'file': sets_prefix + '/manifest.json', 'key': sets_prefix + '/manifest.json',
424
+ 'contentType': 'application/json; charset=utf-8', 'cacheControl': 'public, max-age=60', 'last': True})
425
+ plan_path = dist / 'upload-plan.voice.json'
426
+ core.write_json(plan_path, {'base': p.cfg['cdn']['baseUrl'], 'order': 'clips, then set indexes, the manifest last', 'files': unique})
427
+ for lang, e in languages.items():
428
+ for name, s in e['sets'].items():
429
+ print('%s %-16s voice v%d for text v%d: %d of %d clips (%d behind, %d silent), %.1f MB' % (
430
+ lang, name, s['version'], e['textVersion'], s['clips'], s['lines'], s['behind'], s['silent'], s['bytes'] / 1048576))
431
+ if behind_all:
432
+ print('%d lines play a clip made for an earlier wording (behind), to be remade: %s%s'
433
+ % (len(behind_all), ', '.join(behind_all[:6]), ' …' if len(behind_all) > 6 else ''))
434
+ if silent_all:
435
+ print('%d lines have no usable clip and are silent: %s%s' % (len(silent_all), ', '.join(silent_all[:6]), ' …' if len(silent_all) > 6 else ''))
436
+ if absent:
437
+ print('%d clips are not in the local cache (voice/_audio): fine if they are already on the CDN, else fetch them first' % absent)
438
+ print('voice pack: revision %d dist: %s upload plan: %s' % (manifest['revision'], out.as_posix(), plan_path.as_posix()))
439
+ return 0
440
+
441
+
442
+ def main(argv=None):
443
+ for stream in (sys.stdout, sys.stderr):
444
+ if hasattr(stream, 'reconfigure'):
445
+ stream.reconfigure(encoding='utf-8')
446
+ ap = argparse.ArgumentParser(description='Voice sets of the i18n-multilang skill (optional: most products are text only).')
447
+ ap.add_argument('--config', help='i18n.config.json or its folder')
448
+ sub = ap.add_subparsers(dest='cmd', required=True)
449
+ s = sub.add_parser('plan', help='which lines need audio')
450
+ s.add_argument('--lang')
451
+ s.add_argument('--set')
452
+ s.add_argument('--out', help='with --lang: write the lines to synthesise (new, stale, behind) to this file')
453
+ s.add_argument('--all', action='store_true', help='with --out: every line')
454
+ s.add_argument('--limit', type=int)
455
+ s = sub.add_parser('say', help='write the spoken text of a line by hand, tied to the text it is shown with')
456
+ s.add_argument('speak', help='what the voice says: every number in words')
457
+ s.add_argument('--lang', required=True)
458
+ s.add_argument('--id', required=True, help='ns:key')
459
+ s.add_argument('--numbers', help='only when the reading is right but unusual: the numbers it says, comma separated ("" for none)')
460
+ s = sub.add_parser('keep', help='the text changed a little: let the old clip keep playing until it is remade')
461
+ s.add_argument('--lang', required=True)
462
+ s.add_argument('--id', required=True, nargs='+', help='one or more ns:key')
463
+ s.add_argument('--why', help='one line: why the old words still fit')
464
+ s.add_argument('--undo', action='store_true', help='take the decision back: the line is stale (silent) again')
465
+ s = sub.add_parser('add', help='register finished clips')
466
+ s.add_argument('--lang', required=True)
467
+ s.add_argument('--map', help='JSON {"ns:key": {"file": "…", "speakHash": "…"}} (paths relative to the map file)')
468
+ s.add_argument('--id')
469
+ s.add_argument('--file')
470
+ s.add_argument('--speak-hash')
471
+ sub.add_parser('pack', help='build the CDN sets and the voice manifest')
472
+ a = ap.parse_args(argv)
473
+ v = Voice(core.Project(core.find_config(a.config)))
474
+ return {'plan': cmd_plan, 'say': cmd_say, 'keep': cmd_keep, 'add': cmd_add, 'pack': cmd_pack}[a.cmd](v, a)
475
+
476
+
477
+ if __name__ == '__main__':
478
+ sys.exit(main() or 0)