Spaces:
Runtime error

File size: 97,703 Bytes
dd9d069
 
 
 
 
e7a3196
 
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
 
 
 
 
 
 
 
 
 
 
 
dd9d069
 
 
e7a3196
 
 
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
dd9d069
e7a3196
 
 
 
 
dd9d069
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
 
 
dd9d069
 
e7a3196
 
 
 
 
 
 
 
 
dd9d069
 
 
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
 
 
 
 
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
e7a3196
dd9d069
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
 
 
e7a3196
dd9d069
 
 
 
 
 
 
 
e7a3196
dd9d069
 
e7a3196
 
 
 
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
 
dd9d069
 
 
 
 
 
 
 
 
 
e7a3196
 
 
 
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
 
 
 
dd9d069
 
 
 
e7a3196
 
 
 
dd9d069
e7a3196
dd9d069
 
 
 
 
e7a3196
dd9d069
 
e7a3196
 
 
 
dd9d069
 
e7a3196
 
 
 
 
 
 
 
 
 
 
 
dd9d069
e7a3196
 
dd9d069
 
 
 
e7a3196
 
dd9d069
 
 
 
 
 
 
 
 
 
e7a3196
 
 
 
dd9d069
 
e7a3196
 
 
 
 
 
 
 
 
 
 
 
dd9d069
e7a3196
 
dd9d069
 
 
 
 
 
e7a3196
 
 
 
dd9d069
 
 
 
e7a3196
 
 
 
dd9d069
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
e7a3196
 
 
 
dd9d069
 
 
 
e7a3196
 
 
 
dd9d069
 
 
 
 
 
 
 
 
 
 
 
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
dd9d069
e7a3196
 
 
 
 
 
 
 
 
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
 
 
 
 
 
dd9d069
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
 
e7a3196
dd9d069
 
 
 
 
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
 
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
 
dd9d069
 
 
 
e7a3196
dd9d069
 
 
 
e7a3196
dd9d069
 
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
dd9d069
e7a3196
 
dd9d069
e7a3196
 
 
dd9d069
e7a3196
 
 
dd9d069
e7a3196
 
 
dd9d069
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
 
 
 
a234949
e7a3196
dd9d069
e7a3196
dd9d069
 
 
 
 
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
dd9d069
 
 
e7a3196
dd9d069
e7a3196
dd9d069
e7a3196
 
 
dd9d069
 
e7a3196
 
 
 
 
 
 
 
dd9d069
 
 
e7a3196
dd9d069
 
 
 
 
 
 
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
dd9d069
 
 
 
 
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ba8a79
 
 
dd9d069
e7a3196
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
 
 
 
 
 
 
 
 
 
 
e7a3196
 
dd9d069
 
 
 
 
 
 
 
e7a3196
dd9d069
 
e7a3196
 
dd9d069
 
e7a3196
 
 
 
 
 
 
 
 
 
 
 
dd9d069
 
 
e7a3196
dd9d069
e7a3196
 
dd9d069
 
 
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1da32ab
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1da32ab
e7a3196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd9d069
 
 
e7a3196
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
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
import os
import time
import json
import datetime
from pathlib import Path
import random
import emoji
import pandas as pd
import secrets
import string
import re

from starlette.config import Config
from authlib.integrations.starlette_client import OAuth, OAuthError
from httplib2 import Http
from fastapi import FastAPI, Depends, Request
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import RedirectResponse
from starlette import status
from oauth2client import client
from authlib.oidc.core.claims import UserInfo
from urllib.parse import urlparse, urlunparse

import gradio as gr
import uvicorn
from components.gradio.api import (
    googleAuth_api, checkDB_api, checkUser_api,
    syncNotion_api, updateDB_api, notionAuth_api, 
    notionCreatePage_api, notionUpdatePage_api,
    invokeLLM_api, getLabels_api,
    addSession_api, deleteUser_api, insertDB_api)
from components.llm_response import preprocess_llm_response, NOTION_VALID_EMOJIS
from data.sample import (
    LABEL_COLS, LABEL_DB, 
    EMAIL_COLS, EMAIL_DB, 
    EMAIL_SUMMARY_COLS, EMAIL_SUMMARY_DB, SENDER_SUMMARY_DB,
    UNSUB_COLS, UNSUB_DB,
    PROCESSING_ERRORS_COLS, PROCESSING_ERRORS_DB,
    ANALYSIS_TYPES, FILE_PATHS)
from data.tables import save_data_to_csv, save_data_to_excel
from components.fetch_emails import get_emails


APPLICATION_NAME = "f0"
'''LOAD ENVIRONMENT VARIABLES'''
from dotenv import load_dotenv
load_dotenv()
URL_SCHEMA = os.getenv('URL_SCHEMA')
GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = os.getenv('GOOGLE_CLIENT_SECRET')
SESSION_MIDDLEWARE_SECRET_KEY = os.getenv('SESSION_MIDDLEWARE_SECRET_KEY')
NOTION_AUTHORIZATION_ENDPOINT = os.getenv('NOTION_AUTHORIZATION_URL')
NOTION_REDIRECT_URI = os.getenv('NOTION_REDIRECT_URI')
PUBLIC_NOTION_KEY = os.getenv('PUBLIC_DIR_NOTION_KEY')
# MODEL_NAME = os.getenv('MODEL_NAME')
NOTIONGEN_PUBLIC_PAGE_ID = os.getenv('NOTIONGEN_PUBLIC_DIR_PAGE_ID')
SAMPLE_NOTIONGEN_PAGE_ID = os.getenv('SAMPLE_NOTIONGEN_PAGE_ID')
SAMPLE_NOTIONGEN_PAGE_NAME = os.getenv('SAMPLE_NOTIONGEN_PAGE_NAME')
PUBLIC_NOTION_PAGE_ID = os.getenv("PUBLIC_DIR_NOTION_PAGE_ID")
SAMPLE_EMAIL0_PAGE_ID = os.getenv('SAMPLE_EMAIL0_PAGE_ID')
SAMPLE_EMAIL0_PAGE_NAME = os.getenv('SAMPLE_EMAIL0_PAGE_NAME')

SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' # we are using modify and not readonly, as we will be marking the messages Read
SESSION_DATA={}
SESSION_CHECK_REDIRECTION_URL = "/"
SIGNIN_URL = "/signin"
GOOGLE_SIGNIN_URL = "/signin_with_google"
APP_URL = "/app"
APP_ALTERNATE_ROUTE = "/app1"
GMAIL_SIGNIN_URL = "/signin_with_gmail"
NOTION_AUTH_URL = "/notion_auth"
DATA_LOCATION = "data/emails_data"
LOGOUT_URL = "/logout"
DELETE_ACCOUNT_URL = "/delete_account"
DEMO_USERNAME = 'f0_demo_user'
DEMO_USERPWD = 'f0_demo_pwd'


'''CODE'''
config_data = {'GOOGLE_CLIENT_ID': GOOGLE_CLIENT_ID, 'GOOGLE_CLIENT_SECRET': GOOGLE_CLIENT_SECRET}
starlette_config = Config(environ=config_data)
oauth = OAuth(starlette_config)
oauth.register(
    name='google',
    server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
    client_kwargs={'scope': 'openid email profile'},
)

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=SESSION_MIDDLEWARE_SECRET_KEY)


'''APP CODE'''
# GENERIC FUNCTIONS
def get_user(request: Request): # Dependency to get the current user name
    user = request.session.get('user')
    if user and isinstance(user, dict) and user.get('name',None):
        return user['name']
    return None

def app_auth(request: Request): # Dependency to get the current user name
    user = request.session.get('user')
    # if user is None:
    #     raise HTTPException(status_code=401, detail="Test Unauthorized")
    if user and isinstance(user, dict) and user.get('name',None):
        return user['name']
    return None

# from starlette.exceptions import HTTPException as StarletteHTTPException
# @app.exception_handler(HTTPException)
# def http_exception_handler(request: Request, exc: HTTPException):
#     print("Printing the error.....")
#     print(request.session.get('user'))
#     print(exc.status_code)
#     print("Proceeding with the next action.....")
#     if exc.status_code == 401:
#         # Redirect to the login page if the user is unauthorized
#         return RedirectResponse(url="/signin")
#     # Return the default exception handler for other HTTP errors
#     return JSONResponse(
#         status_code=exc.status_code,
#         content={"detail": exc.detail}
#     )

def get_user_info(user): # Dependency to get the current user info
    # user = request.session.get('user',{})
    _user_type = "google"
    _id_type = 'email'
    _curr_user_id = user.get(_id_type,'')
    if not _curr_user_id:
        _session_user = SESSION_DATA.get('user',{})
        _user_type = "pwd"
        _id_type = 'email'
        _curr_user_id = _session_user.get(_id_type,'')
        if not _curr_user_id:
            _id_type = 'username'
            _curr_user_id = _session_user.get(_id_type,'')
    if _curr_user_id:
        return _user_type, _id_type, _curr_user_id
    return None, None, None

def greet(request: gr.Request):
    return f"""### 👋, <span style="color:#1d4ed8">{SESSION_DATA.get('user',{}).get('username',request.username)}</span>."""

def user_details(request: gr.Request):
    return f"""### My Username: {SESSION_DATA.get('user',{}).get('username',None)}""", f"""### My Name: {SESSION_DATA.get('user',{}).get('name',request.username)}""", f"""### My Email: {SESSION_DATA.get('user',{}).get('email',None)}"""

def get_usage_limits(session_data):
    curr_user = session_data.get('user','')
    _usage_limits = None
    _user_type = None
    _curr_user_email = None
    if curr_user:
        _curr_user_email = curr_user.get('email','')
        _user_type = 'email'
        if not _curr_user_email:
            _curr_user_email = curr_user.get('username','')
            _user_type = 'username'
        response = checkDB_api(row_id_value=_curr_user_email, column="usage_limits, id", table="users", row_id_type=_user_type)
        if response:
            _usage_limits = response
    if _usage_limits:
        return _usage_limits[0], _user_type, _curr_user_email
    else:
        return {}, _user_type, _curr_user_email

def get_connected_notion_info(refresh=False,max_depth=2):
    curr_user = SESSION_DATA.get('user','')
    token = None
    page_id = None
    page_types = None
    if curr_user and (isinstance(curr_user,UserInfo) or isinstance(curr_user,dict)):
        curr_user_email = curr_user.get('email','')
        _user_type = 'email'
        if not curr_user_email:
            curr_user_email = curr_user.get('username','')
            _user_type = 'username'
        if curr_user_email:
            return syncNotion_api(row_id_value=curr_user_email,row_id_type=_user_type,refresh=refresh,max_depth=max_depth)
    return token, page_id, page_types

# ROUTER FUNCTIONS
@app.get(SESSION_CHECK_REDIRECTION_URL)
def app_router(user = Depends(get_user)):
    if user:
        return RedirectResponse(url=APP_URL)
    else:
        return RedirectResponse(url=SIGNIN_URL)

