From 3d27a0ee046f479b913f9bcc61a83a80954a830a Mon Sep 17 00:00:00 2001
From: Remy Moll <me@moll.re>
Date: Mon, 20 Nov 2023 14:41:40 +0100
Subject: [PATCH] better color handling

---
 README                     |  3 ++-
 deploy/deploy.playbook.yml |  2 +-
 deploy/setup.playbook.yml  |  8 --------
 src/get/combined.py        |  2 +-
 src/get/museum.py          | 10 ++++++----
 src/get/template.py        |  7 +++++--
 src/image_convert.py       | 16 ++++++++++------
 src/main.py                | 17 ++++++++++-------
 8 files changed, 35 insertions(+), 30 deletions(-)

diff --git a/README b/README
index ca78f7f..7367024 100644
--- a/README
+++ b/README
@@ -2,7 +2,8 @@
 
 ## Deployment
 Run the ansible playbooks (`setup` once, `deploy` on each code update):
+(Don't forget to set variables!)
 ```
 ansible-playbook deploy/setup.playbook.yml -i <ip of pi>
 ansible-playbook deploy/deploy.playbook.yml -i <ip of pi>
-```
\ No newline at end of file
+```
diff --git a/deploy/deploy.playbook.yml b/deploy/deploy.playbook.yml
index 4b18fe7..e6b7dc4 100644
--- a/deploy/deploy.playbook.yml
+++ b/deploy/deploy.playbook.yml
@@ -33,7 +33,7 @@
 
     - name: Copy keys python file
       copy:
-        src: ../keys.py
+        src: ../src/keys.py
         dest: "{{ code_dest }}/keys.py"
 
     - name: Copy unit files
diff --git a/deploy/setup.playbook.yml b/deploy/setup.playbook.yml
index 06cff61..a5f8558 100644
--- a/deploy/setup.playbook.yml
+++ b/deploy/setup.playbook.yml
@@ -57,14 +57,6 @@
       wait_for_connection:
         delay: 5
         timeout: 300
-      
-    # - name: Add wifi networks from template
-    #   template:
-    #     src: templates/wpa_supplicant.conf.j2
-    #     dest: /etc/wpa_supplicant/wpa_supplicant.conf
-    #     owner: root
-    #     group: root
-    #     mode: 0600
 
     - name: Use raspi-config to set WIFI country
       shell: |
diff --git a/src/get/combined.py b/src/get/combined.py
index c7bce88..81029dc 100644
--- a/src/get/combined.py
+++ b/src/get/combined.py
@@ -17,7 +17,7 @@ class ImageGetCombined:
             + [ugettter] * int(other_image_percent/2) \
             + [mgetter] * int(other_image_percent/2)
         # representing weighted probabilities
-        print(f"Using {len(self.getters)} image sources: ~{own_image_percent}% own, ~{other_image_percent}% foreign images.")
+        print(f"Using 3 image sources: ~{own_image_percent}% own, ~{other_image_percent}% foreign images.")
 
 
     def get_random_image(self) -> bytearray:
diff --git a/src/get/museum.py b/src/get/museum.py
index 8f59490..4ac67e0 100644
--- a/src/get/museum.py
+++ b/src/get/museum.py
@@ -44,7 +44,7 @@ class ImageGetMuseum(ImageGet):
 
         response = h.post(self.base_url + "search", json=post_data, headers=self.headers)
         if not response.status_code == 200:
-            raise ImageGetException("Error in step get_image_file: " + str(response.status_code))
+            raise ImageGetException("Error in step get_random_image_ids: " + str(response.status_code))
 
         response = json.loads(response.text)
         images = response["data"]
@@ -60,7 +60,9 @@ class ImageGetMuseum(ImageGet):
             raise ImageGetException("Error in step get_image_file: " + str(response.status_code))
         
         response = json.loads(response.text)
-        image_url = response["config"]["iiif_url"] + "/" + response["data"]["image_id"] + "/full/843,/0/default.jpg"
-        image = h.get(image_url).content
+        image_url = response["config"]["iiif_url"] + f"/{response['data']['image_id']}/full/843,/0/default.jpg"
+        try:
+            image = h.get(image_url).content
+        except (h.ConnectError, h.NetworkError, h.RequestError, h.HTTPStatusError) as e:
+            raise ImageGetException(f"Error in step get_image_file: {e}")
         return image
-
diff --git a/src/get/template.py b/src/get/template.py
index ac8fe0a..f8c5ab5 100644
--- a/src/get/template.py
+++ b/src/get/template.py
@@ -44,8 +44,11 @@ class ImageGet:
         for i, id in enumerate(ids):
             print(f"Caching image {i + 1}")
             new_cache = self.cache_dir / f"{uuid.uuid4()}"
-            new_cache.write_bytes(self.get_image_file(id))
-
+            try:
+                new_cache.write_bytes(self.get_image_file(id))
+            except ImageGetException:
+                print("Could not cache image, skipping")
+                continue
 
     def load_cached_file(self) -> bytearray:
         """Returns a random file from self.cache_dir"""
diff --git a/src/image_convert.py b/src/image_convert.py
index 89fb564..4680078 100644
--- a/src/image_convert.py
+++ b/src/image_convert.py
@@ -32,9 +32,8 @@ class ImageShrink:
     """Shrinks a given image (bytearray) to a given resolution (width, height)"""
     resolution = (480, 800)
 
-    def __init__(self, dither=True, colors=7) -> None:
-        self.dither = dither
-        self.colors = colors
+    def __init__(self, reduce_colors=False) -> None:
+        self.reduce_colors = reduce_colors
 
 
     def convert(self, image: bytearray) -> Image:
@@ -61,8 +60,13 @@ class ImageShrink:
         if image.mode != "RGB":
             print("Converting image to RGB")
             image = image.convert("RGB")
-        if self.colors == -1:
-            print("Skipping color reduction")
+        if not self.reduce_colors:
+            print("Not manually reducing colors")
             return image
-        new_image = image.quantize(colors = len(palette), palette=ref_image, dither=self.dither)
+        
+        new_image = image.quantize(
+            colors = len(palette),
+            palette = ref_image,
+            dither = True
+            )
         return new_image
diff --git a/src/main.py b/src/main.py
index 7085ea8..ee9de0c 100644
--- a/src/main.py
+++ b/src/main.py
@@ -9,14 +9,17 @@ if len(sys.argv) == 2 and sys.argv[1] == "test":
     shower.draw_sample_image()
     sys.exit()
 
-
 shrink_kwargs = {}
-if "nodither" in sys.argv:
-    print("Disabling dithering")
-    shrink_kwargs["dither"] = False
-if "noreduce" in sys.argv:
-    print("Disabling color reduction")
-    shrink_kwargs["colors"] = -1
+# if "dither" in sys.argv:
+#     print("Enabling dithering")
+#     shrink_kwargs["dither"] = True
+# if "noreduce" in sys.argv:
+#     print("Disabling color reduction")
+#     shrink_kwargs["colors"] = -1
+if "reduce" in sys.argv:
+    print("Enabling color reduction")
+    shrink_kwargs["reduce_colors"] = True
+
 
 getter = ImageGetCombined()
 converter = ImageShrink(**shrink_kwargs)