Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

displaying large video files in google colab

the common way to display videos in google colab is like this:

from IPython.display import HTML
from base64 import b64encode
with open('video.mp4', 'rb') as f:
   display(HTML('<video><source src="data:video/mp4;base64,%s" type="video/mp4"></video>'%b64encode(f.read()).decode()))

however for moderately large video files, say tens of MB, this will cause colab to disconnect (showing only "runtime disconnected") and the video will not be displayed. indeed it does not seem sensible to try to write such a long string into the HTML. what would be the easiest fix? note that the HTML does not have access to the local filesystem due to CORS.

like image 856
o17t H1H' S'k Avatar asked Nov 26 '25 07:11

o17t H1H' S'k


1 Answers

There's no need for base64 encoding. You can use ordinary <video> tags to embed.

Here's a complete example: https://colab.research.google.com/drive/1GqZvHmOwGpo9QsrxeEpH93kswgVliQQl

Replicating the code here:

# Download a video file to be served locally.
!wget https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4

# Start a webserver in the background, running on port 8000.
%%script bash --bg
python3 -m http.server 8000

# Embed the video file.
%%html
<video controls autoplay><source src="http://localhost:8000/flower.mp4" type="video/mp4"></video>

The result is a typical video embed:

enter image description here

Colab will automatically proxy HTTP requests to locahost from Javascript to the backend VM. More details on why this works are described in the documentation here: https://colab.research.google.com/notebooks/snippets/advanced_outputs.ipynb#scrollTo=R8ZvCXC5A0wT

like image 165
Bob Smith Avatar answered Nov 28 '25 20:11

Bob Smith