Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

Write a python script following my instructions. 1) The program takes a path as an…

  1. User

    Write a python script following my instructions.

    1. The program takes a path as an argument. It will check every subdirectory of that path (not recursive) for a file called info.yaml.
    2. The script will show a report of every directory, showing whether there is a yaml file present or not, or if the info.yaml file is invalid. It will then ask whether to proceed or not.

    The valid info.yaml file looks like this:

    ---
    type: progress
    status: active
    data: multi
    rating: low
    ---
    

    These are the possible values for the keys in the info.yaml file:

    type: normal, sponge, outlier
    status: normal, active, research, archive
    data: multi, photo, video
    rating: lowest, low, below average, average, above average, high, highest
    
    1. Depending on the key values, the script should now update a display.jpg file next to the info.yaml file using imagemagick. The display.jpg file will be backed up first by making a copy display.bak.jpg

    The value of the key type will determine the look of the display.jpg like this: If type is normal, there will be no change. If type is sponge, the border will be yellow. If type is outlier, the border will be black.

    The value of the key status will determine the look of the display.jpg like this: If status is normal, there will be no change. If status is active, there will be a red triangle in the corner of the display.jpg saying "NEW". If status is research, there will be a white banner that goes thorugh the center of the image saying "RESEARCH". If status is archive, there will be cardboard colored stripes in every corner of the image.

    The value of the key type will determine the look of the display.jpg like this: If data is multi, there will be no change. If data is photo, there will be no change. If data is video, there will be a small black rounded box with a red dot in the corner with the text "REC." next to it.

    The value of the key rating will determine the look of display.jpg like this: If data is lowest, there will be no change. If data is low, there will be one star at the bottom of the image. If data is below average, there will be two stars at the bottom of the image. If data is average, there will be three stars at the bottom of the image. If data is above average, there will be four stars at the bottom of the image. If data is high, there will be five stars at the bottom of the image. If data is highest, there will be one big star at the bottom of the image.

    1. When a new display.jpg has been created for every directory, the script will exit successfully.
  2. Assistant
    import os
    import sys
    import yaml
    from pathlib import Path
    from wand.image import Image, Color
    
    
    def is_valid_info_yaml(info_yaml):
        valid_keys = {
            "type": ["normal", "sponge", "outlier"],
            "status": ["normal", "active", "research", "archive"],
            "data": ["multi", "photo", "video"],
            "rating": ["lowest", "low", "below average", "average", "above average", "high", "highest"],
        }
    
        return all(k in valid_keys and info_yaml[k] in valid_keys[k] for k in info_yaml)
    
    
    def read_yaml_file(file_path):
        try:
            with open(file_path, "r") as yaml_file:
                info_yaml = yaml.safe_load(yaml_file)
            return info_yaml
        except Exception as e:
            print(f"Error reading {file_path}: {e}")
            return None
    
    
    def update_display_image(info_yaml, img_path):
        with Image(filename=img_path) as img:
            if info_yaml["type"] == "sponge":
                img.border(Color('yellow'), width=img.width//10, height=img.height//10)
                
            if info_yaml["type"] == "outlier":
                img.border(Color('black'), width=img.width//10, height=img.height//10)
    
            # other symbols depending on info_yaml values (status, data, rating)
    
            # save the new image
            img.save(filename=img_path)
    
    
    def main(target_path):
        path = Path(target_path)
        for entry in sorted(path.iterdir()):
            if entry.is_dir():
                yaml_path = entry / "info.yaml"
    
                if yaml_path.exists() and yaml_path.is_file():
                    report = "Valid"
                    info_yaml = read_yaml_file(yaml_path)
    
                    if info_yaml is None:
                        report = "Invalid"
                    elif not is_valid_info_yaml(info_yaml):
                        report = "Invalid"
                else:
                    report = "No YAML"
    
                print(f"{entry.name}: {report}")
    
                if report == "Valid":
                    proceed = input("Proceed? (y/n): ")
                    if proceed.lower() == "y":
                        img_path = entry / "display.jpg"
                        backup_path = entry / "display.bak.jpg"
                        
                        img_path.rename(backup_path)
                        
                        update_display_image(info_yaml, img_path)
    
        print("All image updates complete.")
    
    
    if __name__ == "__main__":
        if len(sys.argv) > 1:
            main(sys.argv[1])
        else:
            print("Please provide a target path.")
    

    Note that Wand does not have built-in methods for creating triangles, banners, and other shapes. You'll need to use additional libraries, such as OpenCV or PIL, to draw these shapes on the image. In addition, make sure you have the Wand library and Imagemagick installed to be able to use the suggested code.

  3. User

    Please implement the libraries as you suggested to draw the shapes on the image and adjust the script accordingly.

  4. Assistant

    I'll modify the script accordingly using the Pillow library. First, make sure you have the Pillow library installed:

    pip install pillow
    

    Now, here is the updated script using the Pillow library for image manipulation:

    import os
    import sys
    import yaml
    from pathlib import Path
    from PIL import Image, ImageDraw
    
    
    def is_valid_info_yaml(info_yaml):
        valid_keys = {
            "type": ["normal", "sponge", "outlier"],
            "status": ["normal", "active", "research", "archive"],
            "data": ["multi", "photo", "video"],
            "rating": ["lowest", "low", "below average", "average", "above average", "high", "highest"],
        }
    
        return all(k in valid_keys and info_yaml[k] in valid_keys[k] for k in info_yaml)
    
    
    def read_yaml_file(file_path):
        try:
            with open(file_path, "r") as yaml_file:
                info_yaml = yaml.safe_load(yaml_file)
            return info_yaml
        except Exception as e:
            print(f"Error reading {file_path}: {e}")
            return None
    
    
    def update_display_image(info_yaml, img_path):
        img = Image.open(img_path)
        draw = ImageDraw.Draw(img)
    
        if info_yaml["type"] == "sponge":
            draw.rectangle([0, 0, img.width, img.height], outline="yellow", width=int(img.width * 0.1))
    
        if info_yaml["type"] == "outlier":
            draw.rectangle([0, 0, img.width, img.height], outline="black", width=int(img.width * 0.1))
    
        # other symbols depending on info_yaml values (status, data, rating)
    
        img.save(img_path)
    
    
    def main(target_path):
        path = Path(target_path)
        for entry in sorted(path.iterdir()):
            if entry.is_dir():
                yaml_path = entry / "info.yaml"
    
                if yaml_path.exists() and yaml_path.is_file():
                    report = "Valid"
                    info_yaml = read_yaml_file(yaml_path)
    
                    if info_yaml is None:
                        report = "Invalid"
                    elif not is_valid_info_yaml(info_yaml):
                        report = "Invalid"
                else:
                    report = "No YAML"
    
                print(f"{entry.name}: {report}")
    
                if report == "Valid":
                    proceed = input("Proceed? (y/n): ")
                    if proceed.lower() == "y":
                        img_path = entry / "display.jpg"
                        backup_path = entry / "display.bak.jpg"
    
                        img_path.rename(backup_path)
    
                        update_display_image(info_yaml, img_path)
    
        print("All image updates complete.")
    
    
    if __name__ == "__main__":
        if len(sys.argv) > 1:
            main(sys.argv[1])
        else:
            print("Please provide a target path.")
    

    This updated script uses the Pillow library, which is simpler to work with for the intended purpose. Note that additional code is needed for drawing the other shapes and symbols (status, data, rating) on the image.

  5. User

    Please implement the additional code for drawing the other shapes and symbols (status, data, rating) on the image. Try to do it as best as you can but it is not required to be a perfect result.

  6. Assistant

    Here's the updated script with the additional shapes and symbols for the status, data, and rating keys:

    import os
    import sys
    import yaml
    from pathlib import Path
    from PIL import Image, ImageDraw, ImageFont
    
    
    def is_valid_info_yaml(info_yaml):
        valid_keys = {
            "type": ["normal", "sponge", "outlier"],
            "status": ["normal", "active", "research", "archive"],
            "data": ["multi", "photo", "video"],
            "rating": ["lowest", "low", "below average", "average", "above average", "high", "highest"],
        }
    
        return all(k in valid_keys and info_yaml[k] in valid_keys[k] for k in info_yaml)
    
    
    def read_yaml_file(file_path):
        try:
            with open(file_path, "r") as yaml_file:
                info_yaml = yaml.safe_load(yaml_file)
            return info_yaml
        except Exception as e:
            print(f"Error reading {file_path}: {e}")
            return None
    
    
    def draw_status_banner(draw, img, status):
        if status == "active":
            draw.polygon([0, 0, img.width//4, 0, 0, img.height//4], fill="red")
            draw.text((10, 10), "NEW", fill="white")
    
        if status == "research":
            banner_height = img.height // 10
            draw.rectangle([0, (img.height // 2) - (banner_height // 2), img.width, (img.height // 2) + (banner_height // 2)],
                           fill="white")
            draw.text((img.width // 3, (img.height // 2) - (banner_height // 2)), "RESEARCH", fill="black")
    
        if status == "archive":
            corner_size = img.width // 10
            corners = [(0, 0), (img.width - corner_size, 0), (0, img.height - corner_size), (img.width - corner_size, img.height - corner_size)]
            for corner in corners:
                draw.rectangle([corner, (corner[0] + corner_size, corner[1] + corner_size)], fill="burlywood")
    
    
    def draw_data_indicator(draw, img, data):
        if data == "video":
            box_width = img.width // 10
            box_height = img.height // 20
            draw.rounded_rectangle([img.width - box_width, 0, img.width, box_height], radius=5, fill="black")
            draw.ellipse([img.width - box_width + 5, 5, img.width - box_width + 15, 15], fill="red")
            draw.text((img.width - box_width + 20, 5), "REC.", fill="white")
    
    
    def draw_rating_stars(draw, img, rating):
        star_ratings = {
            "lowest": 0,
            "low": 1,
            "below average": 2,
            "average": 3,
            "above average": 4,
            "high": 5,
            "highest": 1
        }
        n_stars = star_ratings[rating]
        star_size = img.width // 20
        y = img.height - star_size
        stars_pos = [(img.width // 6 * i, y) for i in range(1, n_stars + 1)]
        for (x, y) in stars_pos:
            draw.text((x, y), "★", fill="gold", font=ImageFont.truetype("arialbd.ttf", star_size))
    
        if rating == "highest":
            draw.text((img.width//2, y), "★", fill="gold", font=ImageFont.truetype("arialbd.ttf", star_size*2))
    
    
    def update_display_image(info_yaml, img_path):
        img = Image.open(img_path)
        draw = ImageDraw.Draw(img)
    
        if info_yaml["type"] == "sponge":
            draw.rectangle([0, 0, img.width, img.height], outline="yellow", width=int(img.width * 0.1))
    
        if info_yaml["type"] == "outlier":
            draw.rectangle([0, 0, img.width, img.height], outline="black", width=int(img.width * 0.1))
    
        draw_status_banner(draw, img, info_yaml["status"])
        draw_data_indicator(draw, img, info_yaml["data"])
        draw_rating_stars(draw, img, info_yaml["rating"])
    
        img.save(img_path)
    
    
    def main(target_path):
        path = Path(target_path)
        for entry in sorted(path.iterdir()):
            if entry.is_dir():
                yaml_path = entry / "info.yaml"
    
                if yaml_path.exists() and yaml_path.is_file():
                    report = "Valid"
                    info_yaml = read_yaml_file(yaml_path)
    
                    if info_yaml is None:
                        report = "Invalid"
                    elif not is_valid_info_yaml(info_yaml):
                        report = "Invalid"
                else:
                    report = "No YAML"
    
                print(f"{entry.name}: {report}")
    
                if report == "Valid":
                    proceed = input("Proceed? (y/n): ")
                    if proceed.lower() == "y":
                        img_path = entry / "display.jpg"
                        backup_path = entry / "display.bak.jpg"
    
                        img_path.rename(backup_path)
    
                        update_display_image(info_yaml, img_path)
    
        print("All image updates complete.")
    
    
    if __name__ == "__main__":
        if len(sys.argv) > 1:
            main(sys.argv[1])
        else:
            print("Please provide a target path.")
    

    This script should draw the symbols (status, data, rating) on the image based on the values in the info.yaml file. The results might not look perfect, but they should be close to your requirements. You can adjust the script as needed to fine-tune based on your preferences.