|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import sys |
| 3 | +import os |
| 4 | +import re |
| 5 | +from tqdm import tqdm |
| 6 | +import frontmatter |
| 7 | + |
| 8 | +# 디렉토리 및 언어 설정 |
| 9 | +posts_dir = '../_posts/' |
| 10 | +source_lang_code = "ko" |
| 11 | +list_lang_codes = ["en", "ko", "ja", "zh-TW", "es", "pt-BR", "fr", "de"] |
| 12 | + |
| 13 | +def convert_image_extension_to_webp(image_path): |
| 14 | + """ |
| 15 | + 기존 이미지 경로는 유지하되 확장자만 .png, .jpg, .jpeg에서 .webp로 변경 |
| 16 | + """ |
| 17 | + if not image_path: |
| 18 | + return None |
| 19 | + base, ext = os.path.splitext(image_path) |
| 20 | + if ext.lower() in [".png", ".jpg", ".jpeg"]: |
| 21 | + return f"{base}.webp" |
| 22 | + return image_path |
| 23 | + |
| 24 | +# frontmatter에서 image 값을 읽고, 파일 내 image: 라인만 교체 |
| 25 | +def overwrite_frontmatter_image_only(file_path): |
| 26 | + """ |
| 27 | + 파일의 YAML frontmatter에서 image: 라인을 찾고, |
| 28 | + 확장자를 변경하여 파일에 다시 씁니다. |
| 29 | + """ |
| 30 | + try: |
| 31 | + # 메타데이터 읽기 |
| 32 | + with open(file_path, 'r', encoding='utf-8') as f: |
| 33 | + post = frontmatter.load(f) |
| 34 | + orig_image = post.metadata.get('image') |
| 35 | + new_image = convert_image_extension_to_webp(orig_image) |
| 36 | + if orig_image and new_image != orig_image: |
| 37 | + # 파일 전체 텍스트 로드 |
| 38 | + with open(file_path, 'r', encoding='utf-8') as f: |
| 39 | + text = f.read() |
| 40 | + # image: 라인만 교체 |
| 41 | + updated = re.sub( |
| 42 | + r'(?m)^(\s*image:\s*).+$', |
| 43 | + fr"\1{new_image}", |
| 44 | + text |
| 45 | + ) |
| 46 | + # 덮어쓰기 |
| 47 | + with open(file_path, 'w', encoding='utf-8') as f: |
| 48 | + f.write(updated) |
| 49 | + except Exception as e: |
| 50 | + print(f"Error processing {file_path}: {e}") |
| 51 | + |
| 52 | +def update_frontmatter_bulk(filename): |
| 53 | + """ |
| 54 | + Bulk update YAML Frontmatter. |
| 55 | + """ |
| 56 | + paths = [ |
| 57 | + os.path.join(posts_dir, lang, filename) |
| 58 | + for lang in list_lang_codes |
| 59 | + ] |
| 60 | + for path in paths: |
| 61 | + if os.path.isfile(path): |
| 62 | + overwrite_frontmatter_image_only(path) |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + # 스크립트 위치로 이동 |
| 67 | + os.chdir(os.path.abspath(os.path.dirname(__file__))) |
| 68 | + source_dir = os.path.join(posts_dir, source_lang_code) |
| 69 | + filelist = [] |
| 70 | + for root, _, files in os.walk(source_dir): |
| 71 | + for file in files: |
| 72 | + if file == ".DS_Store": |
| 73 | + continue |
| 74 | + rel = os.path.relpath(os.path.join(root, file), start=source_dir) |
| 75 | + filelist.append(rel) |
| 76 | + |
| 77 | + if not filelist: |
| 78 | + sys.exit("No files found.") |
| 79 | + |
| 80 | + print("Updating image extensions to .webp for the following files:") |
| 81 | + for f in filelist: |
| 82 | + print(f"- {f}") |
| 83 | + |
| 84 | + for f in tqdm(filelist): |
| 85 | + update_frontmatter_bulk(f) |
0 commit comments