File size: 60,556 Bytes
25d2784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
import xlrd2 as xlrd
import unicodedata
import spacy
import inflect
nlp = spacy.load("es_core_news_sm")
#nlp = spacy.load("es_dep_news_trf")
from inflector import Inflector, Spanish
inflector = Inflector(Spanish)
import speech_recognition as sr
import os
import requests
from requests.auth import HTTPBasicAuth
import asyncio
import aiohttp

auth=aiohttp.BasicAuth('1234','API')
base_url='https://orva.tedcas.com/api/'


xlrd.xlsx.ensure_elementtree_imported(False, None)
xlrd.xlsx.Element_has_iter = True

async def buscar_faq(query, barra):
    archivo = "C:/Users/15572890/Desktop\StockPrediction\Coding\CorrelacionStocks\APIS-StockPlatforms\APIs\QuiroHelpNLP\QuirohelpWebapp/preguntas_qh_tags2.xlsx"
    df = pd.read_excel(archivo, engine="openpyxl")
    p = 0
    result = query
    df2 = []
    print("result" + str(result))
    for index, row in df.iterrows():
        list_words = df.loc[index, 'TAGS2']
        list_words = list_words.split(",")
        df2.append(list_words)
    ls5 = []
    list_words=[]
    for indexw, word in enumerate(result):
        result[indexw]=inflector.singularize(str(word))          
    count_words = np.zeros(len(df.index), dtype=int)
    for index1,row in enumerate(df2):
        ls4=[]
        for word in row:
            if barra == 0:
                if word != []:
                    p = 0
                    for num in range(100):
                        num = num / 10
                        num = str(num)
                        if word == num:
                            num = num.split(".")
                            ls4.append(num[0])
                            ls4.append("con")
                            ls4.append(num[1])
                            p = p + 1
                    if p == 0:
                        ls4.append(word)
            if barra == 1:
                ls4.append(word)
        ls5.append(ls4)
        for resulted in result:
            for index2, word in enumerate(ls5[index1]):
                            if str(resulted)=="maya":
                                resulted="malla"
                            if str(resulted)=="pilos"or str(resulted)=="pilo":
                                resulted="philo"
                            if str(resulted)=="filos"or str(resulted)=="filo":
                                resulted="philo"
                            if str(resulted)=="sinces" or str(resulted)=="sinc":
                                resulted="synthe"
                            if str(resulted)=="sintes" or str(resulted)=="sint":
                                resulted="synthe" 
                            if str(resulted)=="axos" or str(resulted)=="axo":
                                resulted="axso"       
                            if str(resulted)=="uno":
                                resulted="1"
                            if str(resulted)=="dos" or str(resulted)=="do":
                                resulted="2"
                            if str(resulted)=="tres" or str(resulted)=="tr":
                                resulted="3"
                            if str(resulted)=="cuatro":
                                resulted="4"
                            if str(resulted)=="cinco":
                                resulted="5"
                            if str(resulted)=="seis"or str(resulted)=="sei":
                                resulted="6"
                            if str(resulted)=="siete":
                                resulted="7"
                            if str(resulted)=="ocho":
                                resulted="8"
                            if str(resulted)=="nueve":
                                resulted="9"
                            if str(resulted)=="cero":
                                resulted="0"
                            if str(resulted)=="veintiuno":
                                resulted="21"
                            if str(resulted)=="veinte":
                                resulted="20"
                            if str(resulted)=="veintidos"or str(resulted)=="veintido" :
                                resulted="22"
                            if str(resulted)=="veintitres" or str(resulted)=="veintitre" :
                                resulted="23"
                            if str(resulted)=="veinticuatro":
                                resulted="24"
                            if str(resulted)=="veinticinco":
                                resulted="25"
                            if str(resulted)=="veintiseis"or str(resulted)=="veintisei" :
                                resulted="26"
                            if str(resulted)=="veintisiete":
                                resulted="27"
                            if str(resulted)=="veintiocho":
                                resulted="28"
                            if str(resulted)=="veintinueve":
                                resulted="29"
                            if str(resulted)=="treinta":
                                resulted="30"
                            if str(remove_accents(word)).lower() == str(remove_accents(resulted)).lower():
                                count_words[index1]=count_words[index1]+1
                                ls5[index1].pop(index2)

        indexmax = np.argwhere(count_words == np.amax(count_words))
        output=[]
        preguntas={}
        df = xlrd.open_workbook(archivo)
        df = df.sheet_by_index(0)
        if not np.all(count_words == 0):
            for indexin in indexmax:
                sq = df.cell(int(indexin) + 1, 3)
                sr = df.cell(int(indexin) + 1, 4)
                sq = str(sq)
                sr = str(sr)
                sq = sq.split("'")
                sr = sr.split("'")
                output.append(f" {sq[1]} {sr[1]} ")
    return output
    
