diff --git a/tests/speech-tables.test.ts b/tests/speech-tables.test.ts new file mode 100644 index 0000000..b7f5715 --- /dev/null +++ b/tests/speech-tables.test.ts @@ -0,0 +1,36 @@ +/** + * speech-tables — 마크다운 표를 소리 내어 읽기 좋은 문장으로. + * 표본: 2026-10-17 경남 누적 강수량 표(창원·진주·김해), 미국 국채 2열 표. + */ +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const T = require('../web-ui/js/voice/speech-tables.js'); + +describe('narrateTablesInText', () => { + test('첫 칸을 주어, 머리글을 붙여 읽는다', () => { + const out = T.narrateTablesInText('| 지역 | 기온 | 습도 |\n|---|---|---|\n| 창원 | 20.8°C | 58% |\n| 진주 | 14.5°C | 81% |'); + assert.equal(out, '창원은 기온 20.8°C, 습도 58%. 진주는 기온 14.5°C, 습도 81%.'); + }); + test('받침 유무로 은/는, 한글이 아니면 쉼표', () => { + assert.ok(T.narrateTablesInText('| 이름 | 값 |\n|---|---|\n| 김해 | 1 |').startsWith('김해는')); + assert.ok(T.narrateTablesInText('| 이름 | 값 |\n|---|---|\n| 부산 | 1 |').startsWith('부산은')); + assert.ok(T.narrateTablesInText('| 이름 | 값 |\n|---|---|\n| 학생1 | 70 |').startsWith('학생1, 70')); + }); + test('2열 표는 항목은 값으로', () => { + assert.equal(T.narrateTablesInText('| 항목 | 값 |\n|:--|--:|\n| 총 국채 | 40조 달러 |'), '총 국채는 40조 달러.'); + }); + test('행이 많으면 앞 5행만 읽고 나머지는 화면으로 안내', () => { + const rows = Array.from({ length: 9 }, (_, i) => `| 학생${i + 1} | ${70 + i} |`).join('\n'); + const out = T.narrateTablesInText(`| 이름 | 점수 |\n|---|---|\n${rows}`); + assert.ok(out.includes('나머지 4개 항목은 화면을 봐 주세요.')); + assert.ok(!out.includes('학생6')); + }); + test('빈 칸·대시는 건너뛰고, 표 앞뒤 문장은 보존', () => { + const out = T.narrateTablesInText('앞말\n| 지역 | 기온 | 습도 |\n|---|---|---|\n| 김해 | 20.3°C | - |\n뒷말'); + assert.equal(out, '앞말\n김해는 기온 20.3°C.\n뒷말'); + }); + test('표가 없으면 그대로', () => { + assert.equal(T.narrateTablesInText('그냥 문장입니다.'), '그냥 문장입니다.'); + }); +}); diff --git a/web-ui/html/index.html b/web-ui/html/index.html index de119c0..bd5de2b 100644 --- a/web-ui/html/index.html +++ b/web-ui/html/index.html @@ -2087,6 +2087,7 @@ + diff --git a/web-ui/js/app/voice.js b/web-ui/js/app/voice.js index 752f09b..b5c4a41 100644 --- a/web-ui/js/app/voice.js +++ b/web-ui/js/app/voice.js @@ -287,6 +287,7 @@ function _hourReplacer(m, numStr, suffix) { // stop generating audio entirely instead of just mispronouncing it, and a // bare "°C"/"°F" gets read as "그램"(grams) instead of degrees. function _cleanForSpeech(text) { + if (typeof window !== 'undefined' && window.SpeechTables) text = window.SpeechTables.narrateTablesInText(text || ''); // 표 → 문장(speech-tables.js) text = (typeof window !== 'undefined' && window.spellUnitsForSpeech) ? window.spellUnitsForSpeech(text || '') : (text || ''); // g/kg/GB/Hz… 단위 낭독(speech-units.js) return (text || '') .replace(/!\[.*?\]\(.*?\)/g, '') diff --git a/web-ui/js/voice/speech-tables.js b/web-ui/js/voice/speech-tables.js new file mode 100644 index 0000000..0c2faf1 --- /dev/null +++ b/web-ui/js/voice/speech-tables.js @@ -0,0 +1,80 @@ +// speech-tables.js — 마크다운 표를 소리 내어 읽기 좋은 문장으로 +// +// 지금까지는 표의 각 행을 "창원, 0 mm, 20.8°C, 58%"처럼 칸 값만 이어 읽었다. 머리글이 사라져서 숫자가 무엇인지 +// 알 수 없고, 행이 많으면 끝없이 이어진다. 여기서는 +// · 첫 칸을 주어로, 나머지 칸은 "머리글 값"으로 읽고 → "창원은 누적 강수량 0mm, 기온 20.8도, 습도 58퍼센트." +// · 2열짜리 표는 "항목은 값"으로 읽고 +// · 행이 많으면 앞의 몇 행만 읽고 "나머지는 화면을 보세요"로 마무리한다. +// 통화(스트리밍)는 표가 끝날 때까지 행을 모았다가 narrateTableRows로, 읽기 버튼(전체 텍스트)은 +// narrateTablesInText로 쓴다. +(function (root) { + var MAX_ROWS = 5; // 소리로는 이 정도까지만 + var MAX_COLS = 6; + + function splitCells(line) { + var t = String(line).trim(); + if (t.charAt(0) === '|') t = t.slice(1); + if (t.charAt(t.length - 1) === '|') t = t.slice(0, -1); + return t.split('|').map(function (c) { return c.replace(/\*\*|__|`/g, '').trim(); }); + } + + function isSeparator(line) { + return /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(line); + } + + // 받침 유무로 은/는. 한글이 아닌 끝글자(숫자·영문)는 판단하지 않고 null → 쉼표로 이어 읽는다. + function eunNeun(word) { + var ch = word.charAt(word.length - 1); + var c = ch.charCodeAt(0); + if (c < 0xac00 || c > 0xd7a3) return null; + return ((c - 0xac00) % 28) ? '은' : '는'; + } + + function empty(v) { return !v || /^[-–—·]+$/.test(v) || v === 'N/A' || v === '없음'; } + + function narrateTableRows(lines) { + var rows = lines.filter(function (l) { return !isSeparator(l); }).map(splitCells); + if (!rows.length) return ''; + var header = rows[0]; + var body = rows.slice(1); + if (!body.length) return header.filter(Boolean).join(', ') + '.'; + var cols = Math.min(header.length, MAX_COLS); + var out = []; + var shown = body.slice(0, MAX_ROWS); + shown.forEach(function (r) { + var subject = r[0] || ''; + var parts = []; + for (var i = 1; i < cols; i++) { + var val = r[i]; + if (empty(val)) continue; + parts.push(cols === 2 ? val : ((empty(header[i]) ? '' : header[i] + ' ') + val)); + } + if (!parts.length) { if (subject) out.push(subject + '.'); return; } + var josa = subject ? eunNeun(subject) : null; + var lead = subject ? (josa ? subject + josa + ' ' : subject + ', ') : ''; + out.push(lead + parts.join(', ') + '.'); + }); + if (body.length > MAX_ROWS) out.push('나머지 ' + (body.length - MAX_ROWS) + '개 항목은 화면을 봐 주세요.'); + return out.join(' '); + } + + // 전체 텍스트 안의 표 블록(연속된 '|' 줄)을 문장으로 치환 + function narrateTablesInText(text) { + var lines = String(text == null ? '' : text).split('\n'); + var out = []; + for (var i = 0; i < lines.length; ) { + if (/^\s*\|/.test(lines[i])) { + var block = []; + while (i < lines.length && /^\s*\|/.test(lines[i])) block.push(lines[i++]); + out.push(narrateTableRows(block)); + } else { + out.push(lines[i++]); + } + } + return out.join('\n'); + } + + var api = { narrateTableRows: narrateTableRows, narrateTablesInText: narrateTablesInText, isTableLine: function (l) { return /^\s*\|/.test(l); } }; + if (typeof module !== 'undefined' && module.exports) module.exports = api; + if (root) root.SpeechTables = api; +})(typeof window !== 'undefined' ? window : (typeof globalThis !== 'undefined' ? globalThis : null)); diff --git a/web-ui/js/voice/voice-call.js b/web-ui/js/voice/voice-call.js index d5e1985..e20e2db 100644 --- a/web-ui/js/voice/voice-call.js +++ b/web-ui/js/voice/voice-call.js @@ -274,7 +274,7 @@ setCaption(''); const text = (msg.text || '').trim(); if (!text) { state = 'listening'; setStatus('듣는 중…'); break; } - spokenUpTo = 0; pendingTts = ''; spokenKeys.clear(); + spokenUpTo = 0; pendingTts = ''; spokenKeys.clear(); tableLines = []; setStatus('생각 중…'); // 사후 보정(고유어 표기 정리) — 서버 /api/voice/correct. 실패·지연 시 원문 그대로 보낸다(통화가 막히면 안 됨). correctSttText(text).then((fixed) => { @@ -510,6 +510,31 @@ } } + // ── 표(마크다운) 낭독 ───────────────────────────────────────────────────────── + // 표의 행은 스트리밍으로 한 줄씩 들어오지만, 머리글과 함께 읽어야 의미가 산다. 그래서 표 줄('|'로 시작)은 모아 두었다가 + // 표가 끝나면(다음 일반 줄이 오거나 턴이 끝나면) speech-tables.js로 "창원은 기온 20.8도, 습도 58퍼센트."처럼 풀어 읽는다. + let tableLines = []; + + function flushTable() { + if (!tableLines.length) return; + const lines = tableLines; + tableLines = []; + const narrated = window.SpeechTables ? window.SpeechTables.narrateTableRows(lines) : ''; + if (!narrated) return; + flushPendingTts(); + for (const sentence of narrated.split(/(?<=\.)\s+/)) if (sentence.trim()) enqueueSentence(sentence.trim()); + } + + function feedSentence(text, isLineBreak) { + if (text.indexOf('\n') !== -1) { // 여러 줄이 한 덩어리로 온 경우(턴 종료 시 남은 꼬리 등) + for (const line of text.split('\n')) if (line.trim()) feedSentence(line.trim(), true); + return; + } + if (window.SpeechTables && window.SpeechTables.isTableLine(text)) { tableLines.push(text); return; } + flushTable(); + bufferSentence(text, isLineBreak); + } + function splitCompleteSentences(text) { const sentences = []; let start = 0; @@ -552,6 +577,7 @@ // offset into the old string and must be dropped before the new text arrives. window._voiceCallResetSpoken = function () { spokenUpTo = 0; + tableLines = []; }; // Hooked from app.js's SSE token handler — only acts while a call is active. @@ -561,7 +587,7 @@ const { sentences, consumedLength } = splitCompleteSentences(tail); if (consumedLength > 0) { spokenUpTo += consumedLength; - for (const s of sentences) bufferSentence(s.text, s.isLineBreak); + for (const s of sentences) feedSentence(s.text, s.isLineBreak); } }; @@ -569,7 +595,8 @@ window._voiceCallOnTurnDone = function (finalText) { if (!active) return; const remaining = (finalText || '').slice(spokenUpTo).trim(); - if (remaining) bufferSentence(remaining); + if (remaining) feedSentence(remaining); + flushTable(); flushPendingTts(); spokenUpTo = 0; };