I have a video.mp4 in content/video.mp4
if I wanted to play the video in google colab without downloading , ¿what code I should use to open a kind of video player in my jupyter notebook?
To start, log into your Google Account and go to Google Drive. Click on the New button on the left and select Colaboratory if it is installed (if not click on Connect more apps, search for Colaboratory and install it). From there, import Pandas as shown below (Colab has it installed already).
Here's the code
from IPython.display import HTML
from base64 import b64encode
mp4 = open('video.mp4','rb').read()
data_url = "data:video/mp4;base64," + b64encode(mp4).decode()
HTML("""
<video width=400 controls>
<source src="%s" type="video/mp4">
</video>
""" % data_url)
You can test it in a colab notebook here.
To support a big vdo file, I write a library to upload to Google Drive and set it public. Then use the returned URL to display the video.
!pip install -U kora
from kora.drive import upload_public
url = upload_public('video.mp4')
# then display it
from IPython.display import HTML
HTML(f"""<video src={url} width=500 controls/>""")
Currently, we need to compress the video file to play it in google colaboratory, if the format is not supported.
from IPython.display import HTML
from base64 import b64encode
import os
# Input video path
save_path = "/content/videos/result.mp4"
# Compressed video path
compressed_path = "/content/videos/result_compressed.mp4"
os.system(f"ffmpeg -i {save_path} -vcodec libx264 {compressed_path}")
# Show video
mp4 = open(compressed_path,'rb').read()
data_url = "data:video/mp4;base64," + b64encode(mp4).decode()
HTML("""
<video width=400 controls>
<source src="%s" type="video/mp4">
</video>
""" % data_url)
Reference: https://towardsdatascience.com/yolov3-pytorch-on-google-colab-c4a79eeecdea
Just input the mp4 video path to that function and you're good to go.
from IPython.display import HTML
from base64 import b64encode
def show_video(video_path, video_width = 600):
video_file = open(video_path, "r+b").read()
video_url = f"data:video/mp4;base64,{b64encode(video_file).decode()}"
return HTML(f"""<video width={video_width} controls><source src="{video_url}"></video>""")
show_video(video_path)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With