-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
727 lines (577 loc) · 25.3 KB
/
server.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
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
import numpy as np
import random
from flask import Flask
from flask import render_template
from flask import Response, request, jsonify, redirect, url_for
app = Flask(__name__)
learnMaterial = {
"1": {
"id" : "1",
"checkpoint": 0,
"title" : "What is CPR?",
"explanatoryText" : ["Cardiopulmonary resuscitation (CPR) is a multi-step procedure performed on a patient whose heart stops beating.", "According to the American Heart Association, immediate CPR can triple chances of survival after cardiac arrest."],
"template": "step1.html",
"images": ["/static/cpr-header.png"],
"imageSizes": ["300px"],
"nextid" : "/learn/2",
"backid" : "/",
},
"2": {
"id": "2",
"checkpoint": 0,
"title" : "Should you perform CPR?",
"explanatoryText":[""],
"template": "step2.html",
"images": ["/static/setting1.png", "/static/setting2.png"],
"imageSizes": ["500px", "300px"],
"nextid" : "/learn/3",
"backid" : "/learn/1",
},
"3": {
"id" : "3",
"checkpoint": 1,
"title" : "Preparatory steps",
"explanatoryText":["Step 1: Try to find an AED (automated external defibrillator).", "Step 2: Call 911.", "Step 3: Use an AED if accessible.", "Step 4: Begin manual CPR."],
"template":"step3.html",
"images": ["/static/prep1.png", "/static/perp2.png"],
"imageSizes": ["300px", "200px"],
"nextid" : "/learn/4",
"backid" : "/learn/2",
"checkpointlink" : "/prep"
},
"4": {
"id": "4",
"checkpoint": 1,
"title": "Chest compressions",
"explanatoryText" : ["Center your hands on the chest.", "Allow the chest to return to a normal position after each compression.", "Complete one set, then continue on to perform rescue breaths.", "---", "TIP: Rhythm deaf? Just use the beat of Stayin' Alive by the Bee Gees."],
"template":"step4.html",
"images" : ["/static/compressionguide.png", "/static/compressions.gif"],
"imageSizes": ["150px", "150px"],
"nextid" : "/learn/5",
"backid" : "/learn/3",
"checkpointlink" : "/chest"
},
"5": {
"id": "5",
"checkpoint": 1,
"title": "Breaths",
"explanatoryText": ["Step 1: Tilt their head back.", "Step 2: Lift their chin.", "Step 3: Administer 2 rescue breaths.", "The breaths should be approx 1 second in length, and the chest should rise.", "---", "After administering rescue breaths, continue alternating between a set of compressions and two rescue breaths until help arrives."],
"template" : "step5.html",
"images": ["/static/breath1.gif", "/static/breath2.gif", "/static/breath3.gif"],
"imageSizes": ["200px", "200px", "200px"],
"nextid" : "/quiz",
"backid" : "/learn/4",
"checkpointlink" : "/breaths"
}
}
checkpoints = {
"prep": {
"id": 0,
"title": "Preparatory steps",
"text": "Order the following items by precedence (drag and drop):",
"learnid": 3,
"next": "/learn/4",
"back": "/learn/3"
},
"chest": {
"id": 1,
"title": "Chest compressions",
"text": "Click the audio button, then click the start button to practice chest compressions to the beat of \"Stayin' Alive.\"",
"learnid": 4,
"next": "/learn/5",
"back": "/learn/4"
},
"breaths": {
"id": 2,
"title": "Breaths",
"text": "Click the dots in the right order to perform a rescue breath.",
"learnid": 5,
"next": "/quiz",
"back": "/learn/5"
}
}
quizQuestions = {
"1": {
"id": "1",
"questionText": "You’re in a restaurant and see someone fall to the ground suddenly. No one else seems to notice, so you run over and tap them on the shoulder, asking if they’re OK. They don’t respond, and you can see that they’re not breathing. Someone tells you they’re calling 911. What should you do?",
"textEntry": False,
"mc": True,
"categories": ["Administer two breaths", "Try to find an AED", "Begin chest compressions", "Wait for paramedics"],
"img": "",
"topic": "3",
"correctAnswer": "Try to find an AED",
"correctText": "You got it! The first thing you want to do is try to find an AED.",
"incorrectText1": "Try again!",
"incorrectText2": "Incorrect.",
"halfText": "Nice try! You figured it out!"
},
"2": {
"id": "2",
"questionText": "There’s no AED available. You send someone to find one, but you decide to start chest compressions in the meantime. What is the correct number of chest compressions per set?",
"textEntry": True,
"mc": False,
"categories": [],
"img": "",
"topic": "4",
"correctAnswer": "30",
"correctText": "Yep! There are 30 chest compressions in each set.",
"incorrectText1": "Try again!",
"incorrectText2": "Incorrect.",
"halfText": "Nice try! You figured it out!"
},
"3": {
"id": "3",
"questionText": "There’s no AED available. You send someone to find one, but you decide to start chest compressions in the meantime. Click the start button, then tap the chest at the proper rate of chest compressions.",
"textEntry": False,
"mc": False,
"categories": [],
"img": "https://cdn2.iconfinder.com/data/icons/anatomy-malibu-vol-1/128/Chest-512.png",
"topic": "4",
"correctAnswer": 30,
"correctText": "Way to go! You kept the perfect rate throughout the set.",
"incorrectText": "Incorrect.",
"halfText": "Nice try! Just a little off the perfect rate!"
},
"4": {
"id": "4",
"questionText": "You’ve just administered chest compressions. You now move on to give the person rescue breaths. What is the appropriate duration of each rescue breath?",
"textEntry": False,
"mc": True,
"categories": ["1 second", "2 seconds", "4 seconds", "6 seconds"],
"img": "",
"topic": "5",
"correctAnswer": "1 second",
"correctText": "Correct! Each rescue breath should last for approximately 1 second.",
"incorrectText1": "Try again!",
"incorrectText2": "Incorrect.",
"halfText": "Nice try! You figured it out!"
}
}
currentID = 0
userData = {}
topicConversionDic = {"5": "Breaths", "4": "Chest compressions", "3": "Preparatory steps"}
# ROUTES
@app.route('/')
def homepage():
return render_template('home.html')
@app.route('/tutorial')
def tutorial():
return render_template('tutorial.html')
@app.route('/learn/<id>')
def learn(id = None):
content = learnMaterial[id]
if content == None:
return render_template('notfound.html')
user = userData[str(currentID)]
return render_template('learn.html', content=content, user=user)
@app.route('/checkpoint/<topic>')
def checkpt(topic = None):
user = userData[str(currentID)]
user['checkpoint'][checkpoints[topic]['id']] = 1
content = checkpoints[topic]
if content == None:
return render_template('notfound.html')
return render_template('checkpoint.html', content=content, user=user)
@app.route('/quiz')
def quizHome():
return render_template('quiz.html')
@app.route('/quiz/<questionID>')
def quizQuestion(questionID = None):
global quizQuestions
global currentID
curUser = userData[str(currentID)]
curQuizAttempt = curUser["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
if (int(questionID) == 4) and (len(curUser[quizName]["history"]) == 2):
numGood = curUser[quizName]["q3"]["numGood"]
if numGood >= 25:
userAnswerCorrect = "Yes"
answerText = quizQuestions["3"]["correctText"]
userData[str(currentID)][quizName]["score"] += 2
userData[str(currentID)][quizName]["history"].append("greenBackground")
elif numGood >= 19:
userAnswerCorrect = "No"
answerText = quizQuestions["3"]["halfText"]
userData[str(currentID)][quizName]["score"] += 1
userData[str(currentID)][quizName]["areasImprove"].append("4")
userData[str(currentID)][quizName]["areasImprove"] = list(set(userData[str(currentID)][quizName]["areasImprove"]))
userData[str(currentID)][quizName]["history"].append("yellowBackground")
else:
userAnswerCorrect = "No"
answerText = quizQuestions["3"]["incorrectText"]
userData[str(currentID)][quizName]["areasImprove"].append("4")
userData[str(currentID)][quizName]["areasImprove"] = list(set(userData[str(currentID)][quizName]["areasImprove"]))
userData[str(currentID)][quizName]["history"].append("redBackground")
curUser["takingQuiz"] = questionID
question = quizQuestions[questionID]
key = "q" + questionID
if key in curUser[quizName]:
if question["textEntry"] or question["mc"]:
curAttempt = curUser[quizName]["q" + questionID + "Attempt"]
firstTryResult = curUser[quizName]["q" + questionID + "FirstTryResult"]
if curAttempt > 2 or firstTryResult:
if int(questionID) != 4:
nextID = int(questionID) + 1
return redirect(url_for("quizQuestion",questionID=nextID))
else:
return redirect(url_for("quizEnd"))
else:
if int(questionID) != 4:
nextID = int(questionID) + 1
return redirect(url_for("quizQuestion",questionID=nextID))
else:
return redirect(url_for("quizEnd"))
if question["mc"]:
return render_template('mcQuestion.html', question = question)
elif question["textEntry"]:
return render_template('textQuestion.html', question = question)
else:
return render_template('imgQuestion.html', question = question)
@app.route('/quizend')
def quizEnd():
userData[str(currentID)]["takingQuiz"] = -1
return render_template('quizend.html')
# AJAX FUNCTIONS
@app.route('/add_user', methods=['POST'])
def add_user():
global currentID
global userData
currentID += 1
json_data = request.get_json()
newName = json_data["name"].strip()
newUser = {
"id": currentID,
"name": newName,
"takingQuiz": -1,
"quizAttempt": 1,
"bestScore": -1,
"checkpoint": [0, 0, 0],
}
userData[str(currentID)] = newUser
return jsonify(userID = currentID)
@app.route('/add_quiz', methods=['PUT'])
def add_quiz():
curUser = userData[str(currentID)]
curUser["takingQuiz"] = 0
curQuizAttempt = curUser["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
newQuizAttempt = {
"score": 0,
"areasImprove": [],
"history": []
}
curUser[quizName] = newQuizAttempt
return jsonify(quizID = curQuizAttempt)
#------------------------------------------------
@app.route('/add_mc', methods=['PUT'])
def add_mc():
global currentID
global userData
curUser = userData[str(currentID)]
curQuizAttempt = curUser["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
json_data = request.get_json()
questionID = json_data["questionID"]
answer = json_data["answer"]
answerID = json_data["answerID"]
topic = json_data["topic"]
curAttempt = curUser[quizName]["q" + questionID + "Attempt"]
curUser[quizName]["q" + questionID] = answer
correctAnswer = quizQuestions[questionID]["correctAnswer"]
if curAttempt == 1:
if correctAnswer == answer:
userAnswerCorrect = "Yes"
answerText = quizQuestions[questionID]["correctText"]
curUser[quizName]["score"] += 2
curUser[quizName]["history"].append("greenBackground")
questionDone = "Yes"
secondTry = "No"
curUser[quizName]["q" + questionID + "FirstTryResult"] = True
else:
userAnswerCorrect = "No"
answerText = quizQuestions[questionID]["incorrectText1"]
userData[str(currentID)][quizName]["q" + questionID + "Attempt"] += 1
questionDone = "No"
secondTry = "No"
curUser[quizName]["q" + questionID + "FirstTryResult"] = False
curUser[quizName]["q" + questionID + "FirstGuess"] = answerID
else:
questionDone = "Yes"
curUser[quizName]["areasImprove"].append(topic)
curUser[quizName]["areasImprove"] = list(set(userData[str(currentID)][quizName]["areasImprove"]))
userData[str(currentID)][quizName]["q" + questionID + "Attempt"] += 1
if correctAnswer == answer:
userAnswerCorrect = "Yes"
answerText = quizQuestions[questionID]["halfText"]
curUser[quizName]["score"] += 1
curUser[quizName]["history"].append("yellowBackground")
secondTry = "Yes"
else:
userAnswerCorrect = "No"
answerText = quizQuestions[questionID]["incorrectText2"]
curUser[quizName]["history"].append("redBackground")
secondTry = "No"
return jsonify(userCorrect = userAnswerCorrect, answerText = answerText, answerID = answerID, questionDone = questionDone, secondTry = secondTry)
#----------------------------------------------------------
@app.route('/add_text', methods=['PUT'])
def add_text():
global userData
curUser = userData[str(currentID)]
curQuizAttempt = curUser["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
json_data = request.get_json()
questionID = json_data["questionID"]
answer = json_data["answer"]
topic = json_data["topic"]
curAttempt = curUser[quizName]["q" + questionID + "Attempt"]
curUser[quizName]["q" + questionID] = answer
correctAnswer = quizQuestions[questionID]["correctAnswer"]
if curAttempt == 1:
if correctAnswer == answer:
userAnswerCorrect = "Yes"
answerText = quizQuestions[questionID]["correctText"]
curUser[quizName]["score"] += 2
curUser[quizName]["history"].append("greenBackground")
questionDone = "Yes"
secondTry = "No"
curUser[quizName]["q" + questionID + "FirstTryResult"] = True
else:
userAnswerCorrect = "No"
answerText = quizQuestions[questionID]["incorrectText1"]
userData[str(currentID)][quizName]["q" + questionID + "Attempt"] += 1
questionDone = "No"
secondTry = "No"
curUser[quizName]["q" + questionID + "FirstTryResult"] = False
else:
questionDone = "Yes"
curUser[quizName]["areasImprove"].append(topic)
curUser[quizName]["areasImprove"] = list(set(userData[str(currentID)][quizName]["areasImprove"]))
userData[str(currentID)][quizName]["q" + questionID + "Attempt"] += 1
if correctAnswer == answer:
userAnswerCorrect = "Yes"
answerText = quizQuestions[questionID]["halfText"]
curUser[quizName]["score"] += 1
curUser[quizName]["history"].append("yellowBackground")
secondTry = "Yes"
else:
userAnswerCorrect = "No"
answerText = quizQuestions[questionID]["incorrectText2"]
curUser[quizName]["history"].append("redBackground")
secondTry = "No"
return jsonify(userCorrect = userAnswerCorrect, answerText = answerText, questionDone = questionDone, secondTry = secondTry)
#--------------------------------------------------------------------
@app.route('/get_results', methods=['GET'])
def get_results():
global currentID
global userData
curQuizAttempt = userData[str(currentID)]["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
currentUser = userData[str(currentID)][quizName]
userScore = currentUser["score"]
userAreasToImprove = currentUser["areasImprove"]
areasFull = []
for area in userAreasToImprove:
areasFull.append(topicConversionDic[area])
userData[str(currentID)]["quizAttempt"] += 1
curBestScore = userData[str(currentID)]["bestScore"]
if userScore > curBestScore:
userData[str(currentID)]["bestScore"] = userScore
if userScore == 8:
perfectScore = "Yes"
else:
perfectScore = "No"
return jsonify(quizScore = userScore, areas = userAreasToImprove, areaNames = areasFull, perfect = perfectScore)
#----------------------------------------------------------------------------
@app.route('/top_scorers', methods=['GET'])
def top_scorers():
global userData
scores = []
for elem in userData:
curUser = userData[elem]
# This happens when a user is added but never starts a quiz, then uses another name
if curUser["bestScore"] != -1:
scores.append((curUser["name"], curUser["bestScore"]))
withNames = list(filter(lambda x: len(x[0]) > 0, scores))
withNames.sort(key = lambda x: x[1], reverse = True)
if len(withNames) <= 5:
result = withNames
else:
result = withNames[:5]
names = [user[0] for user in result]
scores = [user[1] for user in result]
print(userData)
return jsonify(names = names, scores = scores)
#-----------------------------------------------------------------------------
@app.route('/get_circles', methods=['GET'])
def get_circles():
global userData
curQuizAttempt = userData[str(currentID)]["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
circleHistory = userData[str(currentID)][quizName]["history"]
return jsonify(history = circleHistory)
#----------------------------------------------------------------------------
@app.route('/start_chest', methods=['PUT'])
def start_chest():
global currentID
global userData
curQuizAttempt = userData[str(currentID)]["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
json_data = request.get_json()
questionID = json_data["questionID"]
userData[str(currentID)][quizName]["q" + questionID] = {
"times": [],
"curReps": 0,
"numGood": 0
}
return jsonify(repNum = userData[str(currentID)][quizName]["q" + questionID]["curReps"])
#-------------------------------------------------------------------------------
@app.route('/start_reps', methods=['PUT'])
def start_reps():
global currentID
global userData
curQuizAttempt = userData[str(currentID)]["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
json_data = request.get_json()
questionID = json_data["questionID"]
startTime = json_data["startTime"]
userData[str(currentID)][quizName]["q" + questionID]["times"].append(startTime)
return jsonify(repNum = userData[str(currentID)][quizName]["q" + questionID]["curReps"])
#-------------------------------------------------------------------------------
@app.route('/click_chest', methods=['PUT'])
def click_chest():
global currentID
global userData
curQuizAttempt = userData[str(currentID)]["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
json_data = request.get_json()
questionID = json_data["questionID"]
clickTime = json_data["clickTime"]
lastClick = userData[str(currentID)][quizName]["q" + questionID]["times"][-1]
userData[str(currentID)][quizName]["q" + questionID]["times"].append(clickTime)
diffClickTime = clickTime - lastClick
result = ""
# Ideal rate is 600ms between compressions
if diffClickTime >= 500 and diffClickTime <= 700:
result = "Good"
userData[str(currentID)][quizName]["q" + questionID]["numGood"] += 1
elif diffClickTime < 500:
result = "Slower"
else:
result = "Faster"
userData[str(currentID)][quizName]["q" + questionID]["curReps"] += 1
repNum = userData[str(currentID)][quizName]["q" + questionID]["curReps"]
if repNum == 30:
done = "Yes"
else:
done = "No"
return jsonify(repNum = repNum, clickResult = result, finished = done)
#---------------------------------------------------------------------------
@app.route('/verify_chest', methods=['PUT'])
def verify_chest():
global currentID
global userData
curQuizAttempt = userData[str(currentID)]["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
json_data = request.get_json()
questionID = json_data["questionID"]
topic = json_data["topic"]
numGood = userData[str(currentID)][quizName]["q" + questionID]["numGood"]
if numGood >= 25:
userAnswerCorrect = "Yes"
answerText = quizQuestions[questionID]["correctText"]
userData[str(currentID)][quizName]["score"] += 2
userData[str(currentID)][quizName]["history"].append("greenBackground")
elif numGood >= 19:
userAnswerCorrect = "Half"
answerText = quizQuestions[questionID]["halfText"]
userData[str(currentID)][quizName]["score"] += 1
userData[str(currentID)][quizName]["areasImprove"].append(topic)
userData[str(currentID)][quizName]["areasImprove"] = list(set(userData[str(currentID)][quizName]["areasImprove"]))
userData[str(currentID)][quizName]["history"].append("yellowBackground")
else:
userAnswerCorrect = "No"
answerText = quizQuestions[questionID]["incorrectText"]
userData[str(currentID)][quizName]["areasImprove"].append(topic)
userData[str(currentID)][quizName]["areasImprove"] = list(set(userData[str(currentID)][quizName]["areasImprove"]))
userData[str(currentID)][quizName]["history"].append("redBackground")
return jsonify(userCorrect = userAnswerCorrect, answerText = answerText, numCorrect = numGood)
#--------------------------------------------------------------------------------------
@app.route('/start_question', methods=['PUT'])
def start_question():
global userData
curQuizAttempt = userData[str(currentID)]["quizAttempt"]
quizName = "quiz" + str(curQuizAttempt)
json_data = request.get_json()
questionID = json_data["questionID"]
question = quizQuestions[questionID]
attemptName = "q" + questionID + "Attempt"
firstGuess = "q" + questionID + "FirstGuess"
if attemptName not in userData[str(currentID)][quizName]:
userData[str(currentID)][quizName][attemptName] = 1
if question["mc"]:
if firstGuess not in userData[str(currentID)][quizName]:
userData[str(currentID)][quizName][firstGuess] = -1
userData[str(currentID)][quizName]["q" + questionID + "FirstTryResult"] = False
return jsonify(attemptNumber = userData[str(currentID)][quizName][attemptName], firstGuess = userData[str(currentID)][quizName][firstGuess])
else:
return jsonify(attemptNumber = userData[str(currentID)][quizName][attemptName])
#----------------------------------------------------------------------------
#SEARCH FUNCTIONALITY
@app.route('/search/<searched>', methods=['GET', 'POST'])
def search(searched=None):
titles = []
content = []
num = 0
str = searched.lower()
length = len(str)
for item in learnMaterial.values():
if str in (item["title"]).lower():
num = num + 1
else:
for text in item["explanatoryText"]:
if str in text.lower():
num = num + 1
for item in learnMaterial.values():
start = 0
idx = 0
result = ""
text = item["title"]
while (idx <= len(text)):
idx = (text.lower()).find(searched.lower(), idx)
if (result == ""):
if (idx == -1):
break
result += "<a href='/learn/" + item["id"] + "'>"
if (idx != -1):
result += text[start:idx] + "<mark>" + text[idx:(idx+length)] + "</mark>"
idx += length
start = idx
else:
result += text[start:len(text)] + "</a><hr>"
titles.append(result)
break
result = ""
for word in item["explanatoryText"]:
start = 0
idx = 0
text = word
while (idx <= len(text)):
idx = (text.lower()).find(searched.lower(), idx)
if (result == ""):
if (idx == -1):
break
result += "<a href='/learn/" + item["id"] + "'><i>" + item["title"] + ",</i><br>..."
if (idx != -1):
result += text[start:idx] + "<mark>" + text[idx:(idx+length)] + "</mark>"
idx += length
start = idx
else:
result += text[start:len(text)] + " "
break
if (result != ""):
result = result[0:len(result)-2]
result += "...</a><hr>"
content.append(result)
return render_template('search.html', num=num, learnMaterial=learnMaterial, titles=titles, content=content, searched=searched)
if __name__ == '__main__':
app.run(debug = True)