@app.route(GOOGLE_SIGNIN_URL)
async def google_login(request: Request):
    user = request.session.get('user',{})
    _user_type, _id_type, _curr_user_id = get_user_info(user)
    creds = None
    if user:
        creds_json = None
        response = checkDB_api(row_id_value=user['email'], column="auth_response", table="users", row_id_type="email")
        if response:
            creds_json = response
        if creds_json:
            print(f'User [{user.get("name",None)}, {user.get("email",None)}] already signed-in')
            creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
            if creds.invalid:
                print("Credentials are invalid, attempting to refresh.")
                try:
                    creds.refresh(Http())
                    if not creds.invalid:
                        print("Credentials refreshed successfully.")
                        creds_json = creds.to_json()
                        # data = google_auth_db_sync(creds_json, user, scope='google')
                        # return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
                except client.AccessTokenRefreshError:
                    print("Failed to refresh access token.")
            else:
                print("Valid credentials found. Redirecting.")
                return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
        else:
            print("No credentials found. Initiating Google sign-in flow.")
    else:
        print("No user session found. Initiating Google sign-in flow.")

    # oauth._clients['google'].client_kwargs['scope'] = f'openid email profile'    
    redirect_uri = request.url_for('google_auth')
    redirect_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme=URL_SCHEMA))
    return await oauth.google.authorize_redirect(request, redirect_uri, access_type='offline')

@app.route('/google_auth')
async def google_auth(request: Request):
    try:
        user = request.session.get('user',{})
        creds = None
        if user:
            creds_json = None
            response = checkDB_api(row_id_value=user['email'], column="auth_response", table="users", row_id_type="email")
            if response:
                creds_json = response
            if creds_json:
                print(f'User [{user.get("name",None)}, {user.get("email",None)}] already signed-in')
                creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
                if creds.invalid:
                    print("Credentials are invalid, attempting to refresh.")
                    try:
                        creds.refresh(Http())
                        if not creds.invalid:
                            print("Credentials refreshed successfully.")
                            creds_json = creds.to_json()
                            # data = google_auth_db_sync(creds_json, user, scope='google')
                            # return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
                    except client.AccessTokenRefreshError:
                        print("Failed to refresh access token.")
                else:
                    print("Valid credentials found. Redirecting.")
                    return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
            else:
                print("No credentials found. Initiating Google sign-in flow.")
        else:
            print("No user session found. Initiating Google sign-in flow.")
        
        access_token = await oauth.google.authorize_access_token(request)
        data = []
        response = googleAuth_api(access_token, user, 'google', SESSION_DATA)
        if response:
            data = response
        request.session['user'] = dict(access_token)["userinfo"]
        SESSION_DATA['user'] = dict(access_token)["userinfo"]
        if data and data[0].get('username',None):
            SESSION_DATA['user']['username'] = data[0].get('username')
        _user_type, _id_type, _curr_user_id = get_user_info(request.session.get('user',{}))
        session_data = addSession_api(_curr_user_id, _id_type, request.cookies)
        if session_data and session_data.get('Success') and session_data.get('session_data'):
            SESSION_DATA['user']['session_id'] = session_data.get('session_data')[0].get('id')
        return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
    except OAuthError:
        return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)

@app.route(GMAIL_SIGNIN_URL)
async def gmail_login(request: Request):
    user = request.session.get('user',{})
    _user_type, _id_type, _curr_user_id = get_user_info(user)
    creds = None
    if user:
        creds_json = None
        response = checkDB_api(row_id_value=user['email'], column="gmail_token", table="users", row_id_type="email")
        if response:
            creds_json = response
        if creds_json:
            print(f'User [{user.get("name",None)}, {user.get("email",None)}] already signed-in')
            creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
            if creds.invalid:
                print("Credentials are invalid, attempting to refresh.")
                try:
                    creds.refresh(Http())
                    if not creds.invalid:
                        print("Credentials refreshed successfully.")
                        creds_json = creds.to_json()
                        # data = google_auth_db_sync(creds_json, user, scope='google')
                        # return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
                except client.AccessTokenRefreshError:
                    print("Failed to refresh access token.")
            else:
                print("Valid credentials found. Redirecting.")
                return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
        else:
            print("No credentials found. Initiating Gmail sign-in flow.")
    else:
        print("No user session found. Initiating Gmail sign-in flow.")

    oauth._clients['google'].client_kwargs['scope'] = f'openid email profile {SCOPES}'    
    redirect_uri = request.url_for('gmail_auth')
    redirect_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme=URL_SCHEMA))
    return await oauth.google.authorize_redirect(request, redirect_uri, access_type='offline')

@app.route('/gmail_auth')
async def gmail_auth(request: Request):
    try:
        user = request.session.get('user',{})
        creds = None
        if user:
            creds_json = None
            response = checkDB_api(row_id_value=user['email'], column="gmail_token", table="users", row_id_type="email")
            if response:
                creds_json = response
            if creds_json:
                print(f'User [{user.get("name",None)}, {user.get("email",None)}] already signed-in')
                creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
                if creds.invalid:
                    print("Credentials are invalid, attempting to refresh.")
                    try:
                        creds.refresh(Http())
                        if not creds.invalid:
                            print("Credentials refreshed successfully.")
                            creds_json = creds.to_json()
                            # data = google_auth_db_sync(creds_json, user, scope='google')
                            # return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
                    except client.AccessTokenRefreshError:
                        print("Failed to refresh access token.")
                else:
                    print("Valid credentials found. Redirecting.")
                    return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
            else:
                print("No credentials found. Initiating Gmail sign-in flow.")
        else:
            print("No user session found. Initiating Gmail sign-in flow.")
        
        access_token = await oauth.google.authorize_access_token(request)
        data = []
        response = googleAuth_api(access_token, user, 'gmail', SESSION_DATA)
        if response:
            data = response
        request.session['user'] = dict(access_token)["userinfo"]
        SESSION_DATA['user'] = dict(access_token)["userinfo"]
        if data and data[0].get('username',None):
            SESSION_DATA['user']['username'] = data[0].get('username')
        _user_type, _id_type, _curr_user_id = get_user_info(request.session.get('user',{}))
        session_data = addSession_api(_curr_user_id, _id_type, request.cookies)
        if session_data and session_data.get('Success') and session_data.get('session_data'):
            SESSION_DATA['user']['session_id'] = session_data.get('session_data')[0].get('id')
        return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
    except OAuthError:
        return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)

def generate_random_alphanumeric(length):
    alphabet = string.ascii_letters + string.digits  # Includes uppercase and lowercase letters and digits
    return ''.join(secrets.choice(alphabet) for _ in range(length))

def pwd_auth(username, password): # Dependency for signin with username/password
    if not username or not password or username == '' or password == '':
        print('Empty username or password. Try again..')
        return False
    _userinfo = None
    response = checkUser_api(row_id_value=username, row_id_type="username")
    if response:
        _userinfo = response
    if _userinfo:
        if _userinfo[0].get('password',None) == password:
            print("Password match! You're in..")
            SESSION_DATA['user'] = {"email": _userinfo[0].get("email",username), "name": _userinfo[0].get("name",username), "username": username}
            _user_type, _id_type, _curr_user_id = get_user_info({})
            session_data = addSession_api(_curr_user_id, _id_type, {"session": generate_random_alphanumeric(14)})
            if session_data and session_data.get('Success') and session_data.get('session_data'):
                SESSION_DATA['user']['session_id'] = session_data.get('session_data')[0].get('id')
            return True
        else:
            print("Password didn't match or not found. Try again or use 'Sign in with Google'..")
    else:
        print("User not found. Try again..")
    return False

@app.route(NOTION_AUTH_URL)
async def notion_auth(request: Request):
    try:
        access_code = request.query_params.get('code') # GET TEMPORARY ACCESS CODE
        if access_code:
            notionAuth_api(access_code,NOTION_REDIRECT_URI,SESSION_DATA)
        else:
            error = request.query_params.get('error')
            print(f"""🔴 NotionAuth Error! {error}""")
    except Exception as e:
        print(f"""🔴 Error! {str(e)}""")
    return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)

@app.route(LOGOUT_URL)
async def logout(request: Request):
    if request.session.get('user',{}):
        request.session.pop('user', None)
        SESSION_DATA.pop('user', None)
        return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
    else:
        return pwd_logout(request)

def pwd_logout(request: Request):
    response = RedirectResponse(url="/app1", status_code=status.HTTP_302_FOUND)
    cookies = request.cookies
    for cookie in cookies:
        if cookie.startswith('access-token'):
            response.delete_cookie(cookie)
    return response

@app.route(DELETE_ACCOUNT_URL)
async def delete_account(request: Request):
    user = request.session.get('user',{})
    _user_type, _id_type, _curr_user_id = get_user_info(user)
    if _user_type and _id_type and _curr_user_id:
        updateDB_api(_curr_user_id, {"request_at": datetime.datetime.now().isoformat(),"session": request.cookies,"sessions_id":SESSION_DATA.get('user',{}).get('session_id',None),"userinfo":SESSION_DATA,"client":request.client.host if request.client else None}, "users", _id_type, "delete_request")
        response = deleteUser_api(_curr_user_id, _id_type, SESSION_DATA)
        if response and response.get('Success'):
            return RedirectResponse(url=LOGOUT_URL)
        else:
            print(response.get('Error'))
            return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)
    return RedirectResponse(url=SESSION_CHECK_REDIRECTION_URL)


# SIGNIN PAGE (GRADIO)
with gr.Blocks(
    theme='gradio/base',
    css=f"""{Path('components/gradio/css/signin_css.md').read_text()}""",
    ) as signin_page:
    gr.Markdown("""<br><br/>""")
    gr.Markdown(f"""{Path('components/gradio/guides/app_intro.md').read_text()}""", line_breaks=True)
    gr.Markdown("""&nbsp;""")
    gr.Markdown(f"""**DEMO USERNAME**: {DEMO_USERNAME}<br/>
                **DEMO PASSWORD**: {DEMO_USERPWD}""")
    gr.Button(
        value="Sign in with Password", 
        link=APP_ALTERNATE_ROUTE, 
        icon='https://cdn-icons-png.flaticon.com/512/811/811701.png', 
        variant='primary',
        scale=0,
        elem_classes='btn')
    gr.Markdown('### OR')
    gr.Button(
        value="Sign in with Google", 
        link=GOOGLE_SIGNIN_URL, 
        icon='https://lh3.googleusercontent.com/COxitqgJr1sJnIDe8-jiKhxDx1FrYbtRHKJ9z_hELisAlapwE9LUPh6fcXIfb5vwpbMl4xl9H9TRFPc5NOO8Sb3VSgIBrfRYvW6cUA', 
        scale=0, 
        elem_classes='btn')
    gr.Markdown("""&nbsp;""")
    gr.Markdown("""---""")
    gr.Markdown("""#### 💌 <span style="color:gray">Built by [finding0](https://www.linkedin.com/company/finding0)</span>""", elem_classes="center_text")

app = gr.mount_gradio_app(app, signin_page, path=SIGNIN_URL)


# NOTIONGEN APP FUNCTIONS
ADD_INPUTS = [
    ["NOTION_KEY",None,"https://www.notion.so/my-integrations"],
    ["NOTION_PAGE_ID",None,"https://www.notion.so/{ACCOUNT_DOMAIN}/{PAGETITLE}-{PAGEID}?"],
    ["LLM_API_KEY",None,"https://platform.openai.com/api-keys"],
    ]

