Add TTS markdown sanitization to filter unreadable symbols

This commit is contained in:
OpenCode Agent committed 2025-12-19 02:53:15 +00:00
1 parent 6c4daaeae7
commit 698ad7b020
3 files changed
+191 -2

No files matched your search

+14 -2
View File
@@ -2,6 +2,7 @@ import { useState, useRef, useCallback, useEffect, type ReactNode } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { API_BASE_URL } from '@/config'
import { TTSContext, type TTSState } from './tts-context'
import { sanitizeForTTS } from '@/lib/utils'
export { TTSContext, type TTSContextValue, type TTSState } from './tts-context'
@@ -226,13 +227,24 @@ export function TTSProvider({ children }: TTSProviderProps) {
return false
}
// Sanitize markdown for clean TTS playback
const sanitizedText = sanitizeForTTS(text)
if (!sanitizedText?.trim()) {
setError('No readable content after sanitization')
setState('error')
return false
}
stop()
stoppedRef.current = false
setError(null)
setCurrentText(text)
// Store the sanitized text for playback
setCurrentText(sanitizedText)
abortControllerRef.current = new AbortController()
chunksRef.current = splitIntoChunks(text)
chunksRef.current = splitIntoChunks(sanitizedText)
playChunk(0)
+84
View File
@@ -0,0 +1,84 @@
import { describe, it, expect } from 'vitest'
import { sanitizeForTTS } from './utils'
describe('sanitizeForTTS', () => {
it('should handle headers', () => {
expect(sanitizeForTTS('# Main Header\n## Sub Header\n### Detail')).toBe('Main Header\nSub Header\nDetail')
})
it('should handle bullet lists', () => {
expect(sanitizeForTTS('- Milk\n- Eggs\n* Bread')).toBe('Milk\nEggs\nBread')
})
it('should handle numbered lists', () => {
expect(sanitizeForTTS('1. First\n2. Second')).toBe('First\nSecond')
})
it('should remove inline code but keep content', () => {
expect(sanitizeForTTS('Use `const x = 1` here')).toBe('Use const x = 1 here')
})
it('should remove code blocks entirely', () => {
expect(sanitizeForTTS('Start\n```\ncode\n```\nEnd')).toBe('Start\nEnd')
})
it('should handle bold formatting', () => {
expect(sanitizeForTTS('This is **bold** text')).toBe('This is bold text')
})
it('should handle italic formatting', () => {
expect(sanitizeForTTS('Simple *italic* example')).toBe('Simple italic example')
})
it('should remove markdown links but keep display text', () => {
expect(sanitizeForTTS('Visit [OpenCode](https://opencode.ai)')).toBe('Visit OpenCode')
})
it('should handle images and tables', () => {
expect(sanitizeForTTS('See ![diagram](url) below:\n|A|B|\n|-|-|\n|1|2|')).toBe('See diagram below:\nA B\n1 2')
})
it('should handle blockquotes', () => {
expect(sanitizeForTTS('> Important\n> Note')).toBe('Important\nNote')
})
it('should remove citations and footnotes', () => {
expect(sanitizeForTTS('See [1] and [^2] for more')).toBe('See and for more')
})
it('should handle strikethrough', () => {
expect(sanitizeForTTS('~~removed~~')).toBe('removed')
})
it('should handle complex mixed content', () => {
const input = '# Results\nFunction: `calc()`\nSee [doc](url):\n- A\n- B'
const expected = 'Results\nFunction: calc()\nSee doc:\nA\nB'
expect(sanitizeForTTS(input)).toBe(expected)
})
it('should remove horizontal rules', () => {
expect(sanitizeForTTS('Before\n---\nAfter')).toBe('Before\nAfter')
})
it('should normalize whitespace', () => {
expect(sanitizeForTTS('Line 1\n\n\nLine 2')).toBe('Line 1\nLine 2')
})
it('should fix punctuation spacing', () => {
expect(sanitizeForTTS('Hello , world !')).toBe('Hello, world!')
})
it('should return empty string for empty input', () => {
expect(sanitizeForTTS('')).toBe('')
expect(sanitizeForTTS(' ')).toBe('')
expect(sanitizeForTTS(null as any)).toBe('')
})
it('should handle headers and lists combined', () => {
expect(sanitizeForTTS('## Shopping List\n- Milk\n- Eggs')).toBe('Shopping List\nMilk\nEggs')
})
it('should handle HTML tags', () => {
expect(sanitizeForTTS('Text with <tag>content</tag> here')).toBe('Text with content here')
})
})
+93
View File
@@ -13,3 +13,96 @@ export const GPU_ACCELERATED_STYLE: CSSProperties = {
}
export const MODAL_TRANSITION_MS = 300
/**
* Sanitizes markdown text for TTS playback by removing non-read-aloud symbols
* Converts markdown into clean, readable text suitable for speech synthesis
*/
export function sanitizeForTTS(text: string): string {
if (!text) return ''
let sanitized = text
// Remove code blocks entirely (not readable for TTS)
sanitized = sanitized.replace(/```[\s\S]*?```/g, '')
// Remove inline code, keep content: `code` -> code
sanitized = sanitized.replace(/`([^`]+)`/g, '$1')
// Remove markdown links, keep display text: [text](url) -> text
sanitized = sanitized.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
// Remove markdown images: ![alt](url) -> alt
sanitized = sanitized.replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
// Remove bold markers: **text** -> text or __text__ -> text
sanitized = sanitized.replace(/\*\*([^*]+)\*\*/g, '$1')
sanitized = sanitized.replace(/__([^_]+)__/g, '$1')
// Remove italic markers: *text* -> text or _text_ -> text
sanitized = sanitized.replace(/\*([^*]+)\*/g, '$1')
sanitized = sanitized.replace(/_([^_]+)_/g, '$1')
// Remove strikethrough: ~~text~~ -> text
sanitized = sanitized.replace(/~~([^~]+)~~/g, '$1')
// Remove headers: ### Header -> Header
sanitized = sanitized.replace(/^#{1,6}\s+/gm, '')
// Remove list markers: - item, * item, + item, or 1. item -> item
sanitized = sanitized.replace(/^\s*[-*+]\s+/gm, '')
sanitized = sanitized.replace(/^\s*\d+\.\s+/gm, '')
// Remove blockquotes: > quote -> quote
sanitized = sanitized.replace(/^>\s+/gm, '')
// Remove horizontal rules: --- or *** or ___
sanitized = sanitized.replace(/^(\*\*\*|---|___)\s*$/gm, '')
// Remove footnote references: [^1] -> remove
sanitized = sanitized.replace(/\[\^[^\]]+\]/g, '')
// Remove citation references: [1] or [1,2] -> remove
sanitized = sanitized.replace(/\[\d+(,\d+)*\]/g, '')
// Remove HTML tags: <tag> -> remove
sanitized = sanitized.replace(/<[^>]*>/g, '')
// Process tables: handle line-by-line for proper cell separation
const lines = sanitized.split('\n')
const processedLines: string[] = []
for (const line of lines) {
const trimmed = line.trim()
// Skip table separator rows (only dashes, pipes, equals, spaces)
if (/^[|\s\-_=]+$/.test(trimmed)) {
continue
}
// Handle table rows (contain pipes)
if (trimmed.includes('|')) {
// Remove pipes and multiple spaces
const cells = trimmed.split('|')
.map(s => s.trim())
.filter(s => s.length > 0)
.join(' ')
if (cells) processedLines.push(cells)
} else if (trimmed) {
// Non-table line
processedLines.push(trimmed)
}
}
sanitized = processedLines.join('\n')
// Clean up whitespace
sanitized = sanitized.replace(/\n{3,}/g, '\n\n')
sanitized = sanitized.replace(/[ \t]{2,}/g, ' ')
sanitized = sanitized.trim()
// Fix common punctuation spacing issues
sanitized = sanitized.replace(/\s+([.,!?;:])/g, '$1')
return sanitized
}