-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract-code-in-videos.py
executable file
·100 lines (81 loc) · 2.61 KB
/
extract-code-in-videos.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/usr/bin/env python
"""
tool to produce files like e.g.
w1/w1-s3-av-code.html
sources are in the form
w1/w1-code-in-videos.md
this tool will update as many files of the form
w1/w1-s3-av-code.html
as are mentioned in the sources
Run as follows:
$ cd flotpython-course
$ python ../flotpython-tools/extract-code-in-videos.py w?/w*-code-in-videos.md
"""
import re
from argparse import ArgumentParser
from pathlib import Path
from myst_parser.main import to_html
sequence_pattern = r"# w(?P<week>[0-9])s(?P<seq>[0-9])"
sequence_matcher = re.compile(sequence_pattern)
header = """
<style>
.clipboard {
font-size: 11px;
}
</style>
<h3 style="border: 1px solid #66b; border-radius: 5px; padding: 10px; background-color: #eee;">
<b><i>bloc-note pour copier/coller le code de la vidéo</i></b>
</h3>
"""
def sanitize(lines):
"""
remove any trailing empty line
"""
while lines:
last = lines[-1]
if not last.strip():
lines.pop()
else:
break
return lines
def save_sequence(week, seq, lines):
filename = f"w{week}/w{week}-s{seq}-av-code.html"
print(f"using {len(lines)} (markdown) lines to make {filename}")
text ="".join(sanitize(lines))
#print(text)
with Path(filename).open('w') as writer:
writer.write(f"<div class='clipboard'>{to_html(text)}</div>")
def handle_week(markdown):
with open(markdown) as feed:
lines = []
week, seq = None, None
for line in feed:
if match := sequence_matcher.match(line):
# flush previous sequence if needed
if lines:
if week:
save_sequence(week, seq, lines)
# potential leak ?
else:
# allow empty lines
meaningful = [line.strip() for line in lines]
meaningful = [line for line in meaningful if line]
if meaningful:
print("OOPS !")
week, seq = match.groups()
#print(f"spotted week={week} seq={seq} with {len(lines)} lines")
lines = []
lines.append(header)
# lines.append(line)
else:
lines.append(line)
save_sequence(week, seq, lines)
#print(f"EOF with week={week} seq={seq} and {len(lines)} lines")
def main():
parser = ArgumentParser()
parser.add_argument("markdowns", nargs='+')
args = parser.parse_args()
for markdown in args.markdowns:
handle_week(markdown)
if __name__ == '__main__':
main()