def notiongen_api(
        description:str, llm:str, model:str, 
        temperature:float = 0.7, top_p:float = 0.2,
        autosend_to_notion:bool = False, notion_page_id: str = None, 
        notion_page_type:str = None, notion_access_token:str = None,
        dev_mode:bool = False, key_values:dict = {}
        ):
    _query = {"description": description, "llm": llm, "model": model, 
              "temperature": temperature, "top_p": top_p, "dev_mode": dev_mode, 
              "autosend_to_notion": autosend_to_notion, "notion_page_type": notion_page_type}
    _sample_link = f"""🟡 🏗️ Sample NotionGen Page Link: <a href="https://www.notion.so/{SAMPLE_NOTIONGEN_PAGE_ID}" target="_blank">{SAMPLE_NOTIONGEN_PAGE_NAME} [SAMPLE]</a>"""
    _action_id = "notiongen_generate"
    _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
    _users_id = _usage_limits.get('id',None)
    _sessions_id = SESSION_DATA.get('user').get('session_id',None)
    _usage_limits = _usage_limits.get('usage_limits')
    try:
        _rem_limits = 1
        _speed_break_limit_seconds = 300
        _last_used_at = datetime.datetime.now() - datetime.timedelta(seconds=2*int(_speed_break_limit_seconds))
        gr_tab_id = 1
        if _usage_limits:
            if _usage_limits.get("pages",{}).get(str(gr_tab_id),{}):
                _page_limits = _usage_limits.get("pages",{}).get(str(gr_tab_id),{})
                _rem_limits = _page_limits.get("remaining",0)
                _speed_break_limit_seconds = _page_limits.get("speed_break",300)
                _last_used_at = _page_limits.get("last_used_at",None)
            else:
                _default_limits = _usage_limits.get("default",{})
                _rem_limits = _default_limits.get("remaining",0)
                _speed_break_limit_seconds = _default_limits.get("speed_break",300)
                _last_used_at = _default_limits.get("last_used_at",None)
            if _last_used_at:
                _last_used_at = datetime.datetime.strptime(_last_used_at, "%Y-%m-%d %H:%M:%S")
            else:
                _last_used_at = datetime.datetime.now() - datetime.timedelta(seconds=2*int(_speed_break_limit_seconds))
        if _rem_limits > 0 and _last_used_at < datetime.datetime.now() - datetime.timedelta(seconds=int(_speed_break_limit_seconds)):
            yield f"🟡 🏗️ Initializing NotionGen with model {model[:int(len(model)/2)]}...", _sample_link, {"message": f"Initializing NotionGen..."}
            llm_response = invokeLLM_api(description=description,force_json=True,temperature=temperature,top_p=top_p,llm=llm,model=model,llm_key=None,def_env_var=True,custom_data=None)
            # yield f"🟡 🏗️ NotionGen template generation is in progress...", """""", {"message": f"NotionGen template generation in-progress..."}
            _response_json = ""
            _result = ""
            _response = ""
            for _res in preprocess_llm_response(llm_response):
                time.sleep(0.05)
                if isinstance(_res, dict):
                    _response_json = _res.get('blueprint', {})
                    _titles = re.findall(r'titled "(.*?)"', _response)
                    _title = _titles[0] if _titles else "Uncategorized"
                    _result = f"🟢 🎉 NotionGen template generation is completed. Now, you can 'Send to Notion' (go to Notion Settings section at the end).\n\n{_response}"
                    if _usage_limits:
                        if _usage_limits.get("pages",{}).get(str(gr_tab_id),{}):
                            _usage_limits["pages"][str(gr_tab_id)]["remaining"] = _usage_limits["pages"][str(gr_tab_id)]["remaining"] - 1
                            _usage_limits["pages"][str(gr_tab_id)]["last_used_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        _usage_limits["default"]["remaining"] = _usage_limits["default"]["remaining"] - 1
                        _usage_limits["default"]["last_used_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        updateDB_api(curr_user_email, update_data=_usage_limits, table="users", row_id_type=_user_type, column="usage_limits")
                    if autosend_to_notion:
                        yield f"🟢 🎉 NotionGen template generation is completed. 🟡 🏗️ Now, sending the template content to Notion...\n\n{_response}", _sample_link, _response_json
                        is_invalid = preprocess_validation(notion_access_token,notion_page_id,notion_page_type)
                        if is_invalid:
                            insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": _response, "data": _response_json}, "notion_response": {"success": False, "data": None, "error": is_invalid}},"title":_title}}, "actions")
                            yield f"🟢 🎉 NotionGen template is successfully generated but can't be sent to Notion due to an error!\n\n{_response}", f"""{is_invalid} or use the <a href="https://notion.so/{NOTIONGEN_PUBLIC_PAGE_ID}" target="_blank">public workspace</a>.""", _response_json
                        else:
                            _response_json['properties'] = {
                                'User': {
                                    "rich_text": [{
                                        "text": {
                                            "content": SESSION_DATA.get('user',{}).get('name','Unknown') or 'Unknown'}
                            }]}}
                            page_type = _response_json["type"]
                            _new_page_id, _new_page_title, _new_page_link = create_notion_page(_response_json,notion_page_id,notion_page_type,notion_access_token)
                            if _new_page_id:
                                yield f"🟡 🏗️ Notion Page (or Database) is successfully generated & content writing is initiated....\n\n{_response}", f"""🟡 🏗️ You'll never see William Shakespeare writing on Notion but NotionGen would love a visitor on his latest creation: <a href="{_new_page_link}" target="_blank">{_new_page_title}</a>""", _response_json
                                for _idx, child in enumerate(_response_json.get("children", [])):
                                    block_type = child["type"]
                                    yield f"🟡 🏗️ Notion Page (or Database) is successfully generated & content writing is in-progress for a notion block of type '{block_type}'....\n\n{_response}", f"""🟡 🏗️ You'll never see William Shakespeare writing on Notion but NotionGen would love a visitor on his latest creation: <a href="{_new_page_link}" target="_blank">{_new_page_title}</a>""", _response_json
                                    res = notionUpdatePage_api(parent_id=_new_page_id, block_json=child, notion_access_token=notion_access_token, parent_block_type=page_type)
                                    is_success = res.get("Success",False)
                                    if not is_success:
                                        yield f"🔴 Failed to process block '{block_type}' with error {res.get('Error','')}", f"""🟢 🎉 Check out the NotionGen-generated page: <a href="{_new_page_link}" target="_blank">{_new_page_title}</a>""", _response_json
                                    if _idx == len(_response_json.get("children", [])) - 1:
                                        insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": _response, "data": _response_json}, "notion_response": {"success": True, "result":_new_page_link, "data": "NotionGen template is successfully sent to Notion"}},"title":_title}}, "actions")
                                        yield f"🟢 🎉 NotionGen template is successfully sent to Notion!\n\n{_response}", f"""🟢 🎉 Check out the NotionGen-generated page: <a href="{_new_page_link}" target="_blank">{_new_page_title}</a>""", _response_json
                            else:
                                insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": _response, "data": _response_json}, "notion_response": {"success": False, "result":_new_page_link, "data": "NotionGen template is successfully generated but template generation without a new Notion page is not supported"}},"title":_title}}, "actions")
                                yield f"🟢 🎉 NotionGen template is successfully generated but template generation without a new Notion page is not supported! Try again to generate a page.\n\n{_response}", _sample_link, _response_json
                    else:
                        insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"llm_response": {"success": True, "result": _response, "data": _response_json}},"title":_title}}, "actions")
                        yield _result, _sample_link, _response_json
                else:
                    _response += _res
                    yield _response, _sample_link, {"message": "NotionGen template generation in progress...."}
        else:
            insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": f"usage_limit exceeded or reused before the cooling-off period {_speed_break_limit_seconds} (last used at {_last_used_at})"}}}, "actions")
            yield f"🔴 ⌛ Usage limit exceeded or reuse with a break of {_speed_break_limit_seconds} seconds (last used at {_last_used_at}). Please contact us to generate more content.", _sample_link, {"error": "Usage limit exceeded. Please contact us to generate more content."}
    except Exception as e:
        insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": str(e)}}}, "actions")
        yield f"🔴 Error encountered: {str(e)}. Ensure that the 'Inputs' are correctly filled. Run again.", _sample_link, {"error": f"Failed to generate or process NotionGen template due to error {e}"}

def preprocess_validation(notion_key,notion_page_id,notion_page_type):
    # TODO - Put validation of notion page id & notion key formats
    if not notion_key:
        update = f"""🔴 Error! Connect Notion"""
        print(update)
        return update
    if not notion_page_id:
        update = f"""🔴 Error! Select a parent Notion page/database"""
        print(update)
        return update
    if notion_page_type == 'root':
        update = f"""🔴 Error! Select a non-root page/database"""
        print(update)
        return update
    return None

def create_notion_page(notion_json,parent_page_id,parent_page_type,notion_key):
    page_type = notion_json["type"]
    if page_type == "page":
        page_title = notion_json.get("title", "Untitled Page")
        print(f"🟡 ⏳ Creating {page_type} '{page_title}' inside parent_type '{parent_page_type}'")
        emojis = [em for em in emoji.EMOJI_DATA if not any(char in em for char in ["🏻", "🏼", "🏽", "🏾", "🏿", "\u200d"]) and not em.startswith(("🇦", "🇧", "🇨", "🇩", "🇪", "🇫", "🇬", "🇭", "🇮", "🇯", "🇰", "🇱", "🇲", "🇳", "🇴", "🇵", "🇶", "🇷", "🇸", "🇹", "🇺", "🇻", "🇼", "🇽", "🇾", "🇿"))]
        icon = notion_json.get("icon", random.choice(emojis))
        is_valid_icon = icon in NOTION_VALID_EMOJIS
        if not is_valid_icon:
            icon = random.choice(emojis)
        properties = notion_json.get("properties", {})
        new_page = notionCreatePage_api(parent_page_id, page_title, icon, properties, notion_key, parent_page_type)
        new_page_id = new_page.get("id",None)
        if new_page_id:
            print(f"🟢 🎉 Created {page_type} '{page_title}' inside parent_type '{parent_page_type}'")
            new_page_link = f"https://notion.so/{new_page_id.replace('-','')}"
            return new_page_id, page_title, new_page_link # DO NOT 'YIELD' WHEN USING AS LAMBDA
        else:
            print(f"🔴 Error! {new_page.get('Error','')}")
            return None, None, None
    else:
        return None, None, None

