-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstant-run.py
More file actions
1574 lines (1352 loc) · 80.3 KB
/
instant-run.py
File metadata and controls
1574 lines (1352 loc) · 80.3 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 datetime
import faulthandler
import json
import os
import os.path
import shutil
import sqlite3
import threading
import time
import urllib
import urllib.request
from tkinter import *
from tkinter import ttk as cal
from tkinter.font import nametofont
import requests
from PIL import ImageTk
from openAMR import *
faulthandler.enable()
def clear_field(field):
field.delete(0, "end")
field.focus()
printpath = "sh /home/user/print.sh "
def printtext():
def print_text(text, count=0):
for _ in range(int(count)):
f = open("pname.lbl", "w+")
f.write('\nN\nWY\n')
f.write('q305\n')
f.write('Q101,022\n')
f.write('A50,60,0,3,1,1,N,'),
f.write('"' + str(text.replace("$", "")) + '"\n')
f.write('P1\n')
f.close()
os.system(printpath)
def print_barcode(code, count=0):
for _ in range(int(count)):
dateformat = datetime.datetime.strptime(str(datetime.datetime.now().date()), '%Y-%m-%d').strftime(
'%d-%m-%Y')
f = open("code.lbl", "w+")
f.write('\nN\nWY\n')
f.write('q305\n')
f.write('Q101,022\n')
f.write('B50,0,0,1,2,2,20,B,'),
f.write('"' + str(code.replace("$", "")) + '"\n')
f.write('A50,60,0,3,1,1,N,'),
f.write('"' + str(dateformat) + '"\n')
f.write('P1\n')
f.close()
os.system(printpath)
# creating the print barcode and print label window
agarRoot = Toplevel(base)
set_window_icon_and_make_fullscreen(agarRoot)
baseframe = cal.Frame(agarRoot, padding=20)
agar_frame = cal.Frame(baseframe)
f_left = cal.Frame(agar_frame, relief=SOLID, padding=10)
f_right = cal.Frame(agar_frame, relief=SOLID, padding=10)
cal.Label(f_left, text="Print Barcode ").pack(pady=10)
lb = cal.LabelFrame(f_left, text="Scan Accession Number")
en_barcode = cal.Entry(lb, width=25, justify="center")
en_barcode.pack(ipady=10)
en_barcode.bind("<FocusIn>", lambda _, field=en_barcode: clear_field(field))
lb.pack()
lb = cal.LabelFrame(f_left, text="Number of Labels")
en_bnt = cal.Entry(lb, width=25, justify="center")
en_bnt.pack(ipady=10)
en_bnt.insert(0, "1")
en_bnt.bind("<FocusIn>", lambda _, field=en_bnt: clear_field(field))
lb.pack()
bc_frame = cal.Frame(f_left)
cal.Button(bc_frame, text="Print Barcode Label", padding=20, width=22,
command=lambda: print_barcode(en_barcode.get(), en_bnt.get())).pack(pady=10, side=LEFT)
bc_frame.pack()
cal.Label(f_right, text="Print Label Text ").pack(pady=10)
lb = cal.LabelFrame(f_right, text="Enter Label Text")
en_lbl = cal.Entry(lb, width=25, justify="center")
en_lbl.pack(ipady=10)
# en_lbl.insert(0, "1234567890")
en_lbl.bind("<FocusIn>", lambda _, field=en_lbl: clear_field(field))
lb.pack()
lb = cal.LabelFrame(f_right, text="Number of Labels")
en_lcnt = cal.Entry(lb, width=25, justify="center")
en_lcnt.pack(ipady=10)
en_lcnt.insert(0, "1")
en_lcnt.bind("<FocusIn>", lambda _, field=en_lcnt: clear_field(field))
lb.pack()
tl_frame = cal.Frame(f_right)
cal.Button(tl_frame, text="Print Label Text", padding=20, width=22,
command=lambda: print_text(en_lbl.get(), en_lcnt.get())).pack(pady=10,
side=LEFT) # callling the print barcode function on line 40
tl_frame.pack()
f_left.pack(side=LEFT)
f_right.pack(side=LEFT, padx=20)
agar_frame.pack()
cal.Button(baseframe, padding=20, width=10, image=backImg, command=agarRoot.destroy).pack(side=LEFT, pady=10)
baseframe.pack()
def sQLiteconnection():
try:
return sqlite3.connect("assets/sqlitedb/openamr.db").cursor()
except Exception as e_db:
print(e_db)
def sQLitInsert():
while True:
try:
return sqlite3.connect("assets/sqlitedb/openamr.db")
except Exception as e_db:
print(e_db)
def sQLitQuery(sqlitequery):
try:
sQLiteconnection().execute(sqlitequery)
except Exception as e_table:
print(e_table)
def closewindows():
global isolatewindow, valHolder
isolatewindow.destroy()
valHolder.destroy()
def sQLitQuery0(db, sqlitequery):
try:
db.execute(sqlitequery)
except Exception as e_table:
print(e_table)
finally:
db.close()
def clear_Input(entryfield):
entryfield.delete(0, 'end')
entryfield.focus()
def exceptionprint(name, e_name):
pass
def returnTrue(filename, param):
while True:
try:
_n1 = http_get_request(filename, param)
if _n1.status_code == 200:
for _i in _n1.text:
if _i == "1":
return True
elif _n1.status_code != 200:
transactionReset()
except Exception as e_rt:
exceptionprint("returnTrue", e_rt)
def http_request_return_json_or_boolean(file, param, return_data=True):
while True:
try:
_n1 = http_get_request(file, param)
if _n1.status_code == 200:
if return_data:
return _n1
elif not return_data:
for _i in _n1.text:
if _i == "1":
return True
elif _i != "1":
return False
elif _n1.status_code != 200:
if not return_data:
transactionReset()
except Exception as e_rt:
exceptionprint("http_request_return_json_or_boolean", e_rt)
def set_window_icon_and_make_fullscreen(window):
# window.state("zoomed")
# window.attributes('-fullscreen', True)
try:
window.iconbitmap(icoloc)
except Exception as e_win:
exceptionprint("set_window_icon_and_make_fullscreen", e_win)
# noinspection PyBroadException
def itemselected(event, entryfield, condition=None):
global global_isolate_name, abxname, global_unique_code, global_sample_code
entryfield.delete(0, 'end')
try:
entryfield.insert(0, event.widget.get(event.widget.curselection()))
if condition == 1:
global_isolate_name = event.widget.get(event.widget.curselection())
elif not condition:
abxname = event.widget.get(event.widget.curselection())
elif condition == 2:
global_sample_code = event.widget.get(event.widget.curselection())
else:
global_unique_code = event.widget.get(event.widget.curselection())
except Exception as _:
pass
def toListbox(val, listbox, mydata, sort=True):
value_abx = val.widget.get()
value_abx = value_abx.strip().lower()
if value_abx == '':
data = mydata
else:
data = []
for item in mydata:
if not sort:
if value_abx in item:
data.append(item)
elif sort:
if value_abx in item.lower():
data.append(item)
listboxupdate(data, listbox, False)
def listboxupdate(data, listbox, lower=True):
listbox.delete(0, 'end')
if not lower:
for item in data:
listbox.insert('end', item)
elif lower:
data = sorted(data, key=str.lower)
for item in data:
listbox.insert('end', item)
# noinspection PyUnresolvedReferences
def http_get_request(filename, param):
while True:
try:
http_request = requests.post(domain + str(filename) + ".php", param, timeout=10)
if http_request.status_code == 200:
return http_request
except Exception as e_net:
exceptionprint("http_get_request", e_net)
def transactionReset():
returnTrue("transactionTerminate", {})
# noinspection PyShadowingNames
def downloadImg(global_sample_id_from_database, imgnameftp, imgname, condition, downfactor=.0):
while True:
try:
imgurldown = url + "img/" + str(imgnameftp) + str(
global_sample_id_from_database) + ".png"
imgrequest = urllib.request.urlopen(imgurldown)
downloadimg = np.asarray(bytearray(imgrequest.read()), dtype=np.uint8)
downimg = cv2.imdecode(downloadimg, -1)
if not condition:
cv2.imwrite(imglocationhome + str(imgname) + str(global_sample_id_from_database) + ".png", downimg)
if condition:
cv2.imwrite(imglocationhome + str(imgname) + str(global_sample_id_from_database) + ".png",
cv2.resize(downimg, (0, 0), fx=downfactor, fy=downfactor))
break
except Exception as er_img:
exceptionprint("downloadImg", er_img)
def setprogress(status, filename="setTestStatus"):
while True:
http_request_return_json_or_boolean(file=filename, param={"status": status}, return_data=False)
return
def setlink(status, filename="setLinkStatus"):
while True:
if http_request_return_json_or_boolean(file=filename, param={"link": status}, return_data=False):
return
threadInstance = None
def result_report():
btns = {}
# noinspection PyShadowingNames
def singleTestProgressing(global_sample_id_from_database):
global dictionary_of_discs_from_database, dictionary_of_association_from_database
global global_top_window_tkinter, generalOpt, global_bacteria_id_from_database, global_unique_code, global_isolate_name, generals
global_top_window_tkinter = Toplevel(base)
set_window_icon_and_make_fullscreen(global_top_window_tkinter)
cFrame = cal.Frame(global_top_window_tkinter, padding=5, relief=SOLID)
cal.Label(global_top_window_tkinter,
text="ACCESSION # - " + str(global_unique_code) + " | BACTERIA - " + str(
global_isolate_name)).pack(pady=10)
generalOpt = cal.Frame(cFrame, padding=5, relief=SOLID)
cal.Label(generalOpt, text="Antibiotics", width=20).pack(side="left", padx=3,
anchor="w")
cal.Label(generalOpt, text="Code", width=7).pack(side="left", padx=3, anchor="w")
cal.Label(generalOpt, text="Dose", width=10).pack(side="left", padx=3, anchor="w")
cal.Label(generalOpt, text="Zones (mm)", width=10).pack(side="left", padx=3, anchor="w")
cal.Label(generalOpt, text="R<", width=5).pack(side="left", padx=3, anchor="w")
cal.Label(generalOpt, text="S≥", width=5).pack(side="left", padx=3, anchor="w")
cal.Label(generalOpt, text="Interpretation", width=15).pack(side="left", padx=3,
anchor="w")
generalOpt.pack()
i = 0
generalOpt = {}
try:
btns[0]["state"] = "enabled"
btns[1]["state"] = "enabled"
except Exception as _wd:
exceptionprint("widgets", _wd)
for dt in dictionary_of_discs_from_database:
resultFrame = cal.Frame(cFrame, padding=5, relief=SOLID)
cal.Label(resultFrame, width=20, text=str(i + 1) + ". " + str(
dictionary_of_discs_from_database[dt][0][:18] + "... "
if len(dictionary_of_discs_from_database[dt][0]) > 18 else
dictionary_of_discs_from_database[dt][0])).pack(side="left",
padx=3,
anchor="w")
cal.Label(resultFrame, text=str(dictionary_of_discs_from_database[dt][1]),
width=7).pack(
side="left",
padx=3,
anchor="w")
cal.Label(resultFrame, text=str(dictionary_of_discs_from_database[dt][2]),
width=10).pack(
side="left",
padx=3,
anchor="w")
generalOpt[i + 20] = cal.Label(resultFrame,
text=str(dictionary_of_discs_from_database[dt][3]),
width=10)
generalOpt[i + 20].pack(side="left", padx=3, anchor="w")
cal.Label(resultFrame, text=dictionary_of_association_from_database[dt]["resistance"],
width=5).pack(
side="left",
padx=3,
anchor="w")
cal.Label(resultFrame, text=str(dictionary_of_association_from_database[dt]["susceptible"]),
width=5).pack(
side="left",
padx=3,
anchor="w")
if int(dictionary_of_association_from_database[dt]["resistance"]) == 0 or int(
dictionary_of_association_from_database[dt]["resistance"] == 0):
generalOpt[i + 10] = cal.Label(resultFrame, text="No Breakpoints", width=15)
elif int(dictionary_of_association_from_database[dt]["resistance"]) != 0 or int(
dictionary_of_association_from_database[dt]["resistance"] != 0):
if float(dictionary_of_discs_from_database[dt][3]) >= float(
dictionary_of_association_from_database[dt]["resistance"]):
generalOpt[i + 10] = cal.Label(resultFrame, text="Susceptible", width=15)
elif float(dictionary_of_discs_from_database[dt][3]) < float(
dictionary_of_association_from_database[dt]["resistance"]):
generalOpt[i + 10] = cal.Label(resultFrame, text="Resistant", width=15)
else:
generalOpt[i + 10] = cal.Label(resultFrame, text="Intermediate", width=15)
generalOpt[i + 10].pack(side="left", padx=3, anchor="w")
resultFrame.pack()
i += 1
global global_image, global_scale_image
generals = {}
def savedata():
global global_top_window_tkinter
global_top_window_tkinter.destroy()
cal.Button(cFrame, image=okImg, padding=10, command=savedata).pack(side=RIGHT, pady=10)
newzonead = str(global_sample_id_from_database) + "/zone_adj/" + str(global_sample_id_from_database) + ".png"
newfoundad = imglocationhome + "zonesfoundIm" + str(global_sample_id_from_database) + ".png"
global_image = Image.open(newzonead) if os.path.exists(newzonead) else Image.open(newfoundad)
global_image = global_image.resize((300, 300), Image.ANTIALIAS)
global_scale_image = ImageTk.PhotoImage(global_image)
cal.Label(cFrame, image=global_scale_image).pack(pady=10)
cFrame.pack()
global global_top_window_tkinter, global_sample_code, r_widget, generals
try:
r_widget["text"] = "Please wait ..."
r_widget["state"] = "disabled"
except Exception as _wd:
exceptionprint("widgets", _wd)
d_tem, s_list = {}, []
global_sample_code = None
def get_info():
global global_dictionary_of_completed_info, global_sample_code, global_unique_code, global_isolate_name
m_code = 0
if global_sample_code is None:
return
try:
btns[0]["state"] = "disabled"
btns[1]["state"] = "disabled"
except Exception as _wd:
exceptionprint("widgets", _wd)
for _k, _id in d_tem.items():
if int(global_sample_code.split("|")[0][:]) == _k:
m_code = _id
dictionary_of_discs_from_database.clear()
dictionary_of_association_from_database.clear()
a = 0
global_unique_code = m_code[2]
global_isolate_name = m_code[3]
_test = {}
_data = {"sample_id": m_code[0],
"bacteria_id": m_code[1]}
getDisc = http_get_request("getCDiscs",
{"sample_id": m_code[0]})
if getDisc.status_code == 200:
for dis in getDisc.json()["discId_num"]:
# 0: (Chloramphenicol', 'C30', '30ug', 6, bacteria-12, abx-3')
# noinspection PyTypeChecker
dictionary_of_discs_from_database[a] = (
dis["abx_name"], dis["abx_code"],
dis["abx_content"],
round(float(dis["diameter"])), dis["bacteria_id"], dis["abx_id"])
getAssoc = http_get_request("getAssociation", {
"abx_id": dictionary_of_discs_from_database[a][5],
"bacteria_id": dictionary_of_discs_from_database[a][4]})
if getAssoc.status_code == 200:
double = 0
for assoc in getAssoc.json()["association"]:
if double == 0:
dictionary_of_association_from_database[a] = assoc
double = 1
else:
double = 1
a += 1
if not os.path.exists(str(m_code[0]) + "/zone_adj/" + str(m_code[0]) + ".png"):
if not os.path.exists(imglocationhome + "zonesfoundIm" + str(m_code[0]) + ".png"):
downloadImg(m_code[0], "_zonesfoundIm", "zonesfoundIm",
False)
threading.Thread(target=singleTestProgressing, args=[m_code[0]]).start()
return
_c = 1
_n = None
generals = {}
while True:
try:
for dtest in http_request_return_json_or_boolean(file="getSamples", param={}, return_data=True).json()[
"_List"]:
d_tem[_c] = (int(dtest["sample_id"]), int(dtest["bacteria_id"]), str(dtest["uniquecode"]),
str(dtest["bacteria_name"]))
dateformat = datetime.datetime.strptime(str(dtest["test_on"]), '%Y-%m-%d').strftime('%d-%m-%Y')
if _c < 10:
_n = "0" + str(_c)
s_list.append(str(_n) + " | " + str(dateformat) + " | " + str(dtest["uniquecode"]) + " | " + str(
dtest["bacteria_name"]))
else:
s_list.append(str(_c) + " | " + str(dateformat) + " | " + str(dtest["uniquecode"]) + " | " + str(
dtest["bacteria_name"]))
_c += 1
break
except Exception as _ehttp:
if _ehttp.__doc__.__eq__("Inappropriate argument type."):
r_widget["text"] = "No result at the moment"
time.sleep(3)
try:
r_widget["state"] = "enabled"
r_widget["text"] = "Result Report"
except Exception as _wd:
exceptionprint("widgets", _wd)
return
exceptionprint("result", _ehttp)
try:
r_widget["state"] = "enabled"
r_widget["text"] = "Result Report"
except Exception as _wd:
exceptionprint("widgets", _wd)
global_top_window_tkinter = Toplevel(base)
set_window_icon_and_make_fullscreen(global_top_window_tkinter)
abxFrame = cal.Frame(global_top_window_tkinter, relief=SOLID, padding=20)
cal.Label(global_top_window_tkinter, text="Result Report").pack(pady=10)
anEntry = cal.Entry(abxFrame, width=dimensionPadding+3)
anEntry.pack(ipady=10, pady=10)
listViewFrame = cal.Frame(abxFrame)
scrollbar = Scrollbar(listViewFrame)
scrollbar.pack(side=RIGHT, fill=Y, ipadx=20)
anListbox = Listbox(listViewFrame, width=dimensionPadding, height=10,
yscrollcommand=scrollbar.set)
listboxupdate(s_list, anListbox, False)
scrollbar.config(command=anListbox.yview)
listViewFrame.pack()
anEntry.bind("<KeyRelease>", lambda e, box=anListbox: toListbox(e, box, s_list, False))
anListbox.bind("<<ListboxSelect>>", lambda event, efield=anEntry: itemselected(event, efield, 2))
anListbox.bind("<Double-Button-1>", lambda e: threading.Thread(target=get_info).start())
anListbox.bind("<Return>", lambda e: threading.Thread(target=get_info).start())
anListbox.pack()
btns[0] = cal.Button(abxFrame, image=backImg, padding=20, command=global_top_window_tkinter.destroy)
btns[1] = cal.Button(abxFrame, image=proceedImg, padding=20,
command=lambda: threading.Thread(target=get_info).start())
btns[0].pack(side=LEFT, pady=10)
btns[1].pack(side=RIGHT, pady=10)
abxFrame.pack()
# noinspection PyGlobalUndefined
def start_test():
global threadInstance, isolate_list_from_database
error = None
global_sample_id_from_database = None
# noinspection PyShadowingNames
def proceedtophoto():
try:
global global_unique_code, error
global_unique_code = entryField.get().upper().replace("$", "")
# threading.Thread(target=setprogress, args=[1]).start()
setprogress(1)
except Exception as e_pro:
exceptionprint("proceedtophoto", e_pro)
def discabxConfirm():
global list_of_antibiotic_match_with_isolate, dictionary_of_antibiotic_discs_from_database
global global_image, global_scale_image, global_top_window_tkinter, global_isolate_name, valHolder, generals
global_top_window_tkinter.destroy()
valHolder = Toplevel(base)
set_window_icon_and_make_fullscreen(valHolder)
cal.Label(valHolder, text="Confirm discs - Antibiotics for " + global_isolate_name).pack(pady=20)
discabxFrame = cal.Frame(valHolder, relief=SOLID, padding=30)
global_image = Image.open(imglocationhome + tmpdiscfoundimg + "discsfound.png")
global_image = global_image.resize((600, 600), Image.ANTIALIAS)
global_scale_image = ImageTk.PhotoImage(global_image)
def anproceed():
global dictionary_of_antibiotic_discs_from_database
mycondition = False
for b in dictionary_of_antibiotic_discs_from_database:
if dictionary_of_antibiotic_discs_from_database[b] == "No match found":
mycondition = True
if not mycondition:
threading.Thread(target=testData).start()
# noinspection PyShadowingNames
def nomatchfound(data):
for i in data:
if data[i] == "No match found":
generals[12]["state"] = "disabled"
break
else:
generals[12]["state"] = "enabled"
generals[12].bind("<Button-1>", lambda e: anproceed())
def change_antibiotic_name(antibiotic_name, dictionary_of_antibiotics):
def bacteria_change():
global abxname, dictionary_of_antibiotic_discs_from_database
global_top_window_tkinter.destroy()
antibiotic_name["text"] = "Disc " + str(dictionary_of_antibiotics) + "." + abxname
if dictionary_of_antibiotics:
dictionary_of_antibiotic_discs_from_database[dictionary_of_antibiotics] = abxname
nomatchfound(dictionary_of_antibiotic_discs_from_database)
if not dictionary_of_antibiotics:
dictionary_of_antibiotic_discs_from_database[dictionary_of_antibiotics] = "No match found"
matched = list()
notmatched = list()
for _, a in enumerate(list_of_antibiotic_match_with_isolate):
for _, _name in dictionary_of_antibiotic_discs_from_database.items():
if a == _name:
matched.append(a)
else:
notmatched.append(a)
# noinspection PyShadowingNames
global_top_window_tkinter = Toplevel(base)
set_window_icon_and_make_fullscreen(global_top_window_tkinter)
abxFrame = cal.Frame(global_top_window_tkinter, relief=SOLID, padding=20)
cal.Label(global_top_window_tkinter,
text="Change antibiotic for disk." + str(dictionary_of_antibiotics) + "").pack(pady=10)
anEntry = cal.Entry(abxFrame, width=dimensionPadding+3)
anEntry.pack(ipady=10, pady=10)
listViewFrame = cal.Frame(abxFrame)
scrollbar = Scrollbar(listViewFrame)
anListbox = Listbox(listViewFrame, width=dimensionPadding, height=10,
yscrollcommand=scrollbar.set)
scrollbar.pack(side=RIGHT, fill=Y, ipadx=20)
scrollbar.config(command=anListbox.yview)
listboxupdate(list_of_antibiotic_match_with_isolate, anListbox)
listViewFrame.pack()
anEntry.bind("<KeyRelease>",
lambda e, box=anListbox: toListbox(e, box, list_of_antibiotic_match_with_isolate))
anListbox.bind("<<ListboxSelect>>", lambda event, efield=anEntry: itemselected(event, efield, False))
anListbox.bind("<Double-Button-1>", lambda e: bacteria_change())
anListbox.bind("<Return>", lambda e: bacteria_change())
anListbox.pack()
cal.Button(abxFrame, image=backImg, padding=20, command=global_top_window_tkinter.destroy).pack(
side=LEFT, pady=10)
cal.Button(abxFrame, image=okImg, padding=20, command=bacteria_change).pack(side=RIGHT,
pady=10)
anEntry.pack()
abxFrame.pack()
discabxBox = cal.Frame(discabxFrame, relief=SOLID, padding=10)
discabxL = cal.Frame(discabxBox)
discabxR = cal.Frame(discabxBox)
# Dictionary Label
disclabeldict = generals = {}
generals[10] = cal.Label(discabxFrame, image=global_scale_image)
generals[10].pack(side=LEFT)
# noinspection PyShadowingNames
for i in dictionary_of_antibiotic_discs_from_database:
disclabeldict[i] = cal.Label(discabxL, width=35,
text="Disc " + str(i) + "." + dictionary_of_antibiotic_discs_from_database[
i])
disclabeldict[i].pack(anchor='w', pady=0)
disclabeldict[i].bind("<Double-Button-1>",
lambda eventhandle, akey=i, aname=disclabeldict[i]: change_antibiotic_name(aname,
akey))
discabxL.pack(side=LEFT, ipadx=5)
discabxR.pack(side=RIGHT, ipadx=5)
discabxBox.pack(pady=5)
# noinspection PyShadowingNames,PyAssignmentToLoopOrWithParameter
def testData():
global generals, global_isolate_name, global_unique_code, global_top_window_tkinter, error, global_sample_id_from_database
global_top_window_tkinter = Toplevel(base)
set_window_icon_and_make_fullscreen(global_top_window_tkinter)
generals = dict()
generals[5] = cal.Frame(global_top_window_tkinter, padding=50)
generals[6] = cal.Label(generals[5], width=50)
generals[6].pack(pady=100)
generals[5].pack(pady=100)
generals[6]["text"] = "Preparing for zone detection please wait"
global insertlist
insertlist[:] = []
for _, _a in dictionary_of_antibiotic_discs_from_database.items():
insertlist.append(_a.split(" -")[0])
# print(insertlist)
try:
if not http_request_return_json_or_boolean(file="insertTestData0",
param={"uniquecode": global_unique_code,
"isolatename": global_isolate_name,
"abx_discs": json.dumps(insertlist)},
return_data=False):
generals[6]["text"] = "Oops! Something went wrong please check isolate matches"
time.sleep(3)
global_top_window_tkinter.destroy()
return
except Exception as _ehttp:
exceptionprint("insertTestData0", _ehttp)
closewindows()
threading.Thread(target=setprogress, args=[4]).start()
# noinspection PyShadowingNames
def singleTestProgressing(global_sample_id_from_database):
global global_top_window_tkinter, generalOpt, global_bacteria_id_from_database, global_unique_code, global_isolate_name
global_top_window_tkinter.destroy()
global_top_window_tkinter = Toplevel(base)
set_window_icon_and_make_fullscreen(global_top_window_tkinter)
cFrame = cal.Frame(global_top_window_tkinter, padding=5, relief=SOLID)
cal.Label(global_top_window_tkinter,
text="ACCESSION # - " + str(global_unique_code) + " | BACTERIA - " + str(
global_isolate_name)).pack(pady=10)
generalOpt = cal.Frame(cFrame, padding=5, relief=SOLID)
cal.Label(generalOpt, text="Antibiotics", width=20).pack(side="left", padx=3,
anchor="w")
cal.Label(generalOpt, text="Code", width=7).pack(side="left", padx=3, anchor="w")
cal.Label(generalOpt, text="Dose", width=10).pack(side="left", padx=3, anchor="w")
cal.Label(generalOpt, text="Zones (mm)", width=10).pack(side="left", padx=3, anchor="w")
cal.Label(generalOpt, text="R<", width=5).pack(side="left", padx=3, anchor="w")
cal.Label(generalOpt, text="S≥", width=5).pack(side="left", padx=3, anchor="w")
cal.Label(generalOpt, text="Interpretation", width=15).pack(side="left", padx=3,
anchor="w")
generalOpt.pack()
i = 0
generalOpt = {}
global dictionary_of_discs_from_database, dictionary_of_association_from_database
for dt in dictionary_of_discs_from_database:
resultFrame = cal.Frame(cFrame, padding=5, relief=SOLID)
cal.Label(resultFrame, width=20, text=str(i + 1) + ". " + str(
dictionary_of_discs_from_database[dt][0][:18] + "... "
if len(dictionary_of_discs_from_database[dt][0]) > 18 else
dictionary_of_discs_from_database[dt][0])).pack(side="left",
padx=3,
anchor="w")
cal.Label(resultFrame, text=str(dictionary_of_discs_from_database[dt][1]),
width=7).pack(
side="left",
padx=3,
anchor="w")
cal.Label(resultFrame, text=str(dictionary_of_discs_from_database[dt][2]),
width=10).pack(
side="left",
padx=3,
anchor="w")
generalOpt[i + 20] = cal.Label(resultFrame,
text=str(dictionary_of_discs_from_database[dt][3]),
width=10)
generalOpt[i + 20].pack(side="left", padx=3, anchor="w")
cal.Label(resultFrame, text=dictionary_of_association_from_database[dt]["resistance"],
width=5).pack(
side="left",
padx=3,
anchor="w")
cal.Label(resultFrame, text=str(dictionary_of_association_from_database[dt]["susceptible"]),
width=5).pack(
side="left",
padx=3,
anchor="w")
if int(dictionary_of_association_from_database[dt]["resistance"]) == 0 or int(
dictionary_of_association_from_database[dt]["resistance"] == 0):
generalOpt[i + 10] = cal.Label(resultFrame, text="No Breakpoints", width=15)
elif int(dictionary_of_association_from_database[dt]["resistance"]) != 0 or int(
dictionary_of_association_from_database[dt]["resistance"] != 0):
if float(dictionary_of_discs_from_database[dt][3]) >= float(
dictionary_of_association_from_database[dt]["resistance"]):
generalOpt[i + 10] = cal.Label(resultFrame, text="Susceptible", width=15)
elif float(dictionary_of_discs_from_database[dt][3]) < float(
dictionary_of_association_from_database[dt]["resistance"]):
generalOpt[i + 10] = cal.Label(resultFrame, text="Resistant", width=15)
else:
generalOpt[i + 10] = cal.Label(resultFrame, text="Intermediate", width=15)
generalOpt[i + 10].pack(side="left", padx=3, anchor="w")
resultFrame.pack()
i += 1
global global_image, global_scale_image, generals
generals = {}
# noinspection PyShadowingNames
def adjustTest():
global global_top_window_tkinter, imagefx, imagefxs, generals, global_sample_id_from_database
generals = {}
global_top_window_tkinter.destroy()
global_top_window_tkinter = Toplevel(base)
set_window_icon_and_make_fullscreen(global_top_window_tkinter)
baseFrame = cal.Frame(global_top_window_tkinter)
eFrame = cal.Frame(baseFrame, relief=SOLID, padding=20)
list_distances = []
# noinspection PyShadowingNames
def cAdjust(amount, dics_number, condition):
# noinspection PyShadowingNames,PyBroadException
def background_adjust_thread(dsc, amount, cond):
global imagefx, imagefxs, generals, global_scale_image, global_image
global incount, global_sample_id_from_database, zones_adj, zones
if str(dsc).__eq__("Disc to edit") or str(amount).__eq__("Amount"):
return
mm = 1 if cond else -1
try:
generals[3]["state"] = "disabled"
generals[4]["state"] = "disabled"
except Exception as _:
pass
# noinspection PyShadowingNames
discsTest = {}
zone_distances, dist = [], {}
j = 1
getdiscs = sQLiteconnection().execute("SELECT disc FROM zones WHERE sample_id = ? ",
(str(global_sample_id_from_database),))
for disc in getdiscs.fetchall():
discsTest[j] = (
(int(disc[0].split(",")[0][1:])), (int(disc[0].rsplit(",")[-1][:-1])))
j += 1
incount = True
getzone = sQLiteconnection().execute("SELECT diameter FROM discs WHERE sample_id = ? ",
(str(global_sample_id_from_database),))
for diam in getzone.fetchall():
zone_distances.append(float(diam[0]))
rgb_dir = Path(r'' + imgbase + str(global_sample_id_from_database) + '/rgb')
zones_dir = Path(r'' + imgbase + str(global_sample_id_from_database) + '/zones')
zadjs_dir = Path(r'' + imgbase + str(global_sample_id_from_database) + '/zones_adj')
zadj_dir = Path(r'' + imgbase + str(global_sample_id_from_database) + '/zone_adj')
rgb_path = rgb_dir / (str(global_sample_id_from_database) + '.png')
zones_path = zones_dir / (str(global_sample_id_from_database) + '.txt')
zadjs_path = zadjs_dir / (str(global_sample_id_from_database) + '.txt')
zadj_path = zadj_dir / (str(global_sample_id_from_database) + '.png')
if os.path.exists(imgbase + str(global_sample_id_from_database) + "/zones_adj/" + str(
global_sample_id_from_database) + ".txt"):
zones = load_zones(zadjs_path)
zones_adj = adjust_zones(zones, int(dsc) - 1, mm * int(amount))
save_zones(zones_adj, zadjs_path)
elif not os.path.exists(imgbase + str(global_sample_id_from_database) + "/zones_adj/" + str(
global_sample_id_from_database) + ".txt"):
zones = load_zones(zones_path)
zones_adj = adjust_zones(zones, int(dsc) - 1, mm * int(amount))
save_zones(zones_adj, zadjs_path)
# draw new adjusted zones
rgb_zones = load_image(rgb_path)
draw_zones(rgb_zones, zones_adj)
save_image(rgb_zones, zadj_path)
for z in zones:
for k, i in enumerate(zones[z]):
if k == 3:
list_distances.append(float("{0: .2f}".format(i)))
def sQLitComit(sql, args=None):
sQLit = sQLitInsert()
if args is None:
with sQLit:
sQLit.execute(sql)
elif args is not None:
with sQLit:
sQLit.execute(sql, args)
# noinspection PyShadowingNames
for g, l in enumerate(list_distances):
dist[g] = l
getdiscs0 = sQLiteconnection().execute(
"SELECT * FROM discs WHERE sample_id = " + str(global_sample_id_from_database))
for (_, di), disc_id in zip(dist.items(), getdiscs0.fetchall()):
try:
param = (str(round(float(di))), str(disc_id[0]))
sQLitComit(
''' UPDATE discs set diameter= ? WHERE disc_id = ? ''',
param)
except Exception as e_updsc:
exceptionprint("update discs", e_updsc)
list_distances[:] = []
newzonead = imgbase + str(global_sample_id_from_database) + "/zone_adj/" + str(
global_sample_id_from_database) + ".png"
newfoundad = imglocationhome + "zonesfoundIm" + str(
global_sample_id_from_database) + ".png"
imagefx = Image.open(newzonead) if os.path.exists(newzonead) else Image.open(newfoundad)
imagefx = imagefx.resize((500, 500), Image.ANTIALIAS)
imagefxs = ImageTk.PhotoImage(imagefx)
try:
generals[1]["image"] = imagefxs
generals[3]["state"] = "enabled"
generals[4]["state"] = "enabled"
except Exception as _:
pass
threading.Thread(target=background_adjust_thread,
args=[dics_number, amount, condition]).start()
newzonead = imgbase + str(global_sample_id_from_database) + "/zone_adj/" + str(
global_sample_id_from_database) + ".png"
newfoundad = imglocationhome + "zonesfoundIm" + str(global_sample_id_from_database) + ".png"
imagefx = Image.open(newzonead) if os.path.exists(newzonead) else Image.open(newfoundad)
g = 0
imagefx = imagefx.resize((500, 500), Image.ANTIALIAS)
imagefxs = ImageTk.PhotoImage(imagefx)
imframe = cal.Frame(eFrame)
generals[g + 1] = cal.Label(imframe, image=imagefxs)
generals[g + 1].pack()
combodropList = []
combodropList[:] = range(1, len(dictionary_of_antibiotic_discs_from_database) + 1)
combodropAmount = [x for x in range(1, 9)]
bFrame = cal.Frame(baseFrame)
generals[g + 5] = cal.Combobox(bFrame, width=20, values=combodropList, state="readonly")
generals[g + 5].set("Disc to edit")
generals[g + 5].pack(padx=2)
generals[g + 2] = cal.Combobox(bFrame, width=20, values=combodropAmount, state="readonly")
generals[g + 2].set("Amount")
generals[g + 3] = cal.Button(bFrame, image=plusImg, width=20, padding=20)
generals[g + 3].bind("<Button-1>",
lambda event: cAdjust(generals[g + 2].get(), generals[g + 5].get(), True))
generals[g + 4] = cal.Button(bFrame, image=minusImg, width=20, padding=20)
generals[g + 4].bind("<Button-1>",
lambda event: cAdjust(generals[g + 2].get(), generals[g + 5].get(), False))
generals[g + 4].pack(side=LEFT, padx=2)
generals[g + 2].pack(pady=10, ipady=3, padx=20, side=LEFT)
generals[g + 3].pack(side=LEFT, padx=2)
imframe.pack(side=LEFT)
bFrame.pack(side=RIGHT)
# noinspection PyShadowingNames
def callback():
global dictionary_of_discs_from_database, global_sample_id_from_database
getzone = sQLiteconnection().execute("SELECT diameter FROM discs WHERE sample_id = ? ",
(str(global_sample_id_from_database),))
for _d, di in zip(dictionary_of_discs_from_database, getzone.fetchall()):
l = list(dictionary_of_discs_from_database[_d])
l[3] = di[0]
dictionary_of_discs_from_database[_d] = tuple(l)
# 0: (Chloramphenicol', 'C30', '30ug', 6, bacteria-12, abx-3')
# print(dictionary_of_discs_from_database)
global_top_window_tkinter.destroy()
threading.Thread(target=singleTestProgressing,
args=[global_sample_id_from_database]).start()
eFrame.pack()
cal.Button(baseFrame, image=okImg, width=20, padding=20, command=callback).pack(
pady=3)
baseFrame.pack()
def savedata():
global global_top_window_tkinter, incount
global_top_window_tkinter.destroy()
# noinspection PyShadowingNames
def finish():
global global_sample_id_from_database
shutil.copy(imgbase + str(global_sample_id_from_database) + "/zone_adj/" + str(
global_sample_id_from_database) + ".png",
imglocationhome + "zonesfoundIm" + str(global_sample_id_from_database) + ".png")
getdiscs0 = sQLiteconnection().execute(
"SELECT disc_id FROM discs WHERE sample_id = " + global_sample_id_from_database)
getzone = sQLiteconnection().execute(
"SELECT diameter FROM discs WHERE sample_id = ? ",
(str(global_sample_id_from_database),))
for dis, dia in zip(getdiscs0.fetchall(), getzone.fetchall()):
disc_update_info = {"disc_num": dis[0], "sample_id": global_sample_id_from_database,
"distances": round(float(dia[0]))}
while True:
try:
if http_request_return_json_or_boolean(file="updateDisc",
param=disc_update_info,
return_data=False):
break
except Exception as _ehttp:
exceptionprint("finish", _ehttp)
print("Update complete")
if incount:
threading.Thread(target=finish).start()
cal.Button(cFrame, image=okImg, padding=10, command=savedata).pack(side=RIGHT, pady=10)
modify = cal.Button(cFrame, image=editImg, padding=10, state="disabled", command=adjustTest)
modify.pack(side=LEFT, pady=10)
newzonead = imgbase + str(global_sample_id_from_database) + "/zone_adj/" + str(
global_sample_id_from_database) + ".png"
newfoundad = imglocationhome + "zonesfoundIm" + str(global_sample_id_from_database) + ".png"