-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun.py
More file actions
1522 lines (1185 loc) · 54.2 KB
/
run.py
File metadata and controls
1522 lines (1185 loc) · 54.2 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# import yaml
# import os
# import glob
# import regex as re
# from bs4 import BeautifulSoup
# import lxml
# import shutil
# import stat
# import sys
# import warnings
# import time
# warnings.simplefilter('ignore')
#
# DST_FOLDER = 'docs'
# GAUGE_COUNT = 0
# def get_stars_from_average(avg):
# if avg > 89:
# stars = 1
# elif avg >= 75:
# stars = 2
# elif avg >= 50:
# stars = 3
# elif avg >= 30:
# stars = 4
# else:
# stars = 5
# return stars * '⭐️'
# def delete_folder(path):
# '''Needed for Windows...
# Taken from https://stackoverflow.com/questions/21261132/shutil-rmtree-to-remove-readonly-files
# '''
# def del_rw(action, name, exc):
# os.chmod(name, stat.S_IWRITE)
# os.remove(name)
# return shutil.rmtree(path, onerror=del_rw)
# def format_assignment_name(name):
# '''Takes in a string like 'fa21-final' and returns 'Fall 2021 Final Exam
# Will need to update for discussions at some point <- lol these comments are out of date
# '''
# quarter, type = name.split('-')
# season, year = quarter[:2], quarter[2:]
# season = {'fa': 'Fall', 'wi': 'Winter', 'sp': 'Spring', 'su': 'Summer'}[season]
# year = '20' + year
# return season + ' ' + year + ' ' + type.title() + ' Exam'
# def format_md_path(name):
# '''Example behavior is shown below.
# >>> format_md_path('problems/sp22-midterm/q7-merge')
# 'problems/sp22-midterm/q7-merge.md'
# # new use case for discussion (when there's problem-specific context)
# >>> format_md_path('problems/sp22-midterm/q7-merge, problems/sp22-midterm/data-info-for-discussion')
# 'problems/sp22-midterm/q7-merge.md, problems/sp22-midterm/data-info-for-discussion.md'
# '''
# if ',' not in name:
# return os.path.join('problems', f'{name}.md')
# else:
# names = name.split(', ')
# if len(names) > 2:
# raise Exception(f'Provided more than 2 files in a .yml file. For debugging: {name}')
# return format_md_path(names[0]) + ', ' + format_md_path(names[1])
# def format_md_paths(names):
# paths = [format_md_path(name) for name in names]
# return paths
# def read_html_config(path):
# f = open(path, 'r')
# r = f.read()
# f.close()
# return r + '\n\n'
# def create_top_info(params, is_exam=True):
# inst_info = f"**Instructor(s):** {params['instructors']}" if is_exam else ''
# return f'''
# [← return to practice.dsc10.com](../index.html)
# ---
# {inst_info}
# {params['context']}
# ---
# '''
# # {'_Note: Solutions are currently hidden, and will be made visible at a later date._' if not params['show_solution'] else ''}
# def stitch(files, show_solution, toc=False):
# '''Stitches individual .md files into a longer .md string with problems'''
# paths = format_md_paths(files)
# out = '\n\n'
# if toc:
# # Format a table of contents here
# pass
# for i, path in enumerate(paths):
# # This case only happens for discussion worksheets, when we provide a question along with a "data info" sheet just for that question
# if ', ' in path:
# question_path, info_path = path.split(', ')
# question_text = open(question_path, 'r').read()
# info_text = open(info_path, 'r').read()
# # Need to place the info text at the start of the question text
# # So will replace the # BEGIN PROB in the question text with # BEGIN PROB {context}
# r = question_text.replace("# BEGIN PROB", f"# BEGIN PROB {info_text} <br><br>")
# else:
# r = open(path, 'r', encoding='UTF-8').read()
# q_out = process_problem(problem_str=r, problem_num=i+1, show_solution=show_solution)
# q_out += '\n\n\n---\n\n\n'
# out += q_out
# return out
# # ---
# def pandoc(s, kind='md', flags=''):
# '''Take in a string containing Markdown and return its HTML equivalent, via pandoc'''
# assert kind == 'tex' or kind == 'md', 'kind must be tex or md'
# if not os.path.exists('temp'):
# os.mkdir('temp')
# in_path = os.path.join('temp', f'temp.{kind}')
# in_file = open(in_path, 'w', encoding='UTF-8')
# in_file.write(s)
# in_file.close()
# src_path = os.path.join('temp', f'temp.{kind}')
# dst_path = os.path.join('temp', 'temp.html')
# os.system(f'pandoc -s --standalone --katex --from markdown-markdown_in_html_blocks+raw_html --metadata title=" " -s {src_path} {flags} -o {dst_path}')
# out_path = os.path.join('temp', 'temp.html')
# out_file = open(out_path, 'r', encoding='UTF-8') # CHANGED
# out_s = out_file.read()
# out_file.close()
# delete_folder('temp')
# soup = BeautifulSoup(out_s, features='lxml')
# return str(soup.find('body')).replace('<body>', '').replace('</body>', '')
# def add_solution_box(solution_str, problem_num):
# '''solution_str must be an HTML containing the solution text.'''
# # Using . in attribute names does not work
# if isinstance(problem_num, str) and '.' in problem_num:
# problem_num = problem_num.replace('.', '_')
# out = f'''
# <div class="accordion" id="accordionExample">
# <div class="accordion-item">
# <h2 class="accordion-header" id="heading{problem_num}">
# <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{problem_num}" aria-expanded="true" aria-controls="collapse{problem_num}">
# Click to view the solution.
# </button>
# </h2>
# <div id="collapse{problem_num}" class="accordion-collapse collapse collapse" aria-labelledby="heading{problem_num}" data-bs-parent="#accordionExample">
# <div class="accordion-body">
# {solution_str}
# </div>
# </div>
# </div>
# </div>
# '''
# return out
# def process_MC_matches(matchobj):
# '''Helper function for process_MC'''
# global count
# match_str = matchobj.group()
# # Multiple choice (circular boxes)
# if match_str.count('( )') >= 2:
# exp = r'\( \) (.*)'
# input_type = 'radio'
# # Select all (square boxes)
# elif match_str.count('[ ]') >= 2:
# exp = r'\[ \] (.*)'
# input_type = 'checkbox'
# else:
# print(match_str)
# raise SyntaxError('How did this happen?')
# choices = re.findall(exp, match_str)
# out = '\n\n<ul class="task-list">\n'
# for choice in choices:
# processed_choice = pandoc(choice) # In case the choice includes Markdown
# processed_choice = str(BeautifulSoup(processed_choice, features='lxml').find('p')).replace('<p>', '').replace('</p>', '')
# out += f'<li><p><input type="{input_type}" disabled="" /> {processed_choice}</p></li>\n'
# out += '</ul>\n\n'
# return out
# def process_MC(problem_str):
# '''Critical assumption: any problem with multiple choice or select all options has at least 2 choices'''
# extract_exp = r'\n\n([[(] [])] [\d\D]+?)\n\n'
# return re.sub(extract_exp, process_MC_matches, problem_str)
# def process_problem_no_subparts(problem_str, problem_num, show_solution, heading='##'):
# '''Used for problems with no subparts, and to process individual subparts'''
# if show_solution:
# # Extract solution
# if '# BEGIN SOLUTION' in problem_str:
# sep = 'SOLUTION'
# elif '# BEGIN SOLN' in problem_str:
# sep = 'SOLN'
# else:
# raise AssertionError('Neither # BEGIN SOLUTION nor # BEGIN SOLN were found')
# pattern = r"([\d\D]*?)"
# exp = f"# BEGIN {sep}{pattern}# END {sep}"
# solution_str = re.findall(exp, problem_str)
# if len(solution_str) != 1:
# raise AssertionError('This should not happen')
# # Pass solution_str through pandoc first, then give it the solution box
# solution_str_html = pandoc(solution_str[0])
# solution_processed = add_solution_box(solution_str_html, problem_num)
# problem_only = re.sub(exp, '', problem_str)
# else:
# solution_processed = ''
# # If the solution is there, we need to remove it first
# contains_solution = False
# if '# BEGIN SOLUTION' in problem_str:
# sep = 'SOLUTION'
# contains_solution = True
# elif '# BEGIN SOLN' in problem_str:
# sep = 'SOLN'
# contains_solution = True
# else:
# # No solution was provided
# pass
# if contains_solution:
# raw_pattern = r"([\d\D]*?)"
# exp = f"# BEGIN {sep}{raw_pattern}# END {sep}"
# problem_only = re.sub(exp, '', problem_str)
# else:
# problem_only = problem_str
# # Get the problem text
# problem_only = problem_only.replace('# BEGIN PROB', '').replace('# END PROB', '')
# # Process MC/SA boxes in problem_only
# problem_only = process_MC(problem_only)
# # Put it all together
# out = f'''
# {heading} Problem {problem_num}
# {problem_only}
# {solution_processed}
# '''
# return out
# SUBPART_REGEXP = r'# BEGIN SUBPROB([\d\D]*?)# END SUBPROB'
# # subpart_count = 0
# # def create_subpart_fn(problem_num, show_solution, heading):
# # def subpart_fn(matchobj):
# # global subpart_count
# # subpart_count += 1
# # match_str = re.findall(SUBPART_REGEXP, matchobj[0])[0]
# # subprob_num = str(problem_num) + f'.{subpart_count}'
# # return process_problem_no_subparts(match_str, subprob_num, show_solution, heading)
# # return subpart_fn
# def process_problem_with_subparts(problem_str, problem_num, show_solution):
# # Extract any content before the first # BEGIN SUBPROB
# # preamble = problem_str[problem_str.index('# BEGIN PROB')+12:problem_str.index('# BEGIN SUBPROB')]
# # out = f'## Problem {problem_num}\n\n{preamble}<br>\n\n'
# problem_str = problem_str.replace('# BEGIN PROB', '').replace('# END PROB', '') \
# .replace('# BEGIN PROBLEM', '').replace('# END PROBLEM', '')
# problem_str = f'## Problem {problem_num}\n{problem_str}'
# # other idea
# # while the number of matches is non-zero, replace the first match
# # while len(re.findall(SUBPART_REGEXP, out)) > 0L
# i = 0
# while len(re.findall(SUBPART_REGEXP, problem_str)) > 0:
# # Find the next unprocessed question
# top_match = re.findall(SUBPART_REGEXP, problem_str)[0]
# top_match_processed = process_problem_no_subparts(top_match,
# str(problem_num) + f'.{i+1}',
# show_solution,
# heading='###')
# top_match_processed = '<br>\n' + top_match_processed.replace(r'\ '[0], r'\\ '[:-1]) + '\n<br>'
# problem_str = re.sub(SUBPART_REGEXP, top_match_processed, problem_str, count=1)
# i += 1
# # parts = re.findall(r, problem_str)
# # here, instead of adding to the output, replace each occurrence of a match with its conversion
# # out += re.sub(SUBPART_REGEXP, create_subpart_fn(problem_num, show_solution, heading='###'), problem_str)
# # for i, part in enumerate(parts):
# # out += process_problem_no_subparts(part, str(problem_num) + f'.{i+1}', show_solution, heading='###') + '\n\n<br>\n\n'
# # Remove unnecessary spacing
# problem_str = problem_str.replace('<br>\n\n<br>', '<br>')
# return problem_str
# # renders stars
# AVG_REGEXP = r'<average>(\d+)<\/average>'
# def stars_repl(matchobj, exam=False):
# # global GAUGE_COUNT
# # GAUGE_COUNT += 1
# avg_int = int(re.findall(AVG_REGEXP, matchobj[0])[0])
# stars = get_stars_from_average(avg_int)
# kind = 'exam' if exam else 'problem'
# return f'<hr><h5>Difficulty: {stars}</h5><p>The average score on this {kind} was {avg_int}%.'
# # TOPICS_REGEXP = r'<topics>([A-Za-z ,]+)<\/topics>'
# # def topics_extraction(matchobj, exam=False):
# def process_problem(problem_str, problem_num, show_solution):
# assert problem_str.count('# BEGIN PROB') == problem_str.count('# END PROB') == 1, 'Need exactly one # BEGIN PROB and # END PROB pair'
# problem_str = re.sub(AVG_REGEXP, stars_repl, problem_str)
# if '# BEGIN SUBPROB' in problem_str:
# assert problem_str.count('# BEGIN SUBPROB') == problem_str.count('# END SUBPROB'), f'Different number of # BEGIN SUBPROB and # END SUBPROB in Problem {problem_num}'
# return process_problem_with_subparts(problem_str, problem_num, show_solution)
# else:
# return process_problem_no_subparts(problem_str, problem_num, show_solution)
# # ---
# def process_page(path, is_exam=True):
# '''Takes in a path to a YML file and returns a MD file with everything, along with the title of the page (which we access through params). Defaults to processing exams.'''
# r_file = open(path, 'r')
# r = r_file.read()
# r_file.close()
# params = yaml.safe_load(r)
# if 'show_solution' not in params.keys():
# params['show_solution'] = True
# out = read_html_config('include-head.html')
# out += create_top_info(params, is_exam=is_exam)
# # Add information for the entire exam
# if 'data_info' in params.keys():
# info_path = os.path.join('problems', f'{params["data_info"]}.md')
# info_file = open(info_path, 'r', encoding='UTF-8')
# info = info_file.read()
# info_file.close()
# out += info + '\n\n --- \n\n'
# out += stitch(params['problems'], params['show_solution'])
# out += '$$ $$' # to enable latex always
# if 'footer' in params.keys():
# out += f'\n\n {params["footer"]} \n\n'
# # Temporary summer add-on to collect feedback
# out += '''
# ---
# #### 👋 Feedback: Find an error? Still confused? Have a suggestion? <a href="https://forms.gle/WZ71FchnXU1K154d7">Let us know here</u></a>.
# ---
# '''
# if 'title' in params.keys():
# title = params['title']
# else:
# title = None
# # TODO: easily extract all files for a single final exam
# # TODO: format PDFs for printing: https://stackoverflow.com/problems/1664049/can-i-force-a-page-break-in-html-printing
# return out, title
# def write_page(path, called_from_write_all_pages=False):
# '''Takes in a path to a YML file and writes the MD file, runs pandoc, deletes the MD file'''
# sep = '/' if '/' in path else '\\'
# assignment_name = path.split(sep)[-1].replace('.yml', '')
# # is_discussion = 'disc' in path
# is_exam = 'midterm' in path or 'final' in path
# # Generate the Markdown
# page, title = process_page(path, is_exam=is_exam)
# # Write the Markdown
# open_path = os.path.join(DST_FOLDER, f'{assignment_name}.md')
# f = open(open_path, 'w', encoding='UTF-8') # CHANGED
# f.write(page)
# f.close()
# # Convert to HTML
# dst_folder_path = os.path.join(DST_FOLDER, assignment_name)
# if not os.path.exists(dst_folder_path):
# os.mkdir(dst_folder_path) # make folder
# # If an assignment title wasn't defined in params, try and create it using the file name
# # For discussions at least, we will specify it and process_page will return it
# if not title:
# title = format_assignment_name(assignment_name)
# src_path = os.path.join(DST_FOLDER, f'{assignment_name}.md')
# dst_path = os.path.join(DST_FOLDER, assignment_name, 'index.html')
# css_path = os.path.join('..', 'assets', 'theme.css')
# os.system(f'pandoc -s --standalone --katex --from markdown-markdown_in_html_blocks+raw_html -c {css_path} --metadata title="{title}" {src_path} -o {dst_path}')
# # Delete the intermediate Markdown
# os.remove(src_path)
# # Copy over the images for just that page, but only if called individually
# # If called in bulk, this shouldn't be run, since this is handled by
# # write_all_pages
# if not called_from_write_all_pages:
# src_path = os.path.join('assets', 'images', assignment_name)
# dst_path = os.path.join(DST_FOLDER, src_path)
# if os.path.exists(src_path):
# if os.path.exists(dst_path):
# shutil.rmtree(dst_path)
# shutil.copytree(src_path, dst_path)
# def update_page(path):
# '''Doesn't work for discussion files, yet.'''
# sep = '/' if '/' in path else '\\'
# assignment_name = path.split(sep)[-1].replace('.yml', '')
# # Generate the Markdown
# page = process_page(path)
# # Write the Markdown
# open_path = os.path.join(DST_FOLDER, f'{assignment_name}.md')
# f = open(open_path, 'w')
# f.write(page)
# f.close()
# dst_folder_path = os.path.join(DST_FOLDER, assignment_name)
# # Make the function much faster by not requiring the folder to be recreated
# if not os.path.exists(dst_folder_path):
# os.mkdir(dst_folder_path) # make folder
# title = format_assignment_name(assignment_name)
# src_path = os.path.join(DST_FOLDER, f'{assignment_name}.md')
# # Use a temp HTML file to write over than the main one inorder to minimize delay on viewing the page
# tmp_path = os.path.join(DST_FOLDER, assignment_name, 'temp.html')
# dst_path = os.path.join(DST_FOLDER, assignment_name, 'index.html')
# css_path = os.path.join('..', 'assets', 'theme.css')
# os.system(f'pandoc -s --standalone --katex --from markdown-markdown_in_html_blocks+raw_html -c {css_path} --metadata title="{title}" {src_path} -o {tmp_path}')
# # Delete the intermediate Markdown
# os.remove(src_path)
# if os.path.exists(dst_path):
# os.remove(dst_path)
# os.rename(tmp_path, dst_path)
# def write_all_pages(dir='pages'):
# '''Assumes all pages are specified in YML'''
# if os.path.exists(DST_FOLDER):
# delete_folder(DST_FOLDER)
# os.mkdir(DST_FOLDER)
# # Add CNAME back – this is a massive hack, but whatever
# cname_path = os.path.join(DST_FOLDER, 'CNAME')
# cname = open(cname_path, 'w')
# cname.write('practice.dsc10.com')
# cname.close()
# page_paths = os.path.join(dir, '*', '*.yml')
# all_paths = glob.glob(page_paths)
# for path in all_paths:
# write_page(path, called_from_write_all_pages=True)
# # Copy over images/scripts
# # os.mkdir(f'{DST_FOLDER}/assets/')
# # os.system(f'cp -R assets/ {DST_FOLDER}/assets/')
# dst_path = os.path.join(DST_FOLDER, 'assets')
# shutil.copytree('assets', dst_path)
# def create_index():
# f_index = open('index.md', 'r')
# index_src = f_index.read()
# f_index.close()
# out = read_html_config('include-head.html')
# out += '\n' + index_src
# src_path = os.path.join(DST_FOLDER, 'index.md')
# f = open(src_path, 'w')
# f.write(out)
# f.close()
# css_path = os.path.join('assets', 'theme.css')
# src_path = os.path.join(DST_FOLDER, 'index.md')
# dst_path = os.path.join(DST_FOLDER, 'index.html')
# os.system(f'pandoc -c {css_path} -s {src_path} -o {dst_path}')
# os.remove(src_path)
# # Remove pre-defined title
# src_path = os.path.join(DST_FOLDER, 'index.html')
# f = open(src_path, 'r')
# r = f.read()
# f.close()
# r = re.sub(r'<h1 class="title">.*?</h1>', '', r)
# f = open(src_path, 'w')
# f.write(r)
# f.close()
# if __name__ == '__main__':
# # No arguments: run all
# if len(sys.argv) == 1:
# write_all_pages()
# create_index()
# elif sys.argv[1] == 'index':
# create_index()
# elif sys.argv[1] == "listen":
# # Obtain the file paths for all markdown files.
# # We will be looking to see if the modification time changes to signal an update
# page_paths = os.path.join('pages', '*', '*.yml')
# all_paths = glob.glob(page_paths)
# # This creates an array that contains an entry for each yml file containing all the yml and md paths related to it.
# # These are all the files we would want to check for edits.
# listen_files = []
# for path in all_paths:
# r_file = open(path, 'r')
# r = r_file.read()
# r_file.close()
# params = yaml.safe_load(r)
# listen_files += [[path] + list(map(lambda x: os.path.join("problems",x + ".md"),params.get("problems",[])))]
# # This uses the same format as the listen_files variable to store the timestamp info for each file.
# # Timestamps are used to check for file changes to signal updates.
# cached_stamp = []
# for i,section in enumerate(listen_files):
# cached_stamp += [[]]
# for file in section:
# cached_stamp[i] += [os.stat(file).st_mtime]
# # Beginning of listening loop.
# # This is based on the second response to this post: https://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes
# while True:
# try:
# # Every second
# time.sleep(1)
# # For each markdown file
# for i, section in enumerate(listen_files):
# for j, path in enumerate(section):
# # Get the last modified time stamp
# stamp = os.stat(path).st_mtime
# # Compare to currently cached timestamp
# # If its different then the file in questions has been modified and needs to be reflected on the html file
# if stamp != cached_stamp[i][j]:
# # When a yml file is updated, we also need to update the files listened to reflect changes
# # to the problem section
# if ".yml" in path:
# print(f"Updating tracked problems for {section[0]}")
# r_file = open(path, 'r')
# r = r_file.read()
# r_file.close()
# new_problems = yaml.safe_load(r).get("problems",[])
# # Replace old listened files with new listened files to reflects changes to the .yml file
# listen_files[i] = [path] + list(map(lambda x: os.path.join("problems",x + ".md"),new_problems))
# cached_stamp[i] = [os.stat(file).st_mtime for file in listen_files[i]]
# # Update cached timestamp to reflect the update
# cached_stamp[i][j] = stamp
# print(f"Updating: {section[0]}")
# # Update the new HTML folder
# update_page(section[0])
# print("Finished Updating! Refresh the .html file on your browser to see changes!")
# break
# except KeyboardInterrupt:
# break
# else:
# for page in sys.argv[1:]:
# write_page(page)
import yaml
import os
import glob
import regex as re
from bs4 import BeautifulSoup
import lxml
import shutil
import stat
import sys
import warnings
import time
from collections import defaultdict
warnings.simplefilter('ignore')
DST_FOLDER = 'docs'
# Bare `--katex` uses local paths on Ubuntu CI; CDN keeps GitHub Pages math working.
PANDOC_KATEX = '--katex=https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/'
GAUGE_COUNT = 0
def get_stars_from_average(avg):
if avg >= 90:
stars = 1
elif avg >= 75:
stars = 2
elif avg >= 50:
stars = 3
elif avg >= 30:
stars = 4
else:
stars = 5
return stars * '⭐️'
def delete_folder(path):
'''Needed for Windows...
Taken from https://stackoverflow.com/questions/21261132/shutil-rmtree-to-remove-readonly-files
'''
def del_rw(action, name, exc):
os.chmod(name, stat.S_IWRITE)
os.remove(name)
return shutil.rmtree(path, onerror=del_rw)
def format_assignment_name(name):
'''Takes in a string like 'fa21-final' and returns 'Fall 2021 Final Exam
Will need to update for discussions at some point <- lol these comments are out of date
'''
quarter, type = name.split('-')
season, year = quarter[:2], quarter[2:]
season = {'fa': 'Fall', 'wi': 'Winter', 'sp': 'Spring', 'su': 'Summer'}[season]
year = '20' + year
return season + ' ' + year + ' ' + type.title() + ' Exam'
def format_md_path(name):
'''Example behavior is shown below.
>>> format_md_path('problems/sp22-midterm/q7-merge')
'problems/sp22-midterm/q7-merge.md'
# new use case for discussion (when there's problem-specific context)
>>> format_md_path('problems/sp22-midterm/q7-merge, problems/sp22-midterm/data-info-for-discussion')
'problems/sp22-midterm/q7-merge.md, problems/sp22-midterm/data-info-for-discussion.md'
'''
if ',' not in name:
return os.path.join('problems', f'{name}.md')
else:
names = name.split(', ')
if len(names) > 2:
raise Exception(f'Provided more than 2 files in a .yml file. For debugging: {name}')
return format_md_path(names[0]) + ', ' + format_md_path(names[1])
def format_md_paths(names):
paths = [format_md_path(name) for name in names]
return paths
def read_html_config(path):
f = open(path, 'r')
r = f.read()
f.close()
return r + '\n\n'
def create_top_info(params, is_exam=True):
inst_info = f"**Instructor(s):** {params['instructors']}" if is_exam else ''
return f'''
[← return to practice.dsc10.com](../index.html)
---
{inst_info}
{params['context']}
---
'''
# {'_Note: Solutions are currently hidden, and will be made visible at a later date._' if not params['show_solution'] else ''}
def stitch(files, show_solution, toc=False):
'''Stitches individual .md files into a longer .md string with problems'''
paths = format_md_paths(files)
out = '\n\n'
if toc:
# Format a table of contents here
pass
for i, path in enumerate(paths):
# This case only happens for discussion worksheets, when we provide a question along with a "data info" sheet just for that question
if ', ' in path:
question_path, info_path = path.split(', ')
question_text = open(question_path, 'r').read()
info_text = open(info_path, 'r').read()
# Need to place the info text at the start of the question text
# So will replace the # BEGIN PROB in the question text with # BEGIN PROB {context}
r = question_text.replace("# BEGIN PROB", f"# BEGIN PROB {info_text} <br><br>")
else:
r = open(path, 'r', encoding='UTF-8').read()
# parse front matter once and extract a visible lecture pill
front, body = parse_frontmatter(r)
lec = front.get("lecture")
lec_txt = None
if isinstance(lec, list) and lec:
lec_txt = ", ".join(str(int(x)) for x in sorted({int(x) for x in lec}))
elif isinstance(lec, int):
lec_txt = str(lec)
elif isinstance(lec, str) and lec.strip():
parts = re.split(r"[,\s]+", lec.strip())
nums = [int(p) for p in parts if p]
if nums:
lec_txt = ", ".join(str(x) for x in sorted(set(nums)))
lecture_html = (
f"<div class='meta'><span class='pill pill-lecture' title='Lecture number(s)'>Lecture {lec_txt}</span></div>\n"
if lec_txt else ""
)
# Pass body (content without front matter) so it renders cleanly
q_out = process_problem(problem_str=body, problem_num=i+1, show_solution=show_solution, lecture_html=lecture_html)
q_out += '\n\n\n---\n\n\n'
out += q_out
return out
# ---
def pandoc(s, kind='md', flags=''):
'''Take in a string containing Markdown and return its HTML equivalent, via pandoc'''
assert kind == 'tex' or kind == 'md', 'kind must be tex or md'
if not os.path.exists('temp'):
os.mkdir('temp')
in_path = os.path.join('temp', f'temp.{kind}')
in_file = open(in_path, 'w', encoding='UTF-8')
in_file.write(s)
in_file.close()
src_path = os.path.join('temp', f'temp.{kind}')
dst_path = os.path.join('temp', 'temp.html')
os.system(f'pandoc -s --standalone {PANDOC_KATEX} --from markdown-markdown_in_html_blocks+raw_html --metadata title=" " -s {src_path} {flags} -o {dst_path}')
out_path = os.path.join('temp', 'temp.html')
out_file = open(out_path, 'r', encoding='UTF-8') # CHANGED
out_s = out_file.read()
out_file.close()
delete_folder('temp')
soup = BeautifulSoup(out_s, features='lxml')
return str(soup.find('body')).replace('<body>', '').replace('</body>', '')
def add_solution_box(solution_str, problem_num):
'''solution_str must be an HTML containing the solution text.'''
# Using . in attribute names does not work
if isinstance(problem_num, str) and '.' in problem_num:
problem_num = problem_num.replace('.', '_')
out = f'''
<div class="accordion" id="accordionExample">
<div class="accordion-item">
<h2 class="accordion-header" id="heading{problem_num}">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{problem_num}" aria-expanded="true" aria-controls="collapse{problem_num}">
Click to view the solution.
</button>
</h2>
<div id="collapse{problem_num}" class="accordion-collapse collapse collapse" aria-labelledby="heading{problem_num}" data-bs-parent="#accordionExample">
<div class="accordion-body">
{solution_str}
</div>
</div>
</div>
</div>
'''
return out
def process_MC_matches(matchobj):
'''Helper function for process_MC'''
global count
match_str = matchobj.group()
# Multiple choice (circular boxes)
if match_str.count('( )') >= 2:
exp = r'\( \) (.*)'
input_type = 'radio'
# Select all (square boxes)
elif match_str.count('[ ]') >= 2:
exp = r'\[ \] (.*)'
input_type = 'checkbox'
else:
print(match_str)
raise SyntaxError('How did this happen?')
choices = re.findall(exp, match_str)
out = '\n\n<ul class="task-list">\n'
for choice in choices:
processed_choice = pandoc(choice) # In case the choice includes Markdown
processed_choice = str(BeautifulSoup(processed_choice, features='lxml').find('p')).replace('<p>', '').replace('</p>', '')
out += f'<li><p><input type="{input_type}" disabled="" /> {processed_choice}</p></li>\n'
out += '</ul>\n\n'
return out
def process_MC(problem_str):
'''Critical assumption: any problem with multiple choice or select all options has at least 2 choices'''
extract_exp = r'\n\n([[(] [])] [\d\D]+?)\n\n'
return re.sub(extract_exp, process_MC_matches, problem_str)
def process_problem_no_subparts(problem_str, problem_num, show_solution, heading='##', lecture_html=""):
'''Used for problems with no subparts, and to process individual subparts'''
if show_solution:
# Extract solution
if '# BEGIN SOLUTION' in problem_str:
sep = 'SOLUTION'
elif '# BEGIN SOLN' in problem_str:
sep = 'SOLN'
else:
raise AssertionError('Neither # BEGIN SOLUTION nor # BEGIN SOLN were found')
pattern = r"([\d\D]*?)"
exp = f"# BEGIN {sep}{pattern}# END {sep}"
solution_str = re.findall(exp, problem_str)
if len(solution_str) != 1:
raise AssertionError('This should not happen')
# Pass solution_str through pandoc first, then give it the solution box
solution_str_html = pandoc(solution_str[0])
solution_processed = add_solution_box(solution_str_html, problem_num)
problem_only = re.sub(exp, '', problem_str)
else:
solution_processed = ''
# If the solution is there, we need to remove it first
contains_solution = False
if '# BEGIN SOLUTION' in problem_str:
sep = 'SOLUTION'
contains_solution = True
elif '# BEGIN SOLN' in problem_str:
sep = 'SOLN'
contains_solution = True
else:
# No solution was provided
pass
if contains_solution:
raw_pattern = r"([\d\D]*?)"
exp = f"# BEGIN {sep}{raw_pattern}# END {sep}"
problem_only = re.sub(exp, '', problem_str)
else:
problem_only = problem_str
# Get the problem text
problem_only = problem_only.replace('# BEGIN PROB', '').replace('# END PROB', '')
# Process MC/SA boxes in problem_only
problem_only = process_MC(problem_only)
# Put it all together
out = f'''
{heading} Problem {problem_num}
{lecture_html}
{problem_only}
{solution_processed}
'''
return out
SUBPART_REGEXP = r'# BEGIN SUBPROB([\d\D]*?)# END SUBPROB'
def process_problem_with_subparts(problem_str, problem_num, show_solution, lecture_html=""):
problem_str = problem_str.replace('# BEGIN PROB', '').replace('# END PROB', '') \
.replace('# BEGIN PROBLEM', '').replace('# END PROBLEM', '')
# Add the lecture pill once at the top of the problem
problem_str = f'## Problem {problem_num}\n{lecture_html}{problem_str}'
i = 0
while len(re.findall(SUBPART_REGEXP, problem_str)) > 0:
top_match = re.findall(SUBPART_REGEXP, problem_str)[0]
top_match_processed = process_problem_no_subparts(top_match,
str(problem_num) + f'.{i+1}',
show_solution,
heading='###',
lecture_html="") # no pill per subpart
top_match_processed = '<br>\n' + top_match_processed.replace(r'\ '[0], r'\\ '[:-1]) + '\n<br>'
problem_str = re.sub(SUBPART_REGEXP, top_match_processed, problem_str, count=1)
i += 1
problem_str = problem_str.replace('<br>\n\n<br>', '<br>')
return problem_str
# ===== Lecture-page helpers (Step 2) =====
FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*(.*)\Z", re.DOTALL)
def _parse_frontmatter(text: str):
"""Return (frontmatter_dict, body_without_frontmatter)."""
m = FRONTMATTER_RE.match(text)
if not m:
return {}, text
fm_raw, body = m.group(1), m.group(2)
try:
data = yaml.safe_load(fm_raw) or {}
if not isinstance(data, dict):
data = {}
except Exception:
data = {}
return data, body
def _normalize_lecture_tag(value):
"""Normalize 'lecture' tag into a list of ints."""
if value is None:
return []
if isinstance(value, int):
return [value]
if isinstance(value, list):
out = []
for v in value:
try: