Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

add chirp 2 support via speech-to-text v2 api

Louis Beaumontf1f016d0200e
diff --git a/screenpipe-js/ai-proxy/src/handlers/transcription.ts b/screenpipe-js/ai-proxy/src/handlers/transcription.ts
index c9cd4a78c..9fd644ffe 100644
--- a/screenpipe-js/ai-proxy/src/handlers/transcription.ts
+++ b/screenpipe-js/ai-proxy/src/handlers/transcription.ts
@@ -5,7 +5,7 @@ import { VertexAIProvider } from '../providers/vertex';
/**
* Handles audio file transcription requests
- * Supports both Deepgram (default) and Google Speech-to-Text with Chirp 2
+ * Supports Deepgram (default), Google Speech-to-Text v1, and Chirp 2 (v2 API)
* @param request The HTTP request containing audio data
* @param env Environment variables
* @returns Response with transcription results
@@ -13,6 +13,10 @@ import { VertexAIProvider } from '../providers/vertex';
export async function handleFileTranscription(request: Request, env: Env): Promise<Response> {
const provider = request.headers.get('x-transcription-provider')?.toLowerCase() || 'deepgram';
+ if (provider === 'chirp2' || provider === 'chirp-2') {
+ return handleChirp2Transcription(request, env);
+ }
+
if (provider === 'google' || provider === 'chirp') {
return handleGoogleTranscription(request, env);
}
@@ -57,8 +61,8 @@ async function handleDeepgramTranscription(request: Request, env: Env): Promise<
}
/**
- * Handles transcription using Google Speech-to-Text v2 with Chirp 2 model
- * Chirp 2 is Google's latest SOTA speech recognition model
+ * Handles transcription using Google Speech-to-Text v1 API with latest_long model
+ * For Chirp 2 (v2 API), use x-transcription-provider: chirp2
*/
async function handleGoogleTranscription(request: Request, env: Env): Promise<Response> {
try {
@@ -177,6 +181,128 @@ async function handleGoogleTranscription(request: Request, env: Env): Promise<Re
}
}
+/**
+ * Handles transcription using Google Speech-to-Text v2 API with Chirp 2 model
+ * Chirp 2 is Google's SOTA speech recognition model (GA in us-central1, europe-west4, asia-southeast1)
+ */
+async function handleChirp2Transcription(request: Request, env: Env): Promise<Response> {
+ try {
+ const audioBuffer = await request.arrayBuffer();
+ const languages = request.headers.get('detect_language')?.split(',') || ['en-US'];
+
+ // Get access token using Vertex AI credentials
+ const vertexProvider = new VertexAIProvider(
+ env.VERTEX_SERVICE_ACCOUNT_JSON,
+ env.VERTEX_PROJECT_ID,
+ env.VERTEX_REGION
+ );
+ const accessToken = await vertexProvider.getAccessToken();
+
+ // Convert audio to base64 (chunked to avoid stack overflow)
+ const uint8Array = new Uint8Array(audioBuffer);
+ let binary = '';
+ const chunkSize = 8192;
+ for (let i = 0; i < uint8Array.length; i += chunkSize) {
+ const chunk = uint8Array.subarray(i, i + chunkSize);
+ binary += String.fromCharCode.apply(null, chunk as unknown as number[]);
+ }
+ const audioBase64 = btoa(binary);
+
+ // Map language codes to Google format (e.g., 'en' -> 'en-US')
+ const languageCodes = languages.map(lang => {
+ if (lang.includes('-')) return lang;
+ const mappings: Record<string, string> = {
+ 'en': 'en-US', 'es': 'es-ES', 'fr': 'fr-FR', 'de': 'de-DE',
+ 'it': 'it-IT', 'pt': 'pt-BR', 'ja': 'ja-JP', 'ko': 'ko-KR',
+ 'zh': 'zh-CN', 'ru': 'ru-RU', 'ar': 'ar-SA', 'hi': 'hi-IN',
+ };
+ return mappings[lang] || `${lang}-${lang.toUpperCase()}`;
+ });
+
+ // Chirp 2 is available in: us-central1, europe-west4, asia-southeast1
+ // Use us-central1 as default for best coverage
+ const chirp2Region = 'us-central1';
+ const projectId = env.VERTEX_PROJECT_ID;
+
+ // Speech-to-Text v2 API endpoint for Chirp 2
+ const url = `https://speech.googleapis.com/v2/projects/${projectId}/locations/${chirp2Region}/recognizers/_:recognize`;
+
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ config: {
+ auto_decoding_config: {},
+ language_codes: languageCodes,
+ model: 'chirp_2',
+ features: {
+ enable_automatic_punctuation: true,
+ enable_word_time_offsets: true,
+ },
+ },
+ content: audioBase64,
+ }),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.text();
+ console.error('Chirp 2 error:', response.status, response.statusText, errorData);
+ throw new Error(`Chirp 2 API error (${response.status}): ${errorData || response.statusText}`);
+ }
+
+ const data = await response.json() as {
+ results?: Array<{
+ alternatives?: Array<{
+ transcript?: string;
+ confidence?: number;
+ words?: Array<{
+ word?: string;
+ startOffset?: string;
+ endOffset?: string;
+ }>;
+ }>;
+ languageCode?: string;
+ }>;
+ };
+
+ // Transform to Deepgram-compatible format for easy integration
+ const transcript = data.results?.map(r => r.alternatives?.[0]?.transcript || '').join(' ') || '';
+ const confidence = data.results?.[0]?.alternatives?.[0]?.confidence || 0;
+ const detectedLanguage = data.results?.[0]?.languageCode || languageCodes[0];
+
+ const deepgramFormat = {
+ results: {
+ channels: [{
+ alternatives: [{
+ transcript,
+ confidence,
+ words: data.results?.flatMap(r =>
+ r.alternatives?.[0]?.words?.map(w => ({
+ word: w.word || '',
+ start: parseFloat(w.startOffset?.replace('s', '') || '0'),
+ end: parseFloat(w.endOffset?.replace('s', '') || '0'),
+ confidence: confidence,
+ })) || []
+ ) || [],
+ }],
+ }],
+ metadata: {
+ model_info: { name: 'chirp_2' },
+ detected_language: detectedLanguage,
+ },
+ },
+ };
+
+ return createSuccessResponse(deepgramFormat);
+ } catch (error: any) {
+ console.error('Error in Chirp 2 request:', error);
+ return createErrorResponse(500, error.message);
+ }
+}
+
/**
* Handles WebSocket upgrade for real-time transcription
* @param request The HTTP request for WebSocket upgrade