随着音频内容消费的日益普及,将文档或书面内容转换为真实音频格式的能力最近已成为趋势。
虽然 Google 的 NotebookLM 在这个领域引起了关注,但我想探索使用现代云服务构建类似的系统。在本文中,我将向您介绍如何创建一个可扩展的云原生系统,该系统使用 FastAPI、Firebase、Google Cloud Pub/Sub 和 Azure 的文本转语音服务将文档转换为高质量的播客。
这里有一个展示,您可以参考该系统的结果:MyPodify Showcase
挑战
将文档转换为播客并不像通过文本转语音引擎运行文本那么简单。它需要仔细的处理、自然语言的理解以及处理各种文档格式的能力,同时保持流畅的用户体验。系统需要:
- 高效处理多种文档格式
- 生成具有多种声音的自然声音音频
- 应对大规模文档处理而不影响用户体验
- 为用户提供实时状态更新
- 保持高可用性和可扩展性
架构深度探究
让我们分解关键组件并了解它们如何协同工作:
1.FastAPI后端
FastAPI 作为我们的后端框架,选择它有几个令人信服的原因:
- 异步支持:FastAPI 的异步功能构建于 Starlette 之上,可有效处理并发请求
- 自动 OpenAPI 文档:生成开箱即用的交互式 API 文档
- 类型安全:利用 Python 的类型提示进行运行时验证
- 高性能:速度可与 Node.js 和 Go 相媲美
这是我们的上传端点的详细信息:
@app.post('/upload') async def upload_files( token: Annotated[ParsedToken, Depends(verify_firebase_token)], project_name: str, description: str, website_link: str, host_count: int, files: Optional[List[UploadFile]] = File(None) ): # Validate token user_id = token['uid'] # Generate unique identifiers project_id = str(uuid.uuid4()) podcast_id = str(uuid.uuid4()) # Process and store files file_urls = await process_uploads(files, user_id, project_id) # Create Firestore document await create_project_document(user_id, project_id, { 'status': 'pending', 'created_at': datetime.now(), 'project_name': project_name, 'description': description, 'file_urls': file_urls }) # Trigger async processing await publish_to_pubsub(user_id, project_id, podcast_id, file_urls) return {'project_id': project_id, 'status': 'processing'}
2.Firebase集成
Firebase 为我们的应用程序提供了两项关键服务:
Firebase 存储
- 通过自动缩放处理安全文件上传
- 为生成的音频文件提供 CDN 支持的分发
- 支持大文件断点续传
火库
- 用于项目状态跟踪的实时数据库
- 基于文档的结构非常适合项目元数据
- 自动缩放,无需手动分片
以下是我们实现实时状态更新的方法:
async def update_status(user_id: str, project_id: str, status: str, metadata: dict = None): doc_ref = db.collection('projects').document(f'{user_id}/{project_id}') update_data = { 'status': status, 'updated_at': datetime.now() } if metadata: update_data.update(metadata) await doc_ref.update(update_data)
3. 谷歌云发布/订阅
Pub/Sub 作为我们的消息传递主干,支持:
- 解耦架构以实现更好的可扩展性
- 至少一次交货保证
- 自动消息保留和重播
- 失败消息的死信队列
消息结构示例:
@app.post('/upload') async def upload_files( token: Annotated[ParsedToken, Depends(verify_firebase_token)], project_name: str, description: str, website_link: str, host_count: int, files: Optional[List[UploadFile]] = File(None) ): # Validate token user_id = token['uid'] # Generate unique identifiers project_id = str(uuid.uuid4()) podcast_id = str(uuid.uuid4()) # Process and store files file_urls = await process_uploads(files, user_id, project_id) # Create Firestore document await create_project_document(user_id, project_id, { 'status': 'pending', 'created_at': datetime.now(), 'project_name': project_name, 'description': description, 'file_urls': file_urls }) # Trigger async processing await publish_to_pubsub(user_id, project_id, podcast_id, file_urls) return {'project_id': project_id, 'status': 'processing'}
4. 使用 Azure 语音服务生成语音
我们音频生成的核心使用 Azure 的认知服务语音 SDK。让我们看看我们如何实现听起来自然的语音合成:
async def update_status(user_id: str, project_id: str, status: str, metadata: dict = None): doc_ref = db.collection('projects').document(f'{user_id}/{project_id}') update_data = { 'status': status, 'updated_at': datetime.now() } if metadata: update_data.update(metadata) await doc_ref.update(update_data)
我们系统的独特功能之一是能够使用人工智能生成多语音播客。以下是我们如何处理不同主机的脚本生成:
{ 'user_id': 'uid_123', 'project_id': 'proj_456', 'podcast_id': 'pod_789', 'file_urls': ['gs://bucket/file1.pdf'], 'description': 'Technical blog post about cloud architecture', 'host_count': 2, 'action': 'CREATE_PROJECT' }
对于语音合成,我们将不同的扬声器映射到特定的 Azure 语音:
import azure.cognitiveservices.speech as speechsdk from pathlib import Path class SpeechGenerator: def __init__(self): self.speech_config = speechsdk.SpeechConfig( subscription=os.getenv("AZURE_SPEECH_KEY"), region=os.getenv("AZURE_SPEECH_REGION") ) async def create_speech_segment(self, text, voice, output_file): try: self.speech_config.speech_synthesis_voice_name = voice synthesizer = speechsdk.SpeechSynthesizer( speech_config=self.speech_config, audio_config=None ) # Generate speech from text result = synthesizer.speak_text_async(text).get() if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted: with open(output_file, "wb") as audio_file: audio_file.write(result.audio_data) return True return False except Exception as e: logger.error(f"Speech synthesis failed: {str(e)}") return False
5. 后台处理工作者
工作组件处理繁重的工作:
-
文献分析
- 从各种文档格式中提取文本
- 分析文档结构和内容
- 确定关键主题和部分
-
内容处理
- 生成自然的对话流
- 将内容分割成演讲者片段
- 创建主题之间的过渡
-
音频生成
- 使用 Azure 的神经语音将文本转换为语音
- 处理多个说话者的声音
- 应用音频后处理
这是我们的工作逻辑的简化视图:
async def generate_podcast_script(outline: str, analysis: str, host_count: int): # System instructions for different podcast formats system_instructions = TWO_HOST_SYSTEM_PROMPT if host_count > 1 else ONE_HOST_SYSTEM_PROMPT # Example of how we structure the AI conversation if host_count > 1: script_format = """ **Alex**: "Hello and welcome to MyPodify! I'm your host Alex, joined by..." **Jane**: "Hi everyone! I'm Jane, and today we're diving into {topic}..." """ else: script_format = """ **Alex**: "Welcome to MyPodify! Today we're exploring {topic}..." """ # Generate the complete script using AI script = await generate_content_from_openai( content=f"{outline}\n\nContent Details:{analysis}", system_instructions=system_instructions, purpose="Podcast Script" ) return script
错误处理和可靠性
系统实现了全面的错误处理:
-
重试逻辑
- API 调用失败的指数退避
- 最大重试次数配置
- 失败消息的死信队列
-
状态追踪
- Firestore 中存储的详细错误消息
- 向用户实时更新状态
- 监控错误聚合
-
资源清理
- 自动删除临时文件
- 上传清理失败
- 孤立资源检测
扩展和性能优化
为了处理生产负载,我们实施了多项优化:
-
工作人员缩放
- 基于队列长度的水平扩展
- 基于资源的自动缩放
- 区域部署以降低延迟
-
存储优化
- 内容去重
- 压缩音频存储
- CDN 集成交付
-
处理优化
- 类似文档的批量处理
- 缓存重复内容
- 尽可能并行处理
监控和可观察性
系统包括全面监控:
@app.post('/upload') async def upload_files( token: Annotated[ParsedToken, Depends(verify_firebase_token)], project_name: str, description: str, website_link: str, host_count: int, files: Optional[List[UploadFile]] = File(None) ): # Validate token user_id = token['uid'] # Generate unique identifiers project_id = str(uuid.uuid4()) podcast_id = str(uuid.uuid4()) # Process and store files file_urls = await process_uploads(files, user_id, project_id) # Create Firestore document await create_project_document(user_id, project_id, { 'status': 'pending', 'created_at': datetime.now(), 'project_name': project_name, 'description': description, 'file_urls': file_urls }) # Trigger async processing await publish_to_pubsub(user_id, project_id, podcast_id, file_urls) return {'project_id': project_id, 'status': 'processing'}
未来的增强功能
虽然当前系统运行良好,但未来的改进还有一些令人兴奋的可能性:
-
增强的音频处理
- 背景音乐整合
- 高级音频效果
- 自定义语音训练
-
内容增强
- 自动章节标记
- 互动文字记录
- 多语言支持
-
平台整合
- 直接播客平台发布
- RSS feed 生成
- 社交媒体分享
构建文档到播客转换器是进入现代云架构的激动人心的旅程。 FastAPI、Firebase、Google Cloud Pub/Sub 和 Azure 的文本转语音服务的组合为大规模处理复杂的文档处理提供了坚实的基础。
事件驱动的架构确保系统在负载下保持响应,而托管服务的使用减少了运营开销。无论您是构建类似的系统还是只是探索云原生架构,我希望这次深入研究能够为构建可扩展、生产就绪的应用程序提供宝贵的见解。
想了解更多有关云架构和现代应用程序开发的信息吗?关注我,获取更多技术实用教程。
以上是如何构建您自己的 Google NotebookLM的详细内容。更多信息请关注PHP中文网其他相关文章!

Tomergelistsinpython,YouCanusethe操作员,estextMethod,ListComprehension,Oritertools

在Python3中,可以通过多种方法连接两个列表:1)使用 运算符,适用于小列表,但对大列表效率低;2)使用extend方法,适用于大列表,内存效率高,但会修改原列表;3)使用*运算符,适用于合并多个列表,不修改原列表;4)使用itertools.chain,适用于大数据集,内存效率高。

使用join()方法是Python中从列表连接字符串最有效的方法。1)使用join()方法高效且易读。2)循环使用 运算符对大列表效率低。3)列表推导式与join()结合适用于需要转换的场景。4)reduce()方法适用于其他类型归约,但对字符串连接效率低。完整句子结束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的关键特性包括:1.语法简洁易懂,适合初学者;2.动态类型系统,提高开发速度;3.丰富的标准库,支持多种任务;4.强大的社区和生态系统,提供广泛支持;5.解释性,适合脚本和快速原型开发;6.多范式支持,适用于各种编程风格。

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver CS6
视觉化网页开发工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

WebStorm Mac版
好用的JavaScript开发工具