what github repository of image to video ai can run on free colab?
- User
what github repository of image to video ai can run on free colab?
- Assistant
- User
- Assistant
what github repository of image to video ai can run on free colab?
There are several GitHub repositories for image-to-video AI models that you can run on free Google Colab, depending on what exactly you want to achieve (e.g., animating a single image, generating videos from images, or creating motion from still photos). Here are some of the popular repositories known to work on free Colab:
Pix2PixHD: https://github.com/NVIDIA/pix2pixHD
Vid2Vid: https://github.com/NVIDIA/vid2vid
May require GPUs with more memory than free Colab typically offers but lighter demos exist.
You can just upload your source image and driving video to produce a video output.
image animation first order motion colabimage to video ai colabdeepfake image animation colabIf you want me to share a direct working Colab notebook or help you get started with a specific project, please let me know!
it's a code of fomm for colab. can run it in colab with python 3.11 and verify the code and fix if necessairy: %%capture %pip install ffmpeg-python imageio-ffmpeg !git init . !git remote add origin https://github.com/AliaksandrSiarohin/first-order-model !git pull origin master !git clone https://github.com/graphemecluster/first-order-model-demo demo import IPython.display import PIL.Image import cv2 import ffmpeg import imageio import io import ipywidgets import numpy import os.path import requests import skimage.transform import warnings from base64 import b64encode from demo import load_checkpoints, make_animation # type: ignore (local file) from google.colab import files, output from IPython.display import HTML, Javascript from shutil import copyfileobj from skimage import img_as_ubyte from tempfile import NamedTemporaryFile from tqdm.auto import tqdm warnings.filterwarnings("ignore") os.makedirs("user", exist_ok=True)
display(HTML("""
"""))
def thumbnail(file): return imageio.get_reader(file, mode='I', format='FFMPEG').get_next_data()
def create_image(i, j): image_widget = ipywidgets.Image.from_file('demo/images/%d%d.png' % (i, j)) image_widget.add_class('resource') image_widget.add_class('resource-image') image_widget.add_class('resource-image%d%d' % (i, j)) return image_widget
def create_video(i): video_widget = ipywidgets.Image( value=cv2.imencode('.png', cv2.cvtColor(thumbnail('demo/videos/%d.mp4' % i), cv2.COLOR_RGB2BGR))[1].tostring(), format='png' ) video_widget.add_class('resource') video_widget.add_class('resource-video') video_widget.add_class('resource-video%d' % i) return video_widget
def create_title(title): title_widget = ipywidgets.Label(title) title_widget.add_class('title') return title_widget
def download_output(button): complete.layout.display = 'none' loading.layout.display = '' files.download('output.mp4') loading.layout.display = 'none' complete.layout.display = ''
def convert_output(button): complete.layout.display = 'none' loading.layout.display = '' ffmpeg.input('output.mp4').output('scaled.mp4', vf='scale=1080x1080:flags=lanczos,pad=1920:1080:420:0').overwrite_output().run() files.download('scaled.mp4') loading.layout.display = 'none' complete.layout.display = ''
def back_to_main(button): complete.layout.display = 'none' main.layout.display = ''
label_or = ipywidgets.Label('or') label_or.add_class('label-or')
image_titles = ['Peoples', 'Cartoons', 'Dolls', 'Game of Thrones', 'Statues'] image_lengths = [8, 4, 8, 9, 4]
image_tab = ipywidgets.Tab() image_tab.children = [ipywidgets.HBox([create_image(i, j) for j in range(length)]) for i, length in enumerate(image_lengths)] for i, title in enumerate(image_titles): image_tab.set_title(i, title)
input_image_widget = ipywidgets.Output() input_image_widget.add_class('input-widget') upload_input_image_button = ipywidgets.FileUpload(accept='image/*', button_style='primary') upload_input_image_button.add_class('input-button') image_part = ipywidgets.HBox([ ipywidgets.VBox([input_image_widget, upload_input_image_button]), label_or, image_tab ])
video_tab = ipywidgets.Tab() video_tab.children = [ipywidgets.HBox([create_video(i) for i in range(5)])] video_tab.set_title(0, 'All Videos')
input_video_widget = ipywidgets.Output() input_video_widget.add_class('input-widget') upload_input_video_button = ipywidgets.FileUpload(accept='video/*', button_style='primary') upload_input_video_button.add_class('input-button') video_part = ipywidgets.HBox([ ipywidgets.VBox([input_video_widget, upload_input_video_button]), label_or, video_tab ])
model = ipywidgets.Dropdown( description="Model:", options=[ 'vox', 'vox-adv', 'taichi', 'taichi-adv', 'nemo', 'mgif', 'fashion', 'bair' ] ) warning = ipywidgets.HTML('Warning: Upload your own images and videos (see README)') warning.add_class('warning') model_part = ipywidgets.HBox([model, warning])
relative = ipywidgets.Checkbox(description="Relative keypoint displacement (Inherit object proporions from the video)", value=True) adapt_movement_scale = ipywidgets.Checkbox(description="Adapt movement scale (Don’t touch unless you know want you are doing)", value=True) generate_button = ipywidgets.Button(description="Generate", button_style='primary') main = ipywidgets.VBox([ create_title('Choose Image'), image_part, create_title('Choose Video'), video_part, create_title('Settings'), model_part, relative, adapt_movement_scale, generate_button ])
loader = ipywidgets.Label() loader.add_class("loader") loading_label = ipywidgets.Label("This may take several minutes to process…") loading_label.add_class("loading-label") progress_bar = ipywidgets.Output() loading = ipywidgets.VBox([loader, loading_label, progress_bar]) loading.add_class('loading')
output_widget = ipywidgets.Output() output_widget.add_class('output-widget') download = ipywidgets.Button(description='Download', button_style='primary') download.add_class('output-button') download.on_click(download_output) convert = ipywidgets.Button(description='Convert to 1920×1080', button_style='primary') convert.add_class('output-button') convert.on_click(convert_output) back = ipywidgets.Button(description='Back', button_style='primary') back.add_class('output-button') back.on_click(back_to_main)
comparison_widget = ipywidgets.Output() comparison_widget.add_class('comparison-widget') comparison_label = ipywidgets.Label('Comparison') comparison_label.add_class('comparison-label') complete = ipywidgets.HBox([ ipywidgets.VBox([output_widget, download, convert, back]), ipywidgets.VBox([comparison_widget, comparison_label]) ])
display(ipywidgets.VBox([main, loading, complete])) display(Javascript(""" var images, videos; function deselectImages() { images.forEach(function(item) { item.classList.remove("selected"); }); } function deselectVideos() { videos.forEach(function(item) { item.classList.remove("selected"); }); } function invokePython(func) { google.colab.kernel.invokeFunction("notebook." + func, [].slice.call(arguments, 1), {}); } setTimeout(function() { (images = [].slice.call(document.getElementsByClassName("resource-image"))).forEach(function(item) { item.addEventListener("click", function() { deselectImages(); item.classList.add("selected"); invokePython("select_image", item.className.match(/resource-image(\d\d)/)[1]); }); }); images[0].classList.add("selected"); (videos = [].slice.call(document.getElementsByClassName("resource-video"))).forEach(function(item) { item.addEventListener("click", function() { deselectVideos(); item.classList.add("selected"); invokePython("select_video", item.className.match(/resource-video(\d)/)[1]); }); }); videos[0].classList.add("selected"); }, 1000); """))
selected_image = None def select_image(filename): global selected_image selected_image = resize(PIL.Image.open('demo/images/%s.png' % filename).convert("RGB")) input_image_widget.clear_output(wait=True) with input_image_widget: display(HTML('Image')) input_image_widget.remove_class('uploaded') output.register_callback("notebook.select_image", select_image)
selected_video = None def select_video(filename): global selected_video selected_video = 'demo/videos/%s.mp4' % filename input_video_widget.clear_output(wait=True) with input_video_widget: display(HTML('Video')) input_video_widget.remove_class('uploaded') output.register_callback("notebook.select_video", select_video)
def resize(image, size=(256, 256)): w, h = image.size d = min(w, h) r = ((w - d) // 2, (h - d) // 2, (w + d) // 2, (h + d) // 2) return image.resize(size, resample=PIL.Image.LANCZOS, box=r)
def upload_image(change): global selected_image for name, file_info in upload_input_image_button.value.items(): content = file_info['content'] if content is not None: selected_image = resize(PIL.Image.open(io.BytesIO(content)).convert("RGB")) input_image_widget.clear_output(wait=True) with input_image_widget: display(selected_image) input_image_widget.add_class('uploaded') display(Javascript('deselectImages()')) upload_input_image_button.observe(upload_image, names='value')
def upload_video(change): global selected_video for name, file_info in upload_input_video_button.value.items(): content = file_info['content'] if content is not None: selected_video = 'user/' + name with open(selected_video, 'wb') as video: video.write(content) preview = resize(PIL.Image.fromarray(thumbnail(selected_video)).convert("RGB")) input_video_widget.clear_output(wait=True) with input_video_widget: display(preview) input_video_widget.add_class('uploaded') display(Javascript('deselectVideos()')) upload_input_video_button.observe(upload_video, names='value')
def change_model(change): if model.value.startswith('vox'): warning.remove_class('warn') else: warning.add_class('warn') model.observe(change_model, names='value')
def generate(button): main.layout.display = 'none' loading.layout.display = '' filename = model.value + ('' if model.value == 'fashion' else '-cpk') + '.pth.tar' if not os.path.isfile(filename): response = requests.get('https://github.com/graphemecluster/first-order-model-demo/releases/download/checkpoints/' + filename, stream=True) with progress_bar: with tqdm.wrapattr(response.raw, 'read', total=int(response.headers.get('Content-Length', 0)), unit='B', unit_scale=True, unit_divisor=1024) as raw: with open(filename, 'wb') as file: copyfileobj(raw, file) progress_bar.clear_output() reader = imageio.get_reader(selected_video, mode='I', format='FFMPEG') fps = reader.get_meta_data()['fps'] driving_video = [] for frame in reader: driving_video.append(frame) generator, kp_detector = load_checkpoints(config_path='config/%s-256.yaml' % model.value, checkpoint_path=filename) with progress_bar: predictions = make_animation( skimage.transform.resize(numpy.asarray(selected_image), (256, 256)), [skimage.transform.resize(frame, (256, 256)) for frame in driving_video], generator, kp_detector, relative=relative.value, adapt_movement_scale=adapt_movement_scale.value ) progress_bar.clear_output() imageio.mimsave('output.mp4', [img_as_ubyte(frame) for frame in predictions], fps=fps) try: with NamedTemporaryFile(suffix='.mp4') as output: ffmpeg.output(ffmpeg.input('output.mp4').video, ffmpeg.input(selected_video).audio, output.name, c='copy').run() with open('output.mp4', 'wb') as result: copyfileobj(output, result) except ffmpeg.Error: pass output_widget.clear_output(True) with output_widget: video_widget = ipywidgets.Video.from_file('output.mp4', autoplay=False, loop=False) video_widget.add_class('video') video_widget.add_class('video-left') display(video_widget) comparison_widget.clear_output(True) with comparison_widget: video_widget = ipywidgets.Video.from_file(selected_video, autoplay=False, loop=False, controls=False) video_widget.add_class('video') video_widget.add_class('video-right') display(video_widget) display(Javascript(""" setTimeout(function() { (function(left, right) { left.addEventListener("play", function() { right.play(); }); left.addEventListener("pause", function() { right.pause(); }); left.addEventListener("seeking", function() { right.currentTime = left.currentTime; }); right.muted = true; })(document.getElementsByClassName("video-left")[0], document.getElementsByClassName("video-right")[0]); }, 1000); """)) loading.layout.display = 'none' complete.layout.display = ''
generate_button.on_click(generate)
loading.layout.display = 'none' complete.layout.display = 'none' select_image('00') select_video('0')
Your code is mostly fine but designed originally for Python 3.7-3.9 environments (typical of Colab with default Python), and some parts (like shell commands, package installs, and library usages) might need tweaks to fully run on Python 3.11 and recent package versions on Colab.
Here is a review and fix for anything that might break or is outdated:
%pip install and ! commands should be run in separate cells or modified.!git init . and !git remote add + !git pull are redundant if you already clone.cv2.imencode(...)[1].tostring() is deprecated; use .tobytes().imageio usage (format argument deprecated).ipywidgets.Image.from_file (method not standard; better to use widgets.Image(value=...)).# Run in its own cell to avoid capture issues:
!pip install --quiet --upgrade ffmpeg-python imageio-ffmpeg ipywidgets tqdm
# Clone the demo repo if missing:
import os
if not os.path.exists("demo"):
!git clone https://github.com/graphemecluster/first-order-model-demo demo
Note: The repo
https://github.com/graphemecluster/first-order-model-democontains demos includingload_checkpointsandmake_animation.
import IPython.display
import PIL.Image
import cv2
import ffmpeg
import imageio.v3 as iio # use imageio v3 recommended in new versions
import io
import ipywidgets as widgets # use standard alias
import numpy as np
import os
import requests
import skimage.transform
import warnings
from base64 import b64encode
from demo import load_checkpoints, make_animation
from google.colab import files, output
from IPython.display import HTML, Javascript
from shutil import copyfileobj
from skimage import img_as_ubyte
from tempfile import NamedTemporaryFile
from tqdm.auto import tqdm
warnings.filterwarnings("ignore")
os.makedirs("user", exist_ok=True)
ipywidgets.Image.from_file() usageThere is no ipywidgets.Image.from_file() method in the standard API.
You can replace create_image and similar functions with:
def create_image(i, j):
with open(f'demo/images/{i}{j}.png', 'rb') as f:
img_bytes = f.read()
image_widget = widgets.Image(
value=img_bytes,
format='png',
width=160,
height=160,
)
image_widget.add_class('resource')
image_widget.add_class('resource-image')
image_widget.add_class(f'resource-image{i}{j}')
return image_widget
def create_video(i):
video_path = f'demo/videos/{i}.mp4'
frame = thumbnail(video_path)
_, buf = cv2.imencode('.png', cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
image_widget = widgets.Image(
value=buf.tobytes(),
format='png',
width=160,
height=160,
)
image_widget.add_class('resource')
image_widget.add_class('resource-video')
image_widget.add_class(f'resource-video{i}')
return image_widget
Also fix here:
def thumbnail(file):
reader = imageio.get_reader(file, mode='I', format='ffmpeg')
img = reader.get_next_data()
reader.close()
return img
.tostring() -> .tobytes()Replace any .tostring() calls by .tobytes(). For example:
buf.tobytes()
The dictionary .value might require iteration carefully:
def upload_image(change):
global selected_image
for name, file_info in upload_input_image_button.value.items():
content = file_info['content']
if content is not None:
selected_image = resize(PIL.Image.open(io.BytesIO(content)).convert("RGB"))
input_image_widget.clear_output(wait=True)
with input_image_widget:
display(selected_image)
input_image_widget.add_class('uploaded')
display(Javascript('deselectImages()'))
break # only first file processed
upload_input_image_button.observe(upload_image, names='value')
def upload_video(change):
global selected_video
for name, file_info in upload_input_video_button.value.items():
content = file_info['content']
if content is not None:
selected_video = f'user/{name}'
os.makedirs('user', exist_ok=True)
with open(selected_video, 'wb') as video:
video.write(content)
preview = resize(PIL.Image.fromarray(thumbnail(selected_video)).convert("RGB"))
input_video_widget.clear_output(wait=True)
with input_video_widget:
display(preview)
input_video_widget.add_class('uploaded')
display(Javascript('deselectVideos()'))
break
upload_input_video_button.observe(upload_video, names='value')
generate to work safely in python 3.11Your ffmpeg merge approach (video + audio) might error sometimes — wrap it as you already do but more robustly:
try:
with NamedTemporaryFile(suffix='.mp4') as output_tmp:
(
ffmpeg
.input('output.mp4')
.video
.output(ffmpeg.input(selected_video).audio, output_tmp.name, vcodec='copy', acodec='copy')
.run()
)
with open('output.mp4', 'wb') as result:
copyfileobj(open(output_tmp.name, 'rb'), result)
except ffmpeg.Error:
# fallback: keep video only
pass
Or even simpler:
try:
ffmpeg.input('output.mp4').output('merged.mp4', vcodec='copy', acodec='copy', shortest=None).run(overwrite_output=True)
os.replace('merged.mp4', 'output.mp4')
except ffmpeg.Error:
pass
numpy with nppredictions = make_animation(
skimage.transform.resize(np.asarray(selected_image), (256, 256)),
[skimage.transform.resize(frame, (256, 256)) for frame in driving_video],
generator,
kp_detector,
relative=relative.value,
adapt_movement_scale=adapt_movement_scale.value
)
select_image('00') and select_video('0') calls after all widgets are defined.Ensure you don't call them before those functions exist.
# First cell for installs and cloning
!pip install --quiet --upgrade ffmpeg-python imageio-ffmpeg ipywidgets tqdm
import os
if not os.path.exists("demo"):
!git clone https://github.com/graphemecluster/first-order-model-demo demo
# Second cell: imports (as above)
import IPython.display
import PIL.Image
import cv2
import ffmpeg
import imageio.v3 as iio
import io
import ipywidgets as widgets
import numpy as np
import os
import requests
import skimage.transform
import warnings
from base64 import b64encode
from demo import load_checkpoints, make_animation
from google.colab import files, output
from IPython.display import HTML, Javascript
from shutil import copyfileobj
from skimage import img_as_ubyte
from tempfile import NamedTemporaryFile
from tqdm.auto import tqdm
warnings.filterwarnings("ignore")
os.makedirs("user", exist_ok=True)
# Replace your function definitions for create_image, etc (see edits above)
# Replace all .tostring() with .tobytes()
# Replace file upload handlers and ffmpeg calls as shown above
# At the bottom, after all widget definitions:
select_image('00')
select_video('0')
graphemecluster/first-order-model-demo is well maintained and works on Colab with these minor tweaks.If you want, I can prepare a completely ready-to-run Colab notebook with these fixes applied for upload and usage. Just ask!
Not yet included in a published release.