get_bing_potd.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. found_match = False
  16. try:
  17. yesterday_img = imagehash.average_hash(Image.open(check_path))
  18. today_img = imagehash.average_hash(Image.open(target_path))
  19. cutoff = 5 # maximum bits that could be different between the hashes.
  20. found_match = today_img - yesterday_img < cutoff
  21. except:
  22. pass
  23. if not found_match:
  24. print(f"Bing image for {today} already exists, skipping download")
  25. exit()
  26. print(f"Bing image for {today} same as yesterday, overwriting")
  27. iotd_uri = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=1&n=1"
  28. r = requests.get(iotd_uri)
  29. image_info_uri = r.json()["images"][0]["url"]
  30. img = requests.get(f"https://www.bing.com{image_info_uri}", stream=True)
  31. handle = open(target_path, "wb")
  32. for chunk in img.iter_content(chunk_size=512):
  33. if chunk: # filter out keep-alive new chunks
  34. handle.write(chunk)