-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathapp.py
1404 lines (1332 loc) · 54.1 KB
/
app.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
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
from flask import Flask, render_template, request, send_file, jsonify, redirect, url_for
from pymongo import MongoClient
import requests
import joblib
import smtplib
import pandas as pd
from configparser import ConfigParser
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from docx import Document
from datetime import datetime, timedelta, timezone
import os
import random
config = ConfigParser()
config.read("config.ini")
app = Flask(__name__)
app.secret_key = config["SECRETS"]["APP_SECRET_KEY"]
translate_api_url = config["URL"]["TRANSLATE_URL"]
chatbot_api_url = config["URL"]["CHATBOT_URL"]
feel_api_url = config["URL"]["FEEL_URL"]
model = joblib.load("static/models/disease_prediction_model.joblib")
le_results = joblib.load("static/models/label_encoder_results.joblib")
client = MongoClient(config["DATABASE"]["STRING"])
db = client[config["DATABASE"]["DATABASE_NAME"]]
collection_pl = db[config["DATABASE"]["COLLECTION_PATIENT_LOGIN"]]
collection_dl = db[config["DATABASE"]["COLLECTION_DOCTOR_LOGIN"]]
collection_data = db[config["DATABASE"]["COLLECTION_DATA"]]
collection_as = db[config["DATABASE"]["COLLECTION_APPOINTMENT_STATUS"]]
collection_a = db[config["DATABASE"]["COLLECTION_APPOINTMENT"]]
collection_pi = db[config["DATABASE"]["COLLECTION_PATIENT_INFORMATION"]]
collection_di = db[config["DATABASE"]["COLLECTION_DOCTOR_INFORMATION"]]
collection_c = db[config["DATABASE"]["COLLECTION_CONSULTATION"]]
collection_o = db[config["DATABASE"]["OTP"]]
collection_n = db[config["DATABASE"]["NUMBERS"]]
main_patientusername = ""
main_doctorusername = ""
main_doctorname = ""
temp_username = ""
gemail = ""
new_username = ""
new_email = ""
docnew_username = ""
docnew_email = ""
temp_email = ""
ALLOWED_ROUTES = ["/index"]
def allowed_route(route):
def decorator(func):
def wrapper(*args, **kwargs):
if route in ALLOWED_ROUTES:
return func(*args, **kwargs)
else:
return redirect(url_for("error_404"))
wrapper.__name__ = func.__name__
return wrapper
return decorator
@app.route("/error")
def error_404():
return render_template("error.html"), 404
@app.route("/errorfetch")
def error_500():
return render_template("errorfetch.html"), 500
@app.route("/")
def login():
try:
return render_template("index.html")
except:
return render_template("error.html"), 404
@app.route("/index")
def index():
try:
return render_template("index.html")
except:
return render_template("error.html"), 404
@app.route("/dashboard")
def dashboard():
try:
return render_template("dashboard.html")
except:
return render_template("error.html"), 404
@app.route("/about")
def about():
try:
return render_template("about.html")
except:
return render_template("error.html"), 404
@app.route("/diseasePrediction")
def diseasePrediction():
try:
return render_template("2options.html")
except:
return render_template("error.html"), 404
@app.route("/prediction1")
def prediction1():
try:
return render_template("prediction.html")
except:
return render_template("error.html"), 404
@app.route("/mcq")
def mcq():
try:
return render_template("mcq.html")
except:
return render_template("error.html"), 404
@app.route("/chatbot")
def chatbot():
try:
return render_template("chatbot.html")
except:
return render_template("error.html"), 404
@app.route("/predic")
def predic():
try:
return render_template("predic.html")
except:
return render_template("error.html"), 404
@app.route("/predict2")
def predict2():
try:
return render_template("prediction.html")
except:
return render_template("error.html"), 404
@app.route("/doctorLogin")
def doctorLogin():
try:
return render_template("doctorLogin.html")
except:
return render_template("error.html"), 404
@app.route("/doctordashboard")
def doctordashboard():
try:
return render_template("doctordashboard.html")
except:
return render_template("error.html"), 404
@app.route("/appointments")
def appointments():
try:
return render_template("appointment.html")
except:
return render_template("error.html"), 404
@app.route("/patientReport")
def patientReport():
try:
return render_template("patientReport.html")
except:
return render_template("error.html"), 404
@app.route("/docappointment")
def docappointment():
try:
return render_template("docappointment.html")
except:
return render_template("error.html"), 404
@app.route("/forgotpassword")
def forgotpassword():
try:
return render_template("forgotpassword.html")
except:
return render_template("error.html"), 404
@app.route("/otp")
def otp():
try:
return render_template("otp.html")
except:
return render_template("error.html"), 404
@app.route("/createpassword")
def createpassword():
try:
return render_template("createpassword.html")
except:
return render_template("error.html"), 404
@app.route("/docforgotpassword")
def docforgotpassword():
try:
return render_template("docforgotpassword.html")
except:
return render_template("error.html"), 404
@app.route("/docotp")
def docotp():
try:
return render_template("docotp.html")
except:
return render_template("error.html"), 404
@app.route("/doccreatepassword")
def doccreatepassword():
try:
return render_template("createpassword.html")
except:
return render_template("error.html"), 404
@app.route("/newusername")
def newusername():
try:
return render_template("newusername.html")
except:
return render_template("error.html"), 404
@app.route("/newotp")
def newotp():
try:
return render_template("newotp.html")
except:
return render_template("error.html"), 404
@app.route("/newemail")
def newemail():
try:
return render_template("newemail.html")
except:
return render_template("error.html"), 404
@app.route("/createnewpassword")
def createnewpassword():
try:
return render_template("createnewpassword.html")
except:
return render_template("error.html"), 404
@app.route("/docnewusername")
def docnewusername():
try:
return render_template("docnewusername.html")
except:
return render_template("error.html"), 404
@app.route("/docnewemail")
def docnewemail():
try:
return render_template("docnewemail.html")
except:
return render_template("error.html"), 404
@app.route("/docnewotp")
def docnewotp():
try:
return render_template("docnewotp.html")
except:
return render_template("error.html"), 404
@app.route("/doccreatenewpassword")
def doccreatenewpassword():
try:
return render_template("doccreatenewpassword.html")
except:
return render_template("error.html"), 404
@app.route("/admin")
def admin():
try:
return render_template("admin.html")
except:
return render_template("error.html"), 404
@app.route("/emailsent", methods=["POST"])
def emailsent():
error = "ESEX1"
try:
if request.method == "POST":
name = request.form["name"]
email = request.form["email"]
message = request.form["message"]
sender_email = config["EMAIL"]["SENDER_EMAIL"]
sender_password = config["EMAIL"]["SENDER_PASSWORD"]
to_email = config["EMAIL"]["RECEIVER_EMAIL"]
subject = "Response form Vaidhya"
body = f"Sender Name: {name}\nSender Email: {email}\nMessage: {message}"
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = to_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, to_email, message.as_string())
return render_template("about.html")
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/ask", methods=["POST"])
def ask():
error = "CHTGC1"
try:
questions = request.get_json().get("question")
response = requests.post(
f"{chatbot_api_url}/input_bot", json={"questions": questions}
)
if response.status_code == 200:
answers = response.json().get("answer")
print(answers)
return jsonify({"answers": answers})
else:
return jsonify({"error": "Failed to get answers"})
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/mcqfun1", methods=["GET", "POST"])
def mcqfun1():
error = "MCQXE1"
try:
q1 = request.form["q1"]
q2 = request.form["q2"]
q3 = request.form["q3"]
q4 = request.form["q4"]
q5 = request.form["q5"]
q6 = request.form["q6"]
q7 = request.form["q7"]
q8 = request.form["q8"]
q9 = request.form["q9"]
q10 = request.form["q10"]
input_data = {
"age": 22,
"Your friend has invited you to a party. Consider how you might respond in the given scenario. Choose the option that best reflects your feelings and tendencies": q1,
"You have an upcoming deadline at work. How do you typically handle this": q2,
"You receive unexpected praise for your achievements. How do you react?": q3,
"You witness a car accident on the street. How does it affect you?": q4,
"You are preparing for a social event with friends. How do you approach it?": q5,
"You find yourself in a crowded and noisy environment. How do you react?": q6,
"You encounter a trigger related to a past traumatic event. How do you cope?": q7,
"You are faced with a decision that requires careful consideration. How do you approach it?": q8,
"You are experiencing a period of heightened creativity and productivity. How does it impact you?": q9,
"You are in a situation where you feel judged by others. How do you react?": q10,
}
answer_mapping = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7}
for mcq, answer in input_data.items():
if mcq != "age":
input_data[mcq] = answer_mapping.get(answer, 0)
input_df = pd.DataFrame([input_data])
predictions = model.predict(input_df.iloc[:, 1:])
predictions_decoded = le_results.inverse_transform(predictions)
symptom = predictions_decoded[0]
existing_student = collection_data.find_one({"_id": main_patientusername})
if existing_student:
collection_data.update_one(
{"_id": main_patientusername}, {"$set": {"symptom-test": symptom}}
)
return render_template("predic.html", symp=symptom)
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/translate", methods=["POST"])
def translate():
error = "TRANGC2"
try:
data = request.get_json()
texts = data.get("texts", [])
target_lang = data.get("target_lang", "en")
response = requests.post(
f"{translate_api_url}/translate",
json={"texts": texts, "target_lang": target_lang},
)
if response.status_code == 200:
translated_texts = response.json().get("translated_texts", [])
return jsonify({"translated_texts": translated_texts})
else:
return jsonify({"error": "Failed to get translation"})
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/loginsuccessfull", methods=["GET", "POST"])
def validate_login():
error = "LOGUS1"
try:
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
print(username, password)
required_one = {"_id": username, "password": password}
data = collection_pl.find_one(required_one)
if data:
global main_patientusername, main_doctorname, main_doctorusername
main_patientusername = username
try:
patient_info = collection_pi.find_one(
{"patient_username": username}
)
patient_id = patient_info["_id"]
consultation = collection_c.find_one({"_id": patient_id})
doctor_id = consultation["doctor_id"]
doctor_info = collection_di.find_one({"_id": doctor_id})
main_doctorname = doctor_info["doctor_name"]
main_doctorusername = doctor_info["doctor_username"]
except:
pass
if not collection_pi.find_one(
{"patient_username": main_patientusername}
):
return render_template("patientinfo.html")
return render_template("dashboard.html")
else:
return render_template(
"index.html", message="Invalid username and password!"
)
return render_template("index.html")
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/userfeeling", methods=["GET", "POST"])
def userfeeling():
error = "USFGC3"
try:
if request.method == "POST":
userfeeling = request.form["feeling"]
try:
response = requests.post(
f"{feel_api_url}/feel_bot", json={"question": userfeeling}
)
if response.status_code == 200:
answer = response.json().get("answer")
symptom = answer
existing_student = collection_data.find_one(
{"_id": main_patientusername}
)
if existing_student:
collection_data.update_one(
{"_id": main_patientusername},
{"$set": {"symptom-feel": symptom}},
)
except:
return render_template("prediction.html", symptom="Error 429!")
return render_template("prediction.html", symptom=symptom)
else:
return render_template("prediction.html", symptom=None)
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/doctorloginsuccessfull", methods=["GET", "POST"])
def validate_doctor_login():
error = "LOGUS2"
try:
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
print(username, password)
required_one = {"_id": username, "password": password}
data = collection_dl.find_one(required_one)
if data:
global main_doctorusername
main_doctorusername = username
if not collection_di.find_one({"doctor_username": main_doctorusername}):
return render_template("doctorinfo.html")
return render_template("doctordashboard.html")
else:
return render_template(
"doctorLogin.html", message="Invalid username and password!"
)
return render_template("doctorLogin.html")
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/fetchpatientdetails", methods=["GET", "POST"])
def fetchpatientdetails():
error = "FPDEX1"
patientid = " "
patientname = " "
patientage = " "
sfeel = " "
stest = " "
message = "Data Not Available"
doc_name = " "
doc_id = " "
try:
if request.method == "POST":
patientid = request.form["patientid"]
key = request.form["key"]
required_one = {"patientid": patientid, "key": key}
data = collection_data.find_one(required_one)
if data:
message = "Data Found!"
patientid = data["patientid"]
patientname = data["patientname"]
patientage = data["age"]
sfeel = data["symptom-feel"]
stest = data["symptom-test"]
doc_name = data["doctor_name"]
doc_id = data["doctor_id"]
return render_template(
"patientReport.html",
message=message,
name=patientname,
pid=patientid,
age=patientage,
sfeel=sfeel,
stest=stest,
doc_name=doc_name,
doc_id=doc_id,
)
else:
return render_template(
"patientReport.html",
message=message,
name=patientname,
pid=patientid,
age=patientage,
sfeel=sfeel,
stest=stest,
doc_name=doc_name,
doc_id=doc_id,
)
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/generatereport", methods=["GET"])
def generatereport():
error = "GENRP1"
try:
name = request.args.get("name")
pid = request.args.get("pid")
age = request.args.get("age")
sfeel = request.args.get("sfeel")
stest = request.args.get("stest")
docid = request.args.get("docid")
docname = request.args.get("docname")
data = {
"name": name,
"pid": pid,
"age": age,
"sfeel": sfeel,
"stest": stest,
"doctor_id": docid,
"doctor_name": docname,
}
now = datetime.now()
current_month = str(now.month)
current_date = str(now.day)
current_year = str(now.year)
data["DD"] = current_date
data["MM"] = current_month
data["YYYY"] = current_year
try:
doc = Document("static/documents/patient_report.docx")
except:
errorone = "DOC404"
return render_template("errorfetch.html", message=errorone), 500
for paragraph in doc.paragraphs:
for key, value in data.items():
if key in paragraph.text:
paragraph.text = paragraph.text.replace(
"{{" + key + "}}", str(value)
)
documentsgen_dir = os.path.join(app.root_path, "static", "documentsgen")
os.makedirs(documentsgen_dir, exist_ok=True)
fname = data["pid"]
temp_docx_path = os.path.join(documentsgen_dir, f"{fname}.docx")
doc.save(temp_docx_path)
return send_file(temp_docx_path, as_attachment=True)
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/appointment")
def appointment():
error = "GAP1AP"
try:
doc = collection_di.find_one({"doctor_username": main_doctorusername})
doc_id = doc['_id']
def get_next_weekdays(start_date, num_days):
weekdays = []
current_date = start_date
while len(weekdays) < num_days:
current_date += timedelta(days=1)
if current_date.weekday() >= 5:
current_date += timedelta(days=(7 - current_date.weekday()))
weekdays.append(current_date)
return weekdays
def get_availability(date):
availability = collection_as.find_one({doc_id + "-" + date})
if availability:
return availability
else:
return None
today = datetime.today()
next_weekdays = get_next_weekdays(today, 5)
dates = [date.strftime("%d-%m-%Y") for date in next_weekdays]
dates_with_availability = []
print(main_doctorname)
for date in dates:
availability = get_availability(date)
if availability:
slots_availability = {
key: value for key, value in availability.items() if key != "_id"
}
dates_with_availability.append((date, slots_availability))
return render_template(
"appointment.html",
dates_with_availability=dates_with_availability,
doctor_name=main_doctorname,
)
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/appointment/submitted", methods=["POST", "GET"])
def submit_appointment():
error = "GAP1SP"
try:
doc = collection_di.find_one({"doctor_username": main_doctorusername})
doc_id = doc['_id']
appointment_data = request.get_json(force=True)
name = appointment_data.get("name")
pid = appointment_data.get("pid")
time_slot = appointment_data.get("timeSlot")
mode = appointment_data.get("mode")
date = appointment_data.get("dates")
query = {"_id": doc_id + "-" + date}
newquery = {"$set": {time_slot: 1}}
collection_as.update_one(query, newquery)
new_appointment = {
"_id": f"{pid}_{date}_{time_slot}",
"name": name,
"patient_username": pid,
"time_slot": time_slot,
"mode": mode,
"date": date,
}
collection_a.insert_one(new_appointment)
sender_email = config["EMAIL"]["SENDER_EMAIL"]
sender_password = config["EMAIL"]["SENDER_PASSWORD"]
try:
patient_info = collection_pi.find_one({"patient_username": pid})
patient_id = patient_info["_id"]
patient_email = patient_info["email"]
consultation = collection_c.find_one({"_id": patient_id})
doctor_id = consultation["doctor_id"]
doctor_info = collection_di.find_one({"_id": doctor_id})
doctor_email = doctor_info["email"]
except:
response_data = {"message": "Something Went Wrong! Try Again"}
return jsonify(response_data)
subject_p = f"Appointment Confirmation: Your Upcoming Visit with Dr. {doctor_info['doctor_name']}"
subject_d = f"Appointment Scheduled: Your Upcoming Visit with Mr. {patient_info['patient_name']}"
body_p = f"Dear {patient_info['patient_name']},\n\nWe hope this email finds you well.\n\nWe are writing to confirm your scheduled appointment with Dr. {doctor_info['doctor_name']} on {date} between {time_slot} IST.\n\nLocation: {doctor_info['location']}\nAddress: {doctor_info['consultation_address']}\nRoom/Office: {doctor_info['room']}\n\nPlease arrive 10-15 minutes before your scheduled appointment time to complete any necessary paperwork.In case of online mode Papers will be sent via Email.\n\nIf you need to reschedule or cancel your appointment, please let us know at least 24 hours in advance so we can accommodate other patients.\n\nWe look forward to seeing you on {date}. If you have any questions or concerns in the meantime, please don't hesitate to contact us.\n\nBest regards,\nVaidhya."
body_d = f"Dear Dr. {doctor_info['doctor_name']}\n\nI hope this message finds you well.\n\nThis email is to confirm the upcoming appointment scheduled for {patient_info['patient_name']}, who is {patient_info['age']} years old, with you on {date} between {time_slot}. The appointment will be held in your given location.\n\nPatient Details:\n\nName: {patient_info['patient_name']}\nAge: {patient_info['age']}\nDate: {date}\nTime: {time_slot}\nMode: {mode}\nEmail: {patient_info['email']}\nPh_Nuber: {patient_info['ph_number']}\n\nPlease ensure that all necessary arrangements are made for the appointment.\n\nThank you for your attention to this matter.\n\nBest regards,\nVaidhya."
message_p = MIMEMultipart()
message_p["From"] = sender_email
message_p["To"] = patient_email
message_p["Subject"] = subject_p
message_p.attach(MIMEText(body_p, "plain"))
message_d = MIMEMultipart()
message_d["From"] = sender_email
message_d["To"] = doctor_email
message_d["Subject"] = subject_d
message_d.attach(MIMEText(body_d, "plain"))
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, patient_email, message_p.as_string())
server.sendmail(sender_email, doctor_email, message_d.as_string())
response_data = {"message": "Appointment submitted successfully!"}
return jsonify(response_data)
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/docappointment/submitted", methods=["POST", "GET"])
def submit_docappointment():
error = "GAP2DAP"
try:
appointment_docdata = request.get_json()
if appointment_docdata:
if (
not appointment_docdata["timeSlots"]
and not appointment_docdata["customTimeSlot"]
):
response_data = {"message": "Select Atleast One Time slot!"}
return jsonify(response_data)
datek = datetime.strptime(appointment_docdata["date"], "%Y-%m-%d")
date = datek.strftime("%d-%m-%Y")
time_slots = []
doc = collection_di.find_one({"doctor_username": main_doctorusername})
doc_id = doc['_id']
result = {doc_id + "-" + date}
for time_slot in appointment_docdata.get("timeSlots", []):
time_slots.append(time_slot)
if appointment_docdata["customTimeSlot"]:
time = (
appointment_docdata["customTimeSlot"]["from"]
+ " - "
+ appointment_docdata["customTimeSlot"]["to"]
+ " IST"
)
time_slots.append(time)
def check_overlap(time1, time2):
start1, end1 = map(
lambda x: int(x.split(":")[0]) * 60
+ int(x.split(":")[1].split()[0]),
time1.split(" - "),
)
start2, end2 = map(
lambda x: int(x.split(":")[0]) * 60
+ int(x.split(":")[1].split()[0]),
time2.split(" - "),
)
if start1 <= start2 <= end1 or start1 <= end2 <= end1:
return True
if start2 <= start1 <= end2 or start2 <= end1 <= end2:
return True
return False
for i in range(len(time_slots)):
for j in range(i + 1, len(time_slots)):
if check_overlap(time_slots[i], time_slots[j]):
response_data = {
"message": "Select the Time Slots Such that they don't overlap with each other"
}
return jsonify(response_data)
for t_s in time_slots:
result[t_s] = 0
if collection_as.find_one({"_id": date}):
collection_as.delete_one({"_id": date})
collection_as.insert_one(result)
response_data = {"message": "Appointments Offerd Successfully!"}
return jsonify(response_data)
else:
response_data = {"message": "Something Went Wrong!"}
return jsonify(response_data)
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/forgotpassword/datafound", methods=["POST", "GET"])
def forgotpassworddatafound():
error = "FPPS1"
try:
username = request.form["login-username"]
if collection_pl.find_one({"_id": username}) or collection_pl.find_one(
{"email": username}
):
pin = int("".join(random.choices("0123456789", k=6)))
global temp_username
if collection_pl.find_one({"_id": username}):
temp_username = username
print(temp_username)
data = collection_pl.find_one({"_id": username})
email = data["email"]
else:
global temp_email
temp_email = username
print(temp_email)
data = collection_pl.find_one({"email": username})
email = data["email"]
temp_username = data["_id"]
sender_email = config["EMAIL"]["SENDER_EMAIL"]
sender_password = config["EMAIL"]["SENDER_PASSWORD"]
to_email = email
subject = "One Time Password"
body = f"Your One Time Password is {pin}.\n\nThe OTP will be valid only for 10 minutes.\n\nRegards,\nVaidhya"
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = to_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, to_email, message.as_string())
collection_o.create_index("createdAt", expireAfterSeconds=600)
to_push = {
"createdAt": datetime.now(timezone.utc),
"_id": email,
"otp": pin,
}
if collection_o.find_one({"_id": email}):
query = {"_id": email}
newquery = {"$set": {"otp": pin}}
collection_o.update_one(query, newquery)
else:
collection_o.insert_one(to_push)
return render_template("otp.html")
else:
return render_template(
"forgotpassword.html", message="Invalid username or email"
)
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/otpverified", methods=["POST", "GET"])
def otpverified():
error = "OTPVF1"
try:
one = request.form["input1"]
two = request.form["input2"]
three = request.form["input3"]
four = request.form["input4"]
five = request.form["input5"]
six = request.form["input6"]
pin = int(one + two + three + four + five + six)
make_data = collection_pl.find_one({"_id": temp_username})
email = make_data["email"]
make_datax = collection_o.find_one({"_id": email})
otp_from_mongo = make_datax["otp"]
if otp_from_mongo == pin:
return render_template("createpassword.html")
else:
return render_template("otp.html", message="Invalid OTP")
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/createpasswordsuccessfull", methods=["POST", "GET"])
def createpasswordsuccessfull():
error = "CPPS1"
try:
appointment_data = request.get_json()
password1 = appointment_data["password1"]
password2 = appointment_data["password2"]
print(password1, password2)
if password1 != password2:
print(password1, password2)
return jsonify(message="Password did not match !")
else:
if collection_pl.find_one({"_id": temp_username}):
query = {"_id": temp_username}
new_query = {"$set": {"password": password1}}
collection_pl.update_one(query, new_query)
return jsonify(message="Password Changed Successfully !")
return render_template("error.html")
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/docforgotpassword/docdatafound", methods=["POST", "GET"])
def docforgotpassworddatafound():
error = "FPDC1"
try:
username = request.form["login-username"]
if collection_dl.find_one({"_id": username}) or collection_dl.find_one(
{"email": username}
):
pin = int("".join(random.choices("0123456789", k=6)))
global temp_doc_username
if collection_dl.find_one({"_id": username}):
temp_doc_username = username
data = collection_dl.find_one({"_id": username})
email = data["email"]
else:
global temp_email
temp_email = username
data = collection_dl.find_one({"email": username})
email = data["email"]
temp_doc_username = data["_id"]
sender_email = config["EMAIL"]["SENDER_EMAIL"]
sender_password = config["EMAIL"]["SENDER_PASSWORD"]
to_email = email
subject = "One Time Password"
body = f"Your One Time Password is {pin}.\n\nThe OTP will be valid only for 10 minutes.\n\nRegards,\nVaidhya"
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = to_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, to_email, message.as_string())
collection_o.create_index("createdAt", expireAfterSeconds=600)
to_push = {
"createdAt": datetime.now(timezone.utc),
"_id": email,
"otp": pin,
}
if collection_o.find_one({"_id": email}):
query = {"_id": email}
newquery = {"$set": {"otp": pin}}
collection_o.update_one(query, newquery)
else:
collection_o.insert_one(to_push)
return render_template("docotp.html")
else:
return render_template(
"docforgotpassword.html", message="Invalid Credentials"
)
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/docotpverified", methods=["POST", "GET"])
def docotpverified():
error = "OTPVF2"
try:
one = request.form["input1"]
two = request.form["input2"]
three = request.form["input3"]
four = request.form["input4"]
five = request.form["input5"]
six = request.form["input6"]
pin = int(one + two + three + four + five + six)
make_data = collection_dl.find_one({"_id": temp_doc_username})
email = make_data["email"]
make_datax = collection_o.find_one({"_id": email})
otp_from_mongo = make_datax["otp"]
if otp_from_mongo == pin:
return render_template("doccreatepassword.html")
else:
return render_template("docotp.html", message="Invalid OTP")
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/doccreatepasswordsuccessfull", methods=["POST", "GET"])
def doccreatepasswordsuccessfull():
error = "CPDC1"
try:
appointment_data = request.get_json()
password1 = appointment_data["password1"]
password2 = appointment_data["password2"]
print(password1, password2)
if password1 != password2:
print(password1, password2)
return jsonify(message="Password did not match !")
else:
if collection_dl.find_one({"_id": temp_doc_username}):
query = {"_id": temp_doc_username}
new_query = {"$set": {"password": password1}}
collection_dl.update_one(query, new_query)
return jsonify(message="Password Changed Successfully !")
return render_template("error.html")
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/chooseusername", methods=["POST", "GET"])
def chooseusername():
error = "CHUSPS1"
try:
username = request.form["login-username"]
if collection_pl.find_one({"_id": username}):
return render_template("newusername.html", message="username alreay exist!")
else:
global new_username
new_username = username
return render_template("newemail.html")
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/chooseemail", methods=["POST", "GET"])
def chooseemail():
error = "CHEMPS1"
try:
email = request.form["login-username"]
if collection_pl.find_one({"email": email}):
return render_template("newemail.html", message="email already registered!")
else:
global new_email
new_email = email
pin = int("".join(random.choices("0123456789", k=6)))
sender_email = config["EMAIL"]["SENDER_EMAIL"]
sender_password = config["EMAIL"]["SENDER_PASSWORD"]
to_email = new_email
subject = "One Time Password"
body = f"Your One Time Password is {pin}.\n\nThe OTP will be valid only for 10 minutes.\n\nRegards,\nVaidhya"
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = to_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, to_email, message.as_string())
collection_o.create_index("createdAt", expireAfterSeconds=600)
to_push = {
"createdAt": datetime.now(timezone.utc),
"_id": new_email,
"otp": pin,
}
if collection_o.find_one({"_id": new_email}):
query = {"_id": new_email}
newquery = {"$set": {"otp": pin}}
collection_o.update_one(query, newquery)
else:
collection_o.insert_one(to_push)
return render_template("newotp.html")
except:
return render_template("errorfetch.html", message=error), 500
@app.route("/newotpverified", methods=["POST", "GET"])
def newotpverified():
error = "OTPNVF1"
try: