Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(transcription): describe each model in the picker instead of the field
Elian Doran37b7719531e3
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex c142259867..cb604b3d56 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4631,7 +4631,7 @@"transcription_options": {"recognition_title": "Speech recognition","european_languages": "European languages",- "european_languages_description": "Parakeet TDT 0.6B v3 by NVIDIA recognizes 25 European languages and works out which one is spoken. High accuracy makes fewer mistakes, but it is a 2.4 GB download instead of 0.6 GB and needs about 1.6 GB more memory while recording. A model that is not downloaded yet is downloaded when you start a recording.",+ "european_languages_description": "Recognizes 25 European languages, working out which one is spoken. A model is downloaded the first time you record with it.","model_standard": "Standard","model_high_accuracy": "High accuracy","identify_speakers": "Identify speakers",@@ -4643,7 +4643,10 @@"enabled": "Meeting transcription","enabled_description": "Adds the Transcribe meeting button to the launch bar, which transcribes what you say into your microphone and what the other participants say through your speakers. Recognition runs entirely on this device, so no audio leaves it.","related_resources": "Downloaded resources",- "related_resources_description": "See the speech recognition models downloaded to this device, and delete those you no longer need."+ "related_resources_description": "See the speech recognition models downloaded to this device, and delete those you no longer need.",+ "model_standard_description": "Parakeet TDT 0.6B v3 by NVIDIA, quantized so that it runs well on most computers.",+ "model_high_accuracy_description": "Parakeet TDT 0.6B v3 by NVIDIA at full precision. It makes fewer mistakes, but needs about 1.6 GB more memory while recording.",+ "model_size": "{{size}} download"},"resources_options": {"list_title": "Resources",diff --git a/apps/client/src/widgets/type_widgets/options/transcription.css b/apps/client/src/widgets/type_widgets/options/transcription.cssindex 2eaa8c7823..3b63a58e34 100644--- a/apps/client/src/widgets/type_widgets/options/transcription.css+++ b/apps/client/src/widgets/type_widgets/options/transcription.css@@ -5,3 +5,7 @@.transcription-beta-badge {--color: var(--link-color, var(--main-text-color));}++.transcription-model-picker .description {+ white-space: pre-line;+}diff --git a/apps/client/src/widgets/type_widgets/options/transcription.spec.tsx b/apps/client/src/widgets/type_widgets/options/transcription.spec.tsxindex 6aa995b7f2..29b8f79f02 100644--- a/apps/client/src/widgets/type_widgets/options/transcription.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/transcription.spec.tsx@@ -1,3 +1,4 @@+import $ from "jquery";import { type ComponentChildren, render } from "preact";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -8,7 +9,22 @@ const mocks = vi.hoisted(() => ({saved: [] as string[],bools: {} as Record<string, boolean>,getRecordingsDirectory: vi.fn(),- savedBools: [] as [ string, boolean ][]+ savedBools: [] as [ string, boolean ][],+ getResources: vi.fn()+}));++// Bootstrap places the menu against a real layout, which happy-dom has none of.+vi.mock("bootstrap", () => ({+ Dropdown: { getOrCreateInstance: () => ({ show() {}, hide() {}, update() {}, dispose() {} }) },+ Tooltip: class { static getInstance() { return null; } }+}));++vi.mock("../../../services/server", () => ({+ default: {+ get: (url: string) => (url.startsWith("resources")+ ? mocks.getResources(url)+ : Promise.resolve([]))+ }}));vi.mock("../../../services/utils", async (importOriginal) => ({@@ -16,7 +32,9 @@ vi.mock("../../../services/utils", async (importOriginal) => ({isElectron: () => mocks.electron}));-vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));+vi.mock("../../../services/i18n", () => ({+ t: (key: string, options?: object) => (options ? `${key} ${JSON.stringify(options)}` : key)+}));vi.mock("../../react/hooks", async (importOriginal) => ({...(await importOriginal<typeof import("../../react/hooks")>()),@@ -27,17 +45,28 @@ vi.mock("../../react/hooks", async (importOriginal) => ({useTriliumOptionBool: (name: string) => [mocks.bools[name] ?? false,(value: boolean) => void mocks.savedBools.push([ name, value ])- ]+ ],+ useStaticTooltip: vi.fn(),+ useTooltip: () => ({ showTooltip: vi.fn(), hideTooltip: vi.fn() })}));-vi.mock("./components/OptionsPageHeader", () => ({default: ({ badge, below }: { badge?: ComponentChildren; below?: ComponentChildren }) =><div className="header-stub">{badge}{below}</div>}));+import { formatSize } from "../../../services/utils";import TranscriptionSettings from "./transcription";+globalThis.ResizeObserver = globalThis.ResizeObserver ?? (class {+ observe() {}+ unobserve() {}+ disconnect() {}+} as unknown as typeof ResizeObserver);++const INT8_SIZE = 670_478_772;+const FP32_SIZE = 2_549_800_429;+let host: HTMLElement;beforeEach(() => {@@ -49,6 +78,14 @@ beforeEach(() => {};mocks.savedBools = [];mocks.getRecordingsDirectory.mockReset().mockResolvedValue("/data/transcription-recordings");+ mocks.getResources.mockReset().mockResolvedValue({+ resources: [+ { id: "transcription.parakeet", size: INT8_SIZE },+ { id: "transcription.parakeet-fp32", size: FP32_SIZE }+ ],+ freeBytes: null,+ download: null+ });window.electronApi = {transcription: { getRecordingsDirectory: mocks.getRecordingsDirectory }} as unknown as typeof window.electronApi;@@ -65,28 +102,52 @@ function open() {act(() => {render(<TranscriptionSettings />, host);});- return host.querySelector<HTMLSelectElement>("select");+ return host.querySelector<HTMLElement>(".transcription-model-picker");+}++/** Opens the model picker's menu and returns its rows, which it places in the body. */+function openModelMenu() {+ const toggle = host.querySelector(".transcription-model-picker > button");+ if (!toggle) {+ throw new Error("The model picker is missing.");+ }+ act(() => {+ $(toggle).trigger("click");+ });+ return [ ...document.querySelectorAll<HTMLElement>(".dropdown-item") ];}describe("TranscriptionSettings", () => {- it("selects the model a recording runs on, and saves another choice", () => {- const select = open();- if (!select) {- throw new Error("The model selector is missing.");- }- expect([ ...select.options ].map((option) => [ option.value, option.textContent ])).toEqual([- [ "parakeet-int8", "transcription_options.model_standard" ],- [ "parakeet-fp32", "transcription_options.model_high_accuracy" ]+ it("offers each model with its size and what it is, and saves another choice", async () => {+ const picker = open();+ await act(async () => {});+ expect(mocks.getResources).toHaveBeenCalledExactlyOnceWith(+ "resources?ids=transcription.parakeet,transcription.parakeet-fp32");+ expect(picker?.querySelector("button")?.textContent)+ .toBe("transcription_options.model_high_accuracy");++ const items = openModelMenu();+ expect(items.map((item) => item.querySelector(".description")?.textContent)).toEqual([+ "transcription_options.model_standard_description\n"+ + `transcription_options.model_size {"size":"${formatSize(INT8_SIZE, 1)}"}`,+ "transcription_options.model_high_accuracy_description\n"+ + `transcription_options.model_size {"size":"${formatSize(FP32_SIZE, 1)}"}`]);- expect(select.value).toBe("parakeet-fp32");act(() => {- select.value = "parakeet-int8";- select.dispatchEvent(new Event("change", { bubbles: true }));+ items[0].click();});expect(mocks.saved).toEqual([ "parakeet-int8" ]);});+ it("leaves the size out where the resources cannot be read", async () => {+ mocks.getResources.mockRejectedValue(new Error("offline"));+ open();+ await act(async () => {});+ expect(openModelMenu()[0].querySelector(".description")?.textContent)+ .toBe("transcription_options.model_standard_description");+ });+it("turns speaker identification off", () => {open();const toggle = findToggle("identify-speakers");@@ -137,7 +198,7 @@ describe("TranscriptionSettings", () => {it("offers only the switch that turns transcription on while it is off", () => {mocks.bools.transcriptionEnabled = false;open();- expect(host.querySelector("select")).toBeNull();+ expect(host.querySelector(".transcription-model-picker")).toBeNull();expect(host.querySelector("input.switch-toggle[id^='keep-recordings-']")).toBeNull();const toggle = findToggle("transcription-enabled");@@ -161,7 +222,8 @@ describe("TranscriptionSettings", () => {it("shows the default model for a value it does not know", () => {mocks.stored = "whisper";- expect(open()?.value).toBe("parakeet-int8");+ expect(open()?.querySelector("button")?.textContent)+ .toContain("transcription_options.model_standard");});it("explains that the page applies to desktop builds only, elsewhere", () => {diff --git a/apps/client/src/widgets/type_widgets/options/transcription.tsx b/apps/client/src/widgets/type_widgets/options/transcription.tsxindex a87c7615fd..22e9391085 100644--- a/apps/client/src/widgets/type_widgets/options/transcription.tsx+++ b/apps/client/src/widgets/type_widgets/options/transcription.tsx@@ -1,14 +1,18 @@import "./transcription.css";-import { getTranscriptionModel, TRANSCRIPTION_MODELS, type TranscriptionModelId } from "@triliumnext/commons";+import {+ getTranscriptionModel, type ResourcesStatusResponse, TRANSCRIPTION_MODELS,+ type TranscriptionModelId+} from "@triliumnext/commons";import { useEffect, useState } from "preact/hooks";import { t } from "../../../services/i18n";-import { isElectron } from "../../../services/utils";+import server from "../../../services/server";+import { formatSize, isElectron } from "../../../services/utils";import { Badge } from "../../react/Badge";import { Card, OptionCardSection } from "../../react/Card";import { DirectoryLocation } from "../../react/DirectoryLink";-import FormSelect from "../../react/FormSelect";+import FormDropdownList from "../../react/FormDropdownList";import FormToggle from "../../react/FormToggle";import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";import NoItems from "../../react/NoItems";@@ -64,10 +68,25 @@ export default function TranscriptionSettings() {function RecognitionSettings() {const [ model, setModel ] = useTriliumOption("transcriptionModel");const [ speakersEnabled, setSpeakersEnabled ] = useTriliumOptionBool("transcriptionSpeakersEnabled");- const labels: Record<TranscriptionModelId, string> = {- "parakeet-int8": t("transcription_options.model_standard"),- "parakeet-fp32": t("transcription_options.model_high_accuracy")+ const sizes = useModelSizes();+ const texts: Record<TranscriptionModelId, { label: string; description: string }> = {+ "parakeet-int8": {+ label: t("transcription_options.model_standard"),+ description: t("transcription_options.model_standard_description")+ },+ "parakeet-fp32": {+ label: t("transcription_options.model_high_accuracy"),+ description: t("transcription_options.model_high_accuracy_description")+ }};+ const models = Object.values(TRANSCRIPTION_MODELS).map(({ id, resourceId }) => {+ const size = sizes[resourceId];+ const { label, description } = texts[id];+ const sizeLine = size === undefined+ ? undefined+ : t("transcription_options.model_size", { size: formatSize(size, 1) });+ return { id, label, description: sizeLine ? `${description}\n${sizeLine}` : description };+ });return (<Card heading={t("transcription_options.recognition_title")}>@@ -76,13 +95,14 @@ function RecognitionSettings() {label={t("transcription_options.european_languages")}description={t("transcription_options.european_languages_description")}>- <FormSelect- name="transcription-model"- currentValue={getTranscriptionModel(model).id}- onChange={setModel}+ <FormDropdownList+ className="transcription-model-picker"+ values={models}keyProperty="id"titleProperty="label"- values={Object.values(TRANSCRIPTION_MODELS).map(({ id }) => ({ id, label: labels[id] }))}+ descriptionProperty="description"+ currentValue={getTranscriptionModel(model).id}+ onChange={setModel}/></OptionCardSection>@@ -97,6 +117,31 @@ function RecognitionSettings() {);}+/**+ * The download size of each model's resource, by resource ID. Empty until it arrives, and if it+ * cannot be read, in which case the models are listed without their size.+ */+function useModelSizes() {+ const [ sizes, setSizes ] = useState<Record<string, number>>({});++ useEffect(() => {+ const ids = Object.values(TRANSCRIPTION_MODELS).map(({ resourceId }) => resourceId);+ let isCurrent = true;+ server.get<ResourcesStatusResponse>(`resources?ids=${ids.join(",")}`)+ .then(({ resources }) => {+ if (isCurrent) {+ setSizes(Object.fromEntries(resources.map(({ id, size }) => [ id, size ])));+ }+ })+ .catch(() => {});+ return () => {+ isCurrent = false;+ };+ }, []);++ return sizes;+}+function TroubleshootingSettings() {const [ keepRecordings, setKeepRecordings ] = useTriliumOptionBool("transcriptionKeepRecordings");const [ directory, setDirectory ] = useState<string>();