آخر نشاط 1 month ago

add_alt_text.py خام
1import os
2import re
3import sys
4
5def add_alt_text_to_images(directory):
6 md_files = [f for f in os.listdir(directory) if f.endswith((".md", ".mdx"))]
7 image_pattern = re.compile(r'!\[([^\]]*)\]\(([^\)]+)\)')
8
9 for md_file in md_files:
10 md_path = os.path.join(directory, md_file)
11 with open(md_path, "r", encoding="utf-8") as file:
12 content = file.read()
13
14 def replace_alt(match):
15 alt_text, image_path = match.groups()
16 if alt_text.strip():
17 return match.group(0)
18
19 image_name = os.path.basename(image_path)
20 alt_text = os.path.splitext(image_name)[0].replace("_", " ").replace("-", " ")
21 return f'![{alt_text}]({image_path})'
22
23 new_content = image_pattern.sub(replace_alt, content)
24
25 with open(md_path, "w", encoding="utf-8") as file:
26 file.write(new_content)
27
28 print(f"Processed: {md_file}")
29
30if __name__ == "__main__":
31 if len(sys.argv) != 2:
32 print("Usage: python script.py <directory>")
33 sys.exit(1)
34
35 directory = sys.argv[1]
36 if not os.path.isdir(directory):
37 print("Error: Directory does not exist.")
38 sys.exit(1)
39
40 add_alt_text_to_images(directory)