Научный журнал «Вестник науки»

Режим работы с 09:00 по 23:00

zhurnal@vestnik-nauki.com

Информационное письмо
  1. Главная
  2. Архив
  3. Вестник науки от 13 апреля 2025 г.
  4. Научная статья № 77
Просмотры  212 просмотров

FROM BATCH TO STREAM: SOLVING MEMORY BOTTLENECKS IN VIDEO ML PIPELINES WITH PYAV AND SMART OPEN

Abstract: this article explores the transition from batch video processing to a more scalable and memory-efficient streaming approach using modern Python tools. Initially, the team processed videos by downloading entire files from S3 storage, decoding and analyzing each frame, and reassembling the output before uploading it back to S3. However, this method proved inefficient and unsuitable for scaling within Kubernetes due to high and variable memory usage.To address this, the authors implemented a streaming pipeline using PyAV, smart_open, and boto3, enabling real-time video processing directly from and to S3 – without creating temporary local files. The article details the pipeline’s design, library selection, and implementation, demonstrating how video frames can be processed on the fly through a grayscale conversion example. This approach ensures constant memory usage and offers high flexibility for machine learning applications.

Keywords: video streaming, PyAV, AWS S3, Python, video processing pipeline, Kubernetes, smart open, media processing, memory optimization, scalable architecture.

LENECKS IN VIDEO ML PIPELINES WITH PYAV AND SMART OPEN WWАннотация: this article explores the transition from batch video processing to a more scalable and memory-efficient streaming approach using modern Python tools. Initially, the team processed videos by downloading entire files from S3 storage, decoding and analyzing each frame, and reassembling the output before uploading it back to S3. However, this method proved inefficient and unsuitable for scaling within Kubernetes due to high and variable memory usage.To address this, the authors implemented a streaming pipeline using PyAV, smart_open, and boto3, enabling real-time video processing directly from and to S3 – without creating temporary local files. The article details the pipeline’s design, library selection, and implementation, demonstrating how video frames can be processed on the fly through a grayscale conversion example.

This approach ensures constant memory usage and offers high flexibility for machine learning applications.Ключевые слова: video streaming, PyAV, AWS S3, Python, video processing pipeline, Kubernetes, smart open, media processing, memory optimization, scalable architecture.TTIntroduction. It’s hard to imagine modern life without video streaming – from favorite series on Netflix to educational videos on YouTube and more. In the early days of the internet, such things were inaccessible – if you wanted to watch something, you had to download the entire video file to your device. Given the download speeds back then, this process was painfully slow.In our project, we initially started by downloading the entire video file for processing.

The workflow followed these steps:1.Download the video from S3 storage,2.Split the video frame by frame and save each frame as a separate image,3.Process each image using ML algorithms,4.Reassemble the processed frames into a new video,5.Upload the resulting video to S3,6.Delete temporary files.However, it soon became clear that this approach was not horizontally scalable in Kubernetes for the following reasons:1.Video files were often large – up to 30 minutes long – which forced us to increase memory limits,2.The heterogeneity of input videos and the increasing memory consumption during processing prevented tasks from being scheduled on a single node – containers would crash due to memory shortages.Therefore, we needed to reduce memory consumption and make it constant. The logical solution was to switch to streaming video processing. Let’s now explore the pattern for this solution.Practical Part. Library Selection.

The primary toolkit for working with audio and video is FFmpeg [1]. Most people associate FFmpeg with the command-line utility, which is capable of solving the majority of tasks. However, in our case, we needed direct access to components such as containers, streams, packets, codecs, and frames. The following libraries are essential:1.libavcodec – for encoding and decoding audio and video,2.libavformat – for multiplexing and demultiplexing media containers.These libraries are written in C, whereas our machine learning pipeline is in Python.

Therefore, we needed a higher-level wrapper that provides Python bindings for libavcodec and libavformat. PyAV [2] is one such library – we’ll explore its capabilities with an example later.But first, let’s determine how to read and write data using S3 storage.PyAV accepts file descriptors as input. While it is possible to define file-like objects in Python using the Amazon boto3 library [3], its default interface isn’t particularly user-friendly. In particular, you must implement wrappers manually for the Object.upload_fileobj() and Object.download_fileobj() methods.

