Files
SupplierSystem/server/src/services/speechService.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

193 lines
6.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { randomUUID } from 'crypto';
import { loadEnv } from '../env';
import {
callWithAudio as callArkWithAudio,
hasRuntimeConfig as hasArkRuntimeConfig,
type LlmCallOptions as ArkCallOptions,
} from './llmService';
import { resolvePrompt } from './promptRegistryService';
const FLASH_ASR_URL = 'https://openspeech.bytedance.com/api/v3/auc/bigmodel/recognize/flash';
const RESOURCE_ID = 'volc.bigasr.auc_turbo';
/** Ark 多模态转写兜底提示词(见 docs/design/20260915-voice-transcribe-ark-fallback.md) */
const ARK_FALLBACK_PROMPT_KEY = 'speech.transcribe.ark_fallback';
export type AudioFormat = 'ogg' | 'wav' | 'mp3' | 'webm';
export function isSpeechConfigured(): boolean {
loadEnv();
if (process.env.SPEECH_API_KEY?.trim()) return true;
return Boolean(process.env.SPEECH_APP_KEY?.trim() && process.env.SPEECH_ACCESS_KEY?.trim());
}
/**
* 语音转写可用性:优先豆包 ASR;未配 ASR 时看 LLM 音频运行时(Ark 多模态兜底)。
* 2026-09-15:生产那把 ASR key 失效(401/45000010)时语音全挂,故兜底纳入可用性判定。
*/
export async function isVoiceTranscriptionConfigured(options?: ArkCallOptions): Promise<boolean> {
if (isSpeechConfigured()) return true;
return hasArkRuntimeConfig(options);
}
function buildAsrHeaders(): Record<string, string> {
loadEnv();
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'X-Api-Resource-Id': RESOURCE_ID,
'X-Api-Request-Id': randomUUID(),
'X-Api-Sequence': '-1',
};
const apiKey = process.env.SPEECH_API_KEY?.trim();
if (apiKey) {
headers['X-Api-Key'] = apiKey;
return headers;
}
const appKey = process.env.SPEECH_APP_KEY?.trim();
const accessKey = process.env.SPEECH_ACCESS_KEY?.trim();
if (appKey && accessKey) {
headers['X-Api-App-Key'] = appKey;
headers['X-Api-Access-Key'] = accessKey;
}
return headers;
}
function getSpeechUid(): string {
loadEnv();
return process.env.SPEECH_APP_KEY?.trim() || process.env.SPEECH_API_KEY?.trim() || 'canteen';
}
async function transcribeWithAsr(
audioBase64: string,
_format: AudioFormat = 'ogg'
): Promise<{ text: string; durationMs?: number }> {
if (!isSpeechConfigured()) {
throw new Error('语音识别不可用:请配置豆包 SPEECH_API_KEY(录单语音只走 ASR,转写后再用大模型拆条)');
}
const headers = buildAsrHeaders();
if (!headers['X-Api-Key'] && !headers['X-Api-App-Key']) {
throw new Error('语音识别密钥无效,请检查 SPEECH_API_KEY 或 SPEECH_APP_KEY/SPEECH_ACCESS_KEY');
}
const payload = {
user: { uid: getSpeechUid() },
audio: { data: audioBase64 },
request: {
model_name: 'bigmodel',
enable_itn: true,
enable_punc: true,
},
};
const response = await fetch(FLASH_ASR_URL, {
method: 'POST',
headers,
body: JSON.stringify(payload),
signal: AbortSignal.timeout(Number(process.env.SPEECH_FETCH_TIMEOUT_MS || 15_000)),
});
const statusCode = response.headers.get('X-Api-Status-Code') || '';
const statusMessage = response.headers.get('X-Api-Message') || '';
let body: any = null;
try {
body = await response.json();
} catch {
body = null;
}
if (statusCode && statusCode !== '20000000') {
const detail = statusMessage || body?.message || response.statusText;
if (statusCode === '45000151') {
throw new Error('音频格式不支持,请使用 Chrome/Edge 并允许麦克风权限后重试');
}
throw new Error(`语音识别失败 (${statusCode}): ${detail}`);
}
if (!response.ok) {
throw new Error(`语音识别请求失败: HTTP ${response.status}`);
}
const text = (body?.result?.text || '').trim();
if (!text) {
throw new Error('未识别到语音内容,请靠近麦克风清晰说话后重试');
}
return {
text,
durationMs: body?.audio_info?.duration ?? body?.result?.additions?.duration,
};
}
/**
* Ark 多模态听音频转写(兜底)。失败返回 null,由调用方决定抛什么错。
* 设计:docs/design/20260915-voice-transcribe-ark-fallback.md
*/
async function tryArkFallback(
audioBase64: string,
format: AudioFormat,
options: ArkCallOptions | undefined,
reason: string
): Promise<string | null> {
try {
if (!(await hasArkRuntimeConfig(options))) return null;
const text = await transcribeAudioWithArk(audioBase64, format, options);
if (!text) return null;
console.warn('语音转写:ASR 不可用,已回落 Ark 多模态兜底', {
reason,
branchCode: options?.branchCode || null,
chars: text.length,
});
return text;
} catch (error: any) {
console.warn('语音转写:Ark 兜底失败', { reason, message: error?.message || String(error) });
return null;
}
}
async function transcribeAudioWithArk(
audioBase64: string,
format: AudioFormat,
options?: ArkCallOptions
): Promise<string | null> {
const resolved = await resolvePrompt(ARK_FALLBACK_PROMPT_KEY, {
branchCode: options?.branchCode,
});
const text = await callArkWithAudio(resolved.systemPrompt, audioBase64, format, options);
const cleaned = (text || '')
.replace(/^```[\s\S]*?\n?/, '')
.replace(/```\s*$/, '')
.trim();
return cleaned || null;
}
/**
* 语音转文字:优先豆包 ASR;ASR 未配置或调用失败时回落 Ark 多模态听音频。
* 两条路都不行时抛原始 ASR 错误(保留真实原因,便于排查)。
*/
export async function transcribeAudioBase64(
audioBase64: string,
format: AudioFormat = 'ogg',
options?: ArkCallOptions
): Promise<{ text: string; durationMs?: number }> {
if (isSpeechConfigured()) {
try {
return await transcribeWithAsr(audioBase64, format);
} catch (error: any) {
const text = await tryArkFallback(audioBase64, format, options, error?.message || 'asr_failed');
if (text) return { text };
throw error;
}
}
const text = await tryArkFallback(audioBase64, format, options, 'asr_not_configured');
if (text) return { text };
throw new Error(
'语音识别不可用:请配置豆包 SPEECH_API_KEY(录单语音只走 ASR,转写后再用大模型拆条),或确认 ARK_API_KEY 可用以走 Ark 多模态兜底'
);
}