def send_to_notion(notion_json,notion_key,notion_page_id,notion_page_type,error_page_link,public_workspace,_action_id):
    _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
    _users_id = _usage_limits.get('id',None)
    _sessions_id = SESSION_DATA.get('user').get('session_id',None)
    _usage_limits = _usage_limits.get('usage_limits')
    try:
        if notion_json and type(notion_json) == dict:
            yield error_page_link, f"""🟡 🏗️ Initialized NotionGen to Notion engine. Validating the Notion credentials..."""
            is_invalid = preprocess_validation(notion_key,notion_page_id,notion_page_type)
            if is_invalid:
                insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"notion_input": notion_json, "notion_response": {"success": False, "data": None, "error": is_invalid}}}}, "actions")
                yield error_page_link, f"""{is_invalid} or use the [public workspace](https://notion.so/{public_workspace})."""
            else:
                notion_json['properties'] = {
                    'User': {
                        "rich_text": [{
                            "text": {
                                "content": SESSION_DATA.get('user',{}).get('name','Unknown') or 'Unknown'}
                }]}}
                page_type = notion_json["type"]
                _new_page_id, _new_page_title, _new_page_link = create_notion_page(notion_json,notion_page_id,notion_page_type,notion_key)
                if _new_page_id:
                    page_link = f"""🟡 🏗️ <span style="color:#646400">Notion template creation is in-progress on Notion Page:</span> [{_new_page_title}]({_new_page_link})"""
                    yield page_link, f"🟡 🏗️ Notion Page (or Database) is successfully generated at above link. Content writing is now in-progress...."""
                    for _idx, child in enumerate(notion_json.get("children", [])):
                        block_type = child["type"]
                        yield page_link, f"""🟡 🏗️ You'll never see William Shakespeare writing a block of type '{block_type}' on Notion but NotionGen would love to give you a sneak peek while it writes..."""
                        res = notionUpdatePage_api(parent_id=_new_page_id, block_json=child, notion_access_token=notion_key, parent_block_type=page_type)
                        is_success = res.get("Success",False)
                        if not is_success:
                            yield page_link, f"""🔴 <span style="color:#cc0000">Error!</span> Failed to process block '{block_type}' with error {res.get('Error','')}"""
                    insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"notion_input": notion_json, "notion_response": {"success": True, "result":_new_page_link, "data": "NotionGen template is successfully sent to Notion"}}}}, "actions")
                    page_link = f"""🟢 🎉 <span style="color:#006400">Success! NotionGen Page Link:</span> [{_new_page_title}]({_new_page_link})"""
                    yield page_link, None
                else:
                    insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"notion_input": notion_json, "notion_response": {"success": False, "result":_new_page_link, "data": "Template generation without a new Notion page is not supported"}}}}, "actions")
                    yield error_page_link, f"""🔴 <span style="color:#cc0000">Error!</span> Template generation without a new Notion page is not supported! Try again to generate a page."""
        else:
            insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": "No data found or invalid data"}}}, "actions")
            yield error_page_link, f"""🔴 <span style="color:#cc0000">Error!</span> No data found or invalid data! Click on 'Generate' & then send to Notion.""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
    except Exception as error:
        insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": str(error)}}}, "actions")
        yield error_page_link, f"""🔴 <span style="color:#cc0000">Error!</span> Unable to send data to Notion: {error}""" # DO NOT 'YIELD' WHEN USING AS LAMBDA


# EMAIL0 APP FUNCTIONS
def get_label_info():
    """ Fetches label info including messagesTotal & messagesUnread """
    try:
        curr_user = SESSION_DATA.get('user','')
        if curr_user:
            labels = getLabels_api(userinfo_json=SESSION_DATA)
            return labels
        else:
            print("🔴 Error! Invalid Session. User not found!")
            return pd.DataFrame(columns=LABEL_COLS)
    except Exception as error:
        print(f"🔴 Error fetching labels: {error}")
        return f"🔴 Error fetching labels: {error}"

def get_unread_emails(label_id, num_emails, create_csv):
    """ Fetches unread emails for a specific label """
    _query = {"label_id":label_id,"num_emails":num_emails,"create_csv":create_csv}
    domain_counts = EMAIL_SUMMARY_DB
    sender_counts = SENDER_SUMMARY_DB
    df = EMAIL_DB
    unsub_db = UNSUB_DB
    error_db = PROCESSING_ERRORS_DB
    file_paths = pd.DataFrame(data=[FILE_PATHS],columns=ANALYSIS_TYPES)
    _action_id = "email0_analyze"
    _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
    _users_id = _usage_limits.get('id',None)
    _sessions_id = SESSION_DATA.get('user').get('session_id',None)
    _usage_limits = _usage_limits.get('usage_limits')
    try:
        args_types = [type(label_id),type(num_emails)]
        params_types = [str,int]
        is_args_valid1 = all(a == b for a, b in zip(args_types, params_types)) # Check the validity of arg type
        if is_args_valid1:
            _rem_limits = 1
            _speed_break_limit_seconds = 300
            _last_used_at = datetime.datetime.now() - datetime.timedelta(seconds=2*int(_speed_break_limit_seconds))
            _max_emails_limit = 50000
            gr_tab_id = 0
            _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
            _usage_limits = _usage_limits.get('usage_limits')
            if _usage_limits:
                if _usage_limits.get("pages",{}).get(str(gr_tab_id),{}):
                    _page_limits = _usage_limits.get("pages",{}).get(str(gr_tab_id),{})
                    _rem_limits = _page_limits.get("remaining",0)
                    _speed_break_limit_seconds = _page_limits.get("speed_break",300)
                    _last_used_at = _page_limits.get("last_used_at",None)
                    _max_emails_limit = _page_limits.get("max_emails",1000)
                else:
                    _default_limits = _usage_limits.get("default",{})
                    _rem_limits = _default_limits.get("remaining",0)
                    _speed_break_limit_seconds = _default_limits.get("speed_break",300)
                    _last_used_at = _default_limits.get("last_used_at",None)
                    _max_emails_limit = _default_limits.get("max_emails",1000)
                if _last_used_at:
                    _last_used_at = datetime.datetime.strptime(_last_used_at, "%Y-%m-%d %H:%M:%S")
                else:
                    _last_used_at = datetime.datetime.now() - datetime.timedelta(seconds=2*int(_speed_break_limit_seconds))
            if _rem_limits <=0 or int(num_emails) > int(_max_emails_limit) or _last_used_at > datetime.datetime.now() - datetime.timedelta(seconds=int(_speed_break_limit_seconds)):
                raise ValueError(f"🔴 ⌛ Usage limit exceeded or reuse with a break of {_speed_break_limit_seconds} seconds (last used at {_last_used_at}). Please contact us to generate more content.")
            if int(num_emails) < 10:
                raise ValueError("Number of emails should be a minimum 10")
            if int(num_emails) <= 100:
                batch_results = int(num_emails)
            if int(num_emails) > 100:
                batch_results = 100
            if int(num_emails) > 500:
                batch_results = 500
            
            for update in get_emails(label_id, num_emails, batch_results, SESSION_DATA):
                status = update[0]
                if 'Success' in status:
                    if create_csv:
                        success_file_paths = []
                        emails_dict = {}
                        for i, u in enumerate(update[1:]):
                            emails_dict[ANALYSIS_TYPES[i]] = u
                            now = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f")
                            filename = f"{now}_{label_id}_{ANALYSIS_TYPES[i]}.csv"
                            success_file_paths.append(os.path.join(DATA_LOCATION, filename))
                            filepath = save_data_to_csv(u,filename)
                            if not filepath.endswith('.csv'):
                                success_file_paths[i] = 'No File Found'
                        now = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f")
                        filename = f"{now}_{label_id}.xlsx"
                        success_file_paths.append(os.path.join(DATA_LOCATION, filename))
                        filepath = save_data_to_excel(emails_dict,filename)
                        download_check = "or download it as csv or"
                        if success_file_paths and len(success_file_paths) == len(file_paths.columns):
                            file_paths = pd.DataFrame(data=[success_file_paths],columns=ANALYSIS_TYPES)
                        status = status+f""". Checkout the analysis {download_check} send it to Notion:"""
                    else:
                        status = status+""". Checkout the analysis or send it to Notion:"""
                    if _usage_limits:
                        if _usage_limits.get("pages",{}).get(str(gr_tab_id),{}):
                            _usage_limits["pages"][str(gr_tab_id)]["remaining"] = _usage_limits["pages"][str(gr_tab_id)]["remaining"] - 1
                            _usage_limits["pages"][str(gr_tab_id)]["last_used_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        _usage_limits["default"]["remaining"] = _usage_limits["default"]["remaining"] - 1
                        _usage_limits["default"]["last_used_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        updateDB_api(curr_user_email, _usage_limits, table="users", row_id_type=_user_type, column="usage_limits")
                    insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"email_response": {"success": True, "result": status}}}}, "actions")
                yield status, file_paths, update[1], update[2], update[3], update[4], update[5]
        else:
            update = f"""🔴 Error! Invalid argument types {args_types} vs valid ones {params_types}. OR, Failed argument conditions."""
            print(update)
            insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": f"Invalid argument types {args_types} vs valid ones {params_types}"}}}, "actions")
            yield update, file_paths, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
    except Exception as error:
        update = f"""🔴 Error fetching emails: {error}"""
        print(update)
        insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "query": _query, "response": {"error": str(error)}}}, "actions")
        yield update, file_paths, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)

def email0_to_notion(tables,header_rows,row_limits,table_names,page_title,notion_creds,error_page_link):
    _action_id = "email0_send_to_notion"
    _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
    _users_id = _usage_limits.get('id',None)
    _sessions_id = SESSION_DATA.get('user').get('session_id',None)
    _usage_limits = _usage_limits.get('usage_limits')
    try:
        args_types = [type(tables),type(header_rows),type(row_limits),type(table_names),type(page_title)]
        params_types = [list,list,list,list,str]
        is_args_valid1 = all(a == b for a, b in zip(args_types, params_types)) # Check the validity of arg type
        args_lengths = [len(tables),len(header_rows),len(row_limits),len(table_names),len(page_title)]
        is_args_valid2 = all(l == args_lengths[0] for l in args_lengths[:4]) # Check the validity of list args
        if is_args_valid1 and is_args_valid2:
            valid_tables = []
            valid_header_rows = []
            tables_json = []
            for idx_, table in enumerate(tables):
                valid_tables.append(any(any(index.strip() for index in index_array) for index_array in table))
                valid_header_rows.append(len(header_rows[idx_]) == len(table[0]))
                if valid_tables[-1] and valid_header_rows[-1]:
                    tables_json.append(
                        {"type": "heading_2", "text": table_names[idx_]})
                    tables_json.append(
                        {"type": "table", "rows": [header_rows[idx_]] + table[:row_limits[idx_]]})
            if len(tables_json) == 2*len(tables):
                page_json = {
                    'type': 'page', 'title': page_title, 'icon': '📬', 
                    'children': tables_json}
                notion_key, notion_page_id, notion_page_type = notion_creds
                for _page_link, _progress in send_to_notion(page_json,notion_key,notion_page_id,notion_page_type,error_page_link,PUBLIC_NOTION_PAGE_ID,_action_id=_action_id):
                    yield _page_link, _progress
            else:
                # print(f"""🔴 Error! No data found or invalid data! Generate analysis & then send to Notion.""")
                insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": f"No data found or invalid data"}}}, "actions")
                yield error_page_link, f"""🔴 <span style="color:#cc0000">Error!</span> No data found or invalid data! Generate analysis & then send to Notion.""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
        else:
            # print(f"""🔴 Error! Invalid argument types {args_types} vs valid ones {params_types}. OR, Failed argument conditions.""")
            insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": f"Invalid argument types {args_types} vs valid ones {params_types}"}}}, "actions")
            yield error_page_link, f"""🔴 <span style="color:#cc0000">Error!</span> Invalid argument types {args_types} vs valid ones {params_types}. OR, Failed argument conditions.""" # DO NOT 'YIELD' WHEN USING AS LAMBDA
    except Exception as error:
        # print(f"""🔴 Error! Unable to send data to Notion: {error}""")
        insertDB_api({"users_id":_users_id, "sessions_id":_sessions_id, "action":{"id": _action_id, "response": {"error": str(error)}}}, "actions")
        yield error_page_link, f"""🔴 <span style="color:#cc0000">Error!</span> Unable to send data to Notion: {error}""" # DO NOT 'YIELD' WHEN USING AS LAMBDA

def get_sample_queries(_action_id="notiongen_generate",data=[],data_type=''):
    if not data:
        data = checkDB_api(row_id_value=None,column="id, created_at, action",table="actions",row_id_type="users_id",null_check=True)
        data_type = 'SAMPLE'
    _sample_queries = {}
    _sample_titles = {}
    filtered_data = [item for item in data if item.get("action", {}).get("id") == _action_id]
    sorted_data = sorted(filtered_data, key=lambda x: x['created_at'], reverse=True)
    for _q in sorted_data:
        _query = _q.get('action',{}).get('query',{}).get('description','')
        if _query not in _sample_queries.keys():
            _result = _q.get('action',{}).get('response',{}).get('llm_response',{}).get('result','')
            if _result:
                _sample_queries[_query] = _result
                _sample_titles[_query] = f'[{data_type}] ' + _q.get('action').get('title')
    return _sample_queries, _sample_titles

