get_bing_potd.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. import os
  3. import subprocess
  4. from datetime import datetime, timedelta
  5. from PIL import Image
  6. import imagehash
  7. import requests
  8. today = datetime.today().strftime("%Y-%m-%d")
  9. yesterday = (datetime.today() - timedelta(days=1)).strftime("%Y-%m-%d")
  10. home = os.path.expanduser("~")
  11. check_path = f"{home}/var/media/backgrounds/bing/{yesterday}.jpg"
  12. target_path = f"{home}/var/media/backgrounds/bing/{today}.jpg"
  13. # If the file for today already exists, just exit
  14. if os.path.isfile(target_path):
  15. yesterday_img = imagehash.average_hash(Image.open(check_path))
  16. today_img = imagehash.average_hash(Image.open(target_path))
  17. cutoff = 5 # maximum bits that could be different between the hashes.
  18. found_match = today_img - yesterday_img < cutoff
  19. if not found_match:
  20. print(f"Bing image for {today} already exists, skipping download")
  21. exit()
  22. print(f"Bing image for {today} same as yesterday, overwriting")
  23. iotd_uri = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=1&n=1"
  24. r = requests.get(iotd_uri)
  25. image_info_uri = r.json()["images"][0]["url"]
  26. img = requests.get(f"https://www.bing.com{image_info_uri}", stream=True)
  27. handle = open(target_path, "wb")
  28. for chunk in img.iter_content(chunk_size=512):
  29. if chunk: # filter out keep-alive new chunks
  30. handle.write(chunk)