INTEGRITY Документация

Whisper-large-v3-turbo с Cloudflare Workers AI

В этом руководстве вы узнаете, как:

1: Создайте новый проект Cloudflare Worker

  1. Зарегистрируйтесь для получения Аккаунт Cloudflare.
  2. Установка Node.js.

менеджер версий Node.js

Используйте менеджер версий Node, например Volta или nvm чтобы избежать проблем с правами доступа и переключать версии Node.js. Wrangler, о котором пойдёт речь далее в этом руководстве, требует версию Node 16.17.0 или более поздней версии.

Вы создадите новый проект Worker с помощью create-cloudflare CLI (C3). C3 это инструмент командной строки, который помогает настраивать и развёртывать новые приложения в Cloudflare.

Создайте новый проект с именем whisper-tutorial выполнив:

npm create cloudflare@latest -- whisper-tutorial

Выполнение npm create cloudflare@latest предложит установить create-cloudflare пакет, и проведёт вас через настройку. C3 также установит Wrangler, интерфейс командной строки платформы Cloudflare Developer Platform.

Для настройки выберите следующие параметры:

Это создаст новый whisper-tutorial каталог. Ваш новый whisper-tutorial каталог будет включать:

Перейдите в каталог вашего приложения:

cd whisper-tutorial

2. Подключите свой Worker к Workers AI

Чтобы Worker мог подключаться к Workers AI, необходимо создать привязку AI. Bindings позволяют вашим Workers взаимодействовать с ресурсами Cloudflare Developer Platform, такими как Workers AI.

Чтобы привязать Workers AI к своему Worker, добавьте следующее в конец файла конфигурации Wrangler:

{
	"ai": {
		"binding": "AI"
	}
}
[ai]
binding = "AI"

Ваша привязка: доступно в коде вашего Worker на env.AI.

3. Настройте Wrangler

В файле wrangler добавьте или обновите следующие настройки, чтобы включить Node.js API и полифиллы (с датой совместимости 2024‑09‑23 или более поздней):

{
	"compatibility_flags": [
		"nodejs_compat"
	],
	// Set this to today's date
	"compatibility_date": "2026-08-28"
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-28"

4. Обработка больших аудиофайлов с разбиением на фрагменты

Замените содержимое своего src/index.ts файл, используя приведённый ниже интегрированный код. В этом примере показано, как:

(1) Извлеките URL аудиофайла из параметров запроса.

(2) Загрузите аудиофайл, явно следуя перенаправлениям.

(3) Разделите аудиофайл на более мелкие части (например, по 1 МБ).

(4) Транскрибируйте каждую часть с помощью модели Whisper-large-v3-turbo через привязку Cloudflare AI.

(5) Верните объединённую транскрипцию в виде обычного текста.

import { Buffer } from "node:buffer";
import type { Ai } from "workers-ai";

export interface Env {
	AI: Ai;
	// If needed, add your KV namespace for storing transcripts.
	// MY_KV_NAMESPACE: KVNamespace;
}

/**
 * Fetches the audio file from the provided URL and splits it into chunks.
 * This function explicitly follows redirects.
 *
 * @param audioUrl - The URL of the audio file.
 * @returns An array of ArrayBuffers, each representing a chunk of the audio.
 */
async function getAudioChunks(audioUrl: string): Promise<ArrayBuffer[]> {
	const response = await fetch(audioUrl, { redirect: "follow" });
	if (!response.ok) {
		throw new Error(`Failed to fetch audio: ${response.status}`);
	}
	const arrayBuffer = await response.arrayBuffer();

	// Example: Split the audio into 1MB chunks.
	const chunkSize = 1024 * 1024; // 1MB
	const chunks: ArrayBuffer[] = [];
	for (let i = 0; i < arrayBuffer.byteLength; i += chunkSize) {
		const chunk = arrayBuffer.slice(i, i + chunkSize);
		chunks.push(chunk);
	}
	return chunks;
}

/**
 * Transcribes a single audio chunk using the Whisper‑large‑v3‑turbo model.
 * The function converts the audio chunk to a Base64-encoded string and
 * sends it to the model via the AI binding.
 *
 * @param chunkBuffer - The audio chunk as an ArrayBuffer.
 * @param env - The Cloudflare Worker environment, including the AI binding.
 * @returns The transcription text from the model.
 */
async function transcribeChunk(
	chunkBuffer: ArrayBuffer,
	env: Env,
): Promise<string> {
	const base64 = Buffer.from(chunkBuffer, "binary").toString("base64");
	const res = await env.AI.run("@cf/openai/whisper-large-v3-turbo", {
		audio: base64,
		// Optional parameters (uncomment and set if needed):
		// task: "transcribe",   // or "translate"
		// language: "en",
		// vad_filter: "false",
		// initial_prompt: "Provide context if needed.",
		// prefix: "Transcription:",
	});
	return res.text; // Assumes the transcription result includes a "text" property.
}

/**
 * The main fetch handler. It extracts the 'url' query parameter, fetches the audio,
 * processes it in chunks, and returns the full transcription.
 */
export default {
	async fetch(
		request: Request,
		env: Env,
		ctx: ExecutionContext,
	): Promise<Response> {
		// Extract the audio URL from the query parameters.
		const { searchParams } = new URL(request.url);
		const audioUrl = searchParams.get("url");

		if (!audioUrl) {
			return new Response("Missing 'url' query parameter", { status: 400 });
		}

		// Get the audio chunks.
		const audioChunks: ArrayBuffer[] = await getAudioChunks(audioUrl);
		let fullTranscript = "";

		// Process each chunk and build the full transcript.
		for (const chunk of audioChunks) {
			try {
				const transcript = await transcribeChunk(chunk, env);
				fullTranscript += transcript + "\n";
			} catch (error) {
				fullTranscript += "[Error transcribing chunk]\n";
			}
		}

		return new Response(fullTranscript, {
			headers: { "Content-Type": "text/plain" },
		});
	},
} satisfies ExportedHandler<Env>;

5. Разверните Worker

  1. Запустите Worker локально:

    Используйте режим разработки wrangler, чтобы протестировать Worker локально:

npx wrangler dev

Откройте браузер и перейдите по адресу http://localhost:8787, или используйте curl:

curl "http://localhost:8787?url=https://raw.githubusercontent.com/your-username/your-repo/main/your-audio-file.mp3"

Замените параметр запроса URL на прямую ссылку на ваш аудиофайл. (Для файлов, размещённых на GitHub, используйте ссылку на файл в формате raw.)

  1. Разверните Worker:

    После завершения тестирования разверните Worker с помощью:

npx wrangler deploy
  1. Протестируйте развёрнутый Worker:

    После развёртывания протестируйте свой Worker, передав URL-адрес аудиофайла в качестве параметра запроса:

curl "https://<your-worker-subdomain>.workers.dev?url=https://raw.githubusercontent.com/your-username/your-repo/main/your-audio-file.mp3"

Обязательно замените <your-worker-subdomain>, your-username, your-repo, а также your-audio-file.mp3 вашими фактическими данными.

В случае успеха Worker вернет расшифровку аудиофайла:

This is the transcript of the audio...