你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
生成一个应用程序,将语音音频转换为有组织的笔记, 完全在设备上。 应用首先使用语音转文本模型转录音频文件,然后使用聊天模型来汇总并组织听录到干净的笔记中。
本教程中,您将学习如何:
- 设置项目并安装 Foundry 本地 SDK
- 加载语音转文本模型并转录音频文件
- 加载聊天模型并汇总听录
- 将听录和摘要合并到完整的应用中
- 清理资源
先决条件
- 至少具有 8 GB RAM 的 Windows、macOS 或 Linux 计算机。
-
.wav要转录的音频文件(本教程使用示例文件)。
安装软件包
示例存储库
可以在 Foundry 示例GitHub存储库中找到本文的完整示例代码。 若要克隆存储库并导航到示例,请使用:
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/csharp/foundry-local/tutorial-voice-to-text
dotnet add package Microsoft.AI.Foundry.Local
dotnet add package OpenAI
GitHub存储库中的 C# 示例是预配置项目。 如果要从头开始生成,则应阅读 Foundry Local SDK 参考 ,详细了解如何使用 Foundry Local 设置 C# 项目。
转录音频文件
在此步骤中,将加载语音转文本模型并转录音频文件。 Foundry Local SDK 使用 whisper 模型的别名来为您的硬件选择最佳的 Whisper 变体。
打开
Program.cs并将其内容替换为以下代码来初始化 SDK、加载语音模型并转录音频文件:// Load the speech-to-text model var speechModel = await catalog.GetModelAsync("whisper-tiny") ?? throw new Exception("Speech model not found"); await speechModel.DownloadAsync(progress => { Console.Write($"\rDownloading speech model: {progress:F2}%"); if (progress >= 100f) Console.WriteLine(); }); await speechModel.LoadAsync(); Console.WriteLine("Speech model loaded."); // Transcribe the audio file with the native v2 audio session. var transcriptionText = new StringBuilder(); using var audioSession = new AudioSession(speechModel); audioSession.SetStreaming(true); using var audioRequest = new Request(); audioRequest.AddItem(new AudioItem("meeting-notes.wav")); Console.WriteLine("\nTranscription:"); await using var audioResponse = audioSession.ProcessStreamingRequestAsync(audioRequest, ct); await foreach (var item in audioResponse) { using (item) { if (item is SpeechSegmentItem segment) { Console.Write(segment.Text); transcriptionText.Append(segment.Text); } } } using var finalTranscription = await audioResponse.FinalResponse; Console.WriteLine(); // Unload the speech model to free memory finalTranscription.Dispose(); await audioResponse.DisposeAsync(); audioRequest.Dispose(); audioSession.Dispose(); await speechModel.UnloadAsync();该方法
GetAudioClientAsync返回用于音频操作的客户端。 当转录块可用时,TranscribeAudioStreamingAsync方法会进行流式传输。 你将累积文本,以便在下一步中将其传递给聊天模型。
注释
将"meeting-notes.wav"替换为音频文件的路径。 支持的格式包括 WAV、MP3 和 FLAC。
汇总听录
现在,使用聊天模型将原始听录组织到结构化笔记中。 加载 qwen2.5-0.5b 模型,并将转录内容作为上下文发送,同时使用系统提示指示模型生成干净、摘要化的笔记。
在听录步骤后添加以下代码:
// Load the chat model for summarization
var chatModel = await catalog.GetModelAsync("qwen2.5-0.5b")
?? throw new Exception("Chat model not found");
await chatModel.DownloadAsync(progress =>
{
Console.Write($"\rDownloading chat model: {progress:F2}%");
if (progress >= 100f) Console.WriteLine();
});
await chatModel.LoadAsync();
Console.WriteLine("Chat model loaded.");
// Summarize the transcription into organized notes.
using var chatSession = new ChatSession(chatModel);
using var chatRequest = new Request();
chatRequest.AddItem(MessageItem.System(
"You are a note-taking assistant. Summarize the following transcription " +
"into organized, concise notes with bullet points."));
chatRequest.AddItem(MessageItem.User(transcriptionText.ToString()));
using var chatResponse = await chatSession.ProcessRequestAsync(chatRequest, ct);
var summary = string.Concat(
chatResponse.OfType<MessageItem>()
.SelectMany(message => message.Parts)
.OfType<TextItem>()
.Where(text => text.Type == TextItemType.Default)
.Select(text => text.Text));
Console.WriteLine($"\nSummary:\n{summary}");
// Clean up
chatResponse.Dispose();
chatRequest.Dispose();
chatSession.Dispose();
await chatModel.UnloadAsync();
Console.WriteLine("\nDone. Models unloaded.");
系统提示影响模型的输出格式。 通过指示其生成“结构清晰、简洁并带有项目符号的笔记”,可获得结构化内容,而不是原始改写。
合并成完整的应用
将Program.cs的内容替换为以下完整代码,该代码用于转录音频文件并汇总转录文本:
// <imports>
using Microsoft.AI.Foundry.Local;
using Microsoft.Extensions.Logging;
using System.Text;
// </imports>
// <init>
CancellationToken ct = CancellationToken.None;
var config = new Configuration
{
AppName = "foundry_local_samples",
LogLevel = Microsoft.AI.Foundry.Local.LogLevel.Information
};
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.SetMinimumLevel(
Microsoft.Extensions.Logging.LogLevel.Information
);
});
var logger = loggerFactory.CreateLogger<Program>();
// Initialize the singleton instance
await FoundryLocalManager.CreateAsync(config, logger);
var mgr = FoundryLocalManager.Instance;
// Download and register all execution providers.
var currentEp = "";
await mgr.DownloadAndRegisterEpsAsync((epName, percent) =>
{
if (epName != currentEp)
{
if (currentEp != "") Console.WriteLine();
currentEp = epName;
}
Console.Write($"\r {epName.PadRight(30)} {percent,6:F1}%");
});
if (currentEp != "") Console.WriteLine();
var catalog = await mgr.GetCatalogAsync();
// </init>
// <transcription>
// Load the speech-to-text model
var speechModel = await catalog.GetModelAsync("whisper-tiny")
?? throw new Exception("Speech model not found");
await speechModel.DownloadAsync(progress =>
{
Console.Write($"\rDownloading speech model: {progress:F2}%");
if (progress >= 100f) Console.WriteLine();
});
await speechModel.LoadAsync();
Console.WriteLine("Speech model loaded.");
// Transcribe the audio file with the native v2 audio session.
var transcriptionText = new StringBuilder();
using var audioSession = new AudioSession(speechModel);
audioSession.SetStreaming(true);
using var audioRequest = new Request();
audioRequest.AddItem(new AudioItem("meeting-notes.wav"));
Console.WriteLine("\nTranscription:");
await using var audioResponse = audioSession.ProcessStreamingRequestAsync(audioRequest, ct);
await foreach (var item in audioResponse)
{
using (item)
{
if (item is SpeechSegmentItem segment)
{
Console.Write(segment.Text);
transcriptionText.Append(segment.Text);
}
}
}
using var finalTranscription = await audioResponse.FinalResponse;
Console.WriteLine();
// Unload the speech model to free memory
finalTranscription.Dispose();
await audioResponse.DisposeAsync();
audioRequest.Dispose();
audioSession.Dispose();
await speechModel.UnloadAsync();
// </transcription>
// <summarization>
// Load the chat model for summarization
var chatModel = await catalog.GetModelAsync("qwen2.5-0.5b")
?? throw new Exception("Chat model not found");
await chatModel.DownloadAsync(progress =>
{
Console.Write($"\rDownloading chat model: {progress:F2}%");
if (progress >= 100f) Console.WriteLine();
});
await chatModel.LoadAsync();
Console.WriteLine("Chat model loaded.");
// Summarize the transcription into organized notes.
using var chatSession = new ChatSession(chatModel);
using var chatRequest = new Request();
chatRequest.AddItem(MessageItem.System(
"You are a note-taking assistant. Summarize the following transcription " +
"into organized, concise notes with bullet points."));
chatRequest.AddItem(MessageItem.User(transcriptionText.ToString()));
using var chatResponse = await chatSession.ProcessRequestAsync(chatRequest, ct);
var summary = string.Concat(
chatResponse.OfType<MessageItem>()
.SelectMany(message => message.Parts)
.OfType<TextItem>()
.Where(text => text.Type == TextItemType.Default)
.Select(text => text.Text));
Console.WriteLine($"\nSummary:\n{summary}");
// Clean up
chatResponse.Dispose();
chatRequest.Dispose();
chatSession.Dispose();
await chatModel.UnloadAsync();
Console.WriteLine("\nDone. Models unloaded.");
// </summarization>
注释
将"meeting-notes.wav"替换为音频文件的路径。 支持的格式包括 WAV、MP3 和 FLAC。
运行记事记录器:
dotnet run
会看到类似于以下内容的输出:
Downloading speech model: 100.00%
Speech model loaded.
Transcription:
OK so let's get started with the weekly sync. First, the backend
API is nearly done. Sarah finished the authentication endpoints
yesterday. We still need to add rate limiting before we go to
staging. On the frontend, the dashboard redesign is about seventy
percent complete. Jake, can you walk us through the new layout?
Great. The charts look good. I think we should add a filter for
date range though. For testing, we have about eighty percent code
coverage on the API. We need to write integration tests for the
new auth flow before Friday. Let's plan to do a full regression
test next Tuesday before the release. Any blockers? OK, sounds
like we are in good shape. Let's wrap up.
Downloading chat model: 100.00%
Chat model loaded.
Summary:
- **Backend API**: Authentication endpoints complete. Rate limiting
still needed before staging deployment.
- **Frontend**: Dashboard redesign 70% complete. New chart layout
reviewed. Action item: add a date range filter.
- **Testing**: API code coverage at 80%. Integration tests for the
auth flow due Friday. Full regression test scheduled for next
Tuesday before release.
- **Status**: No blockers reported. Team is on track.
Done. Models unloaded.
应用程序首先使用流式处理输出转录音频内容,然后将累积的文本传递给聊天模型,该模型提取关键点并将其组织成结构化笔记。
安装软件包
示例存储库
本文的完整示例代码在 foundry-samples GitHub 存储库中提供。 若要克隆存储库并导航到示例,请使用:
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/javascript/foundry-local/tutorial-voice-to-text
npm install foundry-local-sdk openai
转录音频文件
在此步骤中,将加载语音转文本模型并转录音频文件。 Foundry Local SDK 使用 whisper 模型的别名来为您的硬件选择最佳的 Whisper 变体。
创建名为 的文件
app.js。添加以下代码以初始化 SDK、加载语音模型并转录音频文件:
// Load the speech-to-text model const speechModel = await manager.catalog.getModel('whisper-tiny'); await speechModel.download((progress) => { process.stdout.write( `\rDownloading speech model: ${progress.toFixed(2)}%` ); }); console.log('\nSpeech model downloaded.'); await speechModel.load(); console.log('Speech model loaded.'); // Transcribe the audio file const audioSession = new AudioSession(speechModel); const audioFile = path.join(__dirname, 'meeting-notes.wav'); const transcriptionResponse = await audioSession.processRequest( new Request().addItem(Item.audioFromUri(audioFile)) ); const transcription = transcriptionResponse.output.find( (item) => item.type === 'speechResult' ); if (!transcription) { throw new Error('The speech model returned no transcription.'); } console.log(`\nTranscription:\n${transcription.text}`); // Unload the speech model to free memory audioSession.dispose(); await speechModel.unload();该方法
createAudioClient返回用于音频操作的客户端。 该方法transcribe接受文件路径,并返回包含text转录内容的属性的对象。
注释
将'./meeting-notes.wav'替换为音频文件的路径。 支持的格式包括 WAV、MP3 和 FLAC。
汇总听录
现在,使用聊天模型将原始听录组织到结构化笔记中。 加载 qwen2.5-0.5b 模型,并将转录内容作为上下文发送,同时使用系统提示指示模型生成干净、摘要化的笔记。
在听录步骤后添加以下代码:
// Load the chat model for summarization
const chatModel = await manager.catalog.getModel('qwen2.5-0.5b');
await chatModel.download((progress) => {
process.stdout.write(
`\rDownloading chat model: ${progress.toFixed(2)}%`
);
});
console.log('\nChat model downloaded.');
await chatModel.load();
console.log('Chat model loaded.');
// Summarize the transcription into organized notes
const chatSession = new ChatSession(chatModel);
const request = new Request()
.addItem(Item.systemMessage(
'You are a note-taking assistant. Summarize ' +
'the following transcription into organized, ' +
'concise notes with bullet points.'
))
.addItem(Item.userMessage(transcription.text));
const response = await chatSession.processRequest(request);
const summary = response.output
.map((item) => item.type === 'message'
? item.content ?? item.parts?.map((part) => part.text ?? '').join('') ?? ''
: item.type === 'text' ? item.text : '')
.join('');
console.log(`\nSummary:\n${summary}`);
// Clean up
chatSession.dispose();
await chatModel.unload();
console.log('\nDone. Models unloaded.');
系统提示影响模型的输出格式。 通过指示其生成“结构清晰、简洁并带有项目符号的笔记”,可获得结构化内容,而不是原始改写。
合并成完整的应用
创建一个名为app.js的文件,并添加以下完整代码,以便转录音频文件并总结转录内容:
// <imports>
import {
AudioSession,
ChatSession,
FoundryLocalManager,
Item,
Request
} from 'foundry-local-sdk';
import { fileURLToPath } from 'url';
import path from 'path';
// </imports>
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// <init>
// Initialize the Foundry Local SDK
const manager = FoundryLocalManager.create({
appName: 'foundry_local_samples',
logLevel: 'info'
});
// </init>
// Download and register all execution providers.
let currentEp = '';
await manager.downloadAndRegisterEps((epName, percent) => {
if (epName !== currentEp) {
if (currentEp !== '') process.stdout.write('\n');
currentEp = epName;
}
process.stdout.write(`\r ${epName.padEnd(30)} ${percent.toFixed(1).padStart(5)}%`);
});
if (currentEp !== '') process.stdout.write('\n');
// <transcription>
// Load the speech-to-text model
const speechModel = await manager.catalog.getModel('whisper-tiny');
await speechModel.download((progress) => {
process.stdout.write(
`\rDownloading speech model: ${progress.toFixed(2)}%`
);
});
console.log('\nSpeech model downloaded.');
await speechModel.load();
console.log('Speech model loaded.');
// Transcribe the audio file
const audioSession = new AudioSession(speechModel);
const audioFile = path.join(__dirname, 'meeting-notes.wav');
const transcriptionResponse = await audioSession.processRequest(
new Request().addItem(Item.audioFromUri(audioFile))
);
const transcription = transcriptionResponse.output.find(
(item) => item.type === 'speechResult'
);
if (!transcription) {
throw new Error('The speech model returned no transcription.');
}
console.log(`\nTranscription:\n${transcription.text}`);
// Unload the speech model to free memory
audioSession.dispose();
await speechModel.unload();
// </transcription>
// <summarization>
// Load the chat model for summarization
const chatModel = await manager.catalog.getModel('qwen2.5-0.5b');
await chatModel.download((progress) => {
process.stdout.write(
`\rDownloading chat model: ${progress.toFixed(2)}%`
);
});
console.log('\nChat model downloaded.');
await chatModel.load();
console.log('Chat model loaded.');
// Summarize the transcription into organized notes
const chatSession = new ChatSession(chatModel);
const request = new Request()
.addItem(Item.systemMessage(
'You are a note-taking assistant. Summarize ' +
'the following transcription into organized, ' +
'concise notes with bullet points.'
))
.addItem(Item.userMessage(transcription.text));
const response = await chatSession.processRequest(request);
const summary = response.output
.map((item) => item.type === 'message'
? item.content ?? item.parts?.map((part) => part.text ?? '').join('') ?? ''
: item.type === 'text' ? item.text : '')
.join('');
console.log(`\nSummary:\n${summary}`);
// Clean up
chatSession.dispose();
await chatModel.unload();
console.log('\nDone. Models unloaded.');
// </summarization>
注释
将'./meeting-notes.wav'替换为音频文件的路径。 支持的格式包括 WAV、MP3 和 FLAC。
运行记事记录器:
node app.js
会看到类似于以下内容的输出:
Downloading speech model: 100.00%
Speech model downloaded.
Speech model loaded.
Transcription:
OK so let's get started with the weekly sync. First, the backend
API is nearly done. Sarah finished the authentication endpoints
yesterday. We still need to add rate limiting before we go to
staging. On the frontend, the dashboard redesign is about seventy
percent complete. Jake, can you walk us through the new layout?
Great. The charts look good. I think we should add a filter for
date range though. For testing, we have about eighty percent code
coverage on the API. We need to write integration tests for the
new auth flow before Friday. Let's plan to do a full regression
test next Tuesday before the release. Any blockers? OK, sounds
like we are in good shape. Let's wrap up.
Downloading chat model: 100.00%
Chat model downloaded.
Chat model loaded.
Summary:
- **Backend API**: Authentication endpoints complete. Rate limiting
still needed before staging deployment.
- **Frontend**: Dashboard redesign 70% complete. New chart layout
reviewed. Action item: add a date range filter.
- **Testing**: API code coverage at 80%. Integration tests for the
auth flow due Friday. Full regression test scheduled for next
Tuesday before release.
- **Status**: No blockers reported. Team is on track.
Done. Models unloaded.
应用程序首先转录音频内容,然后将该文本传递给聊天模型,该模型提取关键点并将其组织成结构化笔记。
安装软件包
示例存储库
本文的完整示例代码在 foundry-samples GitHub 存储库中提供。 若要克隆存储库并导航到示例,请使用:
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/python/foundry-local/tutorial-voice-to-text
pip install foundry-local-sdk openai
转录音频文件
在此步骤中,将加载语音转文本模型并转录音频文件。 Foundry Local SDK 使用 whisper 模型的别名来为您的硬件选择最佳的 Whisper 变体。
创建名为 的文件
app.py。添加以下代码以初始化 SDK、加载语音模型并转录音频文件:
# Load the speech-to-text model. speech_model = manager.catalog.get_model("whisper-tiny") if speech_model is None: raise RuntimeError("Model 'whisper-tiny' was not found in the catalog.") download_if_needed(speech_model, "speech") speech_model.load() print("Speech model loaded.") try: # Transcribe the audio file with a native audio session. with AudioSession(speech_model) as session: with Request().add_item(AudioItem.from_uri(audio_path)) as request: with session.process_request(request) as response: transcription = get_text(response) print(f"\nTranscription:\n{transcription}") finally: # Unload the speech model to free memory. if speech_model.is_loaded: speech_model.unload()该方法
get_audio_client返回用于音频操作的客户端。 该方法transcribe接受文件路径,并返回包含text转录内容的属性的对象。
注释
将"meeting-notes.wav"替换为音频文件的路径。 支持的格式包括 WAV、MP3 和 FLAC。
汇总听录
现在,使用聊天模型将原始听录组织到结构化笔记中。 加载 qwen2.5-0.5b 模型,并将转录内容作为上下文发送,同时使用系统提示指示模型生成干净、摘要化的笔记。
在听录步骤后添加以下代码:
# Load the chat model for summarization.
chat_model = manager.catalog.get_model("qwen2.5-0.5b")
if chat_model is None:
manager.close()
raise RuntimeError("Model 'qwen2.5-0.5b' was not found in the catalog.")
download_if_needed(chat_model, "chat")
chat_model.load()
print("Chat model loaded.")
try:
# Summarize the transcription into organized notes.
with ChatSession(chat_model) as session:
session.set_options(
RequestOptions(
search=SearchOptions(temperature=0.2, max_output_tokens=512)
)
)
with (
Request()
.add_item(
MessageItem.system(
"You are a note-taking assistant. Summarize the following "
"transcription into organized, concise notes with bullet points."
)
)
.add_item(MessageItem.user(transcription)) as request
):
with session.process_request(request) as response:
summary = get_text(response)
print(f"\nSummary:\n{summary}")
finally:
# Clean up.
if chat_model.is_loaded:
chat_model.unload()
manager.close()
print("\nDone. Models unloaded.")
系统提示影响模型的输出格式。 通过指示其生成“结构清晰、简洁并带有项目符号的笔记”,可获得结构化内容,而不是原始改写。
合并成完整的应用
创建一个名为app.py的文件,并添加以下完整代码,以便转录音频文件并总结转录内容:
# <imports>
import sys
from foundry_local_sdk import (
AudioItem,
AudioSession,
ChatSession,
Configuration,
FoundryLocalManager,
MessageItem,
Request,
RequestOptions,
SearchOptions,
SpeechResultItem,
TextItem,
)
# </imports>
def download_if_needed(model, label):
if model.is_cached:
print(f"Using cached {label} model {model.id}.")
return
model.download(
lambda progress: print(
f"\rDownloading {label} model: {progress:.2f}%",
end="",
flush=True,
)
)
print()
def get_text(response):
parts = []
for item in response:
if isinstance(item, SpeechResultItem):
parts.append(item.text)
elif isinstance(item, TextItem):
parts.append(item.text)
elif isinstance(item, MessageItem):
parts.extend(part.text for part in item.parts if isinstance(part, TextItem))
return "".join(parts)
def main():
# <init>
# Initialize the Foundry Local SDK
config = Configuration(app_name="foundry_local_samples")
FoundryLocalManager.initialize(config)
manager = FoundryLocalManager.instance
# </init>
audio_path = sys.argv[1] if len(sys.argv) > 1 else "meeting-notes.wav"
# <transcription>
# Load the speech-to-text model.
speech_model = manager.catalog.get_model("whisper-tiny")
if speech_model is None:
raise RuntimeError("Model 'whisper-tiny' was not found in the catalog.")
download_if_needed(speech_model, "speech")
speech_model.load()
print("Speech model loaded.")
try:
# Transcribe the audio file with a native audio session.
with AudioSession(speech_model) as session:
with Request().add_item(AudioItem.from_uri(audio_path)) as request:
with session.process_request(request) as response:
transcription = get_text(response)
print(f"\nTranscription:\n{transcription}")
finally:
# Unload the speech model to free memory.
if speech_model.is_loaded:
speech_model.unload()
# </transcription>
# <summarization>
# Load the chat model for summarization.
chat_model = manager.catalog.get_model("qwen2.5-0.5b")
if chat_model is None:
manager.close()
raise RuntimeError("Model 'qwen2.5-0.5b' was not found in the catalog.")
download_if_needed(chat_model, "chat")
chat_model.load()
print("Chat model loaded.")
try:
# Summarize the transcription into organized notes.
with ChatSession(chat_model) as session:
session.set_options(
RequestOptions(
search=SearchOptions(temperature=0.2, max_output_tokens=512)
)
)
with (
Request()
.add_item(
MessageItem.system(
"You are a note-taking assistant. Summarize the following "
"transcription into organized, concise notes with bullet points."
)
)
.add_item(MessageItem.user(transcription)) as request
):
with session.process_request(request) as response:
summary = get_text(response)
print(f"\nSummary:\n{summary}")
finally:
# Clean up.
if chat_model.is_loaded:
chat_model.unload()
manager.close()
print("\nDone. Models unloaded.")
# </summarization>
if __name__ == "__main__":
main()
注释
将"meeting-notes.wav"替换为音频文件的路径。 支持的格式包括 WAV、MP3 和 FLAC。
运行记事记录器:
python app.py
会看到类似于以下内容的输出:
Downloading speech model: 100.00%
Speech model loaded.
Transcription:
OK so let's get started with the weekly sync. First, the backend
API is nearly done. Sarah finished the authentication endpoints
yesterday. We still need to add rate limiting before we go to
staging. On the frontend, the dashboard redesign is about seventy
percent complete. Jake, can you walk us through the new layout?
Great. The charts look good. I think we should add a filter for
date range though. For testing, we have about eighty percent code
coverage on the API. We need to write integration tests for the
new auth flow before Friday. Let's plan to do a full regression
test next Tuesday before the release. Any blockers? OK, sounds
like we are in good shape. Let's wrap up.
Downloading chat model: 100.00%
Chat model loaded.
Summary:
- **Backend API**: Authentication endpoints complete. Rate limiting
still needed before staging deployment.
- **Frontend**: Dashboard redesign 70% complete. New chart layout
reviewed. Action item: add a date range filter.
- **Testing**: API code coverage at 80%. Integration tests for the
auth flow due Friday. Full regression test scheduled for next
Tuesday before release.
- **Status**: No blockers reported. Team is on track.
Done. Models unloaded.
应用程序首先转录音频内容,然后将该文本传递给聊天模型,该模型提取关键点并将其组织成结构化笔记。
安装软件包
示例存储库
本文的完整示例代码在 foundry-samples GitHub 存储库中提供。 若要克隆存储库并导航到示例,请使用:
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/rust/foundry-local/tutorial-voice-to-text
cargo add foundry-local-sdk
cargo add tokio --features full
cargo add tokio-stream anyhow
转录音频文件
在此步骤中,将加载语音转文本模型并转录音频文件。 Foundry Local SDK 使用 whisper 模型的别名来为您的硬件选择最佳的 Whisper 变体。
打开
src/main.rs并将其内容替换为以下代码来初始化 SDK、加载语音模型并转录音频文件:let speech_model = manager.catalog().get_model("whisper-tiny").await?; if !speech_model.is_cached().await? { println!("Downloading speech model..."); speech_model .download(Some(|progress: f64| { print!("\r {progress:.1}%"); io::stdout().flush().ok(); })) .await?; println!(); } speech_model.load().await?; println!("Speech model loaded."); let audio_session = AudioSession::new(&speech_model).await?; let audio_path = std::fs::canonicalize("meeting-notes.wav")?; let audio_uri = Url::from_file_path(&audio_path) .map_err(|_| format!("Could not convert {} to a file URI.", audio_path.display()))?; let audio = Item::audio_uri(audio_uri.as_str(), Some("wav"), 0, 0); let transcription = audio_session.transcribe(audio).await?; println!("\nTranscription:\n{transcription}"); drop(audio_session); speech_model.unload().await?;该方法
create_audio_client返回用于音频操作的客户端。 该方法transcribe接受文件路径,并返回包含text转录内容的字段的对象。
注释
将"meeting-notes.wav"替换为音频文件的路径。 支持的格式包括 WAV、MP3 和 FLAC。
汇总听录
现在,使用聊天模型将原始听录组织到结构化笔记中。 加载 qwen2.5-0.5b 模型,并将转录内容作为上下文发送,同时使用系统提示指示模型生成干净、摘要化的笔记。
在转录步骤后,在 main 函数内添加以下代码:
let chat_model = manager.catalog().get_model("qwen2.5-0.5b").await?;
if !chat_model.is_cached().await? {
println!("Downloading chat model...");
chat_model
.download(Some(|progress: f64| {
print!("\r {progress:.1}%");
io::stdout().flush().ok();
}))
.await?;
println!();
}
chat_model.load().await?;
println!("Chat model loaded.");
let chat_session = ChatSession::new(&chat_model).await?;
chat_session
.set_options(RequestOptions {
search: SearchOptions {
temperature: Some(0.7),
max_output_tokens: Some(512),
..Default::default()
},
..Default::default()
})
.await?;
let response = chat_session
.process_request(Request::from_items(vec![
Item::system_message(vec![Item::text(
"You are a note-taking assistant. Summarize the following transcription into \
organized, concise notes with bullet points.",
)]),
Item::user_message(vec![Item::text(transcription)]),
]))
.await?;
println!("\nSummary:");
for item in &response.items {
if let Some(message) = item.as_message() {
print!("{}", message.text());
} else if let Some(text) = item.as_text() {
print!("{text}");
}
}
println!();
drop(chat_session);
chat_model.unload().await?;
println!("\nDone. Models unloaded.");
系统提示影响模型的输出格式。 通过指示其生成“结构清晰、简洁并带有项目符号的笔记”,可获得结构化内容,而不是原始改写。
合并成完整的应用
将src/main.rs的内容替换为以下完整代码,该代码用于转录音频文件并汇总转录文本:
// <imports>
use foundry_local_sdk::{
AudioSession, ChatSession, FoundryLocalConfig, FoundryLocalManager, Item, Request,
RequestOptions, SearchOptions,
};
use std::io::{self, Write};
use url::Url;
// </imports>
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// <init>
// Initialize the Foundry Local SDK
let manager = FoundryLocalManager::create(FoundryLocalConfig::new("foundry_local_samples"))?;
// </init>
manager
.download_and_register_eps_with_progress(None, {
let mut current_ep = String::new();
move |ep_name: &str, percent: f64| {
if ep_name != current_ep {
if !current_ep.is_empty() {
println!();
}
current_ep = ep_name.to_string();
}
print!("\r {ep_name:<30} {percent:5.1}%");
io::stdout().flush().ok();
}
})
.await?;
println!();
// <transcription>
let speech_model = manager.catalog().get_model("whisper-tiny").await?;
if !speech_model.is_cached().await? {
println!("Downloading speech model...");
speech_model
.download(Some(|progress: f64| {
print!("\r {progress:.1}%");
io::stdout().flush().ok();
}))
.await?;
println!();
}
speech_model.load().await?;
println!("Speech model loaded.");
let audio_session = AudioSession::new(&speech_model).await?;
let audio_path = std::fs::canonicalize("meeting-notes.wav")?;
let audio_uri = Url::from_file_path(&audio_path)
.map_err(|_| format!("Could not convert {} to a file URI.", audio_path.display()))?;
let audio = Item::audio_uri(audio_uri.as_str(), Some("wav"), 0, 0);
let transcription = audio_session.transcribe(audio).await?;
println!("\nTranscription:\n{transcription}");
drop(audio_session);
speech_model.unload().await?;
// </transcription>
// <summarization>
let chat_model = manager.catalog().get_model("qwen2.5-0.5b").await?;
if !chat_model.is_cached().await? {
println!("Downloading chat model...");
chat_model
.download(Some(|progress: f64| {
print!("\r {progress:.1}%");
io::stdout().flush().ok();
}))
.await?;
println!();
}
chat_model.load().await?;
println!("Chat model loaded.");
let chat_session = ChatSession::new(&chat_model).await?;
chat_session
.set_options(RequestOptions {
search: SearchOptions {
temperature: Some(0.7),
max_output_tokens: Some(512),
..Default::default()
},
..Default::default()
})
.await?;
let response = chat_session
.process_request(Request::from_items(vec![
Item::system_message(vec![Item::text(
"You are a note-taking assistant. Summarize the following transcription into \
organized, concise notes with bullet points.",
)]),
Item::user_message(vec![Item::text(transcription)]),
]))
.await?;
println!("\nSummary:");
for item in &response.items {
if let Some(message) = item.as_message() {
print!("{}", message.text());
} else if let Some(text) = item.as_text() {
print!("{text}");
}
}
println!();
drop(chat_session);
chat_model.unload().await?;
println!("\nDone. Models unloaded.");
// </summarization>
Ok(())
}
注释
将"meeting-notes.wav"替换为音频文件的路径。 支持的格式包括 WAV、MP3 和 FLAC。
运行记事记录器:
cargo run
会看到类似于以下内容的输出:
Downloading speech model: 100.00%
Speech model loaded.
Transcription:
OK so let's get started with the weekly sync. First, the backend
API is nearly done. Sarah finished the authentication endpoints
yesterday. We still need to add rate limiting before we go to
staging. On the frontend, the dashboard redesign is about seventy
percent complete. Jake, can you walk us through the new layout?
Great. The charts look good. I think we should add a filter for
date range though. For testing, we have about eighty percent code
coverage on the API. We need to write integration tests for the
new auth flow before Friday. Let's plan to do a full regression
test next Tuesday before the release. Any blockers? OK, sounds
like we are in good shape. Let's wrap up.
Downloading chat model: 100.00%
Chat model loaded.
Summary:
- **Backend API**: Authentication endpoints complete. Rate limiting
still needed before staging deployment.
- **Frontend**: Dashboard redesign 70% complete. New chart layout
reviewed. Action item: add a date range filter.
- **Testing**: API code coverage at 80%. Integration tests for the
auth flow due Friday. Full regression test scheduled for next
Tuesday before release.
- **Status**: No blockers reported. Team is on track.
Done. Models unloaded.
应用程序首先转录音频内容,然后将该文本传递给聊天模型,该模型提取关键点并将其组织成结构化笔记。
示例存储库
克隆 Foundry 示例GitHub存储库并转到 C++ 示例:
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/cpp/foundry-local/tutorial-voice-to-text
安装软件包
C++ 示例需要:
配置并生成示例:
cmake -S . -B build
cmake --build build --config Release
在配置期间,示例将 Microsoft.AI.Foundry.Local.Runtime NuGet 包的 2.2.1 版本还原到 build/_packages。 该包包含用于 Windows、Linux 和 macOS 的 C++ 标头和本机库。 不需要单独的 WinML 包。
CMake 配置根据你的操作系统和体系结构选择运行时资源,并将所需的本机库复制到可执行文件所在目录。 在 macOS 和 Linux 上,从 build中运行可执行文件。 在 Windows 上,从 build 中运行 .exe 文件。
转录音频文件
加载语音模型并转录音频文件:
auto speech_model = manager.GetCatalog().GetModel("whisper-tiny");
if (!speech_model) {
throw std::runtime_error("Model 'whisper-tiny' was not found in the catalog.");
}
DownloadIfNeeded(*speech_model, "speech");
speech_model->Load();
std::string transcript;
{
AudioSession session(*speech_model);
Request request{Item::AudioFromUri(argv[1])};
transcript = ResponseText(session.ProcessRequest(request));
}
speech_model->Unload();
std::cout << "Transcription:\n" << transcript << "\n";
汇总听录
加载聊天模型并将转录文本转换为结构化笔记:
auto chat_model = manager.GetCatalog().GetModel("qwen2.5-0.5b");
if (!chat_model) {
throw std::runtime_error("Model 'qwen2.5-0.5b' was not found in the catalog.");
}
DownloadIfNeeded(*chat_model, "chat");
chat_model->Load();
{
ChatSession session(*chat_model);
Request request{
SystemMessage(
"Turn the transcription into concise meeting notes with action items."),
UserMessage(transcript),
};
request.SetOptions({
.search = {.temperature = 0.2F, .max_output_tokens = 512, .seed = 42},
});
std::cout << "Summary:\n" << ResponseText(session.ProcessRequest(request)) << "\n";
}
chat_model->Unload();
合并步骤
#include <foundry_local/foundry_local_cpp.h>
#include <iostream>
#include <string>
using namespace foundry_local;
void DownloadIfNeeded(IModel& model, const std::string& label) {
if (model.IsCached()) {
std::cout << "Using cached " << label << " model.\n";
return;
}
model.Download([&label](float progress) {
std::cout << "\rDownloading " << label << " model: " << static_cast<int>(progress) << "%"
<< std::flush;
return 0;
});
std::cout << "\n";
}
std::string ResponseText(const Response& response) {
std::string text;
for (const Item& item : response.GetItems()) {
if (item.GetType() == FOUNDRY_LOCAL_ITEM_SPEECH_RESULT) {
text.append(item.GetSpeechResult().text);
} else if (item.GetType() == FOUNDRY_LOCAL_ITEM_TEXT) {
text.append(item.GetText().text);
} else if (item.GetType() == FOUNDRY_LOCAL_ITEM_MESSAGE) {
for (const Item& part : item.GetMessage().parts) {
if (part.GetType() == FOUNDRY_LOCAL_ITEM_TEXT) {
text.append(part.GetText().text);
}
}
}
}
return text;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Usage: tutorial-voice-to-text <audio-file>\n";
return 1;
}
try {
Configuration config("foundry_local_cpp_voice_to_text");
Manager manager(std::move(config));
// <transcription>
auto speech_model = manager.GetCatalog().GetModel("whisper-tiny");
if (!speech_model) {
throw std::runtime_error("Model 'whisper-tiny' was not found in the catalog.");
}
DownloadIfNeeded(*speech_model, "speech");
speech_model->Load();
std::string transcript;
{
AudioSession session(*speech_model);
Request request{Item::AudioFromUri(argv[1])};
transcript = ResponseText(session.ProcessRequest(request));
}
speech_model->Unload();
std::cout << "Transcription:\n" << transcript << "\n";
// </transcription>
// <summarization>
auto chat_model = manager.GetCatalog().GetModel("qwen2.5-0.5b");
if (!chat_model) {
throw std::runtime_error("Model 'qwen2.5-0.5b' was not found in the catalog.");
}
DownloadIfNeeded(*chat_model, "chat");
chat_model->Load();
{
ChatSession session(*chat_model);
Request request{
SystemMessage(
"Turn the transcription into concise meeting notes with action items."),
UserMessage(transcript),
};
request.SetOptions({
.search = {.temperature = 0.2F, .max_output_tokens = 512, .seed = 42},
});
std::cout << "Summary:\n" << ResponseText(session.ProcessRequest(request)) << "\n";
}
chat_model->Unload();
// </summarization>
manager.Shutdown();
} catch (const Error& error) {
std::cerr << "Foundry Local error [" << error.Code() << "]: " << error.what() << "\n";
return 1;
} catch (const std::exception& error) {
std::cerr << "Error: " << error.what() << "\n";
return 1;
}
return 0;
}
使用音频文件路径运行笔记记录程序:
./build/tutorial-voice-to-text path/to/audio.wav
清理资源
卸载模型后,模型权重将保留在本地缓存中。 这意味着下次运行应用程序时,将跳过下载步骤,模型加载速度更快。 除非需要回收磁盘空间,否则不需要进行额外的清理。