|
| 1 | +import os |
| 2 | +import re |
| 3 | +import hashlib |
| 4 | +import shutil |
| 5 | +import argparse |
| 6 | + |
| 7 | +# 計算檔案的 MD5 值 |
| 8 | +def calculate_md5(file_path): |
| 9 | + hash_md5 = hashlib.md5() |
| 10 | + with open(file_path, "rb") as f: |
| 11 | + for chunk in iter(lambda: f.read(4096), b""): |
| 12 | + hash_md5.update(chunk) |
| 13 | + return hash_md5.hexdigest() |
| 14 | + |
| 15 | +# 處理 Markdown 檔案 |
| 16 | +def process_markdown(file_path, img_dir, img_url_base): |
| 17 | + # 確保目標目錄存在 |
| 18 | + os.makedirs(img_dir, exist_ok=True) |
| 19 | + |
| 20 | + # 讀取 Markdown 文件 |
| 21 | + with open(file_path, "r", encoding="utf-8") as f: |
| 22 | + content = f.read() |
| 23 | + |
| 24 | + # 正則表達式匹配圖片連結  |
| 25 | + pattern = r"!\[([^\]]*)\]\(([^)]+\.png)\)" |
| 26 | + updated_content = content |
| 27 | + |
| 28 | + for match in re.finditer(pattern, content): |
| 29 | + alt_text, image_path = match.groups() |
| 30 | + |
| 31 | + # 確認圖片是否在與 Markdown 檔案相同目錄下 |
| 32 | + if not os.path.isabs(image_path): |
| 33 | + image_path = os.path.join(os.path.dirname(file_path), image_path) |
| 34 | + |
| 35 | + if os.path.isfile(image_path): |
| 36 | + # 計算 MD5 並生成新檔案名 |
| 37 | + md5_hash = calculate_md5(image_path) |
| 38 | + new_file_name = f"{md5_hash}.png" |
| 39 | + new_file_path = os.path.join(img_dir, new_file_name) |
| 40 | + |
| 41 | + # 移動圖片到目標目錄 |
| 42 | + shutil.move(image_path, new_file_path) |
| 43 | + |
| 44 | + # 更新 Markdown 內容中的圖片路徑 |
| 45 | + new_image_url = f"{img_url_base}/{new_file_name}" |
| 46 | + updated_content = updated_content.replace( |
| 47 | + match.group(0), f"" if alt_text == "alt text" else f"" |
| 48 | + ) |
| 49 | + |
| 50 | + # 將更新後的內容寫回檔案 |
| 51 | + with open(file_path, "w", encoding="utf-8") as f: |
| 52 | + f.write(updated_content) |
| 53 | + |
| 54 | + print("Markdown 文件已處理完成!") |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + # 解析命令列參數 |
| 58 | + parser = argparse.ArgumentParser(description="處理 Markdown 檔案中的圖片連結") |
| 59 | + parser.add_argument("markdown_file", help="Markdown 檔案路徑") |
| 60 | + args = parser.parse_args() |
| 61 | + |
| 62 | + markdown_file = os.path.join(os.getcwd(), args.markdown_file) |
| 63 | + |
| 64 | + script_dir = os.path.dirname(os.path.abspath(__file__)) |
| 65 | + os.chdir(script_dir) |
| 66 | + |
| 67 | + process_markdown(markdown_file, img_dir="static/img/pages", img_url_base="/img/pages") |
0 commit comments