Spaces:
Running
Running
Download static/js/dataset.js from alphappp/PromptDialog-demo: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/spaces/alphappp/PromptDialog-demo/resolve/main/static/js/dataset.js
- Command line
-
hf download hf://spaces/alphappp/PromptDialog-demo/static/js/dataset.js
-
curl -L -o dataset.js https://huggingface.co/spaces/alphappp/PromptDialog-demo/resolve/main/static/js/dataset.js
12.8 kB
| import { fetchText, createAudio, escapeHtml } from "./audio.js"; | |
| const DATASET_SAMPLES = { | |
| cn: ["30s", "74s", "221s"], | |
| en: ["44s", "73s", "190s"] | |
| }; | |
| function formatTime(seconds) { | |
| const value = Math.max(0, Math.floor(seconds)); | |
| return `${Math.floor(value / 60)}:${String(value % 60).padStart(2, "0")}`; | |
| } | |
| function anonymizeDatasetSample(sample, language) { | |
| const aliases = new Map(); | |
| sample.speakers.forEach((speaker, index) => { | |
| const label = String.fromCharCode(65 + index); | |
| const name = speaker.replace(/_\d+$/u, ""); | |
| const shortName = name.replace(/^(?:abbot|duke)\s+/iu, ""); | |
| [speaker, name, shortName].forEach((alias) => { | |
| aliases.set(alias.toLowerCase(), label); | |
| }); | |
| }); | |
| const names = [...aliases.keys()].sort((a, b) => b.length - a.length); | |
| const pattern = names.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"); | |
| const matcher = new RegExp(language === "en" ? `\\b(?:${pattern})\\b` : pattern, "giu"); | |
| const replaceNames = (text) => String(text ?? "").replace(matcher, (name) => aliases.get(name.toLowerCase())); | |
| return { | |
| ...sample, | |
| speakers: sample.speakers.map((_, index) => String.fromCharCode(65 + index)), | |
| turns: sample.turns.map((turn) => ({ | |
| ...turn, | |
| speaker: aliases.get(turn.speaker.toLowerCase()), | |
| text: turn.text, | |
| context: replaceNames(turn.context) | |
| })) | |
| }; | |
| } | |
| function renderDatasetSample(sample, language, index) { | |
| sample = anonymizeDatasetSample(sample, language); | |
| const card = document.createElement("article"); | |
| card.className = "dataset-sample"; | |
| card.id = `dataset-${language}-${sample.sample_id}`; | |
| card.lang = language === "cn" ? "zh-CN" : "en"; | |
| card.hidden = true; | |
| const info = document.createElement("div"); | |
| info.className = "dataset-sample-info"; | |
| info.innerHTML = `<p class="eyebrow">${language === "cn" ? "CHINESE" : "ENGLISH"} / SAMPLE ${String(index + 1).padStart(2, "0")}</p> | |
| <h3>Conversation ${String(index + 1).padStart(2, "0")}</h3> | |
| <p class="dataset-sample-meta">${formatTime(sample.duration_seconds)} · ${sample.speaker_count} speakers · ${sample.turn_count} turns</p> | |
| <p class="dataset-speakers">${sample.speakers.map(escapeHtml).join(" / ")}</p>`; | |
| const audio = createAudio(`./static/task/dataset/${language}/${encodeURIComponent(sample.audio_file)}`); | |
| audio.setAttribute("aria-label", `${language === "cn" ? "Chinese" : "English"} dataset sample ${index + 1}`); | |
| audio.controls = false; | |
| audio.hidden = true; | |
| info.appendChild(audio); | |
| const hint = document.createElement("p"); | |
| hint.className = "dataset-hint"; | |
| hint.textContent = "Click a turn to play from there. Drag to select and copy text."; | |
| info.appendChild(hint); | |
| const playbackStatus = document.createElement("p"); | |
| playbackStatus.className = "dataset-playback-status"; | |
| playbackStatus.setAttribute("role", "status"); | |
| info.appendChild(playbackStatus); | |
| const transcript = document.createElement("div"); | |
| transcript.className = "dataset-transcript"; | |
| transcript.setAttribute("role", "region"); | |
| transcript.setAttribute("aria-label", "Aligned transcript and narrative context"); | |
| transcript.tabIndex = 0; | |
| const heading = document.createElement("p"); | |
| heading.className = "case-section-title"; | |
| heading.textContent = "TRANSCRIPT / NARRATIVE CONTEXT"; | |
| transcript.appendChild(heading); | |
| // A local file URL also permits accurate FLAC seeking on static servers | |
| // that do not support HTTP byte ranges. Load it only when seeking. | |
| let seekSource; | |
| const prepareSeeking = () => { | |
| if (!seekSource) { | |
| seekSource = (async () => { | |
| const response = await fetch(audio.src); | |
| if (!response.ok) throw new Error("Unable to load audio"); | |
| const blob = await response.blob(); | |
| await new Promise((resolve, reject) => { | |
| const cleanup = () => { | |
| audio.removeEventListener("loadedmetadata", ready); | |
| audio.removeEventListener("error", failed); | |
| }; | |
| const ready = () => { cleanup(); resolve(); }; | |
| const failed = () => { cleanup(); reject(new Error("Unable to decode audio")); }; | |
| audio.addEventListener("loadedmetadata", ready); | |
| audio.addEventListener("error", failed); | |
| audio.src = URL.createObjectURL(blob); | |
| audio.load(); | |
| }); | |
| })().catch((error) => { seekSource = null; throw error; }); | |
| } | |
| return seekSource; | |
| }; | |
| const player = document.createElement("div"); | |
| player.className = "dataset-player"; | |
| const playIcon = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m9 5 11 7-11 7z" fill="currentColor"/></svg>'; | |
| const pauseIcon = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 5h4v14H7zm6 0h4v14h-4z" fill="currentColor"/></svg>'; | |
| player.innerHTML = `<button class="dataset-play" type="button" aria-label="Play sample">${playIcon}</button> | |
| <div class="dataset-progress"><div class="dataset-player-label"><span>LISTEN TO THE RECORDING</span><span class="dataset-clock">0:00 / ${formatTime(sample.duration_seconds)}</span></div><input class="dataset-seek" type="range" min="0" max="${sample.duration_seconds}" step="0.01" value="0" aria-label="Audio position" aria-valuetext="0:00" style="--progress:0%"></div> | |
| <button class="dataset-mute" type="button" aria-label="Mute audio" aria-pressed="false"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M11 5 6 9H3v6h3l5 4V5Z" fill="currentColor"/><path d="M15 8a6 6 0 0 1 0 8m3-11a10 10 0 0 1 0 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg></button>`; | |
| const playButton = player.querySelector(".dataset-play"); | |
| const slider = player.querySelector(".dataset-seek"); | |
| const clock = player.querySelector(".dataset-clock"); | |
| const muteButton = player.querySelector(".dataset-mute"); | |
| let dragging = false; | |
| const updatePosition = (time) => { | |
| slider.value = time; | |
| slider.style.setProperty("--progress", `${Math.min(100, time / sample.duration_seconds * 100)}%`); | |
| slider.setAttribute("aria-valuetext", formatTime(time)); | |
| clock.textContent = `${formatTime(time)} / ${formatTime(sample.duration_seconds)}`; | |
| }; | |
| const updatePlaying = () => { | |
| playButton.innerHTML = audio.paused ? playIcon : pauseIcon; | |
| playButton.setAttribute("aria-label", audio.paused ? "Play sample" : "Pause sample"); | |
| }; | |
| playButton.addEventListener("click", async () => { | |
| if (!audio.paused) { audio.pause(); return; } | |
| try { | |
| await audio.play(); | |
| playbackStatus.textContent = ""; | |
| } catch { | |
| playbackStatus.textContent = "Unable to play this sample. Please try again."; | |
| } | |
| }); | |
| slider.addEventListener("input", () => { dragging = true; updatePosition(Number(slider.value)); }); | |
| slider.addEventListener("change", async () => { | |
| const target = Number(slider.value); | |
| const resume = !audio.paused; | |
| try { | |
| playbackStatus.textContent = "Loading audio…"; | |
| await prepareSeeking(); | |
| audio.currentTime = target; | |
| if (resume && !card.hidden) await audio.play(); | |
| playbackStatus.textContent = ""; | |
| } catch { | |
| playbackStatus.textContent = "Unable to seek. Please try again."; | |
| } finally { dragging = false; } | |
| }); | |
| muteButton.addEventListener("click", () => { audio.muted = !audio.muted; }); | |
| audio.addEventListener("volumechange", () => { | |
| muteButton.setAttribute("aria-pressed", String(audio.muted)); | |
| muteButton.setAttribute("aria-label", audio.muted ? "Unmute audio" : "Mute audio"); | |
| }); | |
| ["play", "pause", "ended"].forEach((event) => audio.addEventListener(event, updatePlaying)); | |
| audio.addEventListener("timeupdate", () => { if (!dragging) updatePosition(audio.currentTime); }); | |
| audio.addEventListener("error", () => { playbackStatus.textContent = "Unable to load this recording. Please try again."; }); | |
| info.insertBefore(player, hint); | |
| const rows = sample.turns.map((turn) => { | |
| const row = document.createElement("div"); | |
| row.className = "dataset-turn"; | |
| const seek = document.createElement("button"); | |
| seek.type = "button"; | |
| seek.className = "dataset-timestamp"; | |
| seek.textContent = formatTime(turn.start); | |
| seek.setAttribute("aria-label", `Play ${turn.speaker} at ${formatTime(turn.start)}`); | |
| row.addEventListener("click", async (event) => { | |
| const selection = window.getSelection(); | |
| if (event.target !== seek && selection?.rangeCount && !selection.isCollapsed && | |
| selection.getRangeAt(0).intersectsNode(row)) return; | |
| try { | |
| playbackStatus.textContent = "Loading audio…"; | |
| await prepareSeeking(); | |
| if (card.hidden) return; | |
| audio.currentTime = turn.start; | |
| await audio.play(); | |
| playbackStatus.textContent = ""; | |
| } catch { | |
| playbackStatus.textContent = "Unable to play this sample. Please try the audio controls."; | |
| } | |
| }); | |
| const text = document.createElement("div"); | |
| text.className = "dataset-turn-text"; | |
| const speakerIndex = sample.speakers.indexOf(turn.speaker); | |
| text.innerHTML = `<strong class="dataset-speaker speaker-${speakerIndex % 3}">${escapeHtml(turn.speaker)}</strong><p>${escapeHtml(turn.text)}</p>`; | |
| if (turn.context) { | |
| const context = document.createElement("p"); | |
| context.className = "dataset-context"; | |
| context.textContent = turn.context; | |
| text.appendChild(context); | |
| } | |
| row.append(seek, text); | |
| transcript.appendChild(row); | |
| return row; | |
| }); | |
| let activeIndex = -1; | |
| const highlightTurn = () => { | |
| const nextIndex = sample.turns.findIndex((turn) => audio.currentTime >= turn.start && audio.currentTime < turn.end); | |
| if (nextIndex === activeIndex) return; | |
| if (activeIndex >= 0) rows[activeIndex].classList.remove("is-current"); | |
| if (nextIndex >= 0) { | |
| rows[nextIndex].classList.add("is-current"); | |
| // Keep playback within the transcript panel without moving the page. | |
| if (!audio.paused) { | |
| const rowBox = rows[nextIndex].getBoundingClientRect(); | |
| const panelBox = transcript.getBoundingClientRect(); | |
| if (rowBox.top < panelBox.top || rowBox.bottom > panelBox.bottom) { | |
| transcript.scrollTop += rowBox.top - panelBox.top - 45; | |
| } | |
| } | |
| } | |
| activeIndex = nextIndex; | |
| }; | |
| audio.addEventListener("timeupdate", highlightTurn); | |
| audio.addEventListener("seeked", highlightTurn); | |
| audio.addEventListener("ended", () => { | |
| rows.forEach((row) => row.classList.remove("is-current")); | |
| activeIndex = -1; | |
| }); | |
| card.append(info, transcript); | |
| return card; | |
| } | |
| async function initDataset() { | |
| const samples = await Promise.all(Object.entries(DATASET_SAMPLES).flatMap(([language, ids]) => | |
| ids.map(async (id, index) => ({ language, index, sample: JSON.parse(await fetchText(`./static/task/dataset/${language}/${id}.json`)) })) | |
| )); | |
| const content = document.getElementById("dataset-content"); | |
| content.replaceChildren(...samples.map(({ sample, language, index }) => renderDatasetSample(sample, language, index))); | |
| const selected = { cn: DATASET_SAMPLES.cn[0], en: DATASET_SAMPLES.en[0] }; | |
| let currentLanguage = "cn"; | |
| const selectSample = (id) => { | |
| selected[currentLanguage] = id; | |
| content.querySelectorAll(".dataset-sample").forEach((card) => { | |
| card.hidden = card.id !== `dataset-${currentLanguage}-${id}`; | |
| if (card.hidden) card.querySelector("audio").pause(); | |
| }); | |
| document.querySelectorAll(".dataset-sample-button").forEach((button) => { | |
| button.setAttribute("aria-pressed", String(button.dataset.sample === id)); | |
| }); | |
| }; | |
| const selectLanguage = (language) => { | |
| currentLanguage = language; | |
| document.querySelectorAll("[data-language]").forEach((button) => { | |
| button.setAttribute("aria-pressed", String(button.dataset.language === language)); | |
| }); | |
| const buttons = samples.filter((entry) => entry.language === language).map(({ sample, index }) => { | |
| const button = document.createElement("button"); | |
| button.type = "button"; | |
| button.className = "dataset-sample-button"; | |
| button.dataset.sample = sample.sample_id; | |
| button.innerHTML = `<span>Sample ${index + 1}</span><span class="sample-duration">${formatTime(sample.duration_seconds)}</span>`; | |
| button.addEventListener("click", () => selectSample(sample.sample_id)); | |
| return button; | |
| }); | |
| document.getElementById("dataset-picker").replaceChildren(...buttons); | |
| selectSample(selected[language]); | |
| }; | |
| document.querySelectorAll("[data-language]").forEach((button) => { | |
| button.addEventListener("click", () => selectLanguage(button.dataset.language)); | |
| }); | |
| selectLanguage(currentLanguage); | |
| } | |
| initDataset().catch((error) => { | |
| document.getElementById("dataset-content").textContent = `Unable to load dataset samples: ${error.message}`; | |
| }); | |