Spaces:
Sleeping

interprete / static /index.html
echerkaoui1
Mise à jour depuis GitHub
75fc8b6
Raw History Blame Contribute Delete
41.3 kB
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Interprète</title>
<style>
:root {
--ink: #151C2A; /* fond, encre indigo */
--ink-2: #1C2536; /* tiroir des réglages */
--edge: #2A3549; /* bordures */
--paper: #F1ECE2; /* phrase en cours, papier de riz */
--slate: #8E9AAE; /* historique */
--dim: #5F6B81; /* original, attente */
--jade: #3DAE86; /* écoute, voix */
--jade-soft: rgba(61, 174, 134, .16);
--cinnabar: #C8453C; /* arrêt et erreurs uniquement */
--size: 30px; /* taille de la traduction en cours (réglable) */
--latin: "Segoe UI Variable Display", "Segoe UI", system-ui, sans-serif;
--text: "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif;
--cjk: "Microsoft YaHei UI", "Microsoft YaHei", "PingFang SC", sans-serif;
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
background: var(--ink); color: var(--paper); font-family: var(--text); font-size: 14px;
display: grid; grid-template-rows: auto auto 1fr auto; overflow: hidden;
-webkit-font-smoothing: antialiased;
}
button, select, input { font: inherit; color: inherit; }
:focus-visible { outline: 2px solid var(--paper); outline-offset: 2px; border-radius: 6px; }
/* ---------- barre du haut ---------- */
header {
display: flex; align-items: center; gap: 12px; padding: 14px 24px 10px;
}
.status { display: flex; align-items: center; gap: 10px; min-width: 0; flex: 1; color: var(--slate); }
.status .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--dim); flex: none; transition: background .3s; }
.status[data-state="listening"] .dot { background: var(--jade); }
.status[data-state="loading"] .dot { background: var(--slate); }
.status[data-state="error"] .dot { background: var(--cinnabar); }
.status[data-state="error"] .msg { color: #E6877F; }
.status .msg { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.targets { display: flex; gap: 2px; padding: 3px; border-radius: 10px; background: rgba(255,255,255,.04);
margin-right: 6px; }
.sep { width: 1px; height: 22px; background: var(--edge); }
.targets button {
border: 0; background: none; padding: 6px 11px; border-radius: 7px; cursor: pointer;
color: var(--slate); font-weight: 600; letter-spacing: .01em;
}
.targets button[aria-pressed="true"] { background: var(--paper); color: var(--ink); }
.targets button:not([aria-pressed="true"]):hover { color: var(--paper); }
.ghost {
border: 0; background: none; color: var(--slate); padding: 8px 10px; border-radius: 8px; cursor: pointer;
}
.ghost:hover { color: var(--paper); background: rgba(255,255,255,.05); }
.primary {
border: 0; padding: 9px 20px; border-radius: 9px; cursor: pointer; font-weight: 700;
background: var(--jade); color: var(--ink); min-width: 104px;
}
.primary:hover { filter: brightness(1.08); }
.primary[data-running="true"] { background: var(--cinnabar); color: var(--paper); }
/* ---------- ruban de voix : la seule pièce expressive ---------- */
.ribbon { position: relative; height: 34px; margin: 0 24px; border-bottom: 1px solid var(--edge); }
.ribbon canvas { width: 100%; height: 100%; display: block; }
.ribbon .hint {
position: absolute; right: 0; top: 50%; transform: translateY(-50%); font-size: 12px; color: var(--jade);
padding-left: 28px; background: linear-gradient(90deg, transparent, var(--ink) 24px);
opacity: 0; transition: opacity .25s;
}
body.speaking .ribbon .hint { opacity: 1; }
/* ---------- scène ---------- */
main { overflow-y: auto; padding: 8px 24px 28px; scroll-behavior: smooth; }
main::-webkit-scrollbar, aside::-webkit-scrollbar { width: 8px; }
main::-webkit-scrollbar-thumb, aside::-webkit-scrollbar-thumb { background: var(--edge); border-radius: 8px; }
main::-webkit-scrollbar-track, aside::-webkit-scrollbar-track { background: transparent; }
/* Une seule colonne de lecture, centrée : le français et l'arabe partagent les mêmes bords. */
.empty, .entry { max-width: 760px; margin-left: auto; margin-right: auto; }
.empty { margin-top: 12vh; color: var(--slate); line-height: 1.7; font-size: 15px; }
.empty strong { color: var(--paper); font-weight: 600; }
.entry { padding: 10px 0; }
/* Qui parle : visible dès que deux voix différentes ont été entendues dans la séance */
.who { display: none; align-items: center; gap: 8px; margin: 0 0 4px; font-size: 12px; color: var(--slate); }
body.multi .who.known, .who.over { display: flex; }
.who i { width: 8px; height: 8px; border-radius: 50%; background: var(--voice, var(--dim)); flex: none; }
body:not(.multi) .who i, body:not(.multi) .who .whoName { display: none; }
.whoName { all: unset; cursor: text; color: var(--voice, var(--slate)); font-weight: 600; letter-spacing: .02em; }
.whoName:hover, .whoName:focus-visible { text-decoration: underline dotted; text-underline-offset: 3px; }
.whoEdit { font: inherit; color: var(--paper); background: var(--ink-2); border: 1px solid var(--edge);
border-radius: 6px; padding: 2px 6px; width: 11em; }
.ovl { color: var(--dim); }
.entry[data-v="1"] { --voice: #3DAE86; } .entry[data-v="2"] { --voice: #E0A458; }
.entry[data-v="3"] { --voice: #7FA8E6; } .entry[data-v="4"] { --voice: #D98AA6; }
.entry[data-v="5"] { --voice: #A99AE0; } .entry[data-v="6"] { --voice: #6FC3C9; }
.entry[data-v="7"] { --voice: #C9B86A; } .entry[data-v="8"] { --voice: #B58E7A; }
body.multi .entry[data-v] { border-left: 2px solid var(--voice, transparent); padding-left: 14px; }
body.subtitle .who { display: none !important; }
.tr { margin: 0; font-family: var(--latin); font-size: calc(var(--size) * .55); line-height: 1.45;
color: var(--slate); unicode-bidi: plaintext; }
.tr:lang(zh), .tr.zh { font-family: var(--cjk); }
.orig { margin: 6px 0 0; font-family: var(--cjk); font-size: calc(var(--size) * .45); color: var(--dim);
line-height: 1.6; }
.orig mark {
background: none; color: inherit; text-decoration: underline dotted var(--jade);
text-underline-offset: 4px; text-decoration-thickness: 2px; cursor: help;
}
.meta { margin-top: 6px; font-size: 12px; color: var(--dim); opacity: 0; transition: opacity .3s; }
.entry.latest .meta { opacity: 1; }
.entry.latest .tr { font-size: var(--size); font-weight: 650; color: var(--paper); line-height: 1.32; }
.entry.latest .orig { color: var(--slate); }
.entry.latest { padding: 26px 0 8px; }
.wait { display: inline-flex; gap: 6px; padding: 10px 0; }
.wait i { width: 7px; height: 7px; border-radius: 50%; background: var(--dim); animation: pulse 1.2s infinite ease-in-out; }
.wait i:nth-child(2) { animation-delay: .15s; } .wait i:nth-child(3) { animation-delay: .3s; }
@keyframes pulse { 0%, 80%, 100% { opacity: .25; } 40% { opacity: 1; } }
footer { padding: 10px max(24px, calc((100% - 760px) / 2)) 14px; border-top: 1px solid var(--edge);
color: var(--slate); font-family: var(--cjk); font-size: 15px; min-height: 44px; }
footer:empty { display: none; }
/* ---------- tiroir des réglages ---------- */
.scrim { position: fixed; inset: 0; background: rgba(8, 11, 18, .45); opacity: 0; pointer-events: none; transition: opacity .2s; }
aside {
position: fixed; top: 0; right: 0; bottom: 0; width: min(380px, 92vw); background: var(--ink-2);
border-left: 1px solid var(--edge); padding: 22px 22px 18px; overflow-y: auto;
transform: translateX(100%); transition: transform .22s ease-out; display: flex; flex-direction: column; gap: 16px;
}
body.drawer aside { transform: none; }
body.drawer .scrim { opacity: 1; pointer-events: auto; }
aside .head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px; }
aside h2 { margin: 0; font: 600 17px var(--latin); }
.field { display: grid; gap: 6px; }
.field > span { font-size: 12px; color: var(--slate); }
select, input[type="range"] { width: 100%; }
select {
appearance: none; background: var(--ink) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%238E9AAE'/%3E%3C/svg%3E") no-repeat right 12px center;
border: 1px solid var(--edge); border-radius: 8px; padding: 9px 30px 9px 11px; color: var(--paper);
}
select:focus { border-color: var(--jade); outline: none; }
option { background: var(--ink-2); }
.switch { display: flex; align-items: flex-start; gap: 10px; cursor: pointer; line-height: 1.4; }
.switch input { accent-color: var(--jade); width: 16px; height: 16px; margin-top: 2px; flex: none; }
.switch small { display: block; color: var(--slate); font-size: 12px; }
input[type="range"] { accent-color: var(--jade); }
.note { font-size: 12px; color: var(--dim); line-height: 1.55; margin-top: auto; }
.note kbd { font: inherit; color: var(--slate); border: 1px solid var(--edge); border-radius: 4px; padding: 0 4px; }
/* ---------- mode sous-titres : bande compacte au-dessus d'un appel ou d'une vidéo ---------- */
body.subtitle { grid-template-rows: auto 1fr; }
body.subtitle header { padding: 8px 14px 0; gap: 8px; }
body.subtitle .status .msg, body.subtitle #settingsBtn, body.subtitle footer,
body.subtitle .ribbon .hint { display: none; }
body.subtitle .ribbon { position: absolute; left: 14px; right: 14px; bottom: 0; height: 4px; border: 0; margin: 0; }
body.subtitle main { padding: 0 18px 10px; overflow: hidden; display: flex; flex-direction: column; justify-content: flex-end; }
body.subtitle .entry:not(.latest), body.subtitle .empty { display: none; }
body.subtitle .entry.latest { padding: 4px 0 0; border: 0; max-width: none; }
body.subtitle .entry.latest .tr { font-size: min(var(--size), 30px);
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
body.subtitle .orig { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 2px; }
body.subtitle .meta { display: none; }
body.subtitle .primary { padding: 6px 14px; min-width: 0; }
/* ---------- modes Écoute / Texte ---------- */
.modes { display: flex; gap: 2px; padding: 3px; border-radius: 10px; background: rgba(255,255,255,.04); }
.modes button { border: 0; background: none; padding: 6px 12px; border-radius: 7px; cursor: pointer;
color: var(--slate); font-weight: 600; }
.modes button[aria-selected="true"] { background: var(--edge); color: var(--paper); }
.modes button:not([aria-selected="true"]):hover { color: var(--paper); }
#textPanel { display: none; }
body.text { grid-template-rows: auto 1fr; }
body.text .ribbon, body.text main, body.text footer, body.text #subBtn { display: none; }
body.text #textPanel {
display: grid; grid-template-columns: 1fr 1fr; gap: 16px; padding: 6px 24px 22px; min-height: 0;
}
@media (max-width: 760px) { body.text #textPanel { grid-template-columns: 1fr; grid-template-rows: 1fr 1fr; } }
.pane { display: flex; flex-direction: column; min-height: 0; border: 1px solid var(--edge);
border-radius: 12px; background: rgba(255,255,255,.015); }
.pane:focus-within { border-color: #3A4862; }
.pane-head { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-bottom: 1px solid var(--edge);
min-height: 50px; }
.pane-head .label { color: var(--slate); font-size: 13px; }
.pane-head select { width: auto; padding: 6px 30px 6px 10px; font-size: 13px; }
.pane-head .grow { flex: 1; }
.pane-foot { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-top: 1px solid var(--edge); }
.pane-foot .count, .pane-foot .info { flex: 1; color: var(--dim); font-size: 12px; }
#textIn, #textOut {
flex: 1; min-height: 0; margin: 0; padding: 14px 16px; overflow-y: auto; resize: none; border: 0;
background: transparent; color: var(--paper); font: 17px/1.6 var(--text); unicode-bidi: plaintext;
white-space: pre-wrap; word-wrap: break-word;
}
#textIn:focus { outline: none; }
#textIn::placeholder { color: var(--dim); }
#textOut { user-select: text; cursor: text; }
#textOut.zh, #textIn.zh { font-family: var(--cjk); }
#textOut:empty::before { content: attr(data-empty); color: var(--dim); }
#textOut.error { color: #E6877F; }
.small { padding: 7px 14px; min-width: 0; font-size: 13px; }
.suggest { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 8px 12px;
border-top: 1px solid var(--edge); min-height: 46px; }
.suggest:empty::before { content: "Les suggestions apparaissent ici pendant que tu écris."; color: var(--dim); font-size: 12px; }
.suggest button {
border: 1px solid var(--edge); background: var(--ink); color: var(--paper); border-radius: 8px;
padding: 5px 10px; cursor: pointer; font-size: 14px; max-width: 100%; overflow: hidden; text-overflow: ellipsis;
white-space: nowrap; unicode-bidi: plaintext;
}
.suggest button:hover { border-color: var(--jade); }
.suggest button:first-child { border-color: rgba(61, 174, 134, .55); }
.suggest button.name { color: #9FD9C2; }
.suggest kbd { font: 11px var(--text); color: var(--dim); border: 1px solid var(--edge); border-radius: 4px;
padding: 0 4px; margin-left: 6px; }
.info.busy::after { content: " Mise à jour…"; color: var(--slate); }
#textOut::-webkit-scrollbar, #textIn::-webkit-scrollbar { width: 8px; }
#textOut::-webkit-scrollbar-thumb, #textIn::-webkit-scrollbar-thumb { background: var(--edge); border-radius: 8px; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { transition: none !important; animation: none !important; scroll-behavior: auto !important; }
}
/* ---------- version web : connexion ---------- */
.gate { position: fixed; inset: 0; display: grid; place-items: center; background: var(--ink); z-index: 20; }
.gate[hidden] { display: none; }
.gate form { width: min(360px, 90vw); display: grid; gap: 14px; }
.gate h1 { margin: 0; font: 650 26px var(--latin); }
.gate p { margin: 0; color: var(--slate); line-height: 1.55; }
.gate input { background: var(--ink-2); border: 1px solid var(--edge); border-radius: 9px; padding: 11px 12px;
color: var(--paper); font-size: 16px; }
.gate input:focus { outline: none; border-color: var(--jade); }
.gate .err { color: #E6877F; min-height: 1.2em; font-size: 13px; }
@media (max-width: 640px) {
header { flex-wrap: wrap; padding: 10px 14px 8px; gap: 8px; }
.status { order: 5; flex-basis: 100%; }
.ribbon { margin: 0 14px; }
main { padding: 8px 14px 20px; }
body.text #textPanel { padding: 6px 14px 16px; }
}
</style>
</head>
<body>
<div class="gate" id="gate" hidden>
<form id="gateForm">
<h1>Interprète</h1>
<p>Entre le code d'équipe pour utiliser la traduction en direct.</p>
<input id="gateCode" type="password" autocomplete="current-password" aria-label="Code d'équipe" required>
<div class="err" id="gateErr" role="alert"></div>
<button class="primary" type="submit">Entrer</button>
</form>
</div>
<header>
<nav class="modes" role="tablist" aria-label="Mode">
<button role="tab" id="modeLive" aria-selected="true">Écoute</button>
<button role="tab" id="modeText" aria-selected="false">Texte</button>
</nav>
<div class="status" id="status" data-state="idle" role="status" aria-live="polite">
<span class="dot"></span><span class="msg" id="statusMsg">Connexion au serveur…</span>
</div>
<div class="targets" id="targets" role="group" aria-label="Traduire en"></div>
<span class="sep" aria-hidden="true"></span>
<button class="ghost" id="settingsBtn">Réglages</button>
<button class="primary" id="listenBtn" data-running="false">Écouter</button>
</header>
<section id="textPanel" aria-label="Traduction de texte">
<div class="pane">
<div class="pane-head">
<span class="label">Depuis</span>
<select id="textSrc" aria-label="Langue du texte"></select>
</div>
<textarea id="textIn" spellcheck="false" dir="auto"
placeholder="Écris ou colle un texte ici, en chinois, français, arabe ou anglais. La traduction suit en direct."></textarea>
<div class="suggest" id="suggest" aria-label="Suggestions de mots"></div>
<div class="pane-foot">
<span class="count" id="textCount">0 caractère</span>
<button class="ghost small" id="textClear">Effacer</button>
<button class="primary small" id="textGo" title="Ctrl + Entrée">Traduire</button>
</div>
</div>
<div class="pane">
<div class="pane-head">
<span class="label" id="textOutLabel">Traduction</span><span class="grow"></span>
<button class="ghost small" id="textCopy" disabled>Copier</button>
</div>
<div id="textOut" dir="auto" tabindex="0" aria-live="polite"
data-empty="La traduction apparaîtra ici. La langue se choisit avec les boutons en haut."></div>
<div class="pane-foot"><span class="info" id="textInfo"></span></div>
</div>
</section>
<div class="ribbon" aria-hidden="true"><canvas id="ribbon"></canvas><span class="hint">Il parle…</span></div>
<main id="stage" aria-live="polite">
<div class="empty" id="empty">
<strong>Choisis la langue de traduction en haut, puis appuie sur Écouter.</strong><br>
Le navigateur demande l'accès au micro. La ligne sous la barre bouge avec le son reçu :
si elle reste plate quand quelqu'un parle, le micro est coupé ou la mauvaise source est choisie dans Réglages.
</div>
</main>
<footer id="partial"></footer>
<div class="scrim" id="scrim"></div>
<aside id="drawer" aria-label="Réglages">
<div class="head"><h2>Réglages</h2><button class="ghost" id="closeDrawer">Fermer</button></div>
<label class="field"><span>Écouter</span>
<select id="source">
<option value="mic">Micro de cet appareil</option>
<option value="tab">Son d'un onglet ou de l'écran (appel, vidéo)</option>
</select></label>
<label class="field"><span>On parle</span><select id="spoken"></select></label>
<label class="switch"><input type="checkbox" id="correct" checked>
<span>Corriger les accents avec le contexte
<small>Répare les mots mal entendus, sans reformuler. Les caractères corrigés sont soulignés ; survole-les pour voir ce qui avait été entendu.</small></span></label>
<label class="field"><span>Taille du texte</span><input type="range" id="size" min="20" max="56" step="2" value="30"></label>
<p class="note">La détection de la parole se fait dans ce navigateur. Seules les phrases prononcées partent
vers le serveur, puis chez Groq (et OpenRouter en secours) pour être transcrites et traduites.
Pour « Son d'un onglet », coche « Partager l'audio » dans la fenêtre de partage de Chrome ou Edge.
<kbd>Ctrl</kbd> + <kbd>Espace</kbd> lance ou arrête l'écoute, <kbd>Échap</kbd> ferme ce panneau.</p>
</aside>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/ort.wasm.min.js" integrity="sha384-epp8GDQUoLKx5qHa6SoDHKv7fSHILsEYk4uEsHdPRBztXEIVWCe/lhhrQJUBMZcf" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.31/dist/bundle.min.js" integrity="sha384-BLK6Iw3Zbz9hHmHYBgWHJ8GaGVHf3hfnz95vXOla64ZQHHL/T7r9PeIl6jUx8eer" crossorigin="anonymous"></script>
<script>
const $ = (id) => document.getElementById(id);
const SHORT = { fr: "FR", ar: "عربي", en: "EN", zh: "中文" };
const TARGET_NAME = { fr: "en français", ar: "en arabe", en: "en anglais", zh: "en chinois" };
const S = { // réglages de ce navigateur, gardés d'une visite à l'autre
target: "fr", spoken: "zh", source: "mic", correct: true, size: 30,
...(() => { try { return JSON.parse(localStorage.getItem("interprete") || "{}"); } catch { return {}; } })(),
};
function save() { try { localStorage.setItem("interprete", JSON.stringify(S)); } catch {} }
let cfg = { spoken: [], targets: [], glossary: [] }, running = false, state = "idle", speaking = false;
let myvad = null, stream = null, segId = 0, context = [];
// Une séance = un chargement de page : le serveur numérote les voix (Voix 1, Voix 2...) pour cette séance.
const SID = (crypto.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2)) ;
const voiceNames = {}, voicesSeen = new Set();
function voiceLabel(v) { return voiceNames[v] || `Voix ${v}`; }
function renameVoice(v, btn) {
const input = document.createElement("input");
input.className = "whoEdit"; input.value = voiceNames[v] || ""; input.placeholder = `Nom de la voix ${v}`;
input.maxLength = 30; input.setAttribute("aria-label", `Nom de la voix ${v}`);
const done = (keep) => {
if (keep) { const n = input.value.trim(); if (n) voiceNames[v] = n; else delete voiceNames[v]; }
input.replaceWith(btn);
document.querySelectorAll(`.entry[data-v="${v}"] .whoName`).forEach(b => { b.textContent = voiceLabel(v); });
};
input.addEventListener("keydown", e => { if (e.key === "Enter") done(true); else if (e.key === "Escape") done(false); });
input.addEventListener("blur", () => done(true));
btn.replaceWith(input); input.focus();
}
const entries = new Map();
let lastTranslated = null;
const levels = new Array(160).fill(0);
// ---------- appels au serveur ----------
async function api(path, opts = {}, tries = 4) {
for (let i = 0; i < tries; i++) {
try {
const r = await fetch(path, { credentials: "same-origin", ...opts });
if (r.status === 401) { showGate(); throw new Error("auth"); }
const j = await r.json().catch(() => ({ ok: false, error: `HTTP ${r.status}` }));
if (!r.ok && !j.error) j.error = `HTTP ${r.status}`;
return j;
} catch (e) {
if (e.message === "auth") throw e;
// Render (gratuit) endort le serveur après 15 min : le premier appel le réveille.
if (i === 0) setStatus("loading", "Le serveur se réveille, jusqu'à une minute…");
await new Promise(r => setTimeout(r, 4000 * (i + 1)));
}
}
return { ok: false, error: "Serveur injoignable. Vérifie la connexion puis réessaie." };
}
const postJSON = (path, body) => api(path, { method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(body) });
// ---------- connexion ----------
function showGate() { $("gate").hidden = false; $("gateCode").focus(); }
$("gateForm").onsubmit = async (e) => {
e.preventDefault();
$("gateErr").textContent = "";
const r = await fetch("/api/login", { method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ code: $("gateCode").value }) })
.then(r => r.json()).catch(() => ({ ok: false, error: "Serveur injoignable." }));
if (r.ok) { $("gate").hidden = true; $("gateCode").value = ""; boot(); }
else $("gateErr").textContent = r.error || "Code incorrect.";
};
// ---------- état ----------
function setStatus(st, msg) { state = st; $("status").dataset.state = st; $("statusMsg").textContent = msg; }
function setRunning(r) {
running = r;
$("listenBtn").dataset.running = r; $("listenBtn").textContent = r ? "Arrêter" : "Écouter";
if (!r) setSpeaking(false);
}
function setSpeaking(s) { speaking = s; document.body.classList.toggle("speaking", s); }
// ---------- entrées ----------
function scrollEnd() { const m = $("stage"); m.scrollTop = m.scrollHeight; }
function addEntry(id, text, turn = {}) {
$("empty")?.remove();
const el = document.createElement("article");
el.className = "entry";
el.innerHTML = `<div class="who"><i></i><button class="whoName" type="button" title="Cliquer pour donner un nom à cette voix"></button><span class="ovl"></span></div>
<p class="tr"><span class="wait" aria-label="Traduction en cours"><i></i><i></i><i></i></span></p>
<p class="orig"></p><div class="meta"></div>`;
const who = el.querySelector(".who"), v = turn.speaker || 0;
if (v) {
el.dataset.v = v; who.classList.add("known");
const btn = who.querySelector(".whoName");
btn.textContent = voiceLabel(v);
btn.addEventListener("click", () => renameVoice(v, btn));
voicesSeen.add(v);
if (voicesSeen.size > 1) document.body.classList.add("multi");
}
if (turn.overlap) {
who.classList.add("over");
who.querySelector(".ovl").textContent = "voix superposées, texte moins sûr";
}
el.querySelector(".orig").textContent = text;
$("stage").appendChild(el);
entries.set(id, { el, finalAt: performance.now() });
scrollEnd();
}
function setTranslation(id, text, dst, engine) {
const e = entries.get(id); if (!e) return;
document.querySelectorAll(".entry.latest").forEach(x => x.classList.remove("latest"));
e.el.classList.add("latest");
const tr = e.el.querySelector(".tr");
tr.textContent = text; tr.dir = "auto"; tr.lang = dst; tr.classList.toggle("zh", dst === "zh");
const ms = performance.now() - e.finalAt;
e.el.querySelector(".meta").textContent =
`Traduit par ${engine.replace(/\s*\(.*\)$/, "")} en ${(ms / 1000).toFixed(1).replace(".", ",")} s`;
lastTranslated = id; scrollEnd();
}
function setError(id, msg) {
const e = entries.get(id); if (!e) return;
const tr = e.el.querySelector(".tr"); tr.textContent = msg; tr.style.color = "#E6877F";
}
function setCorrected(id, spans) {
const e = entries.get(id); if (!e || !spans.length) return;
const orig = e.el.querySelector(".orig"); orig.textContent = "";
for (const s of spans) {
if (s.heard !== undefined || s.removed) {
const m = document.createElement("mark");
m.textContent = s.t || "·";
m.title = s.heard ? `Entendu : ${s.heard}` : `« ${s.removed} » retiré`;
orig.appendChild(m);
} else orig.appendChild(document.createTextNode(s.t));
}
}
// ---------- audio -> WAV 16 kHz (format attendu par Whisper) ----------
function toWav(f32) {
const buf = new ArrayBuffer(44 + f32.length * 2), v = new DataView(buf);
const w = (o, s) => { for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i)); };
w(0, "RIFF"); v.setUint32(4, 36 + f32.length * 2, true); w(8, "WAVE"); w(12, "fmt ");
v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
v.setUint32(24, 16000, true); v.setUint32(28, 32000, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true);
w(36, "data"); v.setUint32(40, f32.length * 2, true);
for (let i = 0; i < f32.length; i++) v.setInt16(44 + i * 2, Math.max(-1, Math.min(1, f32[i])) * 0x7fff, true);
return new Blob([buf], { type: "audio/wav" });
}
async function onPhrase(audio) {
setSpeaking(false);
if (!running) return;
const id = ++segId, fd = new FormData();
fd.append("audio", toWav(audio), "phrase.wav");
fd.append("lang", S.spoken || "");
fd.append("sid", SID);
const tr = await api("/api/transcribe", { method: "POST", body: fd }, 2);
if (!tr.ok) { setStatus("error", tr.error || "Transcription impossible."); return; }
// Une phrase peut contenir plusieurs tours de parole (une personne répond à une autre) : un bloc par personne.
const turns = tr.turns || (tr.text ? [{ text: tr.text, alt: "", speaker: 0, overlap: false, lang: tr.lang }] : []);
if (!turns.length) return; // bruit écarté par les filtres
if (state !== "listening") setStatus("listening", "À l'écoute");
const ids = turns.map((t, i) => { const tid = i ? ++segId : id; addEntry(tid, t.text, t); return tid; });
for (let i = 0; i < turns.length; i++) {
const t = turns[i], tid = ids[i];
const r = await postJSON("/api/translate_live", { text: t.text, alt: t.alt || "", src: t.lang || tr.lang,
dst: S.target, context, correct: S.correct });
if (!r.ok) { setError(tid, r.error || "Traduction impossible."); continue; }
setCorrected(tid, r.spans || []);
context = [...context, r.corrected].slice(-5);
setTranslation(tid, r.translation, S.target, r.engine);
}
}
async function getStream() {
if (S.source === "tab") {
const s = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true });
s.getVideoTracks().forEach(t => t.stop());
if (!s.getAudioTracks().length) throw new Error("NO_AUDIO");
return new MediaStream(s.getAudioTracks());
}
return navigator.mediaDevices.getUserMedia({
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true } });
}
async function start() {
setStatus("loading", "Préparation de l'écoute…");
let slow = null;
try {
stream = await getStream();
// Première visite : le navigateur télécharge la détection de voix (une dizaine de Mo, gardés en cache un an).
slow = setTimeout(() => setStatus("loading",
"Chargement de la détection de voix, la première fois seulement (de quelques secondes à quelques minutes selon la connexion)…"), 2500);
myvad = await vad.MicVAD.new({
model: "v5",
baseAssetPath: "https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.31/dist/",
onnxWASMBasePath: "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",
getStream: async () => stream,
pauseStream: async () => {}, resumeStream: async (s) => s,
positiveSpeechThreshold: 0.5, negativeSpeechThreshold: 0.35,
redemptionMs: 800, preSpeechPadMs: 400, minSpeechMs: 500, // mêmes réglages que l'appli de bureau
onFrameProcessed: (p, frame) => {
let peak = 0; for (let i = 0; i < frame.length; i++) peak = Math.max(peak, Math.abs(frame[i]));
levels.push(peak); levels.shift();
},
onSpeechRealStart: () => setSpeaking(true),
onVADMisfire: () => setSpeaking(false),
onSpeechEnd: onPhrase,
});
clearTimeout(slow);
await myvad.start();
stream.getAudioTracks()[0].onended = () => { if (running) stop("La source audio a été fermée."); };
setRunning(true); setStatus("listening", "À l'écoute");
} catch (e) {
clearTimeout(slow);
await stop();
const n = e && (e.name || e.message);
setStatus("error", n === "NotAllowedError" ? "Accès au micro refusé : autorise-le dans la barre d'adresse."
: n === "NO_AUDIO" ? "Aucun son partagé : coche « Partager l'audio » dans la fenêtre de partage."
: n === "NotFoundError" ? "Aucun micro trouvé sur cet appareil."
: "Écoute impossible : " + (e && e.message || e));
}
}
async function stop(msg) {
try { if (myvad) await myvad.destroy(); } catch {}
myvad = null;
if (stream) stream.getTracks().forEach(t => t.stop());
stream = null;
setRunning(false);
if (msg) setStatus("idle", msg); else if (state !== "error") setStatus("idle", "Arrêté");
}
const toggle = () => running ? stop() : start();
// ---------- ruban de voix ----------
const cv = $("ribbon"), cx = cv.getContext("2d");
function drawRibbon() {
const dpr = window.devicePixelRatio || 1, w = cv.clientWidth, h = cv.clientHeight;
if (cv.width !== w * dpr) { cv.width = w * dpr; cv.height = h * dpr; }
cx.setTransform(dpr, 0, 0, dpr, 0, 0); cx.clearRect(0, 0, w, h);
const mid = h / 2, n = levels.length, step = w / (n - 1), amp = new Array(n);
for (let i = 0; i < n; i++) {
const a = (levels[Math.max(0, i - 1)] + 2 * levels[i] + levels[Math.min(n - 1, i + 1)]) / 4;
amp[i] = running ? Math.min(1, Math.sqrt(a) * 1.5) * (mid - 2) : 0;
}
const rgb = !running ? "58,70,92" : speaking ? "61,174,134" : "110,123,146";
cx.beginPath(); cx.moveTo(0, mid);
for (let i = 0; i < n; i++) cx.lineTo(i * step, mid - amp[i]);
for (let i = n - 1; i >= 0; i--) cx.lineTo(i * step, mid + amp[i]);
cx.closePath(); cx.fillStyle = `rgba(${rgb},${speaking ? .55 : .35})`; cx.fill();
cx.beginPath(); cx.moveTo(0, mid); cx.lineTo(w, mid); cx.strokeStyle = `rgba(${rgb},.7)`; cx.lineWidth = 1; cx.stroke();
requestAnimationFrame(drawRibbon);
}
// ---------- réglages ----------
function fill(sel, pairs, current) {
sel.innerHTML = "";
for (const [label, code] of pairs) sel.add(new Option(label, code ?? "", false, (code ?? "") === (current ?? "")));
}
function renderTargets() {
const box = $("targets"); box.innerHTML = "";
for (const [label, code] of cfg.targets) {
const b = document.createElement("button");
b.textContent = SHORT[code] || label; b.title = label; b.setAttribute("aria-pressed", S.target === code);
b.onclick = () => {
S.target = code; save(); renderTargets(); updateOutLabel();
if (document.body.classList.contains("text") && textDone && textDone === $("textIn").value.trim()) translateText();
};
box.appendChild(b);
}
}
function applySize(v) { document.documentElement.style.setProperty("--size", v + "px"); }
function openDrawer(open) { document.body.classList.toggle("drawer", open); if (open) $("source").focus(); }
// ---------- mode Texte (traduction en direct + suggestions) ----------
let textDone = "", trSeq = 0, trTimer = null, sgSeq = 0, sgTimer = null, composing = false, shown = [], autoSpaceAt = -1;
function setMode(text) {
document.body.classList.toggle("text", text);
$("modeLive").setAttribute("aria-selected", !text); $("modeText").setAttribute("aria-selected", text);
if (text) $("textIn").focus();
}
function updateCount() {
const n = $("textIn").value.length;
$("textCount").textContent = `${n.toLocaleString("fr-FR")} caractère${n > 1 ? "s" : ""}`;
$("textIn").classList.toggle("zh", /[一-鿿]/.test($("textIn").value));
}
function updateOutLabel() { $("textOutLabel").textContent = `Traduction ${TARGET_NAME[S.target] || ""}`; }
function isCJK(s) { return /[一-鿿]/.test(s); }
function overlap(text, item) {
const a = text.toLowerCase(), b = item.toLowerCase(), cjk = isCJK(item);
for (let k = Math.min(a.length, b.length); k > 0; k--) {
if (!a.endsWith(b.slice(0, k))) continue;
const before = a.charAt(a.length - k - 1);
if (cjk || !before || !/[\p{L}\p{N}]/u.test(before)) return k;
}
return 0;
}
function remainder(text, item) {
const k = overlap(text, item);
let rest = item.slice(k);
if (!rest.trim()) return "";
if (k === 0 && !isCJK(item) && text && !/\s$/.test(text)) rest = " " + rest.trimStart();
return rest;
}
function currentWord(text) { const m = text.match(/([A-Za-zÀ-ÿ]+)$/); return m ? m[1] : ""; }
function localNameItems(text) {
const w = currentWord(text);
if (w.length < 2) return [];
const lw = w.toLowerCase();
return (cfg.glossary || []).map(n => n.replace(/\s*\(.*\)$/, ""))
.filter(n => n.toLowerCase().startsWith(lw) && n.toLowerCase() !== lw).slice(0, 3).map(n => ({ item: n, name: true }));
}
function renderSuggest(list) {
const box = $("suggest"), text = $("textIn").value, seen = new Set();
shown = [];
for (const s of list) {
const rest = remainder(text, s.item);
if (!rest || seen.has(rest.trim().toLowerCase())) continue;
seen.add(rest.trim().toLowerCase()); shown.push({ ...s, rest });
}
shown = shown.slice(0, 4); box.innerHTML = "";
shown.forEach((s, i) => {
const b = document.createElement("button");
b.className = s.name ? "name" : ""; b.title = s.item; b.tabIndex = -1; b.textContent = s.rest.trim();
if (i === 0) { const k = document.createElement("kbd"); k.textContent = "Tab"; b.appendChild(k); }
b.onmousedown = (e) => e.preventDefault(); b.onclick = () => accept(i);
box.appendChild(b);
});
}
function fixAutoSpace() {
const ta = $("textIn"), v = ta.value;
if (autoSpaceAt > 0 && v.length === autoSpaceAt + 1 && /[,.;:!?)\]»]/.test(v.slice(-1)) && v[autoSpaceAt - 1] === " ") {
ta.value = v.slice(0, autoSpaceAt - 1) + v.slice(-1); ta.selectionStart = ta.selectionEnd = ta.value.length;
}
autoSpaceAt = -1;
}
function accept(i) {
const s = shown[i]; if (!s) return;
const ta = $("textIn"), auto = !isCJK(s.rest);
ta.value = ta.value + s.rest + (auto ? " " : ""); autoSpaceAt = auto ? ta.value.length : -1;
ta.selectionStart = ta.selectionEnd = ta.value.length; ta.focus();
updateCount(); renderSuggest([]); scheduleLive();
}
async function fetchSuggest() {
const text = $("textIn").value, my = ++sgSeq;
if (text.trim().length < 2) return;
const r = await postJSON("/api/suggest", { text });
if (my !== sgSeq || $("textIn").value !== text) return;
renderSuggest([...localNameItems(text), ...(r.items || []).map(item => ({ item }))]);
}
function scheduleLive() {
clearTimeout(trTimer); clearTimeout(sgTimer);
if (composing) return;
const text = $("textIn").value;
if (!text.trim()) { trSeq++; $("textOut").textContent = ""; $("textInfo").textContent = "";
$("textCopy").disabled = true; textDone = ""; renderSuggest([]); return; }
renderSuggest(localNameItems(text));
sgTimer = setTimeout(fetchSuggest, 300);
trTimer = setTimeout(() => { if (text.trim() !== textDone) translateText(true); }, 700);
}
async function translateText(live = false) {
const text = $("textIn").value.trim();
if (!text) return;
const my = ++trSeq, out = $("textOut");
out.classList.remove("error");
if (!live || !out.textContent) {
out.innerHTML = '<span class="wait" aria-label="Traduction en cours"><i></i><i></i><i></i></span>';
$("textCopy").disabled = true;
}
$("textInfo").classList.add("busy");
const target = S.target;
const r = await postJSON("/api/translate_text", { text, src: $("textSrc").value || null, dst: target });
if (my !== trSeq) return;
$("textInfo").classList.remove("busy");
if (r.ok) {
out.textContent = r.text; out.classList.toggle("zh", target === "zh"); out.lang = target;
$("textInfo").textContent = r.ms ? `Traduit par ${r.engine.replace(/\s*\(.*\)$/, "")} en ${(r.ms / 1000).toFixed(1).replace(".", ",")} s` : "";
$("textCopy").disabled = false; textDone = text;
} else { out.textContent = r.error; out.classList.add("error"); }
}
// ---------- démarrage ----------
let booted = false;
async function boot() {
const c = await api("/api/config");
if (!c.spoken) { setStatus("error", c.error || "Configuration indisponible."); return; }
cfg = c;
fill($("spoken"), cfg.spoken, S.spoken); fill($("textSrc"), [["Détection auto", null], ...cfg.spoken.filter(p => p[1])], null);
$("source").value = S.source; $("correct").checked = S.correct; $("size").value = S.size; applySize(S.size);
renderTargets(); updateOutLabel();
setStatus("idle", cfg.engines.length ? "Prêt, appuie sur Écouter" : "Aucun moteur configuré sur le serveur.");
if (booted) return;
booted = true;
$("spoken").onchange = (e) => { S.spoken = e.target.value || null; save(); };
$("source").onchange = (e) => { S.source = e.target.value; save(); if (running) setStatus("listening", "Source changée : arrête puis relance l'écoute."); };
$("correct").onchange = (e) => { S.correct = e.target.checked; save(); };
$("size").oninput = (e) => { S.size = +e.target.value; applySize(S.size); save(); };
$("listenBtn").onclick = toggle;
$("settingsBtn").onclick = () => openDrawer(true);
$("scrim").onclick = () => openDrawer(false);
$("closeDrawer").onclick = () => { openDrawer(false); $("settingsBtn").focus(); };
$("modeLive").onclick = () => setMode(false);
$("modeText").onclick = () => setMode(true);
$("textIn").oninput = () => { fixAutoSpace(); updateCount(); scheduleLive(); };
$("textIn").addEventListener("compositionstart", () => { composing = true; });
$("textIn").addEventListener("compositionend", () => { composing = false; scheduleLive(); });
$("textIn").addEventListener("keydown", (e) => {
if (e.key === "Tab" && !e.shiftKey && shown.length && !composing) { e.preventDefault(); accept(0); }
else if (e.key === "Escape" && shown.length) { e.stopPropagation(); renderSuggest([]); }
});
$("textSrc").onchange = () => { textDone = ""; scheduleLive(); };
$("textGo").onclick = () => translateText(false);
$("textClear").onclick = () => {
trSeq++; sgSeq++; clearTimeout(trTimer); clearTimeout(sgTimer);
$("textIn").value = ""; $("textOut").textContent = ""; $("textInfo").textContent = "";
$("textInfo").classList.remove("busy"); renderSuggest([]); $("textCopy").disabled = true; textDone = "";
updateCount(); $("textIn").focus();
};
$("textCopy").onclick = async () => {
try { await navigator.clipboard.writeText($("textOut").textContent); } catch {}
$("textCopy").textContent = "Copié"; setTimeout(() => $("textCopy").textContent = "Copier", 1400);
};
document.addEventListener("keydown", (e) => {
if (e.ctrlKey && e.key === "Enter" && document.body.classList.contains("text")) { e.preventDefault(); translateText(); }
if (e.ctrlKey && e.code === "Space") { e.preventDefault(); toggle(); }
if (e.key === "Escape") openDrawer(false);
});
requestAnimationFrame(drawRibbon);
}
window.__test = { onPhrase, setStream: (s) => { stream = s; } };
boot().catch(() => {});
</script>
</body>
</html>