随着音频内容消费的日益普及,将文档或书面内容转换为真实音频格式的能力最近已成为趋势。
虽然 Google 的 NotebookLM 在这个领域引起了关注,但我想探索使用现代云服务构建类似的系统。在本文中,我将向您介绍如何创建一个可扩展的云原生系统,该系统使用 FastAPI、Firebase、Google Cloud Pub/Sub 和 Azure 的文本转语音服务将文档转换为高质量的播客。
这里有一个展示,您可以参考该系统的结果:MyPodify Showcase
将文档转换为播客并不像通过文本转语音引擎运行文本那么简单。它需要仔细的处理、自然语言的理解以及处理各种文档格式的能力,同时保持流畅的用户体验。系统需要:
让我们分解关键组件并了解它们如何协同工作:
FastAPI 作为我们的后端框架,选择它有几个令人信服的原因:
这是我们的上传端点的详细信息:
@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'}
Firebase 为我们的应用程序提供了两项关键服务:
以下是我们实现实时状态更新的方法:
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)
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'}
我们音频生成的核心使用 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
工作组件处理繁重的工作:
文献分析
内容处理
音频生成
这是我们的工作逻辑的简化视图:
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
系统实现了全面的错误处理:
重试逻辑
状态追踪
资源清理
为了处理生产负载,我们实施了多项优化:
工作人员缩放
存储优化
处理优化
系统包括全面监控:
@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'}
虽然当前系统运行良好,但未来的改进还有一些令人兴奋的可能性:
增强的音频处理
内容增强
平台整合
构建文档到播客转换器是进入现代云架构的激动人心的旅程。 FastAPI、Firebase、Google Cloud Pub/Sub 和 Azure 的文本转语音服务的组合为大规模处理复杂的文档处理提供了坚实的基础。
事件驱动的架构确保系统在负载下保持响应,而托管服务的使用减少了运营开销。无论您是构建类似的系统还是只是探索云原生架构,我希望这次深入研究能够为构建可扩展、生产就绪的应用程序提供宝贵的见解。
想了解更多有关云架构和现代应用程序开发的信息吗?关注我,获取更多技术实用教程。
以上是如何构建您自己的 Google NotebookLM的详细内容。更多信息请关注PHP中文网其他相关文章!