Skip to content

Instantly share code, notes, and snippets.

@glenrobertson
Last active March 19, 2024 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glenrobertson/a9dcafad0d82a94463f0002d9912f6b8 to your computer and use it in GitHub Desktop.
Save glenrobertson/a9dcafad0d82a94463f0002d9912f6b8 to your computer and use it in GitHub Desktop.
Pimoroni Inky image download script
"""
Set a cron job to run this script every 5 minutes
It will download the image from the given URL and render it.
The ETag header is used to check if the image has changed.
If it has, the image is downloaded and rendered.
If not, the script exits early.
The ETag is saved to a file and checked on the next run.
Requires pimoroni/inky library: https://github.com/pimoroni/inky#installation
Example crontab entry per minute:
* * * * * pi /usr/bin/python3 /home/pi/download-image.py https://example.com/image.jpg 0.5
"""
import os
import sys
import requests
from PIL import Image
from inky.auto import auto
if len(sys.argv) == 1:
print("""
Usage: {file} image-url [saturation]
""".format(file=sys.argv[0]))
sys.exit(1)
image_url = sys.argv[1]
etag_filename = "etag.txt"
etag_filepath = os.path.join(os.path.dirname(__file__), etag_filename)
image_filename = "image.jpg"
image_filepath = os.path.join(os.path.dirname(__file__), image_filename)
head_response = requests.head(image_url)
etag = head_response.headers.get("ETag")
if etag is None:
print("ETag not found in response headers. Skipping download and render")
sys.exit(0)
if os.path.exists(etag_filename):
with open(etag_filename, "r") as file:
old_etag = file.read()
if old_etag == etag:
print(f"Etag {etag} is current. Skipping download and render")
sys.exit(0)
print(f"Downloading image at {image_url}")
with open(etag_filename, "w") as etag_file:
response = requests.get(image_url)
with open(image_filepath, "wb") as image_file:
image_file.write(response.content)
updated_etag = response.headers.get("ETag")
print(f"Updating etag to {updated_etag}")
etag_file.write(updated_etag)
inky = auto(ask_user=True, verbose=True)
saturation = 0.5
image = Image.open(image_filepath)
resizedimage = image.resize(inky.resolution)
if len(sys.argv) > 2:
saturation = float(sys.argv[2])
inky.set_image(resizedimage, saturation=saturation)
inky.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment