Skip to content

Instantly share code, notes, and snippets.

@konradmb
Last active October 27, 2024 13:55
Show Gist options
  • Save konradmb/0550819993126a7c52d1373839b4ab56 to your computer and use it in GitHub Desktop.
Save konradmb/0550819993126a7c52d1373839b4ab56 to your computer and use it in GitHub Desktop.
Generate thumbnails in Gnome
#!/usr/bin/python3
import os
import sys
from concurrent.futures import ThreadPoolExecutor
import gi
from gi.repository import Gio, GnomeDesktop
gi.require_version('GnomeDesktop', '4.0')
MAX_WORKERS=os.cpu_count()
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
def make_thumbnail(factory, filename):
mtime = os.path.getmtime(filename)
# Use Gio to determine the URI and mime type
f = Gio.file_new_for_path(filename)
uri = f.get_uri()
info = f.query_info(
'standard::content-type', Gio.FileQueryInfoFlags.NONE, None)
mime_type = info.get_content_type()
try:
if factory.lookup(uri, mtime) is not None:
print("FRESH %s" % uri)
return False
if not factory.can_thumbnail(uri, mime_type, mtime):
print("UNSUPPORTED %s" % uri)
return False
thumbnail = factory.generate_thumbnail(uri, mime_type)
if thumbnail is None:
print("ERROR %s" % uri)
return False
print("OK %s" % uri)
factory.save_thumbnail(thumbnail, uri, mtime)
except gi.repository.GLib.GError as e:
print(f"ERROR {e} {uri}")
return False
return True
def thumbnail_folder(factory, folder):
for dirpath, dirnames, filenames in os.walk(folder):
for filename in filenames:
executor.submit(make_thumbnail(factory, os.path.join(dirpath, filename)))
def main(argv):
factory = GnomeDesktop.DesktopThumbnailFactory()
for filename in argv[1:]:
if os.path.isdir(filename):
thumbnail_folder(factory, filename)
else:
make_thumbnail(factory, filename)
if __name__ == '__main__':
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment