cosmo / search.py
tripleS-Dev
start
c785888
import os
from PIL import Image
from PIL.PngImagePlugin import PngImageFile, PngInfo
import shutil
def get_png_files(folder_path):
"""Get a list of all PNG files in the specified folder."""
return [f for f in os.listdir(folder_path) if f.endswith('.png')]
def read_metadata(image_path):
"""Read the metadata of a PNG file."""
with Image.open(image_path) as img:
return img.info
def search_in_metadata(folder_path, search_word):
"""Search for a specific word in the metadata of PNG files in the specified folder."""
matching_files = []
folder_path = f"./{folder_path}"
sort_folder_path = f"./{folder_path}_sort"
png_files = get_png_files(folder_path)
for file in png_files:
file_path = os.path.join(folder_path, file)
metadata = read_metadata(file_path)
search_word_lower = search_word.lower()
# Check if the search word is in any of the metadata values
for key, value in metadata.items():
if isinstance(value, str) and search_word_lower in value.lower():
matching_files.append(file)
break
if os.path.exists(sort_folder_path):
shutil.rmtree(sort_folder_path)
os.makedirs(sort_folder_path)
move_files(folder_path, sort_folder_path, matching_files)
return [os.path.splitext(file)[0] for file in matching_files]
def move_files(src_folder, dst_folder, files):
"""Move the specified files from the source folder to the destination folder."""
if not os.path.exists(dst_folder):
os.makedirs(dst_folder)
for file in files:
src_path = os.path.join(src_folder, file)
dst_path = os.path.join(dst_folder, file)
shutil.move(src_path, dst_path)