-
Notifications
You must be signed in to change notification settings - Fork 0
/
fix_html.py
70 lines (60 loc) · 2.31 KB
/
fix_html.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
67
68
69
70
import os
import re
import argparse
def convert_display_math(content):
# Convert double $$...$$ to \[...\]
return re.sub(r'\$\$(.+?)\$\$', r'\\[\1\\]', content, flags=re.DOTALL)
def convert_inline_math(content):
# Convert single $...$ to \( ... \), ensuring not to affect already converted \[...\]
return re.sub(r'(?<!\\)\$(?!\$)(.+?)(?<!\\)\$(?!\$)', r'\\(\1\\)', content)
def replace_mathjax_config(content):
new_mathjax_config = """
<!-- Load mathjax -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS_CHTML-full,Safe"> </script>
<!-- MathJax configuration -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: {
autoNumber: "AMS",
useLabelIds: true
}
},
tex2jax: {
inlineMath: [ ['\\\\\(','\\\\\)']],
displayMath: [ ['\\\\\[','\\\\\]']],
processEscapes: true,
processEnvironments: true
},
displayAlign: 'center',
CommonHTML: {
linebreaks: {
automatic: true
}
}
});
MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
</script>
<!-- End of mathjax configuration --><script type="module">
"""
# Use regex to match and replace the existing MathJax configuration
pattern = re.compile(r'<!-- Load mathjax -->.*?<!-- End of mathjax configuration --><script type="module">', re.DOTALL)
return pattern.sub(new_mathjax_config, content)
def process_file(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
content = convert_display_math(content)
content = convert_inline_math(content)
content = replace_mathjax_config(content)
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
def main():
parser = argparse.ArgumentParser(description='Process HTML files to convert math delimiters and update MathJax configuration.')
parser.add_argument('directory', type=str, help='Directory containing HTML files')
args = parser.parse_args()
directory = args.directory
for filename in os.listdir(directory):
if filename.endswith('.html'):
process_file(os.path.join(directory, filename))
if __name__ == '__main__':
main()