# Страница прослушивания демо «симлиша»: подряд / встреча, значок играющей записи, чекбоксы и копирование отмеченных.
import json
meta = json.load(open('out/meta.json'))
def group(v): return 'si' if v.startswith('silero') else v[:2]
verse = json.load(open('out/verse.json'))  # «складные» — как строка стиха, по одной на голос (gen/verse.py)
data = [{'f': m['file'] + '.mp3', 'v': m['voice'], 's': m['sex'], 't': m['text'], 'g': group(m['voice']), 'sec': sec}
        for sec, ms in (('plain', meta), ('verse', verse)) for m in ms]
html = '''<!doctype html><html lang="ru"><head><meta charset="utf-8"><title>Симлиш — демо</title>
<style>
body{font:14px sans-serif;background:#1b1b24;color:#cde;margin:16px}
table{border-collapse:collapse}td{padding:3px 8px;border-bottom:1px solid #334;vertical-align:middle}
tr.playing td{background:#2e3550}tr.checked td:nth-child(2){color:#9f9}
td.ind{width:18px;color:#7cf;font-size:16px}button{font:14px sans-serif;padding:4px 12px;margin:0 6px 8px 0;cursor:pointer}
audio{height:28px}#now{color:#9aa;margin:4px 0 12px}.bar{margin-bottom:6px}input[type=checkbox]{transform:scale(1.3)}
</style></head><body>
<h2>«Симлиш» — тарабарщина синтезом</h2>
<ul>
<li><b>en</b> — английский, Piper; общественное достояние — чисто</li>
<li><b>zh</b> — китайский, Piper xiao_ya (данные — только некоммерческое); фразы из случайных иероглифов — для носителя это набор настоящих слов</li>
<li><b>silero</b> — русский, Silero v5 (из esay); лицензия моделей CC BY-NC 4.0 — только некоммерческое</li>
</ul>
<div class="bar">Группа: <select id="grp"><option value="all">все</option><option value="en">английские</option><option value="si">русские Silero</option><option value="zh">китайские</option><option value="checked">только отмеченные</option><option value="plain">только обычные</option><option value="verse">только складные</option></select> Мультяшность: <select id="toon"><option value="">нет</option><option value="toon0/">+1,5 полутона</option><option value="toon1/">+3 полутона</option><option value="toon2/">+5 полутонов</option></select></div>
<div class="bar"><button id="seq">▶ подряд по порядку</button><button id="meet">▶ встреча (вперемешку)</button><button id="stop">■ стоп</button></div>
<div class="bar"><button id="copy">Копировать отмеченные</button><button id="none">Снять все отметки</button> <span id="cnt"></span></div>
<div id="now"></div>
<h3>Обычные</h3><table id="tbl"></table>
<h3 id="verse-h">Складные — как строка стиха</h3><p>Два полустишия через запятую, 5 + 7 слогов (китайские — 5 + 5 иероглифов), концы полустиший рифмуются; у Silero ударение на первом слоге каждого слова.</p><table id="tbl-verse"></table>
<script>
const all = DATA;
const KEY = 'simlish-demo-checked';
let checked = new Set();
try { checked = new Set(JSON.parse(localStorage.getItem(KEY) || '[]')); } catch {}
const save = () => { try { localStorage.setItem(KEY, JSON.stringify([...checked])); } catch {} };
const tbls = { plain: document.getElementById('tbl'), verse: document.getElementById('tbl-verse') }, now = document.getElementById('now'), cnt = document.getElementById('cnt');
const rows = new Map();
const toonSel = document.getElementById('toon');
const src = (x) => toonSel.value + x.f;
for (const x of all) {
  const tr = document.createElement('tr');
  tr.innerHTML = `<td class="ind"></td><td><label><input type="checkbox"> ${x.v}</label></td><td>${x.s}</td><td><audio controls preload="none" src="${src(x)}"></audio></td><td><i>${x.t}</i></td>`;
  const cb = tr.querySelector('input'), au = tr.querySelector('audio');
  cb.checked = checked.has(x.f); tr.classList.toggle('checked', cb.checked);
  cb.onchange = () => { cb.checked ? checked.add(x.f) : checked.delete(x.f); tr.classList.toggle('checked', cb.checked); save(); count(); };
  au.onplay = () => { stopAuto(); mark(x); };
  au.onpause = au.onended = () => { if (!auto) mark(null); };
  tbls[x.sec].append(tr); rows.set(x.f, tr);
}
if (!all.some((x) => x.sec === 'verse')) for (const el of [document.getElementById('verse-h'), document.getElementById('verse-h').nextElementSibling]) el.hidden = true;
toonSel.onchange = () => { stopAuto(); mark(null); for (const x of all) rows.get(x.f).querySelector('audio').src = src(x); };
function count() { cnt.textContent = `отмечено: ${checked.size}`; }
count();
function mark(x) {
  for (const [f, tr] of rows) { const on = x && f === x.f; tr.classList.toggle('playing', !!on); tr.querySelector('.ind').textContent = on ? '🔊' : ''; }
  now.textContent = x ? `играет: ${x.v} — ${x.t}` : '';
  if (x) rows.get(x.f).scrollIntoView({ block: 'nearest' });
}
function pool() {
  const g = document.getElementById('grp').value;
  if (g === 'all') return all;
  if (g === 'checked') return all.filter((x) => checked.has(x.f));
  if (g === 'plain' || g === 'verse') return all.filter((x) => x.sec === g);
  return all.filter((x) => g.split(',').includes(x.g));
}
const player = new Audio();
let auto = null, timer = null;
function stopAuto() { auto = null; clearTimeout(timer); player.pause(); }
function playX(x, after) {
  for (const a of document.querySelectorAll('audio')) a.pause();
  mark(x); player.src = src(x); player.play();
  player.onended = () => { if (auto) timer = setTimeout(after, auto === 'meet' ? 300 + Math.random() * 1200 : 400); };
}
document.getElementById('seq').onclick = () => {
  stopAuto(); const list = pool(); if (!list.length) return; auto = 'seq'; let i = 0;
  const next = () => { if (auto !== 'seq') return; if (i >= list.length) { auto = null; mark(null); return; } playX(list[i++], next); };
  next();
};
document.getElementById('meet').onclick = () => {
  stopAuto(); const list = pool(); if (!list.length) return; auto = 'meet'; let last = null;
  const next = () => { if (auto !== 'meet') return; let x; do x = list[Math.floor(Math.random() * list.length)]; while (x.v === last && new Set(list.map((y) => y.v)).size > 1); last = x.v; playX(x, next); };
  next();
};
document.getElementById('stop').onclick = () => { stopAuto(); mark(null); };
document.getElementById('none').onclick = () => { checked.clear(); save(); for (const [, tr] of rows) { tr.querySelector('input').checked = false; tr.classList.remove('checked'); } count(); };
document.getElementById('copy').onclick = async (e) => {
  const text = all.filter((x) => checked.has(x.f)).map((x) => `${x.f}\\t${x.v}\\t${x.t}\\t${toonSel.selectedOptions[0].text}`).join('\\n');
  try { await navigator.clipboard.writeText(text); e.target.textContent = 'Скопировано'; setTimeout(() => (e.target.textContent = 'Копировать отмеченные'), 1500); }
  catch { prompt('Отмеченные', text.replaceAll('\\n', ' | ')); }
};
</script></body></html>'''
open('demo/index.html', 'w').write(html.replace('DATA', json.dumps(data, ensure_ascii=False)))
print(len(data))
