-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathimg-alt-to-figcaption.py
executable file
·66 lines (55 loc) · 2.24 KB
/
img-alt-to-figcaption.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import os
targets = ["./docs/", "./blog/", "./i18n/"]
COUNTER = 0
all_md_files = []
if __name__ == "__main__":
for target in targets:
if not os.path.isdir(target):
continue
for root, dirs, files in os.walk(target):
for file in files:
if file.endswith(".md") or file.endswith(".mdx"):
all_md_files.append(os.path.join(root, file))
print("Found " + str(len(all_md_files)) + " MD and MDX files.")
for md_file in all_md_files:
if md_file.endswith("Hey.md"):
continue
with open(md_file, "r") as f:
lines = f.readlines()
with open(md_file, "w") as f:
for line in lines:
if (
line.startswith("![")
and "]" in line
and "(" in line
and line.endswith(")\n")
):
alt_text = line.split("![")[1].split("]")[0]
filename = line.split("(")[1].split(")")[0]
if (
alt_text.endswith(".png")
or alt_text.endswith(".jpg")
or alt_text.endswith(".jpeg")
or alt_text.endswith(".gif")
or alt_text.endswith(".svg")
or alt_text.startswith("ALT:")
):
line = f"""
<figure>
{line.replace("ALT: ", "").replace("ALT:", "")}
</figure>
"""
else:
line = f"""
<figure>
{line}
<figcaption>{alt_text}</figcaption>
</figure>
"""
COUNTER += 1
# replace mp4, webm with video tag
if filename.endswith(".mp4") or filename.endswith(".webm"):
hex = filename.split("/")[-1].split(".")[0]
line = f"""\n\nimport Video{hex} from "{filename}";\n<figure><video controls muted autoplay playsinline><source src={{Video{hex}}} type="video/{filename.split('.')[-1]}"/></video>{f'<figcaption>{alt_text}</figcaption>' if not filename.lower().endswith(alt_text.lower()) else ''}</figure>\n\n"""
f.write(line)
print("Replaced " + str(COUNTER) + " alt texts.")