Reputation: 2744
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.
Upvotes: 3
Views: 2303
Reputation: 38579
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:
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
Upvotes: 3
Reputation: 353
This problem persists for a couple of years now and the only viable solution that I know is using the kora
Python package. What it does is given a public video file URL, it uploads the video to Google Drive and sets it public, then uses the returned link to display the video.
Here's an example using a large video file that would typically give runtime error using the well-known method that you've mentioned earlier.
!wget http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/VolkswagenGTIReview.mp4
!mv VolkswagenGTIReview.mp4 video.mp4
!pip install -U kora
from IPython.display import HTML
from kora.drive import upload_public
url = upload_public('video.mp4')
HTML(f"""<video src={url} width=500 controls/>""")
The only drawback in the case of a live presentation is perhaps having to do Google account authentication for the API to work, but you can get around that by taking care of this part prior to your demonstration.
Upvotes: 1