def get_user_queries(_action_id="notiongen_generate"):
    _user_queries = {}
    _user_titles = {}
    _sessions_id = SESSION_DATA.get('user',{}).get('session_id',None)
    data = checkDB_api(_sessions_id,"users_id","sessions","id")
    if data:
        data = checkDB_api(data[0].get('users_id'),"id, created_at, action","actions","users_id")
        if data:
            _user_queries, _user_titles = get_sample_queries(_action_id,data,data_type='USER')
    return _user_queries, _user_titles

def get_queries_count(_action_id="notiongen_generate"):
    data = checkDB_api(column="id, users_id, created_at, action",table="actions",all=True)
    filtered_data = [item for item in data if item.get("action", {}).get("id") == _action_id and item.get('users_id') is not None]
    return len(filtered_data)


# APP PAGES (GRADIO)
with gr.Blocks(
    theme='gradio/base',
    css=f"""{Path('components/gradio/css/app_css.md').read_text()}""",
    ) as main_app:
    notion_settings_choices = ['🟢 Live', '🟠 Live (No Page Found)', '🔴 Disconnected','🟢 Live (Public)']  # Define choices as a list of strings

    with gr.Tabs(selected=1) as tabs:
        with gr.TabItem("NotionGen by f0", id=1) as notiongen:
            gr.Markdown("""&nbsp;""")
            with gr.Row():
                with gr.Column(scale=1):
                    main_app.load(greet, None, gr.Markdown())
                    gr.Markdown("""With *a simple prompt*, NotionGen helps *individuals, writers, influencers, professionals, builders & founders* generate *detailed and structured Notion pages/templates* using the advanced capabilities of natural language processing technology (OpenAI). Stop bookmarking *I wish I knew this before...* social media posts, kick-start that vacation or business idea with the advice of multiple subject matter experts. Let's get started on *<span style="color:#1d4ed8">Structured & Actionable Notion Pages with NotionGen (by f0)</span>* journey.<br><br/>""")
                with gr.Column(scale=0):
                    user_limits1 = gr.DataFrame()
                # gr.Image(value='data/images/logo.png', type='filepath', scale=0, show_download_button=False, container=False)

            with gr.Row():
                gr.Column()
                with gr.Column():
                    gr.Markdown("""# NotionGen by [f0](https://linkedin.com/company/finding0)""")
                with gr.Column(variant='panel'):
                    notiongen_pages_counter = gr.Markdown(value=f"NotionGen Pages: Unknown",elem_classes='right_text',show_label=False)
            gr.Markdown("""&nbsp;""")
            gr.Markdown("""---""")

            with gr.Row():
                with gr.Column():
                    description = gr.Textbox(label="Describe your Notion page*", value="Generate me a detailed and comprehensive Notion page to plan a marketing campaign for an oral care brand targeted towards millennials in India.")
                    sample_descriptions = gr.Dropdown(label="Sample prompts to get started",interactive=True,multiselect=False,allow_custom_value=True,filterable=True)
                    with gr.Row():
                        llm_client = gr.Dropdown(label="Select your Expert Community*", choices=['NotionGen','Reforge','GrowthX','ChatPRD'], multiselect=False, allow_custom_value=True, value='NotionGen')
                        model = gr.Dropdown(label="Select the Community Model*", choices=[('GPT 3.5 Turbo','gpt-3.5-turbo')], multiselect=False, allow_custom_value=True, value='gpt-3.5-turbo')
                    with gr.Column(variant='panel'):
                        with gr.Row():
                            autosend_to_notion = gr.Checkbox(label="Auto-send to Notion", value=False, container=False, scale=2, info="Select Notion page or use public workspace")
                            public_workspace_checkbox2 = gr.Checkbox(label=f"Use Public Workspace", value=False, container=False, scale=0, info="To test NotionGen", elem_classes='right_btn') 
                        user_notion_page_id2 = gr.Dropdown(label="Select Notion Page",choices=[],value=None,scale=0,allow_custom_value=False,multiselect=False,interactive=True)
                        with gr.Row():
                            refresh_notion_settings_btn2 = gr.Button(value=f"Refresh Notion Pages", scale=0, size='sm')  
                            gr.Markdown(value=f"""[CheckOut Public Workspace](https://notion.so/{NOTIONGEN_PUBLIC_PAGE_ID})""",elem_classes='right_text')  
                    
                    with gr.Accordion("Advanced Settings", open=False):
                        with gr.Row():
                            temperature = gr.Slider(label="Creativity Score (Temperature)", minimum=0.1, maximum=1.0, step=0.1, value=0.7, info="Make the model more creative.")
                            top_p = gr.Slider(label="Lateral Thinking (Top P)", minimum=0.1, maximum=1.0, step=0.1, value=0.2, info="Out of box thinking.")
                        with gr.Row():
                            use_default_env_vars = gr.Checkbox(label="Use Default Environment Variables", value=False, visible=False)
                            auto_restart = gr.Checkbox(label="Auto-restart (if failed)", value=False, visible=False)
                        with gr.Row():
                            dev_mode = gr.Checkbox(label="Developer Mode", value=False, interactive=True, info="Bring your own API keys", visible=False)
                            force_json = gr.Checkbox(label="Force JSON (LLM response)", value=True, visible=False)
                        additional_inputs = gr.DataFrame(
                            label="Input the values. Use references or scroll down for step-wise instructions.",
                            headers=["Key","Value","Reference"],
                            datatype=["str","str","str"],
                            value=ADD_INPUTS,
                            row_count=(len(ADD_INPUTS),'fixed'),
                            col_count=(3,'fixed'),
                            wrap=True,
                            visible=False)
                    submit_btn = gr.Button("Generate",variant='primary')
                    
                with gr.Column(variant='panel'):
                    html_output = gr.HTML(label="Notion Page Generation Status (if auto-send to notion is selected)",value=f"""🟡 🏗️ Sample NotionGen Page Link: <a href="https://www.notion.so/{SAMPLE_NOTIONGEN_PAGE_ID}" target="_blank">{SAMPLE_NOTIONGEN_PAGE_NAME} [SAMPLE]</a>""")
                    status_output = gr.Text(label="Status",placeholder="Here, you will see how NotionGen creates magic.",show_copy_button=True)
                    
            models_lib = gr.JSON(label="Community Models Library",visible=False)
            notionJSON_output = gr.JSON(label="NotionGen Template JSON",visible=False)
            samples_lib = gr.JSON(label="Sample Input<>Output Library",visible=False)
     
            gr.Markdown("""&nbsp;""")    
            with gr.Column(variant='panel',scale=0):
                with gr.Row():
                    gr.Markdown("""#### ⬇️ Notion Settings""")
                    notion_settings_status2 = gr.Markdown(notion_settings_choices[2],elem_classes='right_text')
                with gr.Row():
                    with gr.Column(scale=0):
                        notion_page_max_depth2 = gr.Slider(maximum=10,minimum=1,value=2,step=1,label="Notion Page Max Depth",interactive=True,scale=0)
                    with gr.Column(scale=2):
                        to_notion_btn2 = gr.Button('Send to Notion 🔴', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='lg', interactive=True, elem_classes='center_btn')
                    with gr.Column(scale=0):
                        connect_to_notion2 = gr.Button(link=NOTION_AUTHORIZATION_ENDPOINT, value='Connect 🟠', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='sm',elem_classes='right_btn')  
                        refresh_notion_conn_btn = gr.Button(value=f"Refresh Notion Connection", interactive=False, scale=0, size='sm', elem_classes='right_btn')  
                with gr.Row():
                    gr.Column(scale=0)  
                    with gr.Column(scale=1):
                        notiongen_page_link = gr.Markdown(value=f"""🎉 <span style="color:#646400">Sample NotionGen Page Link:</span> [{SAMPLE_NOTIONGEN_PAGE_NAME} [SAMPLE]](https://www.notion.so/{SAMPLE_NOTIONGEN_PAGE_ID})""", elem_classes='center_text')
                        to_notion_update2 = gr.Markdown(value=None, elem_classes='center_text')
                    gr.Column(scale=0)
                user_notion_access_token2 = gr.Dropdown(label="Your Notion Integration API Token",choices=[],value=None,interactive=False,visible=False)
                selected_page_type2 = gr.Dropdown(label="Selected Page Type",choices=['page','database','root'],value=None,interactive=True,visible=False)
                user_notion_page_types2 = gr.List(label="Page Types",value=None,scale=0,interactive=True,visible=False)
                    

        with gr.TabItem("Email0 by f0",id=0,interactive=False) as email0:
            gr.Markdown("""&nbsp;""")
            with gr.Row():
                with gr.Column(scale=1):
                    main_app.load(greet, None, gr.Markdown())
                    gr.Markdown("""Email0 by f0 helps *people* do seamless email-cleanup & reach the utopian *Ground Zero*. Let's get started on *<span style="color:#1d4ed8">Ground Zero with Email0 (by f0)</span>* journey with domain-level & sender-level analyses to identify the senders whom you should unsubscribe.<br><br/>""")
                with gr.Column(scale=0):
                    user_limits = gr.DataFrame()
                # gr.Image(value='data/images/logo.png', type='filepath', scale=0, show_download_button=False, container=False)

            with gr.Row():
                gr.Column()
                with gr.Column():
                    gr.Markdown("""# Email0 by [f0](https://linkedin.com/company/finding0)""")            
                with gr.Column():
                    gmail_authenticate_btn = gr.Button("Connect to Gmail", link=GMAIL_SIGNIN_URL, icon="https://upload.wikimedia.org/wikipedia/commons/2/2e/Gmail_2020.png", variant='primary', scale=1, size='sm', elem_classes='right_btn', visible=False)  # Trigger re-authentication
            gr.Markdown("""&nbsp;""")
            gr.Markdown("""---""")

            with gr.Column():
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("""## 📥 <ins>Input to analyse emails</ins>""")
                        with gr.Column(variant='panel'):
                            labels_choices = gr.Dropdown(label="Select Label*", info=f"To auto-update labels, click on 'Fetch/Update Labels' button on the right side.", choices=list(zip(LABEL_DB['label_name'], LABEL_DB['label_id'])), multiselect=False, type="value", value='CATEGORY_PROMOTIONS', allow_custom_value=True)
                            max_emails = gr.Number(100, visible=False)
                            max_emails_slider = gr.Slider(label="Number of Emails*", minimum=0, maximum=max_emails, step=5, value=10, info=f"To analyse (from latest to oldest). Default value is 10% of maximum '{max_emails.value} with increments being half of default value.'", show_label=True)    
                            create_csv_checkbox = gr.Checkbox(label="Create CSV/Excel", info="[Optional] If analysis is required in csv files, select this option. Once downloaded, each csv will be instantly deleted.", value=False)
                            analyze_btn = gr.Button('Analyse', variant='primary', scale=0, elem_classes='center_btn')
                        
                    with gr.Column():
                        gr.Markdown("""## 🏷️ <ins>Label-wise Summary</ins>""")
                        with gr.Column(variant='panel'):
                            labels = gr.DataFrame(label="View #totalEmails & #unreadEmails by Labels in your account (this would also update the inputs to analyse emails)",headers=[col+'_SAMPLE' for col in LABEL_COLS],value=LABEL_DB.values.tolist(),type='array',col_count=(len(LABEL_COLS),'fixed'),interactive=False,height=260)
                            get_labels_btn = gr.Button(value="Fetch Label Summary", variant='secondary', scale=0, size='sm', elem_classes='center_btn')
                            get_labels_update = gr.Markdown(value=None, elem_classes='center_text', visible=False)

                gr.Markdown("""---""")
                gr.Markdown("""## 📤 <ins>Output</ins>""")
                update = gr.Text(label="Status",placeholder="Here, you will see how 'Email0 by f0' creates magic.",show_copy_button=True)        
                
                gr.Markdown("""&nbsp;""")    
                with gr.Column(variant='panel',scale=0):
                    gr.Markdown("""#### ⬇️ Download Section""")
                    download_btn = gr.DownloadButton(label="Download & Delete",icon="https://cdn-icons-png.flaticon.com/512/9496/9496460.png", variant='secondary', scale=0, size='sm', value=FILE_PATHS[5], elem_classes='center_btn')
                    gr.Markdown("""### OR""", elem_classes='center_text')
                    with gr.Row():
                        gr.Column(scale=0)
                        with gr.Column(scale=2):
                            to_notion_btn = gr.Button('Send to Notion 🔴', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='sm', interactive=True, elem_classes='center_btn')
                        with gr.Column(scale=0):
                            notion_settings_status = gr.Markdown(notion_settings_choices[2], elem_classes='right_text')
                    with gr.Row():
                        with gr.Column():
                            refresh_notion_settings_btn = gr.Button(value=f"Refresh Notion Pages", scale=0, size='sm')
                        with gr.Column():
                            user_notion_page_id = gr.Dropdown(label="Select Notion Page",choices=[],value=None,scale=0,allow_custom_value=False,multiselect=False,interactive=True,container=False)
                        with gr.Column():
                            public_workspace_checkbox = gr.Checkbox(label=f"Use Public Workspace", value=False, container=False, scale=0, elem_classes='right_btn') 
                            gr.Markdown(value=f"""[CheckOut Public Workspace](https://notion.so/{PUBLIC_NOTION_PAGE_ID})""", elem_classes='right_text')    
                    with gr.Row():
                        with gr.Column(scale=0):
                            notion_page_max_depth = gr.Slider(maximum=10,minimum=1,value=2,step=1,label="Notion Page Max Depth",interactive=True,scale=0)
                        with gr.Column(scale=1):
                            email0_page_link = gr.Markdown(value=f"""🎉 <span style="color:#646400">Sample Email0 Notion Page Link:</span> [{SAMPLE_EMAIL0_PAGE_NAME} [SAMPLE]](https://www.notion.so/{SAMPLE_EMAIL0_PAGE_ID})""", elem_classes='center_text')
                            to_notion_update = gr.Markdown(value=None, elem_classes='center_text')
                        with gr.Column(scale=0):
                            connect_to_notion = gr.Button(link=NOTION_AUTHORIZATION_ENDPOINT, value='Connect 🟠', icon="https://upload.wikimedia.org/wikipedia/commons/4/45/Notion_app_logo.png", variant='secondary', scale=0, size='sm', elem_classes='right_btn')
                    user_notion_access_token = gr.Dropdown(label="Your Notion Integration API Token",choices=[],value=None,interactive=False,visible=False)
                    selected_page_type = gr.Dropdown(label="Selected Page Type",choices=['page','database','root'],value=None,interactive=True,visible=False)
                    user_notion_page_types = gr.List(label="Page Types",value=None,scale=0,interactive=True,visible=False)
                    
                gr.Markdown("""&nbsp;""")
                with gr.Row():
                    with gr.Column(variant='panel'):
                        with gr.Row():
                            gr.Markdown("""#### 💌 Domain-wise Summary""")
                            domain_analysis_download_btn = gr.DownloadButton(label="Download & Delete",icon="https://cdn-icons-png.flaticon.com/512/9496/9496460.png", variant='secondary', scale=0, size='sm', value=FILE_PATHS[1])
                        domain_analysis = gr.DataFrame(label="""Email count by Domain would be shown here!""",headers=[col+'_SAMPLE' for col in EMAIL_SUMMARY_COLS],value=EMAIL_SUMMARY_DB.values.tolist(),type='array',col_count=(len(EMAIL_SUMMARY_COLS),'fixed'),interactive=False,height=216)
                        
                    with gr.Column(variant='panel'):
                        with gr.Row():
                            gr.Markdown("""#### 📩 Sender-wise Summary""")
                            sender_analysis_download_btn = gr.DownloadButton(label="Download & Delete",icon="https://cdn-icons-png.flaticon.com/512/9496/9496460.png", variant='secondary', scale=0, size='sm', value=FILE_PATHS[0])
                        analysis = gr.DataFrame(label="""Email count by Sender would be shown here!""",headers=[col+'_SAMPLE' for col in EMAIL_SUMMARY_COLS],value=SENDER_SUMMARY_DB.values.tolist(),type='array',col_count=(len(EMAIL_SUMMARY_COLS),'fixed'),interactive=False,height=216)
                        
                gr.Markdown("""&nbsp;""")
                with gr.Column(variant='panel'):
                    with gr.Row():
                        gr.Markdown("""#### ❌ Unsubscribe Links""")
                        unsub_links_download_btn = gr.DownloadButton(label="Download & Delete",icon="https://cdn-icons-png.flaticon.com/512/9496/9496460.png", variant='secondary', scale=0, size='sm', value=FILE_PATHS[3])
                    unsub_links = gr.DataFrame(label="""Unsubscribe Links""",headers=[col+'_SAMPLE' for col in UNSUB_COLS],value=UNSUB_DB.values.tolist(),type='array',col_count=(len(UNSUB_COLS),'fixed'),interactive=False,height=216)
                    
                gr.Markdown("""&nbsp;""")
                with gr.Column(variant='panel'):
                    with gr.Row():
                        gr.Markdown("""#### 🍰 Sample Emails""")
                        emails_download_btn = gr.DownloadButton(label="Download & Delete",icon="https://cdn-icons-png.flaticon.com/512/9496/9496460.png", variant='secondary', scale=0, size='sm', value=FILE_PATHS[2])
                    sample_emails = gr.DataFrame(label="""Latest 10""",headers=[col+'_SAMPLE' for col in EMAIL_COLS],value=EMAIL_DB.values.tolist(),type='array',col_count=(len(EMAIL_COLS),'fixed'),interactive=False,height=216)
                
                gr.Markdown("""&nbsp;""")
                with gr.Column(variant='panel'):
                    with gr.Row():
                        gr.Markdown("""#### 🔴 Error Emails""")
                        email_processing_errors_download_btn = gr.DownloadButton(label="Download & Delete",icon="https://cdn-icons-png.flaticon.com/512/9496/9496460.png", variant='secondary', scale=0, size='sm', value=FILE_PATHS[4])
                    error_emails = gr.DataFrame(label="""Emails with errors during processing""",headers=[col+'_SAMPLE' for col in PROCESSING_ERRORS_COLS],value=PROCESSING_ERRORS_DB.values.tolist(),type='array',col_count=(len(PROCESSING_ERRORS_COLS),'fixed'),interactive=False,height=216)
                
            gr.Markdown("""---""")
            gr.Markdown("""<br><br/>""")
            
        
        with gr.TabItem("Contact Us", id=2) as contact_us:
            gr.Markdown("""<br><br/>""")
            gr.Markdown("""# Reach out to us by clicking [here](https://www.linkedin.com/company/finding0).""")
            gr.Markdown("""<br><br/>""")
        
        
        with gr.TabItem("Settings", id=3) as settings:
            gr.Markdown("""<br><br/>""")
            with gr.Column(variant='panel'):
                users_username = gr.Markdown(elem_classes='center_text')
                users_name = gr.Markdown(elem_classes='center_text')
                users_email = gr.Markdown(elem_classes='center_text')
            main_app.load(user_details, None, [users_username, users_name, users_email])
            gr.Markdown("""&nbsp;""")
            with gr.Row():
                gr.Column(scale=0)
                with gr.Column(scale=1):
                    user_limits2 = gr.DataFrame()
                gr.Column(scale=0)
            gr.Markdown("""&nbsp;""")
            with gr.Row():
                gr.Column()
                with gr.Column(scale=1):
                    with gr.Row():
                        logout_btn = gr.Button("Logout", link=LOGOUT_URL, scale=0, variant='stop', elem_classes='center_btn')
                        delete_account_btn = gr.Button("Delete Account", link=DELETE_ACCOUNT_URL, scale=0, variant='stop', elem_classes='center_btn')
                gr.Column()
            gr.Markdown("""&nbsp;""")
            gr.Markdown("""
                        ### Before clicking on 'Delete Account', please ensure to revoke access to our application 'finding0' in Notion. Notion's API does not provide a specific endpoint for programatically revoking user access tokens. 
                        To revoke access to our application 'finding0' in Notion:
                        1. Go to Notion and open Settings & Members.
                        2. Navigate to 'Integrations' or 'Connected Apps' or 'Connections.
                        3. Find our application 'finding0' in the list and click 'Revoke Access'.""")
            gr.Markdown("""<br><br/>""")
    
    gr.Markdown("""<br><br/>""")
    tab_id_state = gr.Markdown(label="Last Used Tab",value=None,elem_classes='center_text')
    gr.Markdown("""`Note: If you have any feedback, concern or appreciation, don't be a stranger and ping us.`""", elem_classes="center_text")
    gr.Markdown("""#### 💌 <span style="color:gray">Built by [finding0](https://www.linkedin.com/company/finding0)</span>""", elem_classes="center_text")

    def load_usage_limits():
        _gradio_tabs = [[email0.label,email0.id,0], [notiongen.label,notiongen.id,0]]    
        _limits_data = []
        _usage_limits, _user_type, curr_user_email = get_usage_limits(SESSION_DATA)
        _usage_limits = _usage_limits.get('usage_limits')
        if _usage_limits and _usage_limits.get("pages",{}):
            for _idx, _tab in enumerate(_gradio_tabs):
                _page_limits = _usage_limits.get("pages",{}).get(str(_tab[1]),{})
                _usage_limit = _page_limits.get("maximum",0)
                _rem_limit = _page_limits.get("remaining",0)
                _limits_data.append([_tab[0], _usage_limit, _rem_limit])
        if _usage_limits and _usage_limits.get("default",{}):
            _default_limits = _usage_limits.get("default",{})
            _limits_data.append(["Overall", _default_limits.get("maximum",0), _default_limits.get("remaining",0)])
        if _limits_data:
            _headers = ['Feature','Usage Limit','Remaining']
            return gr.DataFrame(label="Usage Limits",interactive=False,headers=_headers,value=[_limits_data[0],_limits_data[-1]],height=120,wrap=True),gr.DataFrame(label="Usage Limits",interactive=False,headers=_headers,value=[_limits_data[1],_limits_data[-1]],height=120,wrap=True),gr.DataFrame(label="Usage Limits",interactive=False,headers=_headers,value=_limits_data)
        return gr.DataFrame(visible=False),gr.DataFrame(visible=False),gr.DataFrame(visible=False)
    main_app.load(load_usage_limits,None,[user_limits,user_limits1,user_limits2])

    def load_notiongen():
        data = checkDB_api(column="*",table="models",all=True)
        _communities = {}
        for _i, _m in enumerate(data):
            if not _communities.get(_m.get('community')):
                _communities[_m.get('community')] = {'llm_source':_m.get('llm_source'),'models':[]}
            _communities[_m.get('community')]['models'].append((_m.get('name'),_m.get('api_name')))
        _llm_clients = list(_communities.keys())
        _def_llm_client = _llm_clients[0]
        _models = _communities[_def_llm_client].get('models')
        if not _models:
            _models = [("TBA","self")]
        _def_model = _models[0][1]
        _sample_queries, _sample_titles = get_sample_queries(_action_id="notiongen_generate")
        _sample_descriptions = [(_value, _key) for _key, _value in _sample_titles.items()]
        _user_queries, _user_titles = get_user_queries(_action_id="notiongen_generate")
        _user_descriptions = [(_value, _key) for _key, _value in _user_titles.items()]
        _all_descriptions = _sample_descriptions + _user_descriptions
        _all_queries = {**_sample_queries, **_user_queries}
        _notiongen_pages_till_now = get_queries_count(_action_id="notiongen_generate")
        _notiongen_pages_till_now = f"""NotionGen Pages: {_notiongen_pages_till_now}"""
        return gr.JSON(_communities), gr.Dropdown(choices=_llm_clients,value=_def_llm_client), gr.Dropdown(choices=_models,value=_def_model), gr.JSON(_all_queries), gr.Dropdown(choices=_all_descriptions,value=_all_descriptions[0][1]), gr.Markdown(value=_notiongen_pages_till_now)
    main_app.load(load_notiongen,None,[models_lib,llm_client,model,samples_lib,sample_descriptions,notiongen_pages_counter])
    
    def update_notiongen_prompt(selected_description,samples_lib):
        # samples_lib[selected_description]
        if selected_description:
            return selected_description, status_output
        else:
            return description,status_output
    sample_descriptions.change(update_notiongen_prompt,[sample_descriptions,samples_lib],[description,status_output])
    
    def update_models(_selected_llm_client,models_lib):
        _models = models_lib.get(_selected_llm_client).get('models')
        if not _models:
            _models = [("TBA","self")]
        _def_model = _models[0][1]
        return gr.Dropdown(choices=_models,value=_def_model)
    llm_client.change(update_models,[llm_client,models_lib],model)
    
    def update_autosend(token):
        if not token:
            return gr.Checkbox(value=False,interactive=False,info="Connect your Notion or use public workspace")
        return gr.Checkbox(interactive=True,info="Select Notion page or use public workspace")
    user_notion_access_token2.change(update_autosend,[user_notion_access_token2],autosend_to_notion)
    
    def refresh_notion_conn_activate():
        return gr.Button(interactive=True)
    connect_to_notion2.click(refresh_notion_conn_activate,None,refresh_notion_conn_btn)
    
    def update_page_type(selected_page_id,page_types,curr_page_type):
        for page_type in page_types[0]:
            if page_type[0] == selected_page_id:
                return page_type[1]
        return curr_page_type
    user_notion_page_id.select(update_page_type, 
        [user_notion_page_id,user_notion_page_types,selected_page_type],[selected_page_type])
    user_notion_page_id2.select(update_page_type, 
        [user_notion_page_id2,user_notion_page_types2,selected_page_type2],[selected_page_type2])

    def set_notion_settings(refresh,max_depth,curr_page_type,tab_name):
        token_option, page_id_option, page_types = get_connected_notion_info(refresh,max_depth=max_depth)
        if token_option:
            token = token_option[0][1]
            page_id = None
            page_type = None
            conn_status = notion_settings_choices[0]
            if page_id_option:
                to_notion_btn_val = "Send to My Notion 🟢"
                page_id = page_id_option[1][1]
                page_types = [page_types]
                page_type = update_page_type(page_id,page_types,curr_page_type)
            else:
                to_notion_btn_val = "Send to Notion 🟠"
                conn_status = notion_settings_choices[1]
            return gr.Button(value="Reconnect 🟠"), gr.Dropdown(choices=token_option, value=token), gr.Dropdown(choices=page_id_option, value=page_id, interactive=True), gr.Button(value=to_notion_btn_val), gr.Checkbox(value=False), gr.List(value=page_types), gr.Dropdown(value=page_type), gr.Markdown(conn_status)
        else:
            if 'notiongen' in tab_name.lower():
                return connect_to_notion2, user_notion_access_token2, user_notion_page_id2, to_notion_btn2, gr.Checkbox(value=True), user_notion_page_types2, selected_page_type2, notion_settings_status2
            if 'email0' in tab_name.lower():
                return connect_to_notion, user_notion_access_token, user_notion_page_id, to_notion_btn, gr.Checkbox(value=False), user_notion_page_types, selected_page_type, notion_settings_status
        return connect_to_notion2, user_notion_access_token2, user_notion_page_id2, to_notion_btn2, gr.Checkbox(value=False), user_notion_page_types2, selected_page_type2, notion_settings_status2
    def load_notion_settings(max_depth,curr_page_type,tab_name):
        return set_notion_settings(False,max_depth,curr_page_type,tab_name)
    main_app.load(
        fn=lambda _max_depth, _curr_page_type :load_notion_settings(
            _max_depth, _curr_page_type, notiongen.label),
        inputs=[notion_page_max_depth2,selected_page_type2],
        outputs=[connect_to_notion2,user_notion_access_token2,user_notion_page_id2,to_notion_btn2,public_workspace_checkbox2,user_notion_page_types2,selected_page_type2,notion_settings_status2],
        show_progress='minimal')
    main_app.load(
        fn=lambda _max_depth, _curr_page_type :load_notion_settings(
            _max_depth, _curr_page_type, email0.label),
        inputs=[notion_page_max_depth,selected_page_type],
        outputs=[connect_to_notion,user_notion_access_token,user_notion_page_id,to_notion_btn,public_workspace_checkbox,user_notion_page_types,selected_page_type,notion_settings_status],
        show_progress='minimal')
    def refresh_notion_settings(max_depth,curr_page_type,tab_name):
        return set_notion_settings(True,max_depth,curr_page_type,tab_name)
    refresh_notion_settings_btn2.click(
        fn=lambda _max_depth, _curr_page_type :refresh_notion_settings(
            _max_depth, _curr_page_type, notiongen.label),
        inputs=[notion_page_max_depth2,selected_page_type2],
        outputs=[connect_to_notion2,user_notion_access_token2,user_notion_page_id2,to_notion_btn2,public_workspace_checkbox2,user_notion_page_types2,selected_page_type2,notion_settings_status2])
    refresh_notion_conn_btn.click(
        fn=lambda _max_depth, _curr_page_type :refresh_notion_settings(
            _max_depth, _curr_page_type, notiongen.label),
        inputs=[notion_page_max_depth2,selected_page_type2],
        outputs=[connect_to_notion2,user_notion_access_token2,user_notion_page_id2,to_notion_btn2,public_workspace_checkbox2,user_notion_page_types2,selected_page_type2,notion_settings_status2])
    refresh_notion_settings_btn.click(
        fn=lambda _max_depth, _curr_page_type :refresh_notion_settings(
            _max_depth, _curr_page_type, notiongen.label),
        inputs=[notion_page_max_depth,selected_page_type],
        outputs=[connect_to_notion,user_notion_access_token,user_notion_page_id,to_notion_btn,public_workspace_checkbox,user_notion_page_types,selected_page_type,notion_settings_status])
    
    def update_notion_settings(selected_public_workspace,curr_page_type,max_depth,tab_name):
        if selected_public_workspace:
            if type(tab_name) == str:
                if 'notiongen' in tab_name.lower():
                    _public_page_type = 'database'
                    return gr.Dropdown(choices=[('Use Public Workspace',PUBLIC_NOTION_KEY)], value=PUBLIC_NOTION_KEY, interactive=False), gr.Dropdown(choices=[('Use Public Workspace',NOTIONGEN_PUBLIC_PAGE_ID)], value=NOTIONGEN_PUBLIC_PAGE_ID, interactive=False), gr.Button(value="Send to Public Notion 🟢"), gr.List(value=[[('Use Public Workspace',_public_page_type)]]), gr.Dropdown(value=_public_page_type), gr.Markdown(notion_settings_choices[3]), gr.Button(visible=False), gr.Slider(visible=False)
                if 'email0' in tab_name.lower():
                    _public_page_type = 'database'
                    return gr.Dropdown(choices=[('Use Public Workspace',PUBLIC_NOTION_KEY)], value=PUBLIC_NOTION_KEY, interactive=False), gr.Dropdown(choices=[('Use Public Workspace',PUBLIC_NOTION_PAGE_ID)], value=PUBLIC_NOTION_PAGE_ID, interactive=False), gr.Button(value="Send to Public Notion 🟢"), gr.List(value=[[('Use Public Workspace',_public_page_type)]]), gr.Dropdown(value=_public_page_type), gr.Markdown(notion_settings_choices[3]), gr.Button(visible=False), gr.Slider(visible=False)
        else:
            token_option, page_id_option, page_types = get_connected_notion_info(max_depth=max_depth)
            if token_option:
                token = token_option[0][1]
                page_id = None
                page_type = None
                conn_status = notion_settings_choices[0]
                if page_id_option:
                    to_notion_btn_val = "Send to My Notion 🟢"
                    page_id = page_id_option[1][1]
                    page_types = [page_types]
                    page_type = update_page_type(page_id,page_types,curr_page_type)
                else:
                    to_notion_btn_val = "Send to Notion 🟠"
                    conn_status = notion_settings_choices[1]
                return gr.Dropdown(choices=token_option, value=token), gr.Dropdown(choices=page_id_option, value=page_id, interactive=True), gr.Button(value=to_notion_btn_val), gr.List(value=page_types), gr.Dropdown(value=page_type), gr.Markdown(conn_status), gr.Button(interactive=True, visible=True), gr.Slider(visible=True, value=max_depth)
        if type(tab_name) == str:
            if 'notiongen' in tab_name.lower():
                return user_notion_access_token2, user_notion_page_id2, to_notion_btn2, user_notion_page_types2, selected_page_type2, notion_settings_status2, gr.Button(visible=True, interactive=False), gr.Slider(visible=True, interactive=False)
            if 'email0' in tab_name.lower():
                return user_notion_access_token, user_notion_page_id, to_notion_btn, user_notion_page_types, selected_page_type, notion_settings_status, gr.Button(visible=True, interactive=False), gr.Slider(visible=True, interactive=False)
        return user_notion_access_token2, user_notion_page_id2, to_notion_btn2, user_notion_page_types2, selected_page_type2, notion_settings_status2, gr.Button(visible=True, interactive=False), gr.Slider(visible=True, interactive=False)
    public_workspace_checkbox2.change(
        fn=lambda public_option_, page_type_, max_depth_: update_notion_settings(
            public_option_, page_type_, max_depth_, notiongen.label),
        inputs=[public_workspace_checkbox2,selected_page_type2,notion_page_max_depth2],
        outputs=[user_notion_access_token2,user_notion_page_id2,to_notion_btn2,user_notion_page_types2,selected_page_type2,notion_settings_status2,refresh_notion_settings_btn2,notion_page_max_depth2],show_progress='minimal')
    public_workspace_checkbox.change(
        fn=lambda public_option_, page_type_, max_depth_: update_notion_settings(
            public_option_, page_type_, max_depth_, email0.label),
        inputs=[public_workspace_checkbox,selected_page_type,notion_page_max_depth],
        outputs=[user_notion_access_token,user_notion_page_id,to_notion_btn,user_notion_page_types,selected_page_type,notion_settings_status,refresh_notion_settings_btn,notion_page_max_depth],show_progress='minimal')
        
    # def dev_mode_activate(dev_mode):
    #     if dev_mode:
    #         return gr.Checkbox(visible=True), gr.DataFrame(visible=True)
    #     return force_json,additional_inputs
    # dev_mode.change(dev_mode_activate,dev_mode,[force_json,additional_inputs])
    
    def update_tab_id(tab_id):
        return f"{tab_id}"  
    submit_btn.click(
        fn=lambda: update_tab_id(notiongen.id), 
        inputs=[], 
        outputs=[tab_id_state])
    analyze_btn.click(
        fn=lambda: update_tab_id(email0.id), 
        inputs=[], 
        outputs=[tab_id_state])

    def notiongen_api_wrapper(description, llm_client, model, temperature, top_p, autosend_to_notion, user_notion_page_id2, selected_page_type2, user_notion_access_token2, dev_mode, additional_inputs, models_lib):
        _models = models_lib.get(llm_client).get('models')
        _matched_model = None
        for _m in _models:
            if model in _m:
                _matched_model = _m
                break
        model = _matched_model[1]
        llm_client = models_lib.get(llm_client).get('llm_source')
        for _status, _notion_link, _notion_json in notiongen_api(description, llm_client, model, temperature, top_p, autosend_to_notion, user_notion_page_id2, selected_page_type2, user_notion_access_token2, dev_mode, additional_inputs):
            yield _status, _notion_link, _notion_json
    submit_btn.click(
        fn=notiongen_api_wrapper,
        inputs=[description, llm_client, model, temperature, top_p, autosend_to_notion, user_notion_page_id2, selected_page_type2, user_notion_access_token2, dev_mode, additional_inputs, models_lib],
        outputs=[status_output, html_output, notionJSON_output])

    def send_to_notion_wrapper(_notion_json, _notion_access_token, _notion_page_id, _notion_page_type, _def_page_link, _public_workspace):
        for _gen_page_link, _progress_update in send_to_notion(
            notion_json=_notion_json,notion_key=_notion_access_token,
            notion_page_id=_notion_page_id,notion_page_type=_notion_page_type,
            error_page_link=_def_page_link,public_workspace=_public_workspace,
            _action_id="notiongen_send_to_notion"):
            yield _gen_page_link, _progress_update
    to_notion_btn2.click(
        fn=send_to_notion_wrapper,
        inputs=[notionJSON_output,user_notion_access_token2,user_notion_page_id2,selected_page_type2,notiongen_page_link,gr.Text(value=NOTIONGEN_PUBLIC_PAGE_ID,visible=False)],
        outputs=[notiongen_page_link,to_notion_update2])

    def load_demo_view():
        _name = SESSION_DATA.get('user',{}).get('name',None)
        _email = SESSION_DATA.get('user',{}).get('email',None)
        _username = SESSION_DATA.get('user',{}).get('username',None)
        if (_username == DEMO_USERNAME) and (not _email) and (not _name):
            return gr.TabItem(interactive=False), gr.Button(interactive=False), gr.Button(interactive=False)
        return gr.TabItem(interactive=True), gr.Button(interactive=True), gr.Button(interactive=True)
    main_app.load(
        fn=load_demo_view,
        inputs=None,
        outputs=[email0,connect_to_notion2,refresh_notion_conn_btn])

    def change_labels():
        fetched_labels = get_label_info()
        if isinstance(fetched_labels,dict) and fetched_labels.get('data') and not all(all(item == '' for item in sublist) for sublist in fetched_labels.get('data', [])):
            _labels = fetched_labels.get('data')
            new_labels = [(label[1],label[0]) for label in _labels]
            default_label = new_labels[3][0]
            default_label_id = new_labels[3][1]
            def_label_max_emails = [label[3] for label in _labels if label[0] == default_label_id][0]
            step = def_label_max_emails/20
            value = int(step*2)
            return fetched_labels, gr.Dropdown(choices=new_labels, value=default_label), gr.Slider(maximum=def_label_max_emails, value=value, step=step, info=f"To analyse (from latest to oldest). Default value is 10% of maximum '{def_label_max_emails}'"), gr.Checkbox(value=False), gr.Button(value="Refresh Label Summary"), gr.Markdown(value=None), gr.Button(variant='secondary',visible=True)
        else:
            return gr.DataFrame(value=LABEL_DB.values.tolist()), gr.Dropdown(value='CATEGORY_PROMOTIONS'), gr.Slider(value=10), gr.Checkbox(value=False), gr.Button(value="Fetch Label Summary"), gr.Markdown(visible=True,value="🔴 Please connect to Gmail to fetch label summary"), gr.Button(variant='primary',visible=True)
    main_app.load(change_labels,None,
        [labels,labels_choices,max_emails_slider,create_csv_checkbox,get_labels_btn,get_labels_update,gmail_authenticate_btn])
    get_labels_btn.click(change_labels,None,
        [labels,labels_choices,max_emails_slider,create_csv_checkbox,get_labels_btn,get_labels_update,gmail_authenticate_btn])
    
    def update_max_emails(labels,labels_choices,def_max,evt:gr.SelectData):
        try:
            def_label_max_emails = [label[3] for label in labels if label[0] == labels_choices][0]
        except:
            def_label_max_emails = -1
        if def_label_max_emails >= 0:
            step = def_label_max_emails/20
            value = int(step*2)
            if type(def_label_max_emails) == int:
                return gr.Slider(maximum=def_label_max_emails, value=value, step=step, info=f"To analyse (from latest to oldest). Default value is 10% of maximum '{def_label_max_emails}'"), gr.Checkbox(value=False)
            else:
                return gr.Slider(maximum=def_max), gr.Checkbox(value=False)
    labels_choices.select(update_max_emails,
        [labels,labels_choices,max_emails],[max_emails_slider,create_csv_checkbox])

    def update_labels(labels,labels_choices,max_emails,evt:gr.SelectData):
        labels_choices = labels[evt.index[0]][evt.index[1]]
        max_emails, csv_checkbox = update_max_emails(labels,labels_choices,max_emails,evt)
        return labels_choices, max_emails, csv_checkbox
    labels.select(update_labels,[labels, labels_choices, max_emails],
        [labels_choices,max_emails_slider,create_csv_checkbox])

    def analyze_btn_deactivate():
        return gr.Button(interactive=False)
    get_labels_btn.click(analyze_btn_deactivate,None,analyze_btn)
    
    def analyze_btn_activate():
        return gr.Button(interactive=True)
    labels.change(analyze_btn_activate,None,analyze_btn)
    
    downloadable_file_paths = gr.DataFrame(label="Files Created for the Last Analysis",value=[FILE_PATHS],type='array',col_count=(len(FILE_PATHS),'fixed'),row_count=(1,'dynamic'),interactive=False,height=216,visible=False)
    analyze_btn.click(get_unread_emails,
        [labels_choices, max_emails_slider, create_csv_checkbox],[update, downloadable_file_paths, analysis, domain_analysis, sample_emails, unsub_links, error_emails])
    
    selected_csv_option = gr.Checkbox(value=False,visible=False)
    def last_csv_option(selected_option):
        return gr.Checkbox(value=selected_option)
    analyze_btn.click(last_csv_option,create_csv_checkbox,selected_csv_option)
    
    def download_links_update(downloadable_file_paths):
        return gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][5],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][1],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][0],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][2],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][3],interactive=True),gr.DownloadButton(label="Download & Delete",value=downloadable_file_paths[0][4],interactive=True)
    downloadable_file_paths.change(download_links_update,downloadable_file_paths,
        [download_btn,domain_analysis_download_btn,sender_analysis_download_btn,emails_download_btn,unsub_links_download_btn,email_processing_errors_download_btn])
            
    def reconnect_to_gmail(analyze_status):
        if isinstance(analyze_status,str) and 'no connection with gmailapi' in analyze_status.lower():
            return gr.Button(variant='primary',visible=True)
        else:
            return gr.Button(variant='secondary',visible=True)
    update.change(reconnect_to_gmail,update,gmail_authenticate_btn)

    def delete(file,sample_file,analysis_status,selected_csv_option):
        file_to_delete = os.path.basename(file)
        if 'Gmail0_SAMPLE' not in file_to_delete and selected_csv_option and "or download it as csv or" in analysis_status:
            file_to_delete = os.path.join(DATA_LOCATION, file_to_delete)
            try:
                if os.path.exists(file_to_delete):
                    os.remove(file_to_delete)
                    print(f"File {file_to_delete} has been deleted.")
                    label="Downloaded & Deleted! Now, clean your inbox?"
                else:
                    label="File Not Found! Click on 'Analyse'"
            except Exception as error:
                print(f"""🔴 Error! {error}""")
                label="Facing Error! Try another time"
        else:
            label="Tick 'Create CSV/Excel', click on 'Analyse' & wait for completion!"
        return gr.DownloadButton(value=sample_file[0][0],label=label)
    download_btn.click(delete,
        [download_btn,gr.List([[FILE_PATHS[5]]],visible=False),update,selected_csv_option],download_btn)
    domain_analysis_download_btn.click(delete,
        [domain_analysis_download_btn,gr.List([[FILE_PATHS[1]]],visible=False),update,selected_csv_option],domain_analysis_download_btn)
    sender_analysis_download_btn.click(delete,
        [sender_analysis_download_btn,gr.List([[FILE_PATHS[0]]],visible=False),update,selected_csv_option],sender_analysis_download_btn)
    emails_download_btn.click(delete,
        [emails_download_btn,gr.List([[FILE_PATHS[2]]],visible=False),update,selected_csv_option],emails_download_btn)
    unsub_links_download_btn.click(delete,
        [unsub_links_download_btn,gr.List([[FILE_PATHS[3]]],visible=False),update,selected_csv_option],unsub_links_download_btn)
    email_processing_errors_download_btn.click(delete,
        [email_processing_errors_download_btn,gr.List([[FILE_PATHS[4]]],visible=False),update,selected_csv_option],email_processing_errors_download_btn)
    
    def send_to_notion_deactivate():
        return gr.Button(interactive=False)
    analyze_btn.click(send_to_notion_deactivate,None,[to_notion_btn])
    
    def send_to_notion_activate():
        return gr.Button(interactive=True)
    domain_analysis.change(
        send_to_notion_activate,None,[to_notion_btn])
    
    def email0_to_notion_wrapper(df1_, df2_, df3_, key_, page_id_, page_type_, def_page_link_):
        for _gen_page_link, _progress_update in email0_to_notion([df1_, df2_, df3_], [EMAIL_SUMMARY_COLS, EMAIL_SUMMARY_COLS, UNSUB_COLS], 
            [20, 20, 20], ['Domain-wise (Top 20) Unread Emails Analysis', 'Sender-wise (Top 20) Unread Emails Analysis', 'Unsubscribe Links (Top 20) for Unread Emails'],
            'Unread Emails Analysis '+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f"),
            [key_, page_id_, page_type_], def_page_link_):
            yield _gen_page_link, _progress_update
    to_notion_btn.click(
        fn=email0_to_notion_wrapper,
        inputs=[domain_analysis, analysis, unsub_links, user_notion_access_token, user_notion_page_id, selected_page_type, email0_page_link],
        outputs=[email0_page_link,to_notion_update])
    
    
app = gr.mount_gradio_app(app, main_app, path=APP_URL, auth_dependency=app_auth)
app = gr.mount_gradio_app(app, main_app, path=APP_ALTERNATE_ROUTE, auth=pwd_auth)

if __name__ == "__main__":
    uvicorn.run(app, port=9000)