Cotton code
123 lines · 5.2 KB · TypeScriptRaw
/** * An outside transcription service for Cotton Meetings — SHIPPED DISABLED * (voice plan, 17 Nov 2026: "interface and one provider adaptor, no key, never * the default"). * * A meeting's audio is sealed on the phone and the object cannot read it, so a * service can only ever be handed audio by the owner's own device, for one * recording, after the owner turned the service on. Until then: * *   * `serviceOf(settings, keys)` answers null: no setting, or no key, or a *     provider this build does not know, is no service; *   * nothing here is called by any route or alarm; there is no default. * * The one interface every transcriber shares is the core's transcript * (cotton_rules::meetings::Transcript): `{ by, languages, speakers, lines }`, * each line `{ speaker, start_ms, end_ms, text, language? }`. * * One adaptor is here, for AssemblyAI's v2 API (speaker labels and language * detection on): `assemblyAi(key, fetch)` uploads, asks, polls and maps the * answer's utterances into the transcript. It is exercised only against a * canned answer in test/meetings.test.ts; no test and no default sends anything * anywhere. */export interface Line {  speaker: string;  start_ms: number;  end_ms: number;  text: string;  language?: string;}export interface Transcript {  by: string;  languages: string[];  speakers: { label: string }[];  lines: Line[];}/** One outside transcriber: audio bytes in, the transcript out. */export interface TranscriptionService {  readonly id: string;  transcribe(audio: Uint8Array, contentType: string, languages: string[]): Promise<Transcript>;}/** The owner's setting for it (a row of their settings, never a default): which provider, if any. */export interface ServiceSetting {  provider?: string | null;  enabled?: boolean | null;}export type Fetch = (input: string, init?: RequestInit) => Promise<Response>;export const PROVIDERS = ["assemblyai"] as const;/** The service the owner turned on and gave a key for, else null (the shipped state). */export function serviceOf(setting: ServiceSetting | null | undefined, keys: Record<string, string | undefined>, fetcher: Fetch = fetch): TranscriptionService | null {  if (!setting || setting.enabled !== true) return null;  const provider = (setting.provider ?? "").trim();  if (provider === "assemblyai") {    const key = keys.ASSEMBLYAI_API_KEY?.trim();    return key ? assemblyAi(key, fetcher) : null;  }  return null;}const BASE = "https://api.assemblyai.com/v2";interface AaiUtterance {  speaker: string;  start: number;  end: number;  text: string;}interface AaiTranscript {  id: string;  status: "queued" | "processing" | "completed" | "error";  error?: string;  language_code?: string;  utterances?: AaiUtterance[] | null;}/** AssemblyAI's answer as the core's transcript: speakers relabelled S1, S2… by first speech. */export function fromAssemblyAi(answer: AaiTranscript): Transcript {  const order: string[] = [];  const lines: Line[] = [];  const language = answer.language_code ? answer.language_code.split("_")[0] : undefined;  for (const u of [...(answer.utterances ?? [])].sort((a, b) => a.start - b.start)) {    const said = u.text.trim();    if (!said) continue;    if (!order.includes(u.speaker)) order.push(u.speaker);    lines.push({ speaker: `S${order.indexOf(u.speaker) + 1}`, start_ms: u.start, end_ms: Math.max(u.end, u.start), text: said, ...(language ? { language } : {}) });  }  return { by: "service:assemblyai", languages: language ? [language] : [], speakers: order.map((_, n) => ({ label: `S${n + 1}` })), lines };}export function assemblyAi(key: string, fetcher: Fetch, wait: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms))): TranscriptionService {  const headers = { authorization: key };  return {    id: "assemblyai",    async transcribe(audio, contentType, languages) {      const up = await fetcher(`${BASE}/upload`, { method: "POST", headers: { ...headers, "content-type": contentType || "application/octet-stream" }, body: audio });      if (!up.ok) throw new Error(`the service refused the audio (${up.status})`);      const { upload_url } = (await up.json()) as { upload_url: string };      const body: Record<string, unknown> = { audio_url: upload_url, speaker_labels: true };      if (languages.length === 1) body.language_code = languages[0];      else body.language_detection = true;      const asked = await fetcher(`${BASE}/transcript`, { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify(body) });      if (!asked.ok) throw new Error(`the service refused the job (${asked.status})`);      let answer = (await asked.json()) as AaiTranscript;      for (let polls = 0; answer.status === "queued" || answer.status === "processing"; polls++) {        if (polls > 720) throw new Error("the service did not finish within an hour");        await wait(5000);        const got = await fetcher(`${BASE}/transcript/${answer.id}`, { headers });        if (!got.ok) throw new Error(`the service did not answer (${got.status})`);        answer = (await got.json()) as AaiTranscript;      }      if (answer.status === "error") throw new Error(answer.error || "the service could not transcribe it");      return fromAssemblyAi(answer);    },  };}