improvements: gapGPT keys and apis used instead of openrouter instead.
This commit is contained in:
@@ -56,16 +56,18 @@ SMS_IR_TEMPLATE_ID=123456
|
||||
# ── Voice treatment entry ──────────────────────────────────────────────────────
|
||||
# Without OPENROUTER_API_KEY the microphone button does not render at all.
|
||||
OPENROUTER_API_KEY=
|
||||
# OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
|
||||
# Local GapGPT, reachable from Iran. Leave unset to keep the code default
|
||||
# https://openrouter.ai/api/v1.
|
||||
# OPENROUTER_BASE_URL=https://api.gapgpt.app/v1
|
||||
|
||||
# Locales the microphone is offered in. An unknown locale here fails at boot.
|
||||
# VOICE_ENABLED_LOCALES=fa,en,nl
|
||||
|
||||
# Models, overridable per locale (VOICE_ASR_MODEL_FA, VOICE_LLM_MODEL_NL, ...).
|
||||
# All locales share these today; the per-locale override exists so Persian can be
|
||||
# repointed at a specialist ASR vendor without a code change.
|
||||
# VOICE_ASR_MODEL=openai/whisper-1
|
||||
# VOICE_LLM_MODEL=google/gemini-3.7-flash
|
||||
# GapGPT ids below. Leave unset to keep the code defaults openai/whisper-1 and
|
||||
# google/gemini-3.7-flash.
|
||||
# VOICE_ASR_MODEL=gapgpt/whisper-1
|
||||
# VOICE_LLM_MODEL=gemini-3.7-flash
|
||||
# VOICE_ASR_PROVIDER_FA=openrouter
|
||||
# VOICE_LLM_PROVIDER_FA=openrouter
|
||||
|
||||
|
||||
@@ -28,8 +28,9 @@ const CATALOG = {
|
||||
};
|
||||
|
||||
type ChatBody = {
|
||||
model: string;
|
||||
temperature: number;
|
||||
provider: { require_parameters: boolean };
|
||||
provider?: { require_parameters: boolean };
|
||||
response_format: { type: string; json_schema: { strict: boolean } };
|
||||
messages: { role: string; content: string }[];
|
||||
};
|
||||
@@ -60,25 +61,29 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('OpenRouterAsrProvider', () => {
|
||||
it('posts base64 JSON with the language hint, per the documented STT contract', async () => {
|
||||
it('posts a multipart file with the language hint', async () => {
|
||||
const spy = mockFetch({
|
||||
ok: true,
|
||||
body: { text: ' سلام ', usage: { seconds: 12, cost: 0.002 } },
|
||||
});
|
||||
const clip = Buffer.from('clip-bytes');
|
||||
|
||||
const result = await new OpenRouterAsrProvider(CONFIG).transcribe(
|
||||
{ data: 'BASE64', format: 'webm' },
|
||||
{ data: clip.toString('base64'), format: 'webm' },
|
||||
'fa',
|
||||
);
|
||||
|
||||
const [url, init] = spy.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('https://openrouter.test/api/v1/audio/transcriptions');
|
||||
expect(init.headers).toMatchObject({ Authorization: 'Bearer test-key' });
|
||||
expect(JSON.parse(init.body as string)).toEqual({
|
||||
model: 'm',
|
||||
input_audio: { data: 'BASE64', format: 'webm' },
|
||||
language: 'fa',
|
||||
});
|
||||
expect(init.headers).toEqual({ Authorization: 'Bearer test-key' });
|
||||
const form = init.body as FormData;
|
||||
expect(form.get('model')).toBe('m');
|
||||
expect(form.get('language')).toBe('fa');
|
||||
const file = form.get('file') as File;
|
||||
expect(file).toBeInstanceOf(File);
|
||||
expect(file.name).toBe('audio.webm');
|
||||
expect(file.type).toBe('audio/webm');
|
||||
expect(Buffer.from(await file.arrayBuffer()).equals(clip)).toBe(true);
|
||||
expect(result.text).toBe('سلام');
|
||||
expect(result.usage).toEqual({ seconds: 12, costUsd: 0.002 });
|
||||
});
|
||||
@@ -187,6 +192,25 @@ describe('OpenRouterExtractionProvider', () => {
|
||||
expect(result.costUsd).toBe(0.0008);
|
||||
});
|
||||
|
||||
it('keeps the JSON schema and omits OpenRouter routing on GapGPT', async () => {
|
||||
const spy = mockFetch({
|
||||
ok: true,
|
||||
body: { choices: [{ message: { content: wireContent } }] },
|
||||
});
|
||||
|
||||
await new OpenRouterExtractionProvider({
|
||||
...CONFIG,
|
||||
baseUrl: 'https://api.gapgpt.app/v1',
|
||||
}).extract('x', CATALOG, 'fa');
|
||||
|
||||
const body = parseBody(spy);
|
||||
expect(body.model).toBe('m');
|
||||
expect(body.temperature).toBe(0);
|
||||
expect(body.response_format.type).toBe('json_schema');
|
||||
expect(body.response_format.json_schema.strict).toBe(true);
|
||||
expect(body.provider).toBeUndefined();
|
||||
});
|
||||
|
||||
it('sends the catalog codes and lab ids the model is allowed to choose from', async () => {
|
||||
const spy = mockFetch({
|
||||
ok: true,
|
||||
|
||||
@@ -35,6 +35,36 @@ function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
/** OpenRouter routing. GapGPT and other OpenAI-compatible hosts reject this field. */
|
||||
function usesOpenRouterRouting(baseUrl: string): boolean {
|
||||
return baseUrl.toLowerCase().includes('openrouter');
|
||||
}
|
||||
|
||||
const AUDIO_MIME: Record<string, string> = {
|
||||
webm: 'audio/webm',
|
||||
mp4: 'audio/mp4',
|
||||
m4a: 'audio/mp4',
|
||||
aac: 'audio/aac',
|
||||
ogg: 'audio/ogg',
|
||||
wav: 'audio/wav',
|
||||
mp3: 'audio/mpeg',
|
||||
flac: 'audio/flac',
|
||||
};
|
||||
|
||||
/** Multipart `file` upload. OpenRouter and GapGPT both accept this shape. */
|
||||
function transcriptionForm(audio: AudioInput, model: string, language: string) {
|
||||
const bytes = Buffer.from(audio.data, 'base64');
|
||||
const form = new FormData();
|
||||
form.append(
|
||||
'file',
|
||||
new Blob([bytes], { type: AUDIO_MIME[audio.format] ?? 'application/octet-stream' }),
|
||||
`audio.${audio.format}`,
|
||||
);
|
||||
form.append('model', model);
|
||||
form.append('language', language);
|
||||
return form;
|
||||
}
|
||||
|
||||
const errorLogger = new Logger('OpenRouterVoice');
|
||||
|
||||
async function readError(
|
||||
@@ -58,7 +88,7 @@ async function readError(
|
||||
);
|
||||
}
|
||||
|
||||
/** Speech → text via OpenRouter's transcription endpoint (whisper-1 and friends). */
|
||||
/** Speech → text via multipart `/audio/transcriptions` (Whisper on OpenRouter or GapGPT). */
|
||||
export class OpenRouterAsrProvider implements AsrProvider {
|
||||
private readonly logger = new Logger(OpenRouterAsrProvider.name);
|
||||
|
||||
@@ -76,13 +106,8 @@ export class OpenRouterAsrProvider implements AsrProvider {
|
||||
signal,
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.config.apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: this.config.model,
|
||||
input_audio: { data: audio.data, format: audio.format },
|
||||
language: localeHint,
|
||||
}),
|
||||
body: transcriptionForm(audio, this.config.model, localeHint),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -126,7 +151,10 @@ export class OpenRouterExtractionProvider implements ExtractionProvider {
|
||||
temperature: 0,
|
||||
// Only route to endpoints that actually honour the JSON schema — otherwise OpenRouter may
|
||||
// pick a provider that treats it as a hint and returns prose, failing intermittently.
|
||||
provider: { require_parameters: true },
|
||||
// GapGPT has no such field and rejects the request when it is present.
|
||||
...(usesOpenRouterRouting(this.config.baseUrl)
|
||||
? { provider: { require_parameters: true } }
|
||||
: {}),
|
||||
messages: buildExtractionPrompt(transcript, catalog, localeHint),
|
||||
response_format: {
|
||||
type: 'json_schema',
|
||||
|
||||
@@ -62,16 +62,12 @@ export function TodaySubscriptionKpiCard({ subscription }: TodaySubscriptionKpiC
|
||||
<div className="flex h-full min-h-0 min-w-0 items-center justify-center">
|
||||
<TodayRadialGaugeChart
|
||||
size="sm"
|
||||
percent={
|
||||
subscription.seatsUnlimited || !subscription.hasActivePlan
|
||||
? 0
|
||||
: subscription.seatsPercent
|
||||
}
|
||||
percent={subscription.hasActivePlan ? subscription.seatsPercent : 0}
|
||||
completed={subscription.seatsUsed}
|
||||
total={seatsRatioTotal}
|
||||
percentLabel={seatsPercentLabel}
|
||||
tasksLabel={seatsTasksLabel}
|
||||
showRatio={!subscription.seatsUnlimited && seatsRatioTotal > 0}
|
||||
tasksLabel={t('subscriptionSeatsLabel')}
|
||||
showRatio={subscription.hasActivePlan && seatsRatioTotal > 0}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex h-full min-h-0 min-w-0 items-center justify-center">
|
||||
|
||||
@@ -10,8 +10,8 @@ const PREFERRED_MIME_TYPES = [
|
||||
|
||||
/**
|
||||
* Pick a container this browser can record AND the backend accepts. Chrome and Android give
|
||||
* webm/opus, Safari and iPad mp4/aac; both go to the vendor unmodified, so there is no
|
||||
* transcode step and the list is an intersection, not a preference.
|
||||
* webm/opus, Safari and iPad mp4/aac. WebM and Ogg are converted to wav before upload
|
||||
* (`wavTranscode.ts`) because GapGPT cannot read a WebM duration. m4a is uploaded as recorded.
|
||||
*/
|
||||
export function pickRecordingMimeType(): string | null {
|
||||
if (typeof MediaRecorder === 'undefined') return null;
|
||||
|
||||
@@ -4,12 +4,8 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { voiceApi } from '@/lib/api/voice';
|
||||
import type { ApiError } from '@/types/api';
|
||||
import type { VoiceExtractionResult, VoicePhase } from '@/types/voice';
|
||||
import {
|
||||
blobToBase64,
|
||||
isMediaRecorderSupported,
|
||||
mimeTypeToFormat,
|
||||
pickRecordingMimeType,
|
||||
} from './audioFormat';
|
||||
import { blobToBase64, isMediaRecorderSupported, pickRecordingMimeType } from './audioFormat';
|
||||
import { prepareRecordingUpload } from './wavTranscode';
|
||||
|
||||
export interface UseVoiceCaptureOptions {
|
||||
/** The locale the clinician is speaking, sent so the server does not have to guess. */
|
||||
@@ -112,11 +108,20 @@ export function useVoiceCapture({
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
try {
|
||||
const audio = await blobToBase64(blob);
|
||||
let prepared: { blob: Blob; format: string };
|
||||
try {
|
||||
prepared = await prepareRecordingUpload(blob, mimeType);
|
||||
} catch {
|
||||
if (!cancelledRef.current && !controller.signal.aborted) {
|
||||
onError(clientError('VOICE_ASR_FAILED'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const audio = await blobToBase64(prepared.blob);
|
||||
const response = await voiceApi.extract(
|
||||
{
|
||||
audio,
|
||||
format: mimeTypeToFormat(mimeType),
|
||||
format: prepared.format,
|
||||
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
durationMs,
|
||||
locale,
|
||||
|
||||
42
frontend/src/lib/voice/wavTranscode.spec.ts
Normal file
42
frontend/src/lib/voice/wavTranscode.spec.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { encodeMonoWav, prepareRecordingUpload, resampleMono, WHISPER_SAMPLE_RATE } from './wavTranscode';
|
||||
|
||||
describe('encodeMonoWav', () => {
|
||||
it('writes a 16 kHz mono PCM header and clamps full-scale samples', () => {
|
||||
const bytes = new DataView(encodeMonoWav(new Float32Array([0, 1, -1]), WHISPER_SAMPLE_RATE));
|
||||
|
||||
expect(String.fromCharCode(bytes.getUint8(0), bytes.getUint8(1), bytes.getUint8(2), bytes.getUint8(3))).toBe(
|
||||
'RIFF',
|
||||
);
|
||||
expect(String.fromCharCode(bytes.getUint8(8), bytes.getUint8(9), bytes.getUint8(10), bytes.getUint8(11))).toBe(
|
||||
'WAVE',
|
||||
);
|
||||
expect(bytes.getUint16(22, true)).toBe(1);
|
||||
expect(bytes.getUint32(24, true)).toBe(WHISPER_SAMPLE_RATE);
|
||||
expect(bytes.getUint16(34, true)).toBe(16);
|
||||
expect(bytes.getInt16(44, true)).toBe(0);
|
||||
expect(bytes.getInt16(46, true)).toBe(32767);
|
||||
expect(bytes.getInt16(48, true)).toBe(-32768);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resampleMono', () => {
|
||||
it('keeps the same samples when the rate already matches', () => {
|
||||
const input = new Float32Array([0.25, -0.5]);
|
||||
expect(resampleMono(input, 16_000, 16_000)).toBe(input);
|
||||
});
|
||||
|
||||
it('stretches a clip to the higher rate', () => {
|
||||
const out = resampleMono(new Float32Array([0, 1]), 8_000, 16_000);
|
||||
expect(out.length).toBe(4);
|
||||
expect(out[0]).toBeCloseTo(0);
|
||||
expect(out[out.length - 1]).toBeCloseTo(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('prepareRecordingUpload', () => {
|
||||
it('leaves an m4a recording in its own container', async () => {
|
||||
const blob = new Blob(['m4a'], { type: 'audio/mp4' });
|
||||
await expect(prepareRecordingUpload(blob, 'audio/mp4')).resolves.toEqual({ blob, format: 'm4a' });
|
||||
});
|
||||
});
|
||||
106
frontend/src/lib/voice/wavTranscode.ts
Normal file
106
frontend/src/lib/voice/wavTranscode.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { mimeTypeToFormat } from './audioFormat';
|
||||
|
||||
/** Whisper's native rate. 16 kHz mono keeps a 2-minute clip under the upload cap. */
|
||||
export const WHISPER_SAMPLE_RATE = 16_000;
|
||||
|
||||
const CONTAINERS_GAPGPT_CANNOT_MEASURE = new Set(['webm', 'ogg']);
|
||||
|
||||
/**
|
||||
* Chrome records WebM. GapGPT rejects that container while measuring duration
|
||||
* (`webm duration parsing requires full EBML parser`). OpenRouter accepts WebM.
|
||||
* Decode in the browser — it already has a WebM parser — and upload wav, which both accept.
|
||||
*/
|
||||
export async function prepareRecordingUpload(
|
||||
blob: Blob,
|
||||
mimeType: string,
|
||||
): Promise<{ blob: Blob; format: string }> {
|
||||
const format = mimeTypeToFormat(mimeType);
|
||||
if (!CONTAINERS_GAPGPT_CANNOT_MEASURE.has(format)) return { blob, format };
|
||||
return { blob: await transcodeToWavBlob(blob), format: 'wav' };
|
||||
}
|
||||
|
||||
export function resampleMono(
|
||||
input: Float32Array,
|
||||
inputRate: number,
|
||||
outputRate: number,
|
||||
): Float32Array {
|
||||
if (input.length === 0 || inputRate === outputRate) return input;
|
||||
const length = Math.max(1, Math.round((input.length * outputRate) / inputRate));
|
||||
const out = new Float32Array(length);
|
||||
const last = input.length - 1;
|
||||
for (let i = 0; i < length; i++) {
|
||||
const src = (i * inputRate) / outputRate;
|
||||
const i0 = Math.min(Math.floor(src), last);
|
||||
const i1 = Math.min(i0 + 1, last);
|
||||
const weight = src - i0;
|
||||
out[i] = input[i0] * (1 - weight) + input[i1] * weight;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 16-bit PCM mono WAV. */
|
||||
export function encodeMonoWav(samples: Float32Array, sampleRate: number): ArrayBuffer {
|
||||
const buffer = new ArrayBuffer(44 + samples.length * 2);
|
||||
const view = new DataView(buffer);
|
||||
writeAscii(view, 0, 'RIFF');
|
||||
view.setUint32(4, 36 + samples.length * 2, true);
|
||||
writeAscii(view, 8, 'WAVE');
|
||||
writeAscii(view, 12, 'fmt ');
|
||||
view.setUint32(16, 16, true);
|
||||
view.setUint16(20, 1, true);
|
||||
view.setUint16(22, 1, true);
|
||||
view.setUint32(24, sampleRate, true);
|
||||
view.setUint32(28, sampleRate * 2, true);
|
||||
view.setUint16(32, 2, true);
|
||||
view.setUint16(34, 16, true);
|
||||
writeAscii(view, 36, 'data');
|
||||
view.setUint32(40, samples.length * 2, true);
|
||||
let offset = 44;
|
||||
for (let i = 0; i < samples.length; i++) {
|
||||
const clamped = Math.max(-1, Math.min(1, samples[i] ?? 0));
|
||||
view.setInt16(offset, clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, true);
|
||||
offset += 2;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
async function transcodeToWavBlob(blob: Blob): Promise<Blob> {
|
||||
const context = createAudioContext();
|
||||
try {
|
||||
if (context.state === 'suspended') await context.resume();
|
||||
const decoded = await context.decodeAudioData(await blob.arrayBuffer());
|
||||
const mixed = mixToMono(decoded);
|
||||
const samples = resampleMono(mixed, decoded.sampleRate, WHISPER_SAMPLE_RATE);
|
||||
if (samples.length === 0) throw new Error('audio-transcode');
|
||||
return new Blob([encodeMonoWav(samples, WHISPER_SAMPLE_RATE)], { type: 'audio/wav' });
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
function mixToMono(buffer: AudioBuffer): Float32Array {
|
||||
const out = new Float32Array(buffer.length);
|
||||
const channels = buffer.numberOfChannels;
|
||||
if (channels === 0 || buffer.length === 0) return out;
|
||||
for (let channel = 0; channel < channels; channel++) {
|
||||
const data = buffer.getChannelData(channel);
|
||||
for (let i = 0; i < data.length; i++) out[i] += data[i] / channels;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function createAudioContext(): AudioContext {
|
||||
const ctor =
|
||||
window.AudioContext ??
|
||||
(window as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
|
||||
if (!ctor) throw new Error('audio-transcode');
|
||||
try {
|
||||
return new ctor({ sampleRate: WHISPER_SAMPLE_RATE });
|
||||
} catch {
|
||||
return new ctor();
|
||||
}
|
||||
}
|
||||
|
||||
function writeAscii(view: DataView, offset: number, value: string) {
|
||||
for (let i = 0; i < value.length; i++) view.setUint8(offset + i, value.charCodeAt(i));
|
||||
}
|
||||
Reference in New Issue
Block a user