|
|
|
|
|
|
|
|
|
import argparse |
|
|
|
|
|
from pathlib import Path |
|
|
|
def create_caption_files(image_folder: str, file_pattern: str, caption_text: str, caption_file_ext: str, overwrite: bool): |
|
|
|
patterns = [pattern.strip() for pattern in file_pattern.split(",")] |
|
|
|
|
|
folder = Path(image_folder) |
|
|
|
|
|
for pattern in patterns: |
|
|
|
files = folder.glob(pattern) |
|
|
|
|
|
for file in files: |
|
|
|
txt_file = file.with_suffix(caption_file_ext) |
|
if not txt_file.exists() or overwrite: |
|
|
|
|
|
with open(txt_file, "w") as f: |
|
f.write(caption_text) |
|
|
|
def main(): |
|
|
|
parser = argparse.ArgumentParser() |
|
parser.add_argument("image_folder", type=str, help="the folder where the image files are located") |
|
parser.add_argument("--file_pattern", type=str, default="*.png, *.jpg, *.jpeg, *.webp", help="the pattern to match the image file names") |
|
parser.add_argument("--caption_file_ext", type=str, default=".caption", help="the caption file extension.") |
|
parser.add_argument("--overwrite", action="store_true", default=False, help="whether to overwrite existing caption files") |
|
|
|
|
|
group = parser.add_mutually_exclusive_group() |
|
group.add_argument("--caption_text", type=str, help="the text to include in the caption files") |
|
group.add_argument("--caption_file", type=argparse.FileType("r"), help="the file containing the text to include in the caption files") |
|
|
|
|
|
args = parser.parse_args() |
|
image_folder = args.image_folder |
|
file_pattern = args.file_pattern |
|
caption_file_ext = args.caption_file_ext |
|
overwrite = args.overwrite |
|
|
|
|
|
if args.caption_text: |
|
caption_text = args.caption_text |
|
elif args.caption_file: |
|
caption_text = args.caption_file.read() |
|
|
|
|
|
folder = Path(image_folder) |
|
|
|
|
|
if not folder.is_dir(): |
|
raise ValueError(f"{image_folder} is not a valid directory.") |
|
|
|
|
|
create_caption_files(image_folder, file_pattern, caption_text, caption_file_ext, overwrite) |
|
|
|
if __name__ == "__main__": |
|
main() |