forked from sci-sim/sci-sim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsim_parser.py
More file actions
executable file
·473 lines (359 loc) · 13.1 KB
/
sim_parser.py
File metadata and controls
executable file
·473 lines (359 loc) · 13.1 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
import codecs
from sys import argv, exit
from scisim.models import *
from scisim import next_id
import re
import traceback
def debug(*exps):
for exp in exps:
print("---------------------")
print(exp)
print("---------------------")
exit()
def parse_sim(sim_template):
sim_template = clean_comments(sim_template)
page_names = find_keyword_value("page_name", sim_template)
page_names = map(lambda x:x.strip(), page_names)
# errors = check_for_errors(sim_template)
# if errors:
# debug(errors)
# return errors
pages = get_all_pages(sim_template)
page_base = (db.engine.execute("select count() from simulations").fetchone()[0]) * 1000
simulation_name = find_keyword_value("simulation_name", sim_template)
password = find_keyword_value("simulation_password", sim_template)
description = find_keyword_value("simulation_description", sim_template)
preview_picture = find_keyword_value("simulation_preview_picture", sim_template)
sim = Simulation(title=simulation_name, desc=description, password=password, preview_image_filename=preview_picture, first_page_id=page_base)
db.session.add(sim)
db.session.commit()
print("Simulation added.")
for page in pages:
process_page(page, sim, page_base, page_names)
page_base += 1
return None
def get_all_pages(sim):
all_lines = sim.splitlines()
pages = []
for i, line in enumerate(all_lines):
if re.match(r'.*page\s*=\s*\[', line): # had to get real specific here.
pages.append(page_loop(i, all_lines))
return pages
def page_loop(start_line, all_lines):
page = all_lines[start_line] + "\n"
for i,line in enumerate(all_lines[(start_line+1):]):
if "page" in line and "[" in line:
return page
else:
page += line + "\n"
return page
def process_page(page_text, sim, page_id, page_names):
page = None
order = 0
skip = 0
all_lines = page_text.splitlines()
for i, line in enumerate(all_lines):
if skip is not 0:
skip = skip - 1
continue
try:
keyword, content = split_key_value(line)
except Exception, e:
# this line doesn't have content we want, so go to the next one
continue
if keyword == "page_name":
print("Adding page")
page = Page(sim=sim, title=strip_braces(content), id=page_id)
db.session.add(page)
db.session.commit()
elif keyword == "heading_big":
print("Found a big heading")
add_section(i, all_lines, order, content, page, "big_heading")
order += 1
elif keyword == "heading_medium":
print("found medium heading")
add_section(i, all_lines, order, content, page, "medium_heading")
order += 1
elif keyword == "heading_small":
print("found small heading")
add_section(i, all_lines, order, content, page, "small_heading")
order += 1
elif keyword == "text":
print("found text")
add_section(i, all_lines, order, content, page, "regular_heading")
order += 1
elif keyword == "media":
print("Found media")
add_section(i, all_lines, order, content, page, "media")
elif keyword == "minimum_choices" or keyword == "choice_minimum" or keyword == "choice_limit":
print("found choices")
add_page_modifier(page, keyword, content)
elif keyword == "choice_limit_page" or keyword == "minimum_choices_reached_page":
print("adding choice")
add_page_modifier(page, keyword, content)
elif keyword == "minimum_choices_reached_page" or keyword == "minimum_choices_reached":
print("Fond min choice page")
page_base = int(str(page.id)[0]) * 1000
page_id = page_base + page_names.index(strip_braces(content).strip())
add_page_modifier(page, keyword, page_id)
elif keyword == "random_choices":
print("Found random choice page")
add_page_modifier(page, keyword, content)
elif keyword == "choice":
print("found choice")
lines = select_until(i, all_lines, "]").splitlines()
parse_choice(lines, page, page_names)
skip = len(lines)
elif keyword == "add_to_notebook":
lines = select_until(i, all_lines, "]")
text = find_keyword_value("text", lines)
tag = find_keyword_value("tag", lines)
add_page_action(page, keyword, text)
skip = len(lines.splitlines())
elif keyword == "pop_up_window" or keyword == "popup_window":
add_page_modifier(page, keyword, content)
elif keyword == "link":
lines = select_until(i, all_lines, ']')
parse_link(lines, page, order)
order += 1
skip = len(lines.splitlines())
elif keyword == "question":
lines = select_until(i, all_lines, ']')
skip = len(lines.splitlines())
parse_question(lines, page)
elif keyword == "can_add_question_groups":
add_page_modifier(page, keyword, strip_braces(content))
elif keyword == "goes_to_page":
content = strip_braces(content).strip()
try:
dest_id = page_names.index(content) + int(str(page.id)[0]) * 1000
except ValueError, e:
continue # to guard for ??? errors
add_page_modifier(page, keyword, dest_id)
elif keyword == "show_patient_choices":
add_page_action(page, keyword, strip_braces(content))
elif keyword == "show_hypotheses":
add_page_action(page, keyword, strip_braces(content))
def parse_choice(lines, page, page_names):
type = None
text = None
page_base = int(str(page.id)[0]) * 1000
try:
destination = page_base + page_names.index(find_keyword_value("goes_to_page", lines))
except Exception, e:
return # TODO: this fails sometimes because we need to make a solution on dynamic pages (normal_heart, etcself.)
for i, line in enumerate(lines):
if "prompt" in line or "textbox" in line:
type = "prompt"
text = get_text(i, line, lines)
elif "binary" in line:
type = "binary"
text = get_text(i, line, lines)
print("Adding a choice to the database")
db.session.add(Choice(type=type, text=text, destination=destination, page_id = page.id))
db.session.commit()
def parse_link(lines, page, order):
# get content from lines
text = find_keyword_value("text", lines)
link = find_keyword_value("url", lines)
content = "<a target='_blank' href='"+link+"'>"+text+" </a>"
db.session.add(Section(show=True, order=order, content=content, page_id=page.id))
db.session.commit()
def parse_question(lines, page):
text = find_keyword_value("text", lines)
tag = find_keyword_value("tag", lines)
db.session.add(Choice(type="question", text=text, page_id = page.id, tag=tag))
db.session.commit()
def add_section(line_number, all_lines, order, content, page, content_type=None):
print("Adding section")
content = get_text(line_number, content, all_lines)
content = content
if content_type == "small_heading":
tags = "<h3>content</h3>"
elif content_type == "big_heading":
tags = "<h1>content</h1>"
elif content_type == "medium_heading":
tags = "<h2>content</h2>"
elif content_type == "regular_heading":
tags = "<p>content</p>"
elif content_type == "media":
if content[-3:] == "jpg":
tags = "<img src='img/content'/>"
else:
tags = "audio:content";
if content_type: # we do this check to make sure that there's no media here. If there's media, then size won't be passed in
content = tags.replace("content", content)
try:
db.session.add(Section(show=True, order=order, content=strip_braces(content), page_id = page.id))
except Exception, e:
debug(all_lines[line_number:line_number+10], e)
db.session.commit()
def add_page_modifier(page, name, value):
print("adding a page modifier")
db.session.add(Page_Modifier(name=name, value=value, page_id=page.id))
db.session.commit()
def add_page_action(page, name, value):
print("adding a page action")
if type(value) is not int and "}" in value and "{" in value:
value = strip_braces(value)
db.session.add(Page_Action(name=name, value=value, page_id=page.id))
db.session.commit()
def check_for_errors(sim):
sim = clean_comments(sim)
errors = {}
essential_keyword_errors = check_for_essential_keywords(sim)
# check to make sure that all keywords have closing tags
tag_errors = check_all_tags_close(sim)
# check to make sure all pages that you go to exist
existant_errors = check_all_pages_exist(sim)
# make sure all pages have either popup_menu, choices, or goes_to_page
continuity_errors = check_pages_have_continuity(get_all_pages(sim))
if tag_errors:
errors['Missing closing tags the middle line:'] = tag_errors
if existant_errors:
errors['These pages do not exist:'] = existant_errors
if continuity_errors:
errors["These pages have continuity errors:"] = continuity_errors
if essential_keyword_errors:
errors['Missing essential keywords:'] = essential_keyword_errors
if len(errors) > 0:
return errors
return None
def check_for_essential_keywords(sim):
keywords = ['simulation_name', "simulation_password", 'simulation_description']
errors = []
for keyword in keywords:
match = find_keyword_value(keyword, sim)
if match == None:
errors.append("Missing keyword: " + keyword)
if len(errors) == 0:
return None
else:
return errors
def check_all_tags_close(sim):
error_lines = []
lines = sim.splitlines();
for i,line in enumerate(lines):
if "=" in line and "{" not in line and "[" not in line and "}" not in line:
error_lines.append("Missing opening tag on middle line: " + lines[i - 1] + "\n" + line + "\n" + lines[i + 1])
# first we're going to check if the number of opening and closing tags are the same.
if sim.count("{") != sim.count("}") or sim.count("[") != sim.count("]"):
for i,line in enumerate(lines):
# if not, we're going to check all the assignments to see if there's an opening tag
if "=" in line:
if "{" not in line and "[" not in line and "}" not in line:
error_lines.append('Missing opening symbol on middle line: ' + (lines[i - 1] + "\n" + line + "\n" + lines[i + 1]))
# now we check to see if there is a closing tag
if "{" in line and "}" not in line:
selection_till_closing_tag = select_until(i, lines, "}")
if selection_till_closing_tag.count("{") > 0:
error_lines.append('Missing closing tag ( } ) on middle line: ' + (lines[i - 1] + "\n" + line + "\n" + lines[i + 1]))
if "[" in line and "page" in line:
selection = select_until(i, lines, "page")
number_of_choices = selection.count("choice")
number_of_closing_tags = selection.count("]")
if number_of_choices == number_of_closing_tags:
error_lines.append("Missing closing tag ( ] ) on middle line: " + (lines[i - 1] + "\n" + line + "\n" + lines[i + 1]))
if len(error_lines) > 0: return error_lines
return None
def check_all_pages_exist(sim):
expected_pages = find_keyword_value("goes_to_page", sim)
actual_pages = find_keyword_value('page_name', sim)
not_found_pages = []
for i in expected_pages:
if i not in actual_pages:
not_found_pages.append(i)
if len(not_found_pages) > 0: return not_found_pages
return None
def check_pages_have_continuity(pages):
non_continuous_pages = []
continuous_indicators = ["popup_window", "pop_up_window", "choice", "goes_to_page"]
for page in pages:
found = None
mismatched = []
for indicator in continuous_indicators:
if page.count(indicator) == 0:
mismatched.append(indicator)
if len(mismatched) == len(continuous_indicators):
non_continuous_pages.append(page)
if len(non_continuous_pages) > 0:
page_names = []
for page in non_continuous_pages:
page_names.append(find_keyword_value("page_name", page))
return page_names
return None
def get_all_media(all_lines):
medias = []
for media in re.findall(r".*media.*=.*",all_lines):
medias.append(strip_braces(re.findall("{.*}", media)[0]))
return medias
def split_key_value(line):
split = line.split("=")
if len(split) == 1:
return None
else:
return split[0].strip(), split[1].lstrip() # key, value
def get_text(line_number, line, lines):
if lines[line_number].count("}") != 1:
return strip_braces(select_until(line_number, lines, "}"))
else:
return strip_braces(re.findall("{.+}", lines[line_number])[0])
def find_keyword_value(keyword, sim):
results = []
if not isinstance(sim, list):
sim = sim.splitlines()
for i, line in enumerate(sim):
if keyword in line and "=" in line:
if "}" not in line and "[" not in line:
text = select_until(i, sim, "}")
else:
text = strip_braces(re.findall("{.*}", line)[0].strip())
results.append(text)
if len(results) == 1:
return results[0]
if len(results) > 1:
return results
return None
def select_until(line_number, lines, item, count = 1):
full = ""
counter = 0
for i, line in enumerate(lines[line_number+1:]):
if item not in line:
full += line + "\n"
else:
full += line + "\n"
counter += 1
if counter == count: break
continue
return full
def strip_braces(content):
return content.replace("{", "").replace("}","")
def clean_comments(sim):
lines = sim.splitlines()
comment_lines = []
for i,line in enumerate(lines):
if "#" in line:
if "}" in line:
if line.index("}") < line.index("#"):
sim = sim.replace(line, line[0:line.index("#") - 1])
else:
sim = sim.replace(line, "")
return sim
if __name__ == '__main__':
the_file = argv[1]
if not the_file:
print("Please pass in a file path.")
exit()
with codecs.open(the_file, "r", 'utf-8') as f:
sim = f.read()
# errors = check_for_errors(sim)
# if errors:
# for key in errors:
# print(key + ":")
# if isinstance(errors[key], list):
# for value in errors[key]:
# print(value)
# else:
# print(errors[key])
# else:
parse_sim(sim)