Skip to content

Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.

A word whisper split across two segments ("In" + "sel") is one word again: a segment with no leading space joins the line before it, and Japanese and Chinese lines are joined without a space

christianmat2b9f4206e5f1
diff --git a/app/src/main/asr/transcribe.ts b/app/src/main/asr/transcribe.ts
index 27e32bc6..c964853a 100644
--- a/app/src/main/asr/transcribe.ts
+++ b/app/src/main/asr/transcribe.ts
@@ -3,6 +3,7 @@ import type { Track } from '../capture'
import type { Chunk } from './chunker'
import { languageName } from './appleSpeech'
import { tokens } from './echo'
+import { joinSaid, unspaced } from '../../shared/transcript'
import { isPromptEcho, isSilenceGuess, isSubtitleCredit, withoutPromptLabel } from './hallucination'
/** What a chunk turns into: lines on meeting time. The meeting and the speaker are added where they are saved. */
@@ -35,9 +36,33 @@ export function isGarbled(text: string): boolean {
/** Noise tags and silence guesses whisper writes when nothing was said */
const NOISE = /^[[(♪*].*[\])♪*]$|^[♪\s.]+$/
-type Verbose = {
- detected_language?: string; language?: string; detected_language_probability?: number
- segments?: Array<{ start: number; end: number; text: string; avg_logprob?: number; no_speech_prob?: number; words?: Array<{ word: string; start: number; end: number }> }>
+type Heard = { start: number; end: number; text: string; avg_logprob?: number; no_speech_prob?: number; words?: Array<{ word: string; start: number; end: number }> }
+type Verbose = { detected_language?: string; language?: string; detected_language_probability?: number; segments?: Heard[] }
+
+/** how a segment starts when it carries on the one before: a letter or digit, or what closes a word or a clause */
+const WORD_ON = /^[\p{L}\p{N}\p{M}]/u, WORD_END = /[\p{L}\p{N}\p{M}'’-]$/u
+const CLOSES = /^[,.!?;:%'’\-…、。,.!?:;%]/u
+
+/**
+ * whisper ends a segment where a timestamp falls, which can be inside a word (" die In" + "sel verlassen") or before
+ * a comma. Only a leading space starts a new word, so a segment without one belongs to the line before it.
+ * Japanese and Chinese have no spaces at all: there a segment is its own line, unless it starts with a comma or a full stop.
+ */
+export function wholeSegments(segments: Heard[]): Heard[] {
+ const out: Heard[] = []
+ for (const s of segments) {
+ const prev = out[out.length - 1]
+ const on = prev && !/\s$/.test(prev.text) && prev.text.trim() && (CLOSES.test(s.text)
+ || (WORD_ON.test(s.text) && WORD_END.test(prev.text) && !unspaced([...s.text][0]) && !unspaced([...prev.text].at(-1))))
+ if (!prev || !on) { out.push({ ...s }); continue }
+ prev.text += s.text
+ prev.end = s.end
+ if (prev.words || s.words) prev.words = [...(prev.words ?? []), ...(s.words ?? [])]
+ // dropped as silence only when both parts would be
+ if (prev.avg_logprob !== undefined && s.avg_logprob !== undefined) prev.avg_logprob = Math.max(prev.avg_logprob, s.avg_logprob)
+ if (prev.no_speech_prob !== undefined && s.no_speech_prob !== undefined) prev.no_speech_prob = Math.min(prev.no_speech_prob, s.no_speech_prob)
+ }
+ return out
}
type Opts = {
@@ -119,7 +144,7 @@ export function createTranscriber(o: Opts): Transcribe {
if (!res.ok) throw new Error(`whisper-server answered ${res.status}`)
const body = (await res.json()) as Verbose
const lines: Line[] = []
- for (const s of body.segments ?? []) {
+ for (const s of wholeSegments(body.segments ?? [])) {
const said = s.text.replace(/\s+/g, ' ').trim()
// names from the prompt read back as a speaker label ("Eric and Sam Lee: so..."): the speech after it stays
const text = withoutPromptLabel(said, prompt)
@@ -133,7 +158,7 @@ export function createTranscriber(o: Opts): Transcribe {
const words = kept?.map((w) => ({ text: w.word, startMs: Math.round(c.startMs + w.start * 1000), endMs: Math.round(c.startMs + w.end * 1000) }))
lines.push({ track: c.track, startMs: Math.round(c.startMs + s.start * 1000), endMs: Math.round(c.startMs + s.end * 1000), text, ...(words?.length ? { words } : {}) })
}
- return { lines, text: lines.map((l) => l.text).join(' '), language: body.detected_language ?? body.language ?? 'auto', prob: body.detected_language_probability ?? 0 }
+ return { lines, text: joinSaid(lines.map((l) => l.text)), language: body.detected_language ?? body.language ?? 'auto', prob: body.detected_language_probability ?? 0 }
}
return async (c, opt) => {
diff --git a/app/src/shared/exportNotes.ts b/app/src/shared/exportNotes.ts
index cf0d337c..9d09eba0 100644
--- a/app/src/shared/exportNotes.ts
+++ b/app/src/shared/exportNotes.ts
@@ -7,7 +7,7 @@ import { transcriptSpeaker } from './transcript'
import { language, t } from './i18n'
import { projectWebsite } from './project'
import { docToMd, escapeText, mdToDoc, type PMNode } from './markdown'
-import { clock, turns } from './transcript'
+import { clock, joinSaid, turns } from './transcript'
import type { Meeting, NoteStatus, Segment } from './types'
const kids = (n: PMNode) => n.content ?? []
@@ -126,7 +126,7 @@ export function transcriptDoc(lines: Segment[], o: { gap?: boolean } = {}): PMNo
content.push(para(text(whoSaid(turn[0]), true), text(` (${clock(turn[0].startMs)})`)))
// in the file a blank line keeps viewers from running the name into the words
if (o.gap) content.push(para())
- content.push(para(text(turn.map((l) => l.text.trim()).join(' '))))
+ content.push(para(text(joinSaid(turn.map((l) => l.text)))))
}
return { type: 'doc', content: content.length ? content : [para()] }
}
diff --git a/app/src/shared/transcript.ts b/app/src/shared/transcript.ts
index 4b73b391..2f91c24a 100644
--- a/app/src/shared/transcript.ts
+++ b/app/src/shared/transcript.ts
@@ -17,6 +17,24 @@ export function echoRuns<L extends { track: string; hidden?: boolean; echoConfid
}
+/** writing with no spaces between words (Japanese, Chinese, Thai…), and its punctuation */
+const NO_SPACE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}\u3000-\u303f\uff01-\uff65]/u
+/** written without spaces between words */
+export const unspaced = (ch: string | undefined): boolean => !!ch && NO_SPACE.test(ch)
+
+/** Lines read as one text: a space between them, except where neither side is written with spaces */
+export function joinSaid(texts: string[]): string {
+ let out = ''
+ for (const raw of texts) {
+ const text = raw.trim()
+ if (!text) continue
+ const last = [...out].at(-1), first = [...text][0]
+ const none = !out || (unspaced(last) && (unspaced(first) || /\p{P}/u.test(first))) || (unspaced(first) && /\p{P}/u.test(last!) && [...out].some(unspaced))
+ out += (none ? '' : ' ') + text
+ }
+ return out
+}
+
/** a pause this long starts a new turn, so the time shows again */
const NEW_TURN_AFTER_MS = 30_000
diff --git a/app/test/exportNotes.test.ts b/app/test/exportNotes.test.ts
index ed546dc3..b60c559c 100644
--- a/app/test/exportNotes.test.ts
+++ b/app/test/exportNotes.test.ts
@@ -76,6 +76,9 @@ describe('transcriptDoc', () => {
it('copies as plain turns', () => {
expect(toPlainText(docToMd(transcriptDoc(segments.slice(0, 3))))).toBe('You (0:00)\nHi all. Starting now.\n\nMaya (0:06)\nHello *there*')
})
+ it('puts no space between lines in a language written without spaces', () => {
+ expect(toPlainText(docToMd(transcriptDoc([seg('me', 0, 'その長い顎には歯が並び'), seg('me', 3000, '郊外には別の手術があり。'), seg('me', 5000, 'つまり'), seg('me', 6000, 'OK then.'), seg('me', 7000, 'Right.')])))).toBe('You (0:00)\nその長い顎には歯が並び郊外には別の手術があり。つまり OK then. Right.')
+ })
})
describe('fileNameFor', () => {
diff --git a/app/test/transcribe.test.ts b/app/test/transcribe.test.ts
index e94abee8..b584edc8 100644
--- a/app/test/transcribe.test.ts
+++ b/app/test/transcribe.test.ts
@@ -304,4 +304,46 @@ describe('the language lock is reported', () => {
await tr(chunk('them', 3000))
expect(heard).toEqual([['spanish', false], ['spanish', true]])
})
+
+ // whisper-server (with VAD) ends a segment where a timestamp falls, even inside a word: only a leading space starts a new word
+ it('joins a segment that carries on a word to the one before it', async () => {
+ const s = await stub([{ language: 'german', segments: [
+ { start: 4.26, end: 8.05, text: ' Für die besten Aussichten auf Hongkong sollten sie die In', words: [{ word: ' die', start: 3.39, end: 3.63 }, { word: ' In', start: 3.63, end: 3.79 }] },
+ { start: 8.05, end: 12.6, text: 'sel verlassen und zum gegenüberliegenden Ufer von Kowloon', words: [{ word: 'sel', start: 3.79, end: 4.02 }, { word: ' verl', start: 4.02, end: 4.34 }] },
+ { start: 12.6, end: 13.63, text: ' fahren.' },
+ ] }])
+ const out = await createTranscriber({ url: async () => s.url })(chunk('them', 1000, 14))
+ expect(out.map((l) => [l.startMs, l.endMs, l.text])).toEqual([
+ [5260, 13_600, 'Für die besten Aussichten auf Hongkong sollten sie die Insel verlassen und zum gegenüberliegenden Ufer von Kowloon'],
+ [13_600, 14_630, 'fahren.'],
+ ])
+ expect(out[0].words?.map((w) => w.text)).toEqual([' die', ' In', 'sel', ' verl'])
+ })
+ it('joins a segment that starts with a comma, an ending or the rest of a hyphenated word', async () => {
+ const texts = async (...segments: string[]) => {
+ const s = await stub([{ segments: segments.map((text, i) => ({ start: i, end: i + 1, text })) }])
+ const out = (await createTranscriber({ url: async () => s.url })(chunk('them', 0, 4))).map((l) => l.text)
+ await new Promise<void>((r) => server!.close(() => r())); server = undefined
+ return out
+ }
+ expect(await texts(' so-and-so spoke of that', ', you know, some sort of research group.')).toEqual(['so-and-so spoke of that, you know, some sort of research group.'])
+ expect(await texts(' I like it, but it', "'s interesting.")).toEqual(["I like it, but it's interesting."])
+ expect(await texts(' over 28% year-on', '-year to 19')).toEqual(['over 28% year-on-year to 19'])
+ expect(await texts(' that thing from TF-', 'IDF, right?')).toEqual(['that thing from TF-IDF, right?'])
+ })
+ it('keeps sentences that start with a space as lines of their own', async () => {
+ const s = await stub([{ segments: [{ start: 0, end: 1, text: ' Hello there.' }, { start: 1, end: 2, text: ' How are you?' }, { start: 2, end: 3, text: '[BLANK_AUDIO]' }, { start: 3, end: 4, text: ' Fine' }] }])
+ expect((await createTranscriber({ url: async () => s.url })(chunk('them', 0, 4))).map((l) => l.text)).toEqual(['Hello there.', 'How are you?', 'Fine'])
+ })
+ it('keeps Japanese and Chinese segments, which never start with a space, as lines of their own', async () => {
+ const ja = await stub([{ language: 'japanese', segments: [{ start: 2.15, end: 5.11, text: 'その長い顎には70本以上の鋭い歯が並び' }, { start: 5.11, end: 6.79, text: '郊外には別の手術があり' }] }])
+ const heard: number[] = []
+ const out = await createTranscriber({ url: async () => ja.url, onLanguage: (_t, _l, chars) => heard.push(chars) })(chunk('them', 0, 8))
+ expect(out.map((l) => [l.startMs, l.text])).toEqual([[2150, 'その長い顎には70本以上の鋭い歯が並び'], [5110, '郊外には別の手術があり']])
+ // no space is counted between them either
+ expect(heard).toEqual(['その長い顎には70本以上の鋭い歯が並び郊外には別の手術があり'.length])
+ await new Promise<void>((r) => server!.close(() => r())); server = undefined
+ const zh = await stub([{ language: 'chinese', segments: [{ start: 0.87, end: 10.64, text: '学生们可以找到自己的立场' }, { start: 10.64, end: 13.43, text: ',并能够提出自己的观点。' }, { start: 13.43, end: 15, text: '钙甲等元素属于金属' }] }])
+ expect((await createTranscriber({ url: async () => zh.url })(chunk('them', 0, 16))).map((l) => [l.startMs, l.endMs, l.text])).toEqual([[870, 13_430, '学生们可以找到自己的立场,并能够提出自己的观点。'], [13_430, 15_000, '钙甲等元素属于金属']])
+ })
})
diff --git a/app/test/transcriptView.test.ts b/app/test/transcriptView.test.ts
index d673ef19..1209fa7d 100644
--- a/app/test/transcriptView.test.ts
+++ b/app/test/transcriptView.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { bubbles, clock, lineAt, recentRuns, stableKeys, turns, withLive } from '../src/shared/transcript'
+import { bubbles, clock, joinSaid, lineAt, recentRuns, stableKeys, turns, withLive } from '../src/shared/transcript'
const l = (track: 'me' | 'them', startMs: number, speaker: string | null = null, endMs = startMs + 2000) => ({ track, startMs, endMs, speaker, text: '' })
@@ -113,3 +113,14 @@ describe('a long recording draws only its latest lines (all of them stay saved)'
expect(r.runs.map((x: { lines: unknown[] }) => x.lines.length)).toEqual([150, 150, 1])
})
})
+
+describe('joinSaid', () => {
+ it('puts a space between lines, except where the writing has none', () => {
+ expect(joinSaid(['Hello there.', 'How are you?'])).toBe('Hello there. How are you?')
+ expect(joinSaid(['银河金等元素', '当然也是金属。', '钙甲等元素'])).toBe('银河金等元素当然也是金属。钙甲等元素')
+ expect(joinSaid(['สวัสดี', 'ครับ'])).toBe('สวัสดีครับ')
+ expect(joinSaid(['안녕하세요.', '반갑습니다.'])).toBe('안녕하세요. 반갑습니다.')
+ expect(joinSaid(['今日は', 'Zoom を使います'])).toBe('今日は Zoom を使います')
+ expect(joinSaid([' a ', '', 'b'])).toBe('a b')
+ })
+})