@eslaykey/dsh-breeze-tts 1.0.4 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/plan.js ADDED
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Speech planning: turn one reply into the exact list of API segments.
3
+ *
4
+ * Everything downstream (requests, budget, cache key) derives from this plan,
5
+ * so a single normalisation decides what is spoken, in which language, with
6
+ * which tone, and how many characters it costs.
7
+ */
8
+
9
+ const CJK = /[\u3400-\u4DBF\u4E00-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/g
10
+ const LATIN = /[A-Za-z]/g
11
+
12
+ const SENTENCE_MARKS = [0x3002, 0xFF01, 0xFF1F, 0x2026, 0xFF1B, 0x21, 0x3F, 0x3B, 0x0A]
13
+ .map((code) => String.fromCharCode(code))
14
+ .join('')
15
+
16
+ const MARKER_PATTERN = /<!--\s*mood:\s*([a-z-]+)\s*-->/gi
17
+ const MARKDOWN_MARKER_PATTERN = /(?<![!\\])\[\p{Extended_Pictographic}\uFE0F?\]\(breeze-mood:([a-z-]+)\)/giu
18
+ const CODE_PATTERN = /`{1,3}[^`]*`{1,3}/g
19
+
20
+ export const DEFAULT_MAX_CHARS = 900
21
+
22
+ const EMOTIONS = {
23
+ curious: ['🤔', '语气带着好奇和疑问,句尾略微上扬。'],
24
+ excited: ['🤩', '语气兴奋,语速稍快,音调偏高。'],
25
+ happy: ['😄', '语气愉快,带着笑意,句尾轻轻上扬。'],
26
+ angry: ['😠', '语气生气,音量略高,语速偏快,带着一点压迫感。'],
27
+ down: ['😞', '语气沮丧,声音发闷,语速放慢。'],
28
+ sad: ['😢', '语气低落,语速放慢,尾音下沉。'],
29
+ whisper: ['🤫', '压低声音像耳语,气息多,音量小。'],
30
+ surprised: ['😮', '语气惊讶,语调突然抬高,语速略快。'],
31
+ afraid: ['😨', '语气带着紧张和不安,声音发抖,语速不稳。'],
32
+ serious: ['😐', '语气严肃克制,吐字清楚,节奏稳定。'],
33
+ tired: ['😩', '语气疲惫,声音有气无力,语速偏慢。'],
34
+ gentle: ['😌', '语气轻柔,像在轻声安慰对方。'],
35
+ }
36
+
37
+ export const EMOTION_MARKERS = Object.entries(EMOTIONS)
38
+ .map(([emotion, [emoji]]) => '[' + emoji + '](breeze-mood:' + emotion + ')')
39
+
40
+ export function emotionInstruction(emotion) {
41
+ const id = String(emotion || '').toLowerCase()
42
+ return Object.hasOwn(EMOTIONS, id) ? EMOTIONS[id][1] : ''
43
+ }
44
+
45
+ function normalizeMarkers(text) {
46
+ return String(text ?? '').replace(MARKDOWN_MARKER_PATTERN, '<!--mood:$1-->')
47
+ }
48
+
49
+ function countMatches(text, pattern) {
50
+ const found = String(text).match(pattern)
51
+ return found ? found.length : 0
52
+ }
53
+
54
+ export function stripEmoji(text) {
55
+ let out = ''
56
+ for (const ch of String(text ?? '')) {
57
+ const cp = ch.codePointAt(0)
58
+ if (cp >= 0x1f000 && cp <= 0x1faff) continue
59
+ if (cp >= 0x2600 && cp <= 0x27bf) continue
60
+ if (cp === 0xfe0f || cp === 0x200d || cp === 0x2b50) continue
61
+ out += ch
62
+ }
63
+ return out
64
+ }
65
+
66
+ export function cleanSpeech(text, keepTags) {
67
+ let value = normalizeMarkers(text)
68
+ const tags = []
69
+ if (keepTags) {
70
+ value = value.replace(/<!--[\s\S]*?-->/g, (match) => {
71
+ tags.push(match)
72
+ return '@@TAG' + (tags.length - 1) + '@@'
73
+ })
74
+ } else {
75
+ value = value.replace(/<!--[\s\S]*?-->/g, ' ')
76
+ }
77
+ value = value.replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
78
+ value = value.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
79
+ value = value.replace(/https?:\/\/[^\s)]+/g, ' ')
80
+ value = value.replace(CODE_PATTERN, ' ')
81
+ value = value.replace(/[*_~#>|]+/g, ' ')
82
+ value = stripEmoji(value)
83
+ value = value.replace(/\s+([:,。!?;、)】」》])/g, '$1')
84
+ value = value.replace(/([(【「《])\s+/g, '$1')
85
+ value = value.replace(/\s+/g, ' ')
86
+ if (keepTags && tags.length) {
87
+ value = value.replace(/@@TAG(\d+)@@/g, (match, index) => tags[Number(index)] || ' ')
88
+ }
89
+ return value.trim()
90
+ }
91
+
92
+ export function detectLanguage(text) {
93
+ const cjk = countMatches(text, CJK)
94
+ const latin = countMatches(text, LATIN)
95
+ if (cjk === 0) return latin > 0 ? 'en' : ''
96
+ return cjk * 2 >= latin ? 'zh' : 'en'
97
+ }
98
+
99
+ export function splitSentences(text) {
100
+ const value = String(text ?? '').trim()
101
+ if (!value) return []
102
+ const parts = []
103
+ let buffer = ''
104
+ for (let index = 0; index < value.length; index += 1) {
105
+ const ch = value[index]
106
+ buffer += ch
107
+ const next = value[index + 1]
108
+ const asciiStop = ch === '.' && (
109
+ next === undefined || next === ' ' || next === '\n' || next === '\t' || next === '"' || next === "'" || next === ')' || next === ']'
110
+ )
111
+ if (SENTENCE_MARKS.includes(ch) || asciiStop) {
112
+ parts.push(buffer)
113
+ buffer = ''
114
+ }
115
+ }
116
+ if (buffer.trim()) parts.push(buffer)
117
+ return parts.map((part) => part.trim()).filter(Boolean)
118
+ }
119
+
120
+ /** Split one text into emotion-tagged units; a leading marker applies to what follows. */
121
+ export function splitByMarker(text) {
122
+ const value = normalizeMarkers(String(text ?? '').replace(CODE_PATTERN, ' '))
123
+ const parts = []
124
+ let lastIndex = 0
125
+ let current = ''
126
+ for (const match of value.matchAll(MARKER_PATTERN)) {
127
+ const before = value.slice(lastIndex, match.index)
128
+ if (before.trim()) parts.push({ text: before, emotion: current })
129
+ current = String(match[1] || '').toLowerCase()
130
+ lastIndex = match.index + match[0].length
131
+ }
132
+ const tail = value.slice(lastIndex)
133
+ if (tail.trim()) parts.push({ text: tail, emotion: current })
134
+ if (!parts.length) parts.push({ text: value.replace(MARKER_PATTERN, ' '), emotion: current })
135
+ return parts
136
+ }
137
+
138
+ function guessEmotion(sentence) {
139
+ const value = String(sentence).trim()
140
+ if (!value) return ''
141
+ if (/[??]\s*$/.test(value)) return 'curious'
142
+ if (/[!!]\s*$/.test(value)) return 'excited'
143
+ if (/(…|\.\.\.)\s*$/.test(value)) return 'sad'
144
+ return ''
145
+ }
146
+
147
+ /** Split a single sentence that alone exceeds the API limit, never breaking a code point. */
148
+ function hardSplit(sentence, maxChars) {
149
+ const chars = Array.from(String(sentence))
150
+ if (chars.length <= maxChars) return [String(sentence)]
151
+ const out = []
152
+ let cursor = 0
153
+ while (cursor < chars.length) {
154
+ let take = Math.min(maxChars, chars.length - cursor)
155
+ if (cursor + take < chars.length) {
156
+ const window = chars.slice(cursor, cursor + take).join('')
157
+ const cut = Math.max(
158
+ window.lastIndexOf(' '),
159
+ window.lastIndexOf(String.fromCharCode(0x3002)),
160
+ window.lastIndexOf(String.fromCharCode(0xFF0C)),
161
+ window.lastIndexOf(','),
162
+ )
163
+ if (cut > maxChars / 2) take = Array.from(window.slice(0, cut + 1)).length
164
+ }
165
+ out.push(chars.slice(cursor, cursor + take).join(''))
166
+ cursor += take
167
+ }
168
+ return out
169
+ }
170
+
171
+ function joinable(previous, next) {
172
+ if (!previous) return next
173
+ const lastCh = previous.slice(-1)
174
+ const firstCh = next.slice(0, 1)
175
+ if (/\s/.test(lastCh) || /\s/.test(firstCh)) return previous + next
176
+ const asciiBoth = /[A-Za-z0-9.!?]$/.test(previous) && /^[A-Za-z0-9]/.test(next)
177
+ if (asciiBoth) return previous + ' ' + next
178
+ return previous + next
179
+ }
180
+
181
+ /**
182
+ * Build the segment plan.
183
+ * @returns {{segments: Array<{text: string, language: string, emotion: string, instructions: string}>, chars: number}}
184
+ */
185
+ export function buildPlan(text, options = {}) {
186
+ const {
187
+ emotionMode = 'fixed',
188
+ baseInstructions = '',
189
+ maxChars = DEFAULT_MAX_CHARS,
190
+ } = options
191
+ const units = emotionMode === 'marker'
192
+ ? splitByMarker(text)
193
+ : [{ text, emotion: '' }]
194
+
195
+ const pieces = []
196
+ let carry = ''
197
+ for (const unit of units) {
198
+ const cleaned = cleanSpeech(unit.text)
199
+ if (!cleaned) continue
200
+ for (const sentence of splitSentences(cleaned)) {
201
+ let emotion = unit.emotion
202
+ if (!emotion && emotionMode === 'infer') {
203
+ const guessed = guessEmotion(sentence)
204
+ if (guessed) {
205
+ emotion = guessed
206
+ carry = guessed
207
+ } else if (carry && sentence.length <= 40) {
208
+ emotion = carry
209
+ }
210
+ }
211
+ const instructions = emotion ? (emotionInstruction(emotion) || baseInstructions) : baseInstructions
212
+ for (const piece of hardSplit(sentence, maxChars)) {
213
+ const last = pieces[pieces.length - 1]
214
+ const speakable = /[A-Za-z0-9\u3400-\u4DBF\u4E00-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/.test(piece)
215
+ if (!speakable) {
216
+ if (last) {
217
+ last.text += piece
218
+ continue
219
+ }
220
+ continue
221
+ }
222
+ const language = detectLanguage(piece) || (last ? last.language : 'zh')
223
+ const sameTone = last && last.instructions === instructions && last.emotion === emotion
224
+ const sameLang = last && last.language === language
225
+ if (sameTone && sameLang && Array.from(last.text).length + Array.from(piece).length <= maxChars) {
226
+ last.text = joinable(last.text, piece)
227
+ continue
228
+ }
229
+ pieces.push({ text: piece, language, emotion, instructions })
230
+ }
231
+ }
232
+ }
233
+
234
+ const segments = pieces.map((piece) => ({
235
+ text: piece.text,
236
+ language: piece.language,
237
+ emotion: piece.emotion,
238
+ instructions: piece.instructions,
239
+ }))
240
+ const chars = segments.reduce((total, segment) => total + Array.from(segment.text).length, 0)
241
+ return { segments, chars }
242
+ }