-
Notifications
You must be signed in to change notification settings - Fork 396
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
processors: add AsyncGeneratorProcessor
- Loading branch information
1 parent
9461bac
commit 94ec68c
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# | ||
# Copyright (c) 2024, Daily | ||
# | ||
# SPDX-License-Identifier: BSD 2-Clause License | ||
# | ||
|
||
import asyncio | ||
|
||
from typing import Any, AsyncGenerator | ||
|
||
from pipecat.frames.frames import ( | ||
CancelFrame, | ||
EndFrame, | ||
Frame, | ||
) | ||
from pipecat.processors.frame_processor import FrameProcessor, FrameDirection | ||
from pipecat.serializers.base_serializer import FrameSerializer | ||
|
||
|
||
class AsyncGeneratorProcessor(FrameProcessor): | ||
def __init__(self, *, serializer: FrameSerializer, **kwargs): | ||
super().__init__(**kwargs) | ||
self._serializer = serializer | ||
self._data_queue = asyncio.Queue() | ||
|
||
async def process_frame(self, frame: Frame, direction: FrameDirection): | ||
await super().process_frame(frame, direction) | ||
|
||
if isinstance(frame, (CancelFrame, EndFrame)): | ||
await self._data_queue.put(None) | ||
else: | ||
data = self._serializer.serialize(frame) | ||
if data: | ||
await self._data_queue.put(data) | ||
|
||
async def generator(self) -> AsyncGenerator[Any, None]: | ||
running = True | ||
while running: | ||
data = await self._data_queue.get() | ||
running = data is not None | ||
if data: | ||
yield data |