A more elegant alternative is the smart_open library [4]. It builds on boto3 and provides a unified, Pythonic API for working with S3.Implementation. After selecting the libraries, here is the full list of dependencies:Note: The following code is suitable for Python version 3.10 and above.To work with S3 storage, you’ll need the following:The first thing to highlight is the use of the Click library [6], which allows this script to be run as a CLI tool with custom arguments.Once dependencies are installed and environment variables are set, you can run the script like so:The result will be a video saved at s3://bucket/output_key.mp4 – without creating any local files!Breakdown of the Workflow. 1.Boto3 client: We create an S3 client for connecting to cloud storage.2.Streamed read/write: We read from and write to S3 using smart_open context managers.3.Non-seekable override: We override the seekable method of the S3 writer. This is necessary because S3 doesn’t support pointer repositioning during writes – as confirmed by the smart_open codebase [7].

This lets PyAV know we’re dealing with a non-seekable stream.4.Container setup: Media containers are opened using PyAV. For the output, we specify the format as mp4 and add the option "movflags": "frag_keyframe+empty_moov". These options are required for non-seekable output but may be unsupported in some players. For streaming tasks, consider using formats like WebM.5.Stream configuration: We create output streams by copying codec and format details from the input streams.

Although PyAV offers a shortcut (add_stream(template=input_stream)), it only works for remuxing (no decoding/encoding).6.Frame processing: The core loop demuxes packets, decodes frames, applies processing (e.g., grayscale conversion), encodes, and muxes them back. You can extend this part with other video transformations.7.Encoder flush: At the end, encoders are flushed to finalize the media file correctly.Conclusion. By shifting from traditional batch processing to a streaming model, the video processing pipeline achieves significant improvements in scalability and memory efficiency – key requirements for modern, containerized environments like Kubernetes. Leveraging PyAV for direct stream manipulation and smart_open for seamless S3 integration, this approach eliminates the need for large local buffers and temporary storage.

The presented solution serves as a flexible foundation for integrating custom ML processing into live media pipelines, and can be easily extended or adapted to support a variety of use cases beyond grayscale transformation. This architecture enables efficient, scalable, and cloud-native video processing, better aligning with the demands of today’s media-rich applications.


Полная версия статьи PDF

Номер журнала «Вестник науки» № 4 (85) том 2


Ссылка для цитирования:

Postovalov R.Y. FROM BATCH TO STREAM: SOLVING MEMORY BOTTLENECKS IN VIDEO ML PIPELINES WITH PYAV AND SMART OPEN // Журнал «Вестник науки» от 13 апреля 2025 г. № 4 (85) том 2. С. 635 - 640. 2025 г. ISSN 2712-8849 // Электронный ресурс: https://www.вестник-науки.рф/article/22257 (дата обращения: 29.11.2026 г.)


Альтернативная ссылка латинскими символами: vestnik-nauki.com/article/22257



Нашли грубую ошибку (плагиат, фальсифицированные данные или иные нарушения научно-издательской этики) ?
- напишите письмо в редакцию журнала: zhurnal@vestnik-nauki.com


Вестник науки © 2025.    16+




* В выпусках журнала могут упоминаться организации (Meta, Facebook, Instagram) в отношении которых судом принято вступившее в законную силу решение о ликвидации или запрете деятельности по основаниям, предусмотренным Федеральным законом от 25 июля 2002 года № 114-ФЗ «О противодействии экстремистской деятельности» (далее - Федеральный закон «О противодействии экстремистской деятельности»), или об организации, включенной в опубликованный единый федеральный список организаций, в том числе иностранных и международных организаций, признанных в соответствии с законодательством Российской Федерации террористическими, без указания на то, что соответствующее общественное объединение или иная организация ликвидированы или их деятельность запрещена.