async def boton_pdf_video(especialidad, field_tipo, nid):
    connector = aiohttp.TCPConnector(ssl=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        r = await session.get(f'{base_url}all-content/{especialidad}', auth=auth)
        data = await r.json()

        nid_list = []
        titulos = {}

        if nid == "0":
            for text in data:
                if text['type'] == "Intervencion":
                    nid_list.append(text['nid'])
        else:
            nid_list.append(nid)

        for nid1 in nid_list:
            r1 = await session.get(f'{base_url}intervenciones/{nid1}', auth=auth)
            data1 = await r1.json()
            data1 = data1[0]
            files = {}

            if field_tipo in data1:
                file_list = data1[field_tipo]
                for file in file_list:
                    if field_tipo == 'field_pdf':
                        files[file['descripcion']] = "https://orva.tedcas.com/"+str(file['url'])
                    if field_tipo == 'field_video':
                        files[file['descripcion']] = str(file['url'])

                titulos[data1['title']] = files
            else:
                if nid == '0':
                    nid = '0'
                else:
                    print("nid dentro del if " + str(nid))
                    files["No hay archivos"] = ""
                    titulos["No hay archivos"] = files
                    return {}

        return titulos

async def boton_word_ppt(especialidad, field_tipo, nid):
    connector = aiohttp.TCPConnector(ssl=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        r = await session.get(f'{base_url}all-content/{especialidad}', auth=auth)
        data = await r.json()

        nid_list = []
        files = {}

        if nid == '0':
            for text in data:
                if text['type'] == "Intervencion":
                    nid_list.append(text['nid'])
        else:
            nid_list.append(nid)

        for nid1 in nid_list:
            r1 = await session.get(f'{base_url}intervenciones/{nid1}', auth=auth)
            data1 = await r1.json()
            data1 = data1[0]
            if len(data1[field_tipo]) != 0:
                files[data1['title']] = "https://orva.tedcas.com/"+str(data1[field_tipo])
            if len(data1[field_tipo]) == 0 and nid != '0':
                files["No hay archivos"] = ""
                return {}

        return files

async def boton_materiales(especialidad, nid):
    connector = aiohttp.TCPConnector(ssl=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        cajas = {}

        if nid == '0':
            r = await session.get(f'{base_url}listado_completo_cajas/{especialidad}', auth=auth)
            data = await r.json()
            for text in data:
                cajas[text['title']] = text['nid']
            cajas[''] = "si hay"
        else:
            r = await session.get(f'{base_url}intervenciones/{nid}', auth=auth)
            data = await r.json()
            data = data[0]
            if 'field_cajas' in data:
                data = data['field_cajas']
                for text in data:
                    cajas[text['caja']] = text['id']
                cajas[''] = "si hay"
            else:
                if nid != 0:
                    cajas[''] = ""
                    return {}
        return cajas
    
async def cargar_base_datos(query, url):
    k1 = None
    output = []
    connector = aiohttp.TCPConnector(ssl=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        r = await session.get('https://orva.tedcas.com/api/all-content/'+str(url), auth=auth)
        data = await r.json()
        count_words = np.zeros(len(data), dtype=int)
        query1 = []
        for z in query:
            cont = 0
            for num in range(100):
                num = num / 10
                if z == str(num):
                    z = str(num).split('.')
                    query1.append(z)
                    cont = cont + 1
            if z == 'con':
                cont = cont + 1
            if cont == 0:
                query1.append(z)
        for i in range(len(data)):
            cont_palabras = 0
            data1 = data[i]
            titulo = str(data1['title']).lower()
            titulo = remove_accents(titulo)
            titulo = titulo.split(' ')
            for index, j in enumerate(titulo):
                for index1, j1 in enumerate(titulo):
                    if index1 != index:
                        if j == j1:
                            titulo.pop(index1)
            for index, j in enumerate(titulo):
                for num in range(100):
                    num = num / 10
                    if j == str(num):
                        j = str(num).split('.')
                        titulo.append(j)
                for k in query1:
                            if k=="maya":
                                k="malla"
                            if k=="pilos"or k=="pilo":
                                k="philo"
                            if k=="filos"or k=="filo":
                                k="philo"
                            if k=="sinces" or k=="sinc":
                                k="synthe"
                            if k=="sintes" or k=="sint":
                                k="synthe" 
                            if k=="axos" or k=="axo":
                                k="axso"       
                            if k=="uno":
                                k=1
                            if k=="dos" or k=="do":
                                k=2
                            if k=="tres" or k=="tr":
                                k=3
                            if k=="cuatro":
                                k=4
                            if k=="cinco":
                                k=5
                            if k=="seis"or k=="sei":
                                k=6
                            if k=="siete":
                                k=7
                            if k=="ocho":
                                k=8
                            if k=="nueve":
                                k=9
                            if k=="cero":
                                k=0
                            if k=="veintiuno":
                                k="21"
                            if k=="veinte":
                                k="20"
                            if k=="veintidos"or k=="veintido" :
                                k="22"
                            if k=="veintitres" or k=="veintitre" :
                                k="23"
                            if k=="veinticuatro":
                                k="24"
                            if k=="veinticinco":
                                k="25"
                            if k=="veintiseis"or k=="veintisei" :
                                k="26"
                            if k=="veintisiete":
                                k="27"
                            if k=="veintiocho":
                                k="28"
                            if k=="veintinueve":
                                k="29"
                            if k=="treinta":
                                k="30"
                            if type(k)==int and type(k1)==int:
                                num=str(k1)+'.'+str(k)
                                k=num.split('.')
                            k1=k                
                            k=inflector.singularize(str(k))
                            j=inflector.singularize(str(j))                           
                            k=remove_accents(k)
                            if j==k:
                                cont_palabras=cont_palabras+1                                                        
            count_words[i] = cont_palabras
        indexmax = np.argwhere(count_words == np.amax(count_words))
        for i in indexmax:
            output.append(data[int(i)])
        if np.all(count_words == 0):
            output = None
    return output

async def cargar_tipo(nid, url):
    connector = aiohttp.TCPConnector(ssl=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        r = await session.get(f'{base_url}all-content/{url}', auth=auth)
        data = await r.json()
        tipo = None
        output = None
        for data1 in data:
            if nid == data1["nid"]:
                tipo = data1["type"]
                output = data1
                break
    return output, tipo

async def cargar_archivo(field_tipo, texto, url):
    file = []
    connector = aiohttp.TCPConnector(ssl=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        r = await session.get('https://orva.tedcas.com/api/'+str(url), auth=auth)
        data = await r.json()
        data = data[0]
        field1 = "field_"+str(field_tipo)
        field = data[field1]
        if field1 == "field_image":
            data=data['field_image']
            data=data.split(',')
            data = [s.replace(' ', '') for s in data]
            for text in data:
                 file.append("https://orva.tedcas.com/"+str(text))                 
            print(file)
            return file
        if len(field)==0 :
             file_texto="No hay archivos subidos"
             file="templates/especialidad"        
        elif type(field)==str:             
             file="https://orva.tedcas.com/"+str(field)
             file_texto=field
        elif type(field)==list:
            for i,files in field:
                file[i]="https://orva.tedcas.com/"+str(files)
                file_texto=field
        return texto,file,file_texto

async def cargar_archivo_grande(field_tipo, texto, url):
    connector = aiohttp.TCPConnector(ssl=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        r = await session.get('https://orva.tedcas.com/api/'+str(url), auth=auth)
        data = await r.json()
        files = {}
        if field_tipo=='title_material':
            for text in data:
                  files[text[field_tipo]]=(text[field_tipo])
            return files,texto
        data = data[0]
        field = "field_"+str(field_tipo)
        field = data[field]
        if len(field) == 0:
             files["No hay archivos"]="templates/especialidad"
        else :            
            for text in field :
                files[text['descripcion']]="https://orva.tedcas.com/"+str(text['url'])
        return texto,files

async def cargar_caja(url, texto):
    instrumental = {}
    connector = aiohttp.TCPConnector(ssl=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        r = await session.get(f'{base_url}intervenciones/{url}', auth=auth)
        data = await r.json()
        data = data[0]
    if 'field_cajas' in data:
        data=data['field_cajas']
        for text in data:
            instrumental[text['id']]=text['caja']
    else:
        instrumental[str(url)]="No hay archivos"  
    return instrumental,texto

async def cargar_instrumental(nid, url):
    cajas = {}
    connector = aiohttp.TCPConnector(ssl=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        r = await session.get('https://orva.tedcas.com/api/'+str(url), auth=auth)
        data = await r.json()
        for text in data :
         if 'instrumental' in text:
            for word in text['instrumental']:
                if word['id']==nid:
                    cajas[text['nid']]=text['title']
    return cajas

async def cargar_botones_pdf_admision():
    mapa_camas = {}
    ambulancias = {}
    programacion_quirurgica = {}
    otros = {}
    connector = aiohttp.TCPConnector(ssl=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        r = await session.get('https://orva.tedcas.com/api/all-content/1621', auth=auth)
        data = await r.json()
        for text in data:
            r1 = await session.get('https://orva.tedcas.com/api/intervenciones/'+str(text['nid']), auth=auth)
            data1 = await r1.json()
            data1 = data1[0]
            data2 = data1['field_pdf']
            data2 = data2[0]
            if data1['field_tecnica'] == "Mapa de camas":
                mapa_camas[data1['title']] = "https://orva.tedcas.com/"+str(data2['url'])
            elif data1['field_tecnica'] == "Ambulancias":
                ambulancias[data1['title']] = "https://orva.tedcas.com/"+str(data2['url'])
            elif data1['field_tecnica'] == "Programación quirúrgica":
                programacion_quirurgica[data1['title']] = "https://orva.tedcas.com/"+str(data2['url'])
            elif data1['field_tecnica'] == "Otros":
                otros[data1['title']] = "https://orva.tedcas.com/"+str(data2['url'])
    return mapa_camas, ambulancias, programacion_quirurgica, otros

def remove_accents(input_str):
    nfkd_form = unicodedata.normalize('NFKD', input_str)
    return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])

def adaptar_salida(query):
    result = []
    query = str(query).lower()
    query = query.split("}")
    query = query[0].split(":")
    if len(query) >= 2:
        result1 = query[1].split("'")
        result = result1[1].split()
    return result

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.adjust_for_ambient_noise(source)
        audio = r.listen(source)
    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='es-ES')
        print(f"User said: {query}\n")
    except Exception as e:
        print(e)
        print("Unable to Recognize your voice.")
        return "none"

    
    # automatically load the interface from a HF model 
    # you can remove the api_key parameter if you don't care about rate limiting. 
    #import gradio as gr
    #from transformers import pipeline
    #import numpy as np

    #transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-base.en")

    #def transcribe(audio):
    #    sr, y = audio
    #    y = y.astype(np.float32)
    #    y /= np.max(np.abs(y))

    #    return transcriber({"sampling_rate": sr, "raw": y})["text"]


    #demo = gr.Interface(
    #    transcribe,
    #    gr.Audio(source="microphone"),
    #    "text",
    #)

    #demo.launch()
    #query=text
    #########################################


    return query

app = Flask (__name__)
app.config['SECRET_KEY'] = 'mysecretkey'

IMG_FOLDER = os.path.join('static','IMG')
app.config['UPLOAD_FOLDER'] = IMG_FOLDER
   
@app.route("/")
async def hello():
    trauma = os.path.join(app.config['UPLOAD_FOLDER'], 'trauma.jpeg')
    uro = os.path.join(app.config['UPLOAD_FOLDER'], 'uro.jpeg')
    adm = os.path.join(app.config['UPLOAD_FOLDER'], 'adm.jpeg')
    tijeras = os.path.join(app.config['UPLOAD_FOLDER'], 'tijerass.png')
    return render_template('especialidad.html',user_image0=tijeras, user_image1=trauma, user_image2=uro, user_image3=adm)

@app.route("/especialidad")
async def especialidad():
    trauma = os.path.join(app.config['UPLOAD_FOLDER'], 'trauma.jpeg')
    uro = os.path.join(app.config['UPLOAD_FOLDER'], 'uro.jpeg')
    adm = os.path.join(app.config['UPLOAD_FOLDER'], 'adm.jpeg')  
    tijeras = os.path.join(app.config['UPLOAD_FOLDER'], 'tijerass.png') 
    return render_template('especialidad.html',user_image0=tijeras,user_image1=trauma, user_image2=uro, user_image3=adm)

@app.route("/seleccion_trauma", methods=['GET','POST'])
async def seleccion_trauma():
    lupa = os.path.join(app.config['UPLOAD_FOLDER'], 'lupa.png')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png') 
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')  
    return render_template('seleccion_trauma.html',user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha)

@app.route("/buscador_trauma", methods=['GET','POST'])
async def buscador_trauma():
    lupa = os.path.join(app.config['UPLOAD_FOLDER'], 'lupa.png')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png') 
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    guia_visual_ppt = os.path.join(app.config['UPLOAD_FOLDER'], 'guia_visual.png')
    materiales = os.path.join(app.config['UPLOAD_FOLDER'], 'materiales.png')
    pdf_casa = os.path.join(app.config['UPLOAD_FOLDER'], 'pdf_casa.jpg')
    protocolo_word = os.path.join(app.config['UPLOAD_FOLDER'], 'protocolo.jpg')
    visualizar_videos = os.path.join(app.config['UPLOAD_FOLDER'], 'visualizar_video.png')
    query=str(request.form.to_dict())
    query=adaptar_salida(query)
    result_busqueda={}
    result_busqueda[""]=""
    if len(query)==0:
        return render_template('buscador_trauma.html',result_busqueda=result_busqueda, user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 )    
    elif query!=None or "{}":
        url=1
        output=await cargar_base_datos(query,url)
        output2=await buscar_faq(query,1)
        if output==None :             
            if len(output2)==0:
                return render_template('buscador_trauma.html',result_busqueda=result_busqueda,prediction_text="No hay resultados para tu busqueda", user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 )
            else:
                 return render_template('buscador_trauma.html',faqs=output2,faq_titulo="Preguntas y respuestas: ",result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 ) 
        elif len(output)>=1:
            titulo=[]
            nid=[]
            result_busqueda={}
            for text in output:
                titulo.append(text["title"])
                nid.append(text["nid"])
            for i,text in enumerate(titulo):
                 result_busqueda[nid[i]]=text

            if len(output2)!=0:
                return render_template('buscador_trauma1.html',faqs=output2,faq_titulo="Preguntas y respuestas: ",result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 ) 
            else:
                return render_template('buscador_trauma1.html',result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 ) 
            
@app.route("/resultado_trauma", methods=['GET','POST'])
async def resultado_trauma():
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    guia_visual_ppt = os.path.join(app.config['UPLOAD_FOLDER'], 'guia_visual.png')
    materiales = os.path.join(app.config['UPLOAD_FOLDER'], 'materiales.png')
    pdf_casa = os.path.join(app.config['UPLOAD_FOLDER'], 'pdf_casa.jpg')
    protocolo_word = os.path.join(app.config['UPLOAD_FOLDER'], 'protocolo.jpg')
    visualizar_videos = os.path.join(app.config['UPLOAD_FOLDER'], 'visualizar_video.png')
    nid=request.args.get('link')
    output,tipo=await cargar_tipo(nid,1)
    title=output['title'] 
    #if tipo="instrumen"
    if tipo=="Intervencion":
        instrumental,texto_cajas=await cargar_caja(str(nid),'Instrumental - Cajas: ')        
        return render_template('intervencion_trauma.html',user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,instrumental=instrumental,texto_cajas=texto_cajas, title=title, user_image6=ajustes,user_image7=flecha,nid2=nid )
    elif tipo=='Caja':
        texto_ubi,file_ubi,file_texto_ubi=await cargar_archivo("ubicacion","Ubicacion: ","cajas/"+str(nid))
        file_imagen=await cargar_archivo("image","Imagen: ","cajas/"+str(nid))
        files_instru, texto_instru=await cargar_archivo_grande("title_material","Instrumental : ","cajas/"+str(nid))
        if len(title)==1:
            return render_template('caja_trauma1.html',title=title,files_instru=files_instru, texto_instru=texto_instru,texto_ubi=texto_ubi,file_texto_ubi=file_texto_ubi,file_imagen=file_imagen,user_image6=ajustes,user_image7=flecha )
        else:
            return render_template('caja_trauma.html',title=title,files_instru=files_instru, texto_instru=texto_instru,texto_ubi=texto_ubi,file_texto_ubi=file_texto_ubi,file_imagen=file_imagen,user_image6=ajustes,user_image7=flecha )
    elif tipo=='Instrumental':
        cajas=await cargar_instrumental(nid,'listado_completo_cajas/1')
        if len(cajas)==1:
            return render_template('instrumental_trauma1.html',cajas=cajas,texto='El instrumental que buscas esta presente en las siguientes cajas: ',title=title,user_image6=ajustes,user_image7=flecha )
        else:
            return render_template('instrumental_trauma.html',cajas=cajas,texto='El instrumental que buscas esta presente en las siguientes cajas: ',title=title,user_image6=ajustes,user_image7=flecha )

@app.route("/protocolos_trauma", methods=['GET','POST'])
async def protocolos_trauma():
    nid2=request.args.get('link2')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')        
    protocolos=await boton_word_ppt(1,"field_protocolo",nid2)
    if len(protocolos)==1:
        return render_template('protocolo1.html',protocolos=protocolos,user_image7=flecha)
    else:
        return render_template('protocolo.html',protocolos=protocolos,user_image7=flecha)

@app.route("/guia_visual_trauma", methods=['GET','POST'])
async def guia_visual_trauma():
    nid2=request.args.get('link2')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')        
    guia_visual=await boton_word_ppt(1,"field_guia_visual",nid2)
    if len(guia_visual)==1:
        return render_template('guia_visual1.html',guia_visual=guia_visual,user_image7=flecha)
    else:
        return render_template('guia_visual.html',guia_visual=guia_visual,user_image7=flecha)

@app.route("/pdf_casa_trauma", methods=['GET','POST'])
async def pdf_casa_trauma():
    nid2=request.args.get('link2')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')   
    titulos=await boton_pdf_video(1,"field_pdf",nid2)
    contador_pdf_trauma = 0
    for titulo1, pdfs in titulos.items():
        for titulo2, url in pdfs.items():
            contador_pdf_trauma = contador_pdf_trauma + 1
    if len(titulos.items())==1:
        if contador_pdf_trauma==1:
            print("bien")
            return render_template('pdf_casa_comercial1.html',user_image7=flecha,titulos=titulos)
        else:
            return render_template('pdf_casa_comercial.html',user_image7=flecha,titulos=titulos)
    else:
        return render_template('pdf_casa_comercial.html',user_image7=flecha,titulos=titulos)

@app.route("/videos_trauma", methods=['GET','POST'])
async def videos_trauma():
    nid2=request.args.get('link2')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')   
    titulos=await boton_pdf_video(1,"field_video",nid2)
    contador_videos_trauma = 0
    for titulo1, pdfs in titulos.items():
        for titulo2, url in pdfs.items():
            contador_videos_trauma = contador_videos_trauma + 1
    if len(titulos.items())==1:
        if contador_videos_trauma==1:
            print("bien")
            return render_template('videos1.html',user_image7=flecha,titulos=titulos)
        else:
            return render_template('videos.html',user_image7=flecha,titulos=titulos)    
    else:
        return render_template('videos.html',user_image7=flecha,titulos=titulos)    
        
@app.route("/materiales_trauma", methods=['GET','POST'])
async def materiales_trauma():
    nid2=request.args.get('link2')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    cajas=await boton_materiales(1,nid2) 
    if len(cajas[''])==0:
       return render_template('materiales_uro.html',user_image7=flecha,cajas=cajas,no_hay="No hay instrumental")
    else:
        if len(cajas)==1:
            return render_template('materiales_uro1.html',user_image7=flecha,cajas=cajas)
        else:           
            return render_template('materiales_uro.html',user_image7=flecha,cajas=cajas)    

@app.route("/escuchar_trauma1", methods=['GET','POST'])
async def escuchar_trauma1():
    guia_visual_ppt = os.path.join(app.config['UPLOAD_FOLDER'], 'guia_visual.png')
    materiales = os.path.join(app.config['UPLOAD_FOLDER'], 'materiales.png')
    pdf_casa = os.path.join(app.config['UPLOAD_FOLDER'], 'pdf_casa.jpg')
    protocolo_word = os.path.join(app.config['UPLOAD_FOLDER'], 'protocolo.jpg')
    visualizar_videos = os.path.join(app.config['UPLOAD_FOLDER'], 'visualizar_video.png')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png')
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png')  
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    return render_template('escuchar_trauma1.html',nid2=0,prediction_text="Dale a `Escuchar´ y haz tu pregunta",user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )

@app.route("/escuchar_trauma", methods=['GET','POST'])
#@app.route("/escuchar_trauma", methods=['POST'])
async def escuchar_trauma():
    #########################################################################

    lupa = os.path.join(app.config['UPLOAD_FOLDER'], 'lupa.png')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png') 
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    guia_visual_ppt = os.path.join(app.config['UPLOAD_FOLDER'], 'guia_visual.png')
    materiales = os.path.join(app.config['UPLOAD_FOLDER'], 'materiales.png')
    pdf_casa = os.path.join(app.config['UPLOAD_FOLDER'], 'pdf_casa.jpg')
    protocolo_word = os.path.join(app.config['UPLOAD_FOLDER'], 'protocolo.jpg')
    visualizar_videos = os.path.join(app.config['UPLOAD_FOLDER'], 'visualizar_video.png')












    ###########################################################################
    guia_visual_ppt = os.path.join(app.config['UPLOAD_FOLDER'], 'guia_visual.png')
    materiales = os.path.join(app.config['UPLOAD_FOLDER'], 'materiales.png')
    pdf_casa = os.path.join(app.config['UPLOAD_FOLDER'], 'pdf_casa.jpg')
    protocolo_word = os.path.join(app.config['UPLOAD_FOLDER'], 'protocolo.jpg')
    visualizar_videos = os.path.join(app.config['UPLOAD_FOLDER'], 'visualizar_video.png')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png')
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png')  
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')


    #########################################################################################
    r = sr.Recognizer()
    #if request.method == 'POST':
        
    recognized_text = ""  # Valor predeterminado

    if request.method == "POST":
        f = request.files['audio_data']
        # Cargar el archivo adjunto directamente
        with sr.AudioFile(f) as source:
            audio_data = r.record(source)

        # Realizar el reconocimiento de voz
        try:
            recognized_text = r.recognize_google(audio_data, language='es-ES')
        except sr.UnknownValueError:
            recognized_text = "No se pudo reconocer el audio"
        except sr.RequestError as e:
            recognized_text = f"Error en la solicitud: {str(e)}"
        print(recognized_text)
    #return render_template('index.html', recognized_text=recognized_text)
    

    #else: 
    ##########################################################################################
    query=recognized_text
    print("TEXTO")
    print(query)
    #query = takeCommand()
    query=str(query).lower()
    query=query.split()
    result_busqueda={}
    result_busqueda[""]=""
    if query[0]!="none":
        url=1
        output=await cargar_base_datos(query,url)
        output2=await buscar_faq(query,0)
        if output==None:
            if len(output2)==0:            
                return render_template('escuchar_trauma.html',nid2=0,result_busqueda=result_busqueda,prediction_text="No hay resultados para tu busqueda",user_image6=ajustes,user_image7=flecha,user_image5=micro,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )
                
            else:
                return render_template('escuchar_trauma.html',nid2=0,faqs=output2,faq_titulo="Preguntas y respuestas: ",result_busqueda=result_busqueda,user_image6=ajustes,user_image7=flecha,user_image5=micro,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )
                
        elif len(output)>=1:
            titulo=[]
            nid=[]
            result_busqueda={}
            for text in output:
                titulo.append(text["title"])
                nid.append(text["nid"])
            for i,text in enumerate(titulo):
                    result_busqueda[nid[i]]=text
            print("RESULT BUSQUEDA")
            print(result_busqueda)
            if len(output2)==0:
                print("render1")
                return render_template('escuchar_trauma.html',nid2=0,result_busqueda=result_busqueda,user_image6=ajustes,user_image7=flecha,user_image5=micro, user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )
                
            else:
                print("render2")
                #return render_template('especialidad.html')
                return render_template('buscador_trauma.html',faqs=output2,faq_titulo="Preguntas y respuestas: ",result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 )
                #return render_template('escuchar_trauma.html',nid2=0,faqs=output2,faq_titulo="Preguntas y respuestas: ",result_busqueda=result_busqueda,user_image6=ajustes,user_image7=flecha,user_image5=micro, user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )
    else :
        return render_template('escuchar_trauma.html',nid2=0,result_busqueda=result_busqueda,prediction_text="No te he entendido bien, dale al boton `Escuchar´ y repite tu pregunta",user_image5=micro,user_image6=ajustes,user_image7=flecha, user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )

@app.route("/buscador_admision", methods=['GET','POST'])
async def buscador_admision():
    lupa = os.path.join(app.config['UPLOAD_FOLDER'], 'lupa.png')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png') 
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    otros_img = os.path.join(app.config['UPLOAD_FOLDER'], 'otros_img.png')
    programacion_img = os.path.join(app.config['UPLOAD_FOLDER'], 'programacion_img.png')
    ambulancias_img = os.path.join(app.config['UPLOAD_FOLDER'], 'ambulancias_img.jpg')
    mapa_camas_img = os.path.join(app.config['UPLOAD_FOLDER'], 'mapa_camas_img.jpg')
    query=str(request.form.to_dict())
    query=adaptar_salida(query)
    result_busqueda={}
    result_busqueda[""]=""
    if len(query)==0:
        return render_template('buscador_admision.html',user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,result_busqueda=result_busqueda,prediction_text="ya puedes hacer tu pregunta", user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha )    
    elif query!=None or "{}":
        url=1621
        output=await cargar_base_datos(query,url)
        output2=await buscar_faq(query,1)
        if output==None:
            if len(output2)==0:
                return render_template('buscador_admision.html',user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,result_busqueda=result_busqueda,prediction_text="No hay resultados para tu busqueda", user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha)
            else:
                return render_template('buscador_admision.html',user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,faqs=output2,faq_titulo="Preguntas y respuestas: ",result_busqueda=result_busqueda, user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha)
        elif len(output)>=1:
            titulo=[]
            nid=[]
            result_busqueda={}
            for text in output:
                nid.append(text["nid"])
                for nid1 in nid:
                    connector = aiohttp.TCPConnector(ssl=True)
                    async with aiohttp.ClientSession(connector=connector) as session:
                        r1 = await session.get('https://orva.tedcas.com/api/intervenciones/'+str(nid1), auth=auth) 
                        data1=await r1.json()
                        data1=data1[0]
                        data2=data1['field_pdf']
                        data2=data2[0]
                        result_busqueda[data1['title']]="https://orva.tedcas.com/"+str(data2['url'])    
            if len(output2)==0:
                return render_template('buscador_admision1.html',user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha ) 
            else:
                return render_template('buscador_admision1.html',faqs=output2,faq_titulo="Preguntas y respuestas: ",user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha ) 

@app.route("/mapa_camas", methods=['GET','POST'])
async def mapa_camas():
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')    
    mapa_camas1,ambulancias,programacion_quirurgica,otros =await cargar_botones_pdf_admision()
    return render_template('mapa_camas.html', text=mapa_camas1,user_image6=ajustes,user_image7=flecha)

@app.route("/ambulancias", methods=['GET','POST'])
async def ambulancias():
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    mapa_camas,ambulancias,programacion_quirurgica,otros =await cargar_botones_pdf_admision()
    return render_template('ambulancias.html', text=ambulancias,user_image6=ajustes,user_image7=flecha)

@app.route("/programacion_quirurgica", methods=['GET','POST'])
async def programacion_quirurgica():
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')    
    mapa_camas,ambulancias,programacion_quirurgica,otros =await cargar_botones_pdf_admision()
    return render_template('programacion_quirurgica.html', text=programacion_quirurgica,user_image6=ajustes,user_image7=flecha)

@app.route("/otros", methods=['GET','POST'])
async def otros():
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')    
    mapa_camas,ambulancias,programacion_quirurgica,otros =await cargar_botones_pdf_admision()
    return render_template('otros.html', text=otros,user_image6=ajustes,user_image7=flecha)

@app.route("/escuchar_admision1", methods=['GET','POST'])
async def escuchar_admision1():
    otros_img = os.path.join(app.config['UPLOAD_FOLDER'], 'otros_img.png')
    programacion_img = os.path.join(app.config['UPLOAD_FOLDER'], 'programacion_img.png')
    ambulancias_img = os.path.join(app.config['UPLOAD_FOLDER'], 'ambulancias_img.jpg')
    mapa_camas_img = os.path.join(app.config['UPLOAD_FOLDER'], 'mapa_camas_img.jpg')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png')
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png')  
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    return render_template('escuchar_admision1.html',user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,prediction_text="Dale a `Escuchar´ y haz tu pregunta",user_image5=micro,user_image6=ajustes,user_image7=flecha)

@app.route("/escuchar_admision", methods=['GET','POST'])
async def escuchar_admision():
    otros_img = os.path.join(app.config['UPLOAD_FOLDER'], 'otros_img.png')
    programacion_img = os.path.join(app.config['UPLOAD_FOLDER'], 'programacion_img.png')
    ambulancias_img = os.path.join(app.config['UPLOAD_FOLDER'], 'ambulancias_img.jpg')
    mapa_camas_img = os.path.join(app.config['UPLOAD_FOLDER'], 'mapa_camas_img.jpg')
    lupa = os.path.join(app.config['UPLOAD_FOLDER'], 'lupa.png')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png') 
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    query = takeCommand()
    query=str(query).lower()
    query=query.split()
    result_busqueda={}
    result_busqueda[""]=""    
    if query[0]!="none":
        url=1621
        output=await cargar_base_datos(query,url)
        output2=await buscar_faq(query,0)
        if output==None:
            if len(output2)==0:
                return render_template('escuchar_admision.html',user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,result_busqueda=result_busqueda,prediction_text="No hay resultados para tu busqueda", user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha)
            else:
                return render_template('escuchar_admision.html',faqs=output2,faq_titulo="Preguntas y respuestas: ",user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,result_busqueda=result_busqueda, user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha)
        elif len(output)>=1:
            titulo=[]
            nid=[]
            result_busqueda={}
            for text in output:
                nid.append(text["nid"])
                for nid1 in nid:
                    connector = aiohttp.TCPConnector(ssl=True)
                    async with aiohttp.ClientSession(connector=connector) as session:
                        r1 = await session.get('https://orva.tedcas.com/api/intervenciones/'+str(nid1), auth=auth) 
                        data1=await r1.json()
                        data1=data1[0]
                        data2=data1['field_pdf']
                        data2=data2[0]
                        result_busqueda[data1['title']]="https://orva.tedcas.com/"+str(data2['url'])    
            if len(output2)==0:
                return render_template('escuchar_admision.html',user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha ) 
            else:
                return render_template('escuchar_admision.html',faqs=output2,faq_titulo="Preguntas y respuestas: ",user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha ) 
    else:
        return render_template('escuchar_admision.html',user_image8=mapa_camas_img,user_image9=ambulancias_img,user_image10=programacion_img,user_image11=otros_img,prediction_text="No te he entendido bien, dale al boton `Escuchar´ y repite tu pregunta",result_busqueda=result_busqueda, user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha )
    
@app.route("/buscador_uro", methods=['GET','POST'])
async def buscador_uro():
    lupa = os.path.join(app.config['UPLOAD_FOLDER'], 'lupa.png')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png') 
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    guia_visual_ppt = os.path.join(app.config['UPLOAD_FOLDER'], 'guia_visual.png')
    materiales = os.path.join(app.config['UPLOAD_FOLDER'], 'materiales.png')
    pdf_casa = os.path.join(app.config['UPLOAD_FOLDER'], 'pdf_casa.jpg')
    protocolo_word = os.path.join(app.config['UPLOAD_FOLDER'], 'protocolo.jpg')
    visualizar_videos = os.path.join(app.config['UPLOAD_FOLDER'], 'visualizar_video.png')
    query=str(request.form.to_dict())
    query=adaptar_salida(query)
    result_busqueda={}
    result_busqueda[""]=""
    if len(query)==0:
        return render_template('buscador_uro.html',result_busqueda=result_busqueda, user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 )    
    elif query!=None or "{}":
        url=1620
        output=await cargar_base_datos(query,url)
        output2=await buscar_faq(query,1)
        if output==None :            
            if len(output2)==0:
                return render_template('buscador_uro.html',result_busqueda=result_busqueda,prediction_text="No hay resultados para tu busqueda", user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 )
            else:
                 return render_template('buscador_uro.html',faqs=output2,faq_titulo="Preguntas y respuestas: ",result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 ) 
        elif len(output)>=1:
            titulo=[]
            nid=[]
            result_busqueda={}
            for text in output:
                titulo.append(text["title"])
                nid.append(text["nid"])
            for i,text in enumerate(titulo):
                 result_busqueda[nid[i]]=text
            if len(output2)!=0:
                return render_template('buscador_uro1.html',faqs=output2,faq_titulo="Preguntas y respuestas: ",result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 ) 
            else:
                return render_template('buscador_uro1.html',result_busqueda=result_busqueda,user_image4=lupa,user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,nid2=0 ) 

@app.route("/resultado_uro", methods=['GET','POST'])
async def resultado_uro():
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png') 
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    guia_visual_ppt = os.path.join(app.config['UPLOAD_FOLDER'], 'guia_visual.png')
    materiales = os.path.join(app.config['UPLOAD_FOLDER'], 'materiales.png')
    pdf_casa = os.path.join(app.config['UPLOAD_FOLDER'], 'pdf_casa.jpg')
    protocolo_word = os.path.join(app.config['UPLOAD_FOLDER'], 'protocolo.jpg')
    visualizar_videos = os.path.join(app.config['UPLOAD_FOLDER'], 'visualizar_video.png')
    nid=request.args.get('link')
    output,tipo=await cargar_tipo(nid,1620)
    title=output['title']     
    if tipo=="Intervencion":
        print("hola1")
        instrumental,texto_cajas=await cargar_caja(str(nid),'Instrumental - Cajas: ')
        return render_template('intervencion_uro.html',user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales,instrumental=instrumental,texto_cajas=texto_cajas, title=title, user_image6=ajustes,user_image7=flecha,nid2=nid )
    elif tipo=='Caja':
        texto_ubi,file_ubi,file_texto_ubi=await cargar_archivo("ubicacion","Ubicacion: ","cajas/"+str(nid))
        file_imagen=await cargar_archivo("image","Imagen: ","cajas/"+str(nid))
        files_instru, texto_instru=await cargar_archivo_grande("title_material","Instrumental : ","cajas/"+str(nid))
        if len(title)==1:
            return render_template('caja_trauma1.html',title=title,files_instru=files_instru, texto_instru=texto_instru,texto_ubi=texto_ubi,file_texto_ubi=file_texto_ubi,file_imagen=file_imagen,user_image6=ajustes,user_image7=flecha )            
        else:
            return render_template('caja_trauma.html',title=title,files_instru=files_instru, texto_instru=texto_instru,texto_ubi=texto_ubi,file_texto_ubi=file_texto_ubi,file_imagen=file_imagen,user_image6=ajustes,user_image7=flecha )
    elif tipo=='Instrumental':
        print("hola2")
        cajas=await cargar_instrumental(nid,'listado_completo_cajas/1620')
        if len(cajas)==1:
            return render_template('instrumental_uro1.html',cajas=cajas,texto='El instrumental que buscas esta presente en las siguientes cajas: ',title=title,user_image6=ajustes,user_image7=flecha )            
        else:
            return render_template('instrumental_uro.html',cajas=cajas,texto='El instrumental que buscas esta presente en las siguientes cajas: ',title=title,user_image6=ajustes,user_image7=flecha )

@app.route("/protocolos_uro", methods=['GET','POST'])
async def protocolos_uro():
    nid2=request.args.get('link2')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')        
    protocolos=await boton_word_ppt(1620,"field_protocolo",nid2)
    if len(protocolos)==1:
        return render_template('protocolo1.html',protocolos=protocolos,user_image7=flecha)
    else:    
        return render_template('protocolo.html',protocolos=protocolos,user_image7=flecha)

@app.route("/guia_visual_uro", methods=['GET','POST'])
async def guia_visual_uro():
    nid2=request.args.get('link2')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')        
    guia_visual=await boton_word_ppt(1620,"field_guia_visual",nid2)
    if len(guia_visual)==1:
        return render_template('guia_visual1.html',guia_visual=guia_visual,user_image7=flecha)
    else:
        return render_template('guia_visual.html',guia_visual=guia_visual,user_image7=flecha)

@app.route("/pdf_casa_uro", methods=['GET','POST'])
async def pdf_casa_uro():
    nid2=request.args.get('link2')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')   
    titulos=await boton_pdf_video(1620,"field_pdf",nid2)
    contador_pdf_uro = 0
    for titulo1, pdfs in titulos.items():
       for titulo2, url in pdfs.items():
           contador_pdf_uro = contador_pdf_uro + 1
    if len(titulos.items())==1:
        if contador_pdf_uro==1:
            print("bien")
            return render_template('pdf_casa_comercial1.html',user_image7=flecha,titulos=titulos)
        else:
            return render_template('pdf_casa_comercial.html',user_image7=flecha,titulos=titulos)
    else:
        return render_template('pdf_casa_comercial.html',user_image7=flecha,titulos=titulos)

@app.route("/videos_uro", methods=['GET','POST'])
async def videos_uro():
    nid2=request.args.get('link2')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')   
    titulos=await boton_pdf_video(1620,"field_video",nid2)
    contador_videos_uro=0
    for titulo1, pdfs in titulos.items():
       for titulo2, url in pdfs.items():
           contador_videos_uro = contador_videos_uro + 1
    if len(titulos.items())==1:
        if contador_videos_uro==1:
            return render_template('videos1.html',user_image7=flecha,titulos=titulos)    
        else:
            return render_template('videos.html',user_image7=flecha,titulos=titulos)    
    else:
        return render_template('videos.html',user_image7=flecha,titulos=titulos)    
        
@app.route("/materiales_uro", methods=['GET','POST'])
async def materiales_uro():
    nid2=request.args.get('link2')
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    cajas=await boton_materiales(1620,nid2) 
    if len(cajas[''])==0:
       return render_template('materiales_uro.html',user_image7=flecha,cajas=cajas,no_hay="No hay instrumental")
    else:
        if len(cajas)==1:
            return render_template('materiales_uro1.html',user_image7=flecha,cajas=cajas)
        else:           
            return render_template('materiales_uro.html',user_image7=flecha,cajas=cajas)    
 
@app.route("/escuchar_uro1", methods=['GET','POST'])
async def escuchar_uro1():
    guia_visual_ppt = os.path.join(app.config['UPLOAD_FOLDER'], 'guia_visual.png')
    materiales = os.path.join(app.config['UPLOAD_FOLDER'], 'materiales.png')
    pdf_casa = os.path.join(app.config['UPLOAD_FOLDER'], 'pdf_casa.jpg')
    protocolo_word = os.path.join(app.config['UPLOAD_FOLDER'], 'protocolo.jpg')
    visualizar_videos = os.path.join(app.config['UPLOAD_FOLDER'], 'visualizar_video.png')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png')
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png')  
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    return render_template('escuchar_uro1.html',nid2=0,prediction_text="Dale a `Escuchar´ y haz tu pregunta",user_image5=micro,user_image6=ajustes,user_image7=flecha,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )

@app.route("/escuchar_uro", methods=['GET','POST'])
async def escuchar_uro():
    guia_visual_ppt = os.path.join(app.config['UPLOAD_FOLDER'], 'guia_visual.png')
    materiales = os.path.join(app.config['UPLOAD_FOLDER'], 'materiales.png')
    pdf_casa = os.path.join(app.config['UPLOAD_FOLDER'], 'pdf_casa.jpg')
    protocolo_word = os.path.join(app.config['UPLOAD_FOLDER'], 'protocolo.jpg')
    visualizar_videos = os.path.join(app.config['UPLOAD_FOLDER'], 'visualizar_video.png')
    micro = os.path.join(app.config['UPLOAD_FOLDER'], 'micro.png')
    ajustes = os.path.join(app.config['UPLOAD_FOLDER'], 'ajustes.png')  
    flecha = os.path.join(app.config['UPLOAD_FOLDER'], 'flecha.png')
    query = takeCommand()
    query=str(query).lower()
    query=query.split()
    result_busqueda={}
    result_busqueda[""]=""
    if query[0]!="none":
        url=1620
        output=await cargar_base_datos(query,url)
        output2=await buscar_faq(query,0)
        if output==None:
            if len(output2)==0:
                return render_template('escuchar_uro.html',nid2=0,result_busqueda=result_busqueda,prediction_text="No hay resultados para tu busqueda",user_image6=ajustes,user_image7=flecha,user_image5=micro,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )
            else:
                return render_template('escuchar_uro.html',nid2=0,faqs=output2,faq_titulo="Preguntas y respuestas: ",result_busqueda=result_busqueda,user_image6=ajustes,user_image7=flecha,user_image5=micro,user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )
        elif len(output)>=1:
            titulo=[]
            nid=[]
            result_busqueda={}
            for text in output:
                titulo.append(text["title"])
                nid.append(text["nid"])
            for i,text in enumerate(titulo):
                 result_busqueda[nid[i]]=text

            if len(output2)==0:
                return render_template('escuchar_uro.html',nid2=0,result_busqueda=result_busqueda,user_image6=ajustes,user_image7=flecha,user_image5=micro, user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )
            else:
                return render_template('escuchar_uro.html',nid2=0,faqs=output2,faq_titulo="Preguntas y respuestas: ",result_busqueda=result_busqueda,user_image6=ajustes,user_image7=flecha,user_image5=micro, user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )  
    else :
        return render_template('escuchar_uro.html',nid2=0,result_busqueda=result_busqueda,prediction_text="No te he entendido bien, dale al boton `Escuchar´ y repite tu pregunta",user_image5=micro,user_image6=ajustes,user_image7=flecha, user_image8=pdf_casa,user_image9=protocolo_word,user_image10=guia_visual_ppt,user_image11=visualizar_videos,user_image12=materiales )
 
@app.route("/ajustes")
async def ajustes():
    estrella = os.path.join(app.config['UPLOAD_FOLDER'], 'estrella.png')
    return render_template('ajustes.html',user_image7=estrella)
   
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)#7860)