Spaces:
Running
Running
Update mtdna_backend.py
Browse files- mtdna_backend.py +906 -896
mtdna_backend.py
CHANGED
@@ -1,897 +1,907 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
from collections import Counter
|
3 |
-
import csv
|
4 |
-
import os
|
5 |
-
from functools import lru_cache
|
6 |
-
#import app
|
7 |
-
from mtdna_classifier import classify_sample_location
|
8 |
-
import data_preprocess, model, pipeline
|
9 |
-
import subprocess
|
10 |
-
import json
|
11 |
-
import pandas as pd
|
12 |
-
import io
|
13 |
-
import re
|
14 |
-
import tempfile
|
15 |
-
import gspread
|
16 |
-
from oauth2client.service_account import ServiceAccountCredentials
|
17 |
-
from io import StringIO
|
18 |
-
import hashlib
|
19 |
-
import threading
|
20 |
-
|
21 |
-
# @lru_cache(maxsize=3600)
|
22 |
-
# def classify_sample_location_cached(accession):
|
23 |
-
# return classify_sample_location(accession)
|
24 |
-
|
25 |
-
@lru_cache(maxsize=3600)
|
26 |
-
def pipeline_classify_sample_location_cached(accession):
|
27 |
-
print("inside pipeline_classify_sample_location_cached, and [accession] is ", [accession])
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
#
|
34 |
-
#
|
35 |
-
#
|
36 |
-
#
|
37 |
-
# row
|
38 |
-
#
|
39 |
-
#
|
40 |
-
#
|
41 |
-
|
42 |
-
#
|
43 |
-
#
|
44 |
-
|
45 |
-
#
|
46 |
-
#
|
47 |
-
#
|
48 |
-
#
|
49 |
-
#
|
50 |
-
|
51 |
-
#
|
52 |
-
#
|
53 |
-
|
54 |
-
# # Step
|
55 |
-
#
|
56 |
-
|
57 |
-
# # Step
|
58 |
-
#
|
59 |
-
|
60 |
-
|
61 |
-
#
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
sheet.
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
return
|
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 |
-
"Predicted
|
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 |
-
# try:
|
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 |
-
# sheet.
|
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 |
-
if
|
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 |
-
# return {}
|
582 |
-
|
583 |
-
# try:
|
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 |
-
for
|
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 |
-
df_old.
|
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 |
return all_rows, output_file_path, total_queries, "\n".join(progress_lines), warning
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from collections import Counter
|
3 |
+
import csv
|
4 |
+
import os
|
5 |
+
from functools import lru_cache
|
6 |
+
#import app
|
7 |
+
from mtdna_classifier import classify_sample_location
|
8 |
+
import data_preprocess, model, pipeline
|
9 |
+
import subprocess
|
10 |
+
import json
|
11 |
+
import pandas as pd
|
12 |
+
import io
|
13 |
+
import re
|
14 |
+
import tempfile
|
15 |
+
import gspread
|
16 |
+
from oauth2client.service_account import ServiceAccountCredentials
|
17 |
+
from io import StringIO
|
18 |
+
import hashlib
|
19 |
+
import threading
|
20 |
+
|
21 |
+
# @lru_cache(maxsize=3600)
|
22 |
+
# def classify_sample_location_cached(accession):
|
23 |
+
# return classify_sample_location(accession)
|
24 |
+
|
25 |
+
@lru_cache(maxsize=3600)
|
26 |
+
def pipeline_classify_sample_location_cached(accession,stop_flag):
|
27 |
+
print("inside pipeline_classify_sample_location_cached, and [accession] is ", [accession])
|
28 |
+
if stop_flag is not None and stop_flag.value:
|
29 |
+
print(f"π Skipped {accession} mid-pipeline.")
|
30 |
+
return []
|
31 |
+
return pipeline.pipeline_with_gemini([accession],stop_flag)
|
32 |
+
|
33 |
+
# Count and suggest final location
|
34 |
+
# def compute_final_suggested_location(rows):
|
35 |
+
# candidates = [
|
36 |
+
# row.get("Predicted Location", "").strip()
|
37 |
+
# for row in rows
|
38 |
+
# if row.get("Predicted Location", "").strip().lower() not in ["", "sample id not found", "unknown"]
|
39 |
+
# ] + [
|
40 |
+
# row.get("Inferred Region", "").strip()
|
41 |
+
# for row in rows
|
42 |
+
# if row.get("Inferred Region", "").strip().lower() not in ["", "sample id not found", "unknown"]
|
43 |
+
# ]
|
44 |
+
|
45 |
+
# if not candidates:
|
46 |
+
# return Counter(), ("Unknown", 0)
|
47 |
+
# # Step 1: Combine into one string and split using regex to handle commas, line breaks, etc.
|
48 |
+
# tokens = []
|
49 |
+
# for item in candidates:
|
50 |
+
# # Split by comma, whitespace, and newlines
|
51 |
+
# parts = re.split(r'[\s,]+', item)
|
52 |
+
# tokens.extend(parts)
|
53 |
+
|
54 |
+
# # Step 2: Clean and normalize tokens
|
55 |
+
# tokens = [word.strip() for word in tokens if word.strip().isalpha()] # Keep only alphabetic tokens
|
56 |
+
|
57 |
+
# # Step 3: Count
|
58 |
+
# counts = Counter(tokens)
|
59 |
+
|
60 |
+
# # Step 4: Get most common
|
61 |
+
# top_location, count = counts.most_common(1)[0]
|
62 |
+
# return counts, (top_location, count)
|
63 |
+
|
64 |
+
# Store feedback (with required fields)
|
65 |
+
|
66 |
+
def store_feedback_to_google_sheets(accession, answer1, answer2, contact=""):
|
67 |
+
if not answer1.strip() or not answer2.strip():
|
68 |
+
return "β οΈ Please answer both questions before submitting."
|
69 |
+
|
70 |
+
try:
|
71 |
+
# β
Step: Load credentials from Hugging Face secret
|
72 |
+
creds_dict = json.loads(os.environ["GCP_CREDS_JSON"])
|
73 |
+
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
|
74 |
+
creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
|
75 |
+
|
76 |
+
# Connect to Google Sheet
|
77 |
+
client = gspread.authorize(creds)
|
78 |
+
sheet = client.open("feedback_mtdna").sheet1 # make sure sheet name matches
|
79 |
+
|
80 |
+
# Append feedback
|
81 |
+
sheet.append_row([accession, answer1, answer2, contact])
|
82 |
+
return "β
Feedback submitted. Thank you!"
|
83 |
+
|
84 |
+
except Exception as e:
|
85 |
+
return f"β Error submitting feedback: {e}"
|
86 |
+
|
87 |
+
# helper function to extract accessions
|
88 |
+
def extract_accessions_from_input(file=None, raw_text=""):
|
89 |
+
print(f"RAW TEXT RECEIVED: {raw_text}")
|
90 |
+
accessions = []
|
91 |
+
seen = set()
|
92 |
+
if file:
|
93 |
+
try:
|
94 |
+
if file.name.endswith(".csv"):
|
95 |
+
df = pd.read_csv(file)
|
96 |
+
elif file.name.endswith(".xlsx"):
|
97 |
+
df = pd.read_excel(file)
|
98 |
+
else:
|
99 |
+
return [], "Unsupported file format. Please upload CSV or Excel."
|
100 |
+
for acc in df.iloc[:, 0].dropna().astype(str).str.strip():
|
101 |
+
if acc not in seen:
|
102 |
+
accessions.append(acc)
|
103 |
+
seen.add(acc)
|
104 |
+
except Exception as e:
|
105 |
+
return [], f"Failed to read file: {e}"
|
106 |
+
|
107 |
+
if raw_text:
|
108 |
+
text_ids = [s.strip() for s in re.split(r"[\n,;\t]", raw_text) if s.strip()]
|
109 |
+
for acc in text_ids:
|
110 |
+
if acc not in seen:
|
111 |
+
accessions.append(acc)
|
112 |
+
seen.add(acc)
|
113 |
+
|
114 |
+
return list(accessions), None
|
115 |
+
# β
Add a new helper to backend: `filter_unprocessed_accessions()`
|
116 |
+
def get_incomplete_accessions(file_path):
|
117 |
+
df = pd.read_excel(file_path)
|
118 |
+
|
119 |
+
incomplete_accessions = []
|
120 |
+
for _, row in df.iterrows():
|
121 |
+
sample_id = str(row.get("Sample ID", "")).strip()
|
122 |
+
|
123 |
+
# Skip if no sample ID
|
124 |
+
if not sample_id:
|
125 |
+
continue
|
126 |
+
|
127 |
+
# Drop the Sample ID and check if the rest is empty
|
128 |
+
other_cols = row.drop(labels=["Sample ID"], errors="ignore")
|
129 |
+
if other_cols.isna().all() or (other_cols.astype(str).str.strip() == "").all():
|
130 |
+
# Extract the accession number from the sample ID using regex
|
131 |
+
match = re.search(r"\b[A-Z]{2,4}\d{4,}", sample_id)
|
132 |
+
if match:
|
133 |
+
incomplete_accessions.append(match.group(0))
|
134 |
+
print(len(incomplete_accessions))
|
135 |
+
return incomplete_accessions
|
136 |
+
|
137 |
+
# GOOGLE_SHEET_NAME = "known_samples"
|
138 |
+
# USAGE_DRIVE_FILENAME = "user_usage_log.json"
|
139 |
+
|
140 |
+
def summarize_results(accession, stop_flag=None):
|
141 |
+
# Early bail
|
142 |
+
if stop_flag is not None and stop_flag.value:
|
143 |
+
print(f"π Skipping {accession} before starting.")
|
144 |
+
return []
|
145 |
+
# try cache first
|
146 |
+
cached = check_known_output(accession)
|
147 |
+
if cached:
|
148 |
+
print(f"β
Using cached result for {accession}")
|
149 |
+
return [[
|
150 |
+
cached["Sample ID"] or "unknown",
|
151 |
+
cached["Predicted Country"] or "unknown",
|
152 |
+
cached["Country Explanation"] or "unknown",
|
153 |
+
cached["Predicted Sample Type"] or "unknown",
|
154 |
+
cached["Sample Type Explanation"] or "unknown",
|
155 |
+
cached["Sources"] or "No Links",
|
156 |
+
cached["Time cost"]
|
157 |
+
]]
|
158 |
+
# only run when nothing in the cache
|
159 |
+
try:
|
160 |
+
print("try gemini pipeline: ",accession)
|
161 |
+
outputs = pipeline_classify_sample_location_cached(accession, stop_flag)
|
162 |
+
if stop_flag is not None and stop_flag.value:
|
163 |
+
print(f"π Skipped {accession} mid-pipeline.")
|
164 |
+
return []
|
165 |
+
# outputs = {'KU131308': {'isolate':'BRU18',
|
166 |
+
# 'country': {'brunei': ['ncbi',
|
167 |
+
# 'rag_llm-The text mentions "BRU18 Brunei Borneo" in a table listing various samples, and it is not described as ancient or archaeological.']},
|
168 |
+
# 'sample_type': {'modern':
|
169 |
+
# ['rag_llm-The text mentions "BRU18 Brunei Borneo" in a table listing various samples, and it is not described as ancient or archaeological.']},
|
170 |
+
# 'query_cost': 9.754999999999999e-05,
|
171 |
+
# 'time_cost': '24.776 seconds',
|
172 |
+
# 'source': ['https://doi.org/10.1007/s00439-015-1620-z',
|
173 |
+
# 'https://static-content.springer.com/esm/art%3A10.1007%2Fs00439-015-1620-z/MediaObjects/439_2015_1620_MOESM1_ESM.pdf',
|
174 |
+
# 'https://static-content.springer.com/esm/art%3A10.1007%2Fs00439-015-1620-z/MediaObjects/439_2015_1620_MOESM2_ESM.xls']}}
|
175 |
+
except Exception as e:
|
176 |
+
return []#, f"Error: {e}", f"Error: {e}", f"Error: {e}"
|
177 |
+
|
178 |
+
if accession not in outputs:
|
179 |
+
print("no accession in output ", accession)
|
180 |
+
return []#, "Accession not found in results.", "Accession not found in results.", "Accession not found in results."
|
181 |
+
|
182 |
+
row_score = []
|
183 |
+
rows = []
|
184 |
+
save_rows = []
|
185 |
+
for key in outputs:
|
186 |
+
pred_country, pred_sample, country_explanation, sample_explanation = "unknown","unknown","unknown","unknown"
|
187 |
+
for section, results in outputs[key].items():
|
188 |
+
if section == "country" or section =="sample_type":
|
189 |
+
pred_output = []#"\n".join(list(results.keys()))
|
190 |
+
output_explanation = ""
|
191 |
+
for result, content in results.items():
|
192 |
+
if len(result) == 0: result = "unknown"
|
193 |
+
if len(content) == 0: output_explanation = "unknown"
|
194 |
+
else:
|
195 |
+
output_explanation += 'Method: ' + "\nMethod: ".join(content) + "\n"
|
196 |
+
pred_output.append(result)
|
197 |
+
pred_output = "\n".join(pred_output)
|
198 |
+
if section == "country":
|
199 |
+
pred_country, country_explanation = pred_output, output_explanation
|
200 |
+
elif section == "sample_type":
|
201 |
+
pred_sample, sample_explanation = pred_output, output_explanation
|
202 |
+
if outputs[key]["isolate"].lower()!="unknown":
|
203 |
+
label = key + "(Isolate: " + outputs[key]["isolate"] + ")"
|
204 |
+
else: label = key
|
205 |
+
if len(outputs[key]["source"]) == 0: outputs[key]["source"] = ["No Links"]
|
206 |
+
row = {
|
207 |
+
"Sample ID": label or "unknown",
|
208 |
+
"Predicted Country": pred_country or "unknown",
|
209 |
+
"Country Explanation": country_explanation or "unknown",
|
210 |
+
"Predicted Sample Type":pred_sample or "unknown",
|
211 |
+
"Sample Type Explanation":sample_explanation or "unknown",
|
212 |
+
"Sources": "\n".join(outputs[key]["source"]) or "No Links",
|
213 |
+
"Time cost": outputs[key]["time_cost"]
|
214 |
+
}
|
215 |
+
#row_score.append(row)
|
216 |
+
rows.append(list(row.values()))
|
217 |
+
|
218 |
+
save_row = {
|
219 |
+
"Sample ID": label or "unknown",
|
220 |
+
"Predicted Country": pred_country or "unknown",
|
221 |
+
"Country Explanation": country_explanation or "unknown",
|
222 |
+
"Predicted Sample Type":pred_sample or "unknown",
|
223 |
+
"Sample Type Explanation":sample_explanation or "unknown",
|
224 |
+
"Sources": "\n".join(outputs[key]["source"]) or "No Links",
|
225 |
+
"Query_cost": outputs[key]["query_cost"],
|
226 |
+
"Time cost": outputs[key]["time_cost"]
|
227 |
+
}
|
228 |
+
#row_score.append(row)
|
229 |
+
save_rows.append(list(save_row.values()))
|
230 |
+
|
231 |
+
# #location_counts, (final_location, count) = compute_final_suggested_location(row_score)
|
232 |
+
# summary_lines = [f"### π§ Location Summary:\n"]
|
233 |
+
# summary_lines += [f"- **{loc}**: {cnt} times" for loc, cnt in location_counts.items()]
|
234 |
+
# summary_lines.append(f"\n**Final Suggested Location:** πΊοΈ **{final_location}** (mentioned {count} times)")
|
235 |
+
# summary = "\n".join(summary_lines)
|
236 |
+
|
237 |
+
# save the new running sample to known excel file
|
238 |
+
# try:
|
239 |
+
# df_new = pd.DataFrame(save_rows, columns=["Sample ID", "Predicted Country", "Country Explanation", "Predicted Sample Type", "Sample Type Explanation", "Sources", "Query_cost","Time cost"])
|
240 |
+
# if os.path.exists(KNOWN_OUTPUT_PATH):
|
241 |
+
# df_old = pd.read_excel(KNOWN_OUTPUT_PATH)
|
242 |
+
# df_combined = pd.concat([df_old, df_new]).drop_duplicates(subset="Sample ID")
|
243 |
+
# else:
|
244 |
+
# df_combined = df_new
|
245 |
+
# df_combined.to_excel(KNOWN_OUTPUT_PATH, index=False)
|
246 |
+
# except Exception as e:
|
247 |
+
# print(f"β οΈ Failed to save known output: {e}")
|
248 |
+
# try:
|
249 |
+
# df_new = pd.DataFrame(save_rows, columns=[
|
250 |
+
# "Sample ID", "Predicted Country", "Country Explanation",
|
251 |
+
# "Predicted Sample Type", "Sample Type Explanation",
|
252 |
+
# "Sources", "Query_cost", "Time cost"
|
253 |
+
# ])
|
254 |
+
|
255 |
+
# # β
Google Sheets API setup
|
256 |
+
# creds_dict = json.loads(os.environ["GCP_CREDS_JSON"])
|
257 |
+
# scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
|
258 |
+
# creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
|
259 |
+
# client = gspread.authorize(creds)
|
260 |
+
|
261 |
+
# # β
Open the known_samples sheet
|
262 |
+
# spreadsheet = client.open("known_samples") # Replace with your sheet name
|
263 |
+
# sheet = spreadsheet.sheet1
|
264 |
+
|
265 |
+
# # β
Read old data
|
266 |
+
# existing_data = sheet.get_all_values()
|
267 |
+
# if existing_data:
|
268 |
+
# df_old = pd.DataFrame(existing_data[1:], columns=existing_data[0])
|
269 |
+
# else:
|
270 |
+
# df_old = pd.DataFrame(columns=df_new.columns)
|
271 |
+
|
272 |
+
# # β
Combine and remove duplicates
|
273 |
+
# df_combined = pd.concat([df_old, df_new], ignore_index=True).drop_duplicates(subset="Sample ID")
|
274 |
+
|
275 |
+
# # β
Clear and write back
|
276 |
+
# sheet.clear()
|
277 |
+
# sheet.update([df_combined.columns.values.tolist()] + df_combined.values.tolist())
|
278 |
+
|
279 |
+
# except Exception as e:
|
280 |
+
# print(f"β οΈ Failed to save known output to Google Sheets: {e}")
|
281 |
+
try:
|
282 |
+
# Prepare as DataFrame
|
283 |
+
df_new = pd.DataFrame(save_rows, columns=[
|
284 |
+
"Sample ID", "Predicted Country", "Country Explanation",
|
285 |
+
"Predicted Sample Type", "Sample Type Explanation",
|
286 |
+
"Sources", "Query_cost", "Time cost"
|
287 |
+
])
|
288 |
+
|
289 |
+
# β
Setup Google Sheets
|
290 |
+
creds_dict = json.loads(os.environ["GCP_CREDS_JSON"])
|
291 |
+
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
|
292 |
+
creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
|
293 |
+
client = gspread.authorize(creds)
|
294 |
+
spreadsheet = client.open("known_samples")
|
295 |
+
sheet = spreadsheet.sheet1
|
296 |
+
|
297 |
+
# β
Read existing data
|
298 |
+
existing_data = sheet.get_all_values()
|
299 |
+
if existing_data:
|
300 |
+
df_old = pd.DataFrame(existing_data[1:], columns=existing_data[0])
|
301 |
+
else:
|
302 |
+
df_old = pd.DataFrame(columns=[
|
303 |
+
"Sample ID", "Actual_country", "Actual_sample_type", "Country Explanation",
|
304 |
+
"Match_country", "Match_sample_type", "Predicted Country", "Predicted Sample Type",
|
305 |
+
"Query_cost", "Sample Type Explanation", "Sources", "Time cost"
|
306 |
+
])
|
307 |
+
|
308 |
+
# β
Index by Sample ID
|
309 |
+
df_old.set_index("Sample ID", inplace=True)
|
310 |
+
df_new.set_index("Sample ID", inplace=True)
|
311 |
+
|
312 |
+
# β
Update only matching fields
|
313 |
+
update_columns = [
|
314 |
+
"Predicted Country", "Predicted Sample Type", "Country Explanation",
|
315 |
+
"Sample Type Explanation", "Sources", "Query_cost", "Time cost"
|
316 |
+
]
|
317 |
+
for idx, row in df_new.iterrows():
|
318 |
+
if idx not in df_old.index:
|
319 |
+
df_old.loc[idx] = "" # new row, fill empty first
|
320 |
+
for col in update_columns:
|
321 |
+
if pd.notna(row[col]) and row[col] != "":
|
322 |
+
df_old.at[idx, col] = row[col]
|
323 |
+
|
324 |
+
# β
Reset and write back
|
325 |
+
df_old.reset_index(inplace=True)
|
326 |
+
sheet.clear()
|
327 |
+
sheet.update([df_old.columns.values.tolist()] + df_old.values.tolist())
|
328 |
+
print("β
Match results saved to known_samples.")
|
329 |
+
|
330 |
+
except Exception as e:
|
331 |
+
print(f"β Failed to update known_samples: {e}")
|
332 |
+
|
333 |
+
|
334 |
+
return rows#, summary, labelAncient_Modern, explain_label
|
335 |
+
|
336 |
+
# save the batch input in excel file
|
337 |
+
# def save_to_excel(all_rows, summary_text, flag_text, filename):
|
338 |
+
# with pd.ExcelWriter(filename) as writer:
|
339 |
+
# # Save table
|
340 |
+
# df_new = pd.DataFrame(all_rows, columns=["Sample ID", "Predicted Country", "Country Explanation", "Predicted Sample Type", "Sample Type Explanation", "Sources", "Time cost"])
|
341 |
+
# df.to_excel(writer, sheet_name="Detailed Results", index=False)
|
342 |
+
# try:
|
343 |
+
# df_old = pd.read_excel(filename)
|
344 |
+
# except:
|
345 |
+
# df_old = pd.DataFrame([[]], columns=["Sample ID", "Predicted Country", "Country Explanation", "Predicted Sample Type", "Sample Type Explanation", "Sources", "Time cost"])
|
346 |
+
# df_combined = pd.concat([df_old, df_new]).drop_duplicates(subset="Sample ID")
|
347 |
+
# # if os.path.exists(filename):
|
348 |
+
# # df_old = pd.read_excel(filename)
|
349 |
+
# # df_combined = pd.concat([df_old, df_new]).drop_duplicates(subset="Sample ID")
|
350 |
+
# # else:
|
351 |
+
# # df_combined = df_new
|
352 |
+
# df_combined.to_excel(filename, index=False)
|
353 |
+
# # # Save summary
|
354 |
+
# # summary_df = pd.DataFrame({"Summary": [summary_text]})
|
355 |
+
# # summary_df.to_excel(writer, sheet_name="Summary", index=False)
|
356 |
+
|
357 |
+
# # # Save flag
|
358 |
+
# # flag_df = pd.DataFrame({"Flag": [flag_text]})
|
359 |
+
# # flag_df.to_excel(writer, sheet_name="Ancient_Modern_Flag", index=False)
|
360 |
+
# def save_to_excel(all_rows, summary_text, flag_text, filename):
|
361 |
+
# df_new = pd.DataFrame(all_rows, columns=[
|
362 |
+
# "Sample ID", "Predicted Country", "Country Explanation",
|
363 |
+
# "Predicted Sample Type", "Sample Type Explanation",
|
364 |
+
# "Sources", "Time cost"
|
365 |
+
# ])
|
366 |
+
|
367 |
+
# try:
|
368 |
+
# if os.path.exists(filename):
|
369 |
+
# df_old = pd.read_excel(filename)
|
370 |
+
# else:
|
371 |
+
# df_old = pd.DataFrame(columns=df_new.columns)
|
372 |
+
# except Exception as e:
|
373 |
+
# print(f"β οΈ Warning reading old Excel file: {e}")
|
374 |
+
# df_old = pd.DataFrame(columns=df_new.columns)
|
375 |
+
|
376 |
+
# #df_combined = pd.concat([df_new, df_old], ignore_index=True).drop_duplicates(subset="Sample ID", keep="first")
|
377 |
+
# df_old.set_index("Sample ID", inplace=True)
|
378 |
+
# df_new.set_index("Sample ID", inplace=True)
|
379 |
+
|
380 |
+
# df_old.update(df_new) # <-- update matching rows in df_old with df_new content
|
381 |
+
|
382 |
+
# df_combined = df_old.reset_index()
|
383 |
+
|
384 |
+
# try:
|
385 |
+
# df_combined.to_excel(filename, index=False)
|
386 |
+
# except Exception as e:
|
387 |
+
# print(f"β Failed to write Excel file {filename}: {e}")
|
388 |
+
def save_to_excel(all_rows, summary_text, flag_text, filename, is_resume=False):
|
389 |
+
df_new = pd.DataFrame(all_rows, columns=[
|
390 |
+
"Sample ID", "Predicted Country", "Country Explanation",
|
391 |
+
"Predicted Sample Type", "Sample Type Explanation",
|
392 |
+
"Sources", "Time cost"
|
393 |
+
])
|
394 |
+
|
395 |
+
if is_resume and os.path.exists(filename):
|
396 |
+
try:
|
397 |
+
df_old = pd.read_excel(filename)
|
398 |
+
except Exception as e:
|
399 |
+
print(f"β οΈ Warning reading old Excel file: {e}")
|
400 |
+
df_old = pd.DataFrame(columns=df_new.columns)
|
401 |
+
|
402 |
+
# Set index and update existing rows
|
403 |
+
df_old.set_index("Sample ID", inplace=True)
|
404 |
+
df_new.set_index("Sample ID", inplace=True)
|
405 |
+
df_old.update(df_new)
|
406 |
+
|
407 |
+
df_combined = df_old.reset_index()
|
408 |
+
else:
|
409 |
+
# If not resuming or file doesn't exist, just use new rows
|
410 |
+
df_combined = df_new
|
411 |
+
|
412 |
+
try:
|
413 |
+
df_combined.to_excel(filename, index=False)
|
414 |
+
except Exception as e:
|
415 |
+
print(f"β Failed to write Excel file {filename}: {e}")
|
416 |
+
|
417 |
+
|
418 |
+
# save the batch input in JSON file
|
419 |
+
def save_to_json(all_rows, summary_text, flag_text, filename):
|
420 |
+
output_dict = {
|
421 |
+
"Detailed_Results": all_rows#, # <-- make sure this is a plain list, not a DataFrame
|
422 |
+
# "Summary_Text": summary_text,
|
423 |
+
# "Ancient_Modern_Flag": flag_text
|
424 |
+
}
|
425 |
+
|
426 |
+
# If all_rows is a DataFrame, convert it
|
427 |
+
if isinstance(all_rows, pd.DataFrame):
|
428 |
+
output_dict["Detailed_Results"] = all_rows.to_dict(orient="records")
|
429 |
+
|
430 |
+
with open(filename, "w") as external_file:
|
431 |
+
json.dump(output_dict, external_file, indent=2)
|
432 |
+
|
433 |
+
# save the batch input in Text file
|
434 |
+
def save_to_txt(all_rows, summary_text, flag_text, filename):
|
435 |
+
if isinstance(all_rows, pd.DataFrame):
|
436 |
+
detailed_results = all_rows.to_dict(orient="records")
|
437 |
+
output = ""
|
438 |
+
#output += ",".join(list(detailed_results[0].keys())) + "\n\n"
|
439 |
+
output += ",".join([str(k) for k in detailed_results[0].keys()]) + "\n\n"
|
440 |
+
for r in detailed_results:
|
441 |
+
output += ",".join([str(v) for v in r.values()]) + "\n\n"
|
442 |
+
with open(filename, "w") as f:
|
443 |
+
f.write("=== Detailed Results ===\n")
|
444 |
+
f.write(output + "\n")
|
445 |
+
|
446 |
+
# f.write("\n=== Summary ===\n")
|
447 |
+
# f.write(summary_text + "\n")
|
448 |
+
|
449 |
+
# f.write("\n=== Ancient/Modern Flag ===\n")
|
450 |
+
# f.write(flag_text + "\n")
|
451 |
+
|
452 |
+
def save_batch_output(all_rows, output_type, summary_text=None, flag_text=None):
|
453 |
+
tmp_dir = tempfile.mkdtemp()
|
454 |
+
|
455 |
+
#html_table = all_rows.value # assuming this is stored somewhere
|
456 |
+
|
457 |
+
# Parse back to DataFrame
|
458 |
+
#all_rows = pd.read_html(all_rows)[0] # [0] because read_html returns a list
|
459 |
+
all_rows = pd.read_html(StringIO(all_rows))[0]
|
460 |
+
print(all_rows)
|
461 |
+
|
462 |
+
if output_type == "Excel":
|
463 |
+
file_path = f"{tmp_dir}/batch_output.xlsx"
|
464 |
+
save_to_excel(all_rows, summary_text, flag_text, file_path)
|
465 |
+
elif output_type == "JSON":
|
466 |
+
file_path = f"{tmp_dir}/batch_output.json"
|
467 |
+
save_to_json(all_rows, summary_text, flag_text, file_path)
|
468 |
+
print("Done with JSON")
|
469 |
+
elif output_type == "TXT":
|
470 |
+
file_path = f"{tmp_dir}/batch_output.txt"
|
471 |
+
save_to_txt(all_rows, summary_text, flag_text, file_path)
|
472 |
+
else:
|
473 |
+
return gr.update(visible=False) # invalid option
|
474 |
+
|
475 |
+
return gr.update(value=file_path, visible=True)
|
476 |
+
# save cost by checking the known outputs
|
477 |
+
|
478 |
+
# def check_known_output(accession):
|
479 |
+
# if not os.path.exists(KNOWN_OUTPUT_PATH):
|
480 |
+
# return None
|
481 |
+
|
482 |
+
# try:
|
483 |
+
# df = pd.read_excel(KNOWN_OUTPUT_PATH)
|
484 |
+
# match = re.search(r"\b[A-Z]{2,4}\d{4,}", accession)
|
485 |
+
# if match:
|
486 |
+
# accession = match.group(0)
|
487 |
+
|
488 |
+
# matched = df[df["Sample ID"].str.contains(accession, case=False, na=False)]
|
489 |
+
# if not matched.empty:
|
490 |
+
# return matched.iloc[0].to_dict() # Return the cached row
|
491 |
+
# except Exception as e:
|
492 |
+
# print(f"β οΈ Failed to load known samples: {e}")
|
493 |
+
# return None
|
494 |
+
|
495 |
+
# def check_known_output(accession):
|
496 |
+
# try:
|
497 |
+
# # β
Load credentials from Hugging Face secret
|
498 |
+
# creds_dict = json.loads(os.environ["GCP_CREDS_JSON"])
|
499 |
+
# scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
|
500 |
+
# creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
|
501 |
+
# client = gspread.authorize(creds)
|
502 |
+
|
503 |
+
# # β
Open the known_samples sheet
|
504 |
+
# spreadsheet = client.open("known_samples") # Replace with your sheet name
|
505 |
+
# sheet = spreadsheet.sheet1
|
506 |
+
|
507 |
+
# # β
Read all rows
|
508 |
+
# data = sheet.get_all_values()
|
509 |
+
# if not data:
|
510 |
+
# return None
|
511 |
+
|
512 |
+
# df = pd.DataFrame(data[1:], columns=data[0]) # Skip header row
|
513 |
+
|
514 |
+
# # β
Normalize accession pattern
|
515 |
+
# match = re.search(r"\b[A-Z]{2,4}\d{4,}", accession)
|
516 |
+
# if match:
|
517 |
+
# accession = match.group(0)
|
518 |
+
|
519 |
+
# matched = df[df["Sample ID"].str.contains(accession, case=False, na=False)]
|
520 |
+
# if not matched.empty:
|
521 |
+
# return matched.iloc[0].to_dict()
|
522 |
+
|
523 |
+
# except Exception as e:
|
524 |
+
# print(f"β οΈ Failed to load known samples from Google Sheets: {e}")
|
525 |
+
# return None
|
526 |
+
def check_known_output(accession):
|
527 |
+
try:
|
528 |
+
# β
Load credentials from Hugging Face secret
|
529 |
+
creds_dict = json.loads(os.environ["GCP_CREDS_JSON"])
|
530 |
+
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
|
531 |
+
creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
|
532 |
+
client = gspread.authorize(creds)
|
533 |
+
|
534 |
+
spreadsheet = client.open("known_samples")
|
535 |
+
sheet = spreadsheet.sheet1
|
536 |
+
|
537 |
+
data = sheet.get_all_values()
|
538 |
+
if not data:
|
539 |
+
print("β οΈ Google Sheet 'known_samples' is empty.")
|
540 |
+
return None
|
541 |
+
|
542 |
+
df = pd.DataFrame(data[1:], columns=data[0])
|
543 |
+
if "Sample ID" not in df.columns:
|
544 |
+
print("β Column 'Sample ID' not found in Google Sheet.")
|
545 |
+
return None
|
546 |
+
|
547 |
+
match = re.search(r"\b[A-Z]{2,4}\d{4,}", accession)
|
548 |
+
if match:
|
549 |
+
accession = match.group(0)
|
550 |
+
|
551 |
+
matched = df[df["Sample ID"].str.contains(accession, case=False, na=False)]
|
552 |
+
if not matched.empty:
|
553 |
+
#return matched.iloc[0].to_dict()
|
554 |
+
row = matched.iloc[0]
|
555 |
+
country = row.get("Predicted Country", "").strip().lower()
|
556 |
+
sample_type = row.get("Predicted Sample Type", "").strip().lower()
|
557 |
+
|
558 |
+
if country and country != "unknown" and sample_type and sample_type != "unknown":
|
559 |
+
return row.to_dict()
|
560 |
+
else:
|
561 |
+
print(f"β οΈ Accession {accession} found but country/sample_type is unknown or empty.")
|
562 |
+
return None
|
563 |
+
else:
|
564 |
+
print(f"π Accession {accession} not found in known_samples.")
|
565 |
+
return None
|
566 |
+
|
567 |
+
except Exception as e:
|
568 |
+
import traceback
|
569 |
+
print("β Exception occurred during check_known_output:")
|
570 |
+
traceback.print_exc()
|
571 |
+
return None
|
572 |
+
|
573 |
+
|
574 |
+
def hash_user_id(user_input):
|
575 |
+
return hashlib.sha256(user_input.encode()).hexdigest()
|
576 |
+
|
577 |
+
# β
Load and save usage count
|
578 |
+
|
579 |
+
# def load_user_usage():
|
580 |
+
# if not os.path.exists(USER_USAGE_TRACK_FILE):
|
581 |
+
# return {}
|
582 |
+
|
583 |
+
# try:
|
584 |
+
# with open(USER_USAGE_TRACK_FILE, "r") as f:
|
585 |
+
# content = f.read().strip()
|
586 |
+
# if not content:
|
587 |
+
# return {} # file is empty
|
588 |
+
# return json.loads(content)
|
589 |
+
# except (json.JSONDecodeError, ValueError):
|
590 |
+
# print("β οΈ Warning: user_usage.json is corrupted or invalid. Resetting.")
|
591 |
+
# return {} # fallback to empty dict
|
592 |
+
# def load_user_usage():
|
593 |
+
# try:
|
594 |
+
# creds_dict = json.loads(os.environ["GCP_CREDS_JSON"])
|
595 |
+
# scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
|
596 |
+
# creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
|
597 |
+
# client = gspread.authorize(creds)
|
598 |
+
|
599 |
+
# sheet = client.open("user_usage_log").sheet1
|
600 |
+
# data = sheet.get_all_records() # Assumes columns: email, usage_count
|
601 |
+
|
602 |
+
# usage = {}
|
603 |
+
# for row in data:
|
604 |
+
# email = row.get("email", "").strip().lower()
|
605 |
+
# count = int(row.get("usage_count", 0))
|
606 |
+
# if email:
|
607 |
+
# usage[email] = count
|
608 |
+
# return usage
|
609 |
+
# except Exception as e:
|
610 |
+
# print(f"β οΈ Failed to load user usage from Google Sheets: {e}")
|
611 |
+
# return {}
|
612 |
+
# def load_user_usage():
|
613 |
+
# try:
|
614 |
+
# parent_id = pipeline.get_or_create_drive_folder("mtDNA-Location-Classifier")
|
615 |
+
# iterate3_id = pipeline.get_or_create_drive_folder("iterate3", parent_id=parent_id)
|
616 |
+
|
617 |
+
# found = pipeline.find_drive_file("user_usage_log.json", parent_id=iterate3_id)
|
618 |
+
# if not found:
|
619 |
+
# return {} # not found, start fresh
|
620 |
+
|
621 |
+
# #file_id = found[0]["id"]
|
622 |
+
# file_id = found
|
623 |
+
# content = pipeline.download_drive_file_content(file_id)
|
624 |
+
# return json.loads(content.strip()) if content.strip() else {}
|
625 |
+
|
626 |
+
# except Exception as e:
|
627 |
+
# print(f"β οΈ Failed to load user_usage_log.json from Google Drive: {e}")
|
628 |
+
# return {}
|
629 |
+
def load_user_usage():
|
630 |
+
try:
|
631 |
+
creds_dict = json.loads(os.environ["GCP_CREDS_JSON"])
|
632 |
+
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
|
633 |
+
creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
|
634 |
+
client = gspread.authorize(creds)
|
635 |
+
|
636 |
+
sheet = client.open("user_usage_log").sheet1
|
637 |
+
data = sheet.get_all_values()
|
638 |
+
print("data: ", data)
|
639 |
+
print("π§ͺ Raw header row from sheet:", data[0])
|
640 |
+
print("π§ͺ Character codes in each header:")
|
641 |
+
for h in data[0]:
|
642 |
+
print([ord(c) for c in h])
|
643 |
+
|
644 |
+
if not data or len(data) < 2:
|
645 |
+
print("β οΈ Sheet is empty or missing rows.")
|
646 |
+
return {}
|
647 |
+
|
648 |
+
headers = [h.strip().lower() for h in data[0]]
|
649 |
+
if "email" not in headers or "usage_count" not in headers:
|
650 |
+
print("β Header format incorrect. Must have 'email' and 'usage_count'.")
|
651 |
+
return {}
|
652 |
+
|
653 |
+
permitted_index = headers.index("permitted_samples") if "permitted_samples" in headers else None
|
654 |
+
df = pd.DataFrame(data[1:], columns=headers)
|
655 |
+
|
656 |
+
usage = {}
|
657 |
+
permitted = {}
|
658 |
+
for _, row in df.iterrows():
|
659 |
+
email = row.get("email", "").strip().lower()
|
660 |
+
try:
|
661 |
+
#count = int(row.get("usage_count", 0))
|
662 |
+
try:
|
663 |
+
count = int(float(row.get("usage_count", 0)))
|
664 |
+
except Exception:
|
665 |
+
print(f"β οΈ Invalid usage_count for {email}: {row.get('usage_count')}")
|
666 |
+
count = 0
|
667 |
+
|
668 |
+
if email:
|
669 |
+
usage[email] = count
|
670 |
+
if permitted_index is not None:
|
671 |
+
try:
|
672 |
+
permitted_count = int(float(row.get("permitted_samples", 50)))
|
673 |
+
permitted[email] = permitted_count
|
674 |
+
except:
|
675 |
+
permitted[email] = 50
|
676 |
+
|
677 |
+
except ValueError:
|
678 |
+
print(f"β οΈ Invalid usage_count for {email}: {row.get('usage_count')}")
|
679 |
+
return usage, permitted
|
680 |
+
|
681 |
+
except Exception as e:
|
682 |
+
print(f"β Error in load_user_usage: {e}")
|
683 |
+
return {}, {}
|
684 |
+
|
685 |
+
|
686 |
+
|
687 |
+
# def save_user_usage(usage):
|
688 |
+
# with open(USER_USAGE_TRACK_FILE, "w") as f:
|
689 |
+
# json.dump(usage, f, indent=2)
|
690 |
+
|
691 |
+
# def save_user_usage(usage_dict):
|
692 |
+
# try:
|
693 |
+
# creds_dict = json.loads(os.environ["GCP_CREDS_JSON"])
|
694 |
+
# scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
|
695 |
+
# creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
|
696 |
+
# client = gspread.authorize(creds)
|
697 |
+
|
698 |
+
# sheet = client.open("user_usage_log").sheet1
|
699 |
+
# sheet.clear() # clear old contents first
|
700 |
+
|
701 |
+
# # Write header + rows
|
702 |
+
# rows = [["email", "usage_count"]] + [[email, count] for email, count in usage_dict.items()]
|
703 |
+
# sheet.update(rows)
|
704 |
+
# except Exception as e:
|
705 |
+
# print(f"β Failed to save user usage to Google Sheets: {e}")
|
706 |
+
# def save_user_usage(usage_dict):
|
707 |
+
# try:
|
708 |
+
# parent_id = pipeline.get_or_create_drive_folder("mtDNA-Location-Classifier")
|
709 |
+
# iterate3_id = pipeline.get_or_create_drive_folder("iterate3", parent_id=parent_id)
|
710 |
+
|
711 |
+
# import tempfile
|
712 |
+
# tmp_path = os.path.join(tempfile.gettempdir(), "user_usage_log.json")
|
713 |
+
# print("πΎ Saving this usage dict:", usage_dict)
|
714 |
+
# with open(tmp_path, "w") as f:
|
715 |
+
# json.dump(usage_dict, f, indent=2)
|
716 |
+
|
717 |
+
# pipeline.upload_file_to_drive(tmp_path, "user_usage_log.json", iterate3_id)
|
718 |
+
|
719 |
+
# except Exception as e:
|
720 |
+
# print(f"β Failed to save user_usage_log.json to Google Drive: {e}")
|
721 |
+
# def save_user_usage(usage_dict):
|
722 |
+
# try:
|
723 |
+
# creds_dict = json.loads(os.environ["GCP_CREDS_JSON"])
|
724 |
+
# scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
|
725 |
+
# creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
|
726 |
+
# client = gspread.authorize(creds)
|
727 |
+
|
728 |
+
# spreadsheet = client.open("user_usage_log")
|
729 |
+
# sheet = spreadsheet.sheet1
|
730 |
+
|
731 |
+
# # Step 1: Convert new usage to DataFrame
|
732 |
+
# df_new = pd.DataFrame(list(usage_dict.items()), columns=["email", "usage_count"])
|
733 |
+
# df_new["email"] = df_new["email"].str.strip().str.lower()
|
734 |
+
|
735 |
+
# # Step 2: Load existing data
|
736 |
+
# existing_data = sheet.get_all_values()
|
737 |
+
# print("π§ͺ Sheet existing_data:", existing_data)
|
738 |
+
|
739 |
+
# # Try to load old data
|
740 |
+
# if existing_data and len(existing_data[0]) >= 1:
|
741 |
+
# df_old = pd.DataFrame(existing_data[1:], columns=existing_data[0])
|
742 |
+
|
743 |
+
# # Fix missing columns
|
744 |
+
# if "email" not in df_old.columns:
|
745 |
+
# df_old["email"] = ""
|
746 |
+
# if "usage_count" not in df_old.columns:
|
747 |
+
# df_old["usage_count"] = 0
|
748 |
+
|
749 |
+
# df_old["email"] = df_old["email"].str.strip().str.lower()
|
750 |
+
# df_old["usage_count"] = pd.to_numeric(df_old["usage_count"], errors="coerce").fillna(0).astype(int)
|
751 |
+
# else:
|
752 |
+
# df_old = pd.DataFrame(columns=["email", "usage_count"])
|
753 |
+
|
754 |
+
# # Step 3: Merge
|
755 |
+
# df_combined = pd.concat([df_old, df_new], ignore_index=True)
|
756 |
+
# df_combined = df_combined.groupby("email", as_index=False).sum()
|
757 |
+
|
758 |
+
# # Step 4: Write back
|
759 |
+
# sheet.clear()
|
760 |
+
# sheet.update([df_combined.columns.tolist()] + df_combined.astype(str).values.tolist())
|
761 |
+
# print("β
Saved user usage to user_usage_log sheet.")
|
762 |
+
|
763 |
+
# except Exception as e:
|
764 |
+
# print(f"β Failed to save user usage to Google Sheets: {e}")
|
765 |
+
def save_user_usage(usage_dict):
|
766 |
+
try:
|
767 |
+
creds_dict = json.loads(os.environ["GCP_CREDS_JSON"])
|
768 |
+
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
|
769 |
+
creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope)
|
770 |
+
client = gspread.authorize(creds)
|
771 |
+
|
772 |
+
spreadsheet = client.open("user_usage_log")
|
773 |
+
sheet = spreadsheet.sheet1
|
774 |
+
|
775 |
+
# Build new df
|
776 |
+
df_new = pd.DataFrame(list(usage_dict.items()), columns=["email", "usage_count"])
|
777 |
+
df_new["email"] = df_new["email"].str.strip().str.lower()
|
778 |
+
df_new["usage_count"] = pd.to_numeric(df_new["usage_count"], errors="coerce").fillna(0).astype(int)
|
779 |
+
|
780 |
+
# Read existing data
|
781 |
+
existing_data = sheet.get_all_values()
|
782 |
+
if existing_data and len(existing_data[0]) >= 2:
|
783 |
+
df_old = pd.DataFrame(existing_data[1:], columns=existing_data[0])
|
784 |
+
df_old["email"] = df_old["email"].str.strip().str.lower()
|
785 |
+
df_old["usage_count"] = pd.to_numeric(df_old["usage_count"], errors="coerce").fillna(0).astype(int)
|
786 |
+
else:
|
787 |
+
df_old = pd.DataFrame(columns=["email", "usage_count"])
|
788 |
+
|
789 |
+
# β
Overwrite specific emails only
|
790 |
+
df_old = df_old.set_index("email")
|
791 |
+
for email, count in usage_dict.items():
|
792 |
+
email = email.strip().lower()
|
793 |
+
df_old.loc[email, "usage_count"] = count
|
794 |
+
df_old = df_old.reset_index()
|
795 |
+
|
796 |
+
# Save
|
797 |
+
sheet.clear()
|
798 |
+
sheet.update([df_old.columns.tolist()] + df_old.astype(str).values.tolist())
|
799 |
+
print("β
Saved user usage to user_usage_log sheet.")
|
800 |
+
|
801 |
+
except Exception as e:
|
802 |
+
print(f"β Failed to save user usage to Google Sheets: {e}")
|
803 |
+
|
804 |
+
|
805 |
+
|
806 |
+
|
807 |
+
# def increment_usage(user_id, num_samples=1):
|
808 |
+
# usage = load_user_usage()
|
809 |
+
# if user_id not in usage:
|
810 |
+
# usage[user_id] = 0
|
811 |
+
# usage[user_id] += num_samples
|
812 |
+
# save_user_usage(usage)
|
813 |
+
# return usage[user_id]
|
814 |
+
# def increment_usage(email: str, count: int):
|
815 |
+
# usage = load_user_usage()
|
816 |
+
# email_key = email.strip().lower()
|
817 |
+
# usage[email_key] = usage.get(email_key, 0) + count
|
818 |
+
# save_user_usage(usage)
|
819 |
+
# return usage[email_key]
|
820 |
+
def increment_usage(email: str, count: int = 1):
|
821 |
+
usage, permitted = load_user_usage()
|
822 |
+
email_key = email.strip().lower()
|
823 |
+
#usage[email_key] = usage.get(email_key, 0) + count
|
824 |
+
current = usage.get(email_key, 0)
|
825 |
+
new_value = current + count
|
826 |
+
max_allowed = permitted.get(email_key) or 50
|
827 |
+
usage[email_key] = max(current, new_value) # β
Prevent overwrite with lower
|
828 |
+
print(f"π§ͺ increment_usage saving: {email_key=} {current=} + {count=} => {usage[email_key]=}")
|
829 |
+
print("max allow is: ", max_allowed)
|
830 |
+
save_user_usage(usage)
|
831 |
+
return usage[email_key], max_allowed
|
832 |
+
|
833 |
+
|
834 |
+
# run the batch
|
835 |
+
def summarize_batch(file=None, raw_text="", resume_file=None, user_email="",
|
836 |
+
stop_flag=None, output_file_path=None,
|
837 |
+
limited_acc=50, yield_callback=None):
|
838 |
+
if user_email:
|
839 |
+
limited_acc += 10
|
840 |
+
accessions, error = extract_accessions_from_input(file, raw_text)
|
841 |
+
if error:
|
842 |
+
#return [], "", "", f"Error: {error}"
|
843 |
+
return [], f"Error: {error}", 0, "", ""
|
844 |
+
if resume_file:
|
845 |
+
accessions = get_incomplete_accessions(resume_file)
|
846 |
+
tmp_dir = tempfile.mkdtemp()
|
847 |
+
if not output_file_path:
|
848 |
+
if resume_file:
|
849 |
+
output_file_path = os.path.join(tmp_dir, resume_file)
|
850 |
+
else:
|
851 |
+
output_file_path = os.path.join(tmp_dir, "batch_output_live.xlsx")
|
852 |
+
|
853 |
+
all_rows = []
|
854 |
+
# all_summaries = []
|
855 |
+
# all_flags = []
|
856 |
+
progress_lines = []
|
857 |
+
warning = ""
|
858 |
+
if len(accessions) > limited_acc:
|
859 |
+
accessions = accessions[:limited_acc]
|
860 |
+
warning = f"Your number of accessions is more than the {limited_acc}, only handle first {limited_acc} accessions"
|
861 |
+
for i, acc in enumerate(accessions):
|
862 |
+
if stop_flag and stop_flag.value:
|
863 |
+
line = f"π Stopped at {acc} ({i+1}/{len(accessions)})"
|
864 |
+
progress_lines.append(line)
|
865 |
+
if yield_callback:
|
866 |
+
yield_callback(line)
|
867 |
+
print("π User requested stop.")
|
868 |
+
break
|
869 |
+
print(f"[{i+1}/{len(accessions)}] Processing {acc}")
|
870 |
+
try:
|
871 |
+
# rows, summary, label, explain = summarize_results(acc)
|
872 |
+
rows = summarize_results(acc)
|
873 |
+
all_rows.extend(rows)
|
874 |
+
# all_summaries.append(f"**{acc}**\n{summary}")
|
875 |
+
# all_flags.append(f"**{acc}**\n### πΊ Ancient/Modern Flag\n**{label}**\n\n_Explanation:_ {explain}")
|
876 |
+
#save_to_excel(all_rows, summary_text="", flag_text="", filename=output_file_path)
|
877 |
+
save_to_excel(all_rows, summary_text="", flag_text="", filename=output_file_path, is_resume=bool(resume_file))
|
878 |
+
line = f"β
Processed {acc} ({i+1}/{len(accessions)})"
|
879 |
+
progress_lines.append(line)
|
880 |
+
if yield_callback:
|
881 |
+
yield_callback(f"β
Processed {acc} ({i+1}/{len(accessions)})")
|
882 |
+
except Exception as e:
|
883 |
+
print(f"β Failed to process {acc}: {e}")
|
884 |
+
continue
|
885 |
+
#all_summaries.append(f"**{acc}**: Failed - {e}")
|
886 |
+
#progress_lines.append(f"β
Processed {acc} ({i+1}/{len(accessions)})")
|
887 |
+
limited_acc -= 1
|
888 |
+
"""for row in all_rows:
|
889 |
+
source_column = row[2] # Assuming the "Source" is in the 3rd column (index 2)
|
890 |
+
|
891 |
+
if source_column.startswith("http"): # Check if the source is a URL
|
892 |
+
# Wrap it with HTML anchor tags to make it clickable
|
893 |
+
row[2] = f'<a href="{source_column}" target="_blank" style="color: blue; text-decoration: underline;">{source_column}</a>'"""
|
894 |
+
if not warning:
|
895 |
+
warning = f"You only have {limited_acc} left"
|
896 |
+
if user_email.strip():
|
897 |
+
user_hash = hash_user_id(user_email)
|
898 |
+
total_queries = increment_usage(user_hash, len(all_rows))
|
899 |
+
else:
|
900 |
+
total_queries = 0
|
901 |
+
yield_callback("β
Finished!")
|
902 |
+
|
903 |
+
# summary_text = "\n\n---\n\n".join(all_summaries)
|
904 |
+
# flag_text = "\n\n---\n\n".join(all_flags)
|
905 |
+
#return all_rows, summary_text, flag_text, gr.update(visible=True), gr.update(visible=False)
|
906 |
+
#return all_rows, gr.update(visible=True), gr.update(visible=False)
|
907 |
return all_rows, output_file_path, total_queries, "\n".join(progress_lines), warning
|