import os from string import Template from typing import List from natsort import os_sorted from tqdm.auto import tqdm from wand.image import Image CONFIG_TEMPLATE = Template('{id: uuidv4(), category: "$category", image: "$filename", thumbSize: {w: $width, h: $height}},\n') def run(gallery_folder, resize_config='400x400>') -> List[str]: """ For each image in given folder, generate the thumbnail and prepare a config string @param gallery_folder: Path to gallery folder @param resize_config: Options are described here: https://docs.wand-py.org/en/stable/guide/resizecrop.html#transform-images """ result = [] for current_dir, dirs, files in os.walk(gallery_folder): with tqdm(os_sorted(files), desc='Processing images', leave=False) as files_pbar: for file in files_pbar: if current_dir.startswith('_'): tqdm.write(f"Skipping: {file} from {current_dir}") continue # Don't go deeper if current_dir != gallery_folder: continue file_path = os.path.join(current_dir, file) category = os.path.basename(current_dir) files_pbar.set_postfix({"Working on": file_path}) # Create thumbnail folder thumbnail_folder = os.path.join(current_dir, "thumbs") os.makedirs(thumbnail_folder, exist_ok=True) try: with Image(filename=file_path) as img: # Generate thumbnail img.auto_orient() img.transform(resize=resize_config) # Save it to file thumbnail_path = os.path.join(thumbnail_folder, file) img.save(filename=thumbnail_path) # Use thumbnail size later width = img.width height = img.height except: tqdm.write(f"Failed to open file:{file_path}") continue # Template string config_string = CONFIG_TEMPLATE.substitute(category=category, filename=file, width=width, height=height) result.append(config_string) return result if __name__ == '__main__': config_strings = run('/Users/phzhik/repo/alex-sharoff/public/gallery/interior') with open("result.js", "w") as f: f.writelines(config_strings) tqdm.write('Done')