File size: 115,577 Bytes
db5855f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f6aa8c52-9bde-41a6-a5f7-4fa93d5c2a6c",
   "metadata": {},
   "source": [
    "# LLM Instruction-following pipeline with OpenVINO \n",
    "\n",
    "LLM stands for “Large Language Model,” which refers to a type of artificial intelligence model that is designed to understand and generate human-like text based on the input it receives. LLMs are trained on large datasets of text to learn patterns, grammar, and semantic relationships, allowing them to generate coherent and contextually relevant responses. One core capability of Large Language Models (LLMs) is to follow natural language instructions. Instruction-following models are capable of generating text in response to prompts and are often used for tasks like writing assistance, chatbots, and content generation.\n",
    "\n",
    "In this tutorial, we consider how to run an instruction-following text generation pipeline using popular LLMs and OpenVINO. We will use pre-trained models from the [Hugging Face Transformers](https://huggingface.co/docs/transformers/index) library. To simplify the user experience, the [Hugging Face Optimum Intel](https://huggingface.co/docs/optimum/intel/index) library converts the models to OpenVINO™ IR format.\n",
    "\n",
    "The tutorial consists of the following steps:\n",
    "\n",
    "- Install prerequisites\n",
    "- Download and convert the model from a public source using the [OpenVINO integration with Hugging Face Optimum](https://huggingface.co/blog/openvino).\n",
    "- Compress model weights to INT8 and INT4 with [OpenVINO NNCF](https://github.com/openvinotoolkit/nncf)\n",
    "- Create an instruction-following inference pipeline\n",
    "- Run instruction-following pipeline\n",
    "\n",
    "\n",
    "#### Table of contents:\n",
    "\n",
    "- [Prerequisites](#Prerequisites)\n",
    "- [Select model for inference](#Select-model-for-inference)\n",
    "- [Instantiate Model using Optimum Intel](#Instantiate-Model-using-Optimum-Intel)\n",
    "- [Compress model weights](#Compress-model-weights)\n",
    "    - [Weights Compression using Optimum Intel](#Weights-Compression-using-Optimum-Intel)\n",
    "    - [Weights Compression using NNCF](#Weights-Compression-using-NNCF)\n",
    "- [Select device for inference and model variant](#Select-device-for-inference-and-model-variant)\n",
    "- [Create an instruction-following inference pipeline](#Create-an-instruction-following-inference-pipeline)\n",
    "    - [Setup imports](#Setup-imports)\n",
    "    - [Prepare template for user prompt](#Prepare-template-for-user-prompt)\n",
    "    - [Main generation function](#Main-generation-function)\n",
    "    - [Helpers for application](#Helpers-for-application)\n",
    "- [Run instruction-following pipeline](#Run-instruction-following-pipeline)\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "027108c2-1fbe-4be5-9e23-3fc359185a42",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5d0473c6-3734-422d-a370-2e39d576be0e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
      "ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
      "openvino-dev 2024.2.0 requires openvino==2024.2.0, but you have openvino 2024.3.0.dev20240627 which is incompatible.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n"
     ]
    }
   ],
   "source": [
    "%pip install -Uq pip\n",
    "%pip uninstall -q -y optimum optimum-intel\n",
    "%pip install --pre -Uq openvino openvino-tokenizers[transformers] --extra-index-url https://storage.openvinotoolkit.org/simple/wheels/nightly\n",
    "%pip install -q \"torch>=2.1\" \"nncf>=2.7\" \"transformers>=4.36.0\" onnx \"optimum>=1.16.1\" \"accelerate\" \"datasets>=2.14.6\" \"gradio>=4.19\" \"git+https://github.com/huggingface/optimum-intel.git\" --extra-index-url https://download.pytorch.org/whl/cpu"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "611cc777-d5bc-4c7b-92e4-a4befa13b2ce",
   "metadata": {},
   "source": [
    "## Select model for inference\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "The tutorial supports different models, you can select one from the provided options to compare the quality of open source LLM solutions.\n",
    ">**Note**: conversion of some models can require additional actions from user side and at least 64GB RAM for conversion.\n",
    "\n",
    "The available options are:\n",
    "\n",
    "* **tiny-llama-1b-chat** - This is the chat model finetuned on top of [TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T](https://huggingface.co/TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T). The TinyLlama project aims to pretrain a 1.1B Llama model on 3 trillion tokens with the adoption of the same architecture and tokenizer as Llama 2. This means TinyLlama can be plugged and played in many open-source projects built upon Llama. Besides, TinyLlama is compact with only 1.1B parameters. This compactness allows it to cater to a multitude of applications demanding a restricted computation and memory footprint. More details about model can be found in [model card](https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0)\n",
    "* **phi-2** - Phi-2 is a Transformer with 2.7 billion parameters. It was trained using the same data sources as [Phi-1.5](https://huggingface.co/microsoft/phi-1_5), augmented with a new data source that consists of various NLP synthetic texts and filtered websites (for safety and educational value). When assessed against benchmarks testing common sense, language understanding, and logical reasoning, Phi-2 showcased a nearly state-of-the-art performance among models with less than 13 billion parameters. More details about model can be found in [model card](https://huggingface.co/microsoft/phi-2#limitations-of-phi-2).\n",
    "* **dolly-v2-3b** - Dolly 2.0 is an instruction-following large language model trained on the Databricks machine-learning platform that is licensed for commercial use. It is based on [Pythia](https://github.com/EleutherAI/pythia) and is trained on ~15k instruction/response fine-tuning records generated by Databricks employees in various capability domains, including brainstorming, classification, closed QA, generation, information extraction, open QA, and summarization. Dolly 2.0 works by processing natural language instructions and generating responses that follow the given instructions. It can be used for a wide range of applications, including closed question-answering, summarization, and generation. More details about model can be found in [model card](https://huggingface.co/databricks/dolly-v2-3b).\n",
    "* **red-pajama-3b-instruct** -  A 2.8B parameter pre-trained language model based on GPT-NEOX architecture. The model was fine-tuned for few-shot applications on the data of [GPT-JT](https://huggingface.co/togethercomputer/GPT-JT-6B-v1), with exclusion of tasks that overlap with the HELM core scenarios.More details about model can be found in [model card](https://huggingface.co/togethercomputer/RedPajama-INCITE-Instruct-3B-v1).\n",
    "* **mistral-7b** - The Mistral-7B-v0.2 Large Language Model (LLM) is a pretrained generative text model with 7 billion parameters. You can find more details about model in the [model card](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2), [paper](https://arxiv.org/abs/2310.06825) and [release blog post](https://mistral.ai/news/announcing-mistral-7b/).\n",
    "* **llama-3-8b-instruct** - Llama 3 is an auto-regressive language model that uses an optimized transformer architecture. The tuned versions use supervised fine-tuning (SFT) and reinforcement learning with human feedback (RLHF) to align with human preferences for helpfulness and safety. The Llama 3 instruction tuned models are optimized for dialogue use cases and outperform many of the available open source chat models on common industry benchmarks. More details about model can be found in [Meta blog post](https://ai.meta.com/blog/meta-llama-3/), [model website](https://llama.meta.com/llama3) and [model card](https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct).\n",
    ">**Note**: run model with demo, you will need to accept license agreement. \n",
    ">You must be a registered user in 🤗 Hugging Face Hub. Please visit [HuggingFace model card](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf), carefully read terms of usage and click accept button.  You will need to use an access token for the code below to run. For more information on access tokens, refer to [this section of the documentation](https://huggingface.co/docs/hub/security-tokens).\n",
    ">You can login on Hugging Face Hub in notebook environment, using following code:\n",
    " \n",
    "```python\n",
    "    ## login to huggingfacehub to get access to pretrained model \n",
    "\n",
    "    from huggingface_hub import notebook_login, whoami\n",
    "\n",
    "    try:\n",
    "        whoami()\n",
    "        print('Authorization token already provided')\n",
    "    except OSError:\n",
    "        notebook_login()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "51920510-effc-49ef-8c6f-81c951d96a9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "import requests\n",
    "\n",
    "# Fetch `notebook_utils` module\n",
    "r = requests.get(\n",
    "    url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
    ")\n",
    "open(\"notebook_utils.py\", \"w\").write(r.text)\n",
    "from notebook_utils import download_file\n",
    "\n",
    "if not Path(\"./config.py\").exists():\n",
    "    download_file(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/notebooks/llm-question-answering/config.py\")\n",
    "from config import SUPPORTED_LLM_MODELS\n",
    "import ipywidgets as widgets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "27b42290-a9b5-4453-9a4c-ffa44bbd966d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9e754e8bf3ff46f59b28018d9d8cd3e4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Model:', index=1, options=('tiny-llama-1b', 'phi-2', 'dolly-v2-3b', 'red-pajama-instruct…"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model_ids = list(SUPPORTED_LLM_MODELS)\n",
    "\n",
    "model_id = widgets.Dropdown(\n",
    "    options=model_ids,\n",
    "    value=model_ids[1],\n",
    "    description=\"Model:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "model_id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "37e9634f-4fc7-4d9c-9ade-b3e8684a0828",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Selected model phi-2\n"
     ]
    }
   ],
   "source": [
    "model_configuration = SUPPORTED_LLM_MODELS[model_id.value]\n",
    "print(f\"Selected model {model_id.value}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "4e4fd394-b4fb-4eef-8bdc-d116572aa8f0",
   "metadata": {},
   "source": [
    "## Instantiate Model using Optimum Intel\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Optimum Intel can be used to load optimized models from the [Hugging Face Hub](https://huggingface.co/docs/optimum/intel/hf.co/models) and create pipelines to run an inference with OpenVINO Runtime using Hugging Face APIs. The Optimum Inference models are API compatible with Hugging Face Transformers models.  This means we just need to replace `AutoModelForXxx` class with the corresponding `OVModelForXxx` class.\n",
    "\n",
    "Below is an example of the RedPajama model\n",
    "\n",
    "```diff\n",
    "-from transformers import AutoModelForCausalLM\n",
    "+from optimum.intel.openvino import OVModelForCausalLM\n",
    "from transformers import AutoTokenizer, pipeline\n",
    "\n",
    "model_id = \"togethercomputer/RedPajama-INCITE-Chat-3B-v1\"\n",
    "-model = AutoModelForCausalLM.from_pretrained(model_id)\n",
    "+model = OVModelForCausalLM.from_pretrained(model_id, export=True)\n",
    "```\n",
    "\n",
    "Model class initialization starts with calling `from_pretrained` method. When downloading and converting the Transformers model, the parameter `export=True` should be added. We can save the converted model for the next usage with the `save_pretrained` method.\n",
    "Tokenizer class and pipelines API are compatible with Optimum models.\n",
    "\n",
    "To optimize the generation process and use memory more efficiently, the `use_cache=True` option is enabled. Since the output side is auto-regressive, an output token hidden state remains the same once computed for every further generation step. Therefore, recomputing it every time you want to generate a new token seems wasteful. With the cache, the model saves the hidden state once it has been computed. The model only computes the one for the most recently generated output token at each time step, re-using the saved ones for hidden tokens. This reduces the generation complexity from $O(n^3)$ to $O(n^2)$ for a transformer model. More details about how it works can be found in this [article](https://scale.com/blog/pytorch-improvements#Text%20Translation). With this option, the model gets the previous step's hidden states (cached attention keys and values) as input and additionally provides hidden states for the current step as output. It means for all next iterations, it is enough to provide only a new token obtained from the previous step and cached key values to get the next token prediction. \n",
    "\n",
    "## Compress model weights\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "The Weights Compression algorithm is aimed at compressing the weights of the models and can be used to optimize the model footprint and performance of large models where the size of weights is relatively larger than the size of activations, for example, Large Language Models (LLM). Compared to INT8 compression, INT4 compression improves performance even more but introduces a minor drop in prediction quality.\n",
    "\n",
    "\n",
    "### Weights Compression using Optimum Intel\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Optimum Intel supports weight compression via NNCF out of the box. For 8-bit compression we pass `load_in_8bit=True` to `from_pretrained()` method of `OVModelForCausalLM`. For 4 bit compression we provide `quantization_config=OVWeightQuantizationConfig(bits=4, ...)` argument containing number of bits and other compression parameters. An example of this approach usage you can find in [llm-chatbot notebook](../llm-chatbot)\n",
    "\n",
    "### Weights Compression using NNCF\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "You also can perform weights compression for OpenVINO models using NNCF directly. `nncf.compress_weights` function accepts the OpenVINO model instance and compresses its weights for Linear and Embedding layers. We will consider this variant in this notebook for both int4 and int8 compression.\n",
    "\n",
    "\n",
    ">**Note**: This tutorial involves conversion model for FP16 and INT4/INT8 weights compression scenarios. It may be memory and time-consuming in the first run. You can manually control the compression precision below.\n",
    ">**Note**: There may be no speedup for INT4/INT8 compressed models on dGPU"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f81602ca-4674-4b61-b2c8-ca11631428b1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "52695cd0fed544ca90f54f97bb9b1f69",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Checkbox(value=True, description='Prepare INT4 model')"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9f35f892ffe247eda40119c6d96fc9a5",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Checkbox(value=False, description='Prepare INT8 model')"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "32fcf7ba43e34ce6b0f4d3ac71908f2e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Checkbox(value=False, description='Prepare FP16 model')"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import display\n",
    "\n",
    "prepare_int4_model = widgets.Checkbox(\n",
    "    value=True,\n",
    "    description=\"Prepare INT4 model\",\n",
    "    disabled=False,\n",
    ")\n",
    "prepare_int8_model = widgets.Checkbox(\n",
    "    value=False,\n",
    "    description=\"Prepare INT8 model\",\n",
    "    disabled=False,\n",
    ")\n",
    "prepare_fp16_model = widgets.Checkbox(\n",
    "    value=False,\n",
    "    description=\"Prepare FP16 model\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "display(prepare_int4_model)\n",
    "display(prepare_int8_model)\n",
    "display(prepare_fp16_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0066fbec-b89b-4caa-94fb-9ea8598c22e0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino\n"
     ]
    }
   ],
   "source": [
    "from pathlib import Path\n",
    "import logging\n",
    "import openvino as ov\n",
    "import nncf\n",
    "from optimum.intel.openvino import OVModelForCausalLM, OVWeightQuantizationConfig\n",
    "import gc\n",
    "\n",
    "\n",
    "nncf.set_log_level(logging.ERROR)\n",
    "\n",
    "pt_model_id = model_configuration[\"model_id\"]\n",
    "fp16_model_dir = Path(model_id.value) / \"FP16\"\n",
    "int8_model_dir = Path(model_id.value) / \"INT8_compressed_weights\"\n",
    "int4_model_dir = Path(model_id.value) / \"INT4_compressed_weights\"\n",
    "\n",
    "core = ov.Core()\n",
    "\n",
    "\n",
    "def convert_to_fp16():\n",
    "    if (fp16_model_dir / \"openvino_model.xml\").exists():\n",
    "        return\n",
    "    ov_model = OVModelForCausalLM.from_pretrained(pt_model_id, export=True, compile=False, load_in_8bit=False)\n",
    "    ov_model.half()\n",
    "    ov_model.save_pretrained(fp16_model_dir)\n",
    "    del ov_model\n",
    "    gc.collect()\n",
    "\n",
    "\n",
    "def convert_to_int8():\n",
    "    if (int8_model_dir / \"openvino_model.xml\").exists():\n",
    "        return\n",
    "    ov_model = OVModelForCausalLM.from_pretrained(pt_model_id, export=True, compile=False, load_in_8bit=True)\n",
    "    ov_model.save_pretrained(int8_model_dir)\n",
    "    del ov_model\n",
    "    gc.collect()\n",
    "\n",
    "\n",
    "def convert_to_int4():\n",
    "    compression_configs = {\n",
    "        \"mistral-7b\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 64,\n",
    "            \"ratio\": 0.6,\n",
    "        },\n",
    "        \"red-pajama-3b-instruct\": {\n",
    "            \"sym\": False,\n",
    "            \"group_size\": 128,\n",
    "            \"ratio\": 0.5,\n",
    "        },\n",
    "        \"dolly-v2-3b\": {\"sym\": False, \"group_size\": 32, \"ratio\": 0.5},\n",
    "        \"llama-3-8b-instruct\": {\"sym\": True, \"group_size\": 128, \"ratio\": 1.0},\n",
    "        \"default\": {\n",
    "            \"sym\": False,\n",
    "            \"group_size\": 128,\n",
    "            \"ratio\": 0.8,\n",
    "        },\n",
    "    }\n",
    "\n",
    "    model_compression_params = compression_configs.get(model_id.value, compression_configs[\"default\"])\n",
    "    if (int4_model_dir / \"openvino_model.xml\").exists():\n",
    "        return\n",
    "    ov_model = OVModelForCausalLM.from_pretrained(\n",
    "        pt_model_id,\n",
    "        export=True,\n",
    "        compile=False,\n",
    "        quantization_config=OVWeightQuantizationConfig(bits=4, **model_compression_params),\n",
    "    )\n",
    "    ov_model.save_pretrained(int4_model_dir)\n",
    "    del ov_model\n",
    "    gc.collect()\n",
    "\n",
    "\n",
    "if prepare_fp16_model.value:\n",
    "    convert_to_fp16()\n",
    "if prepare_int8_model.value:\n",
    "    convert_to_int8()\n",
    "if prepare_int4_model.value:\n",
    "    convert_to_int4()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5f31838-c7d6-4f52-aa2d-1f29c6f3b397",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "60355f86-2250-4ebe-82ac-950f2d4fb01b",
   "metadata": {},
   "source": [
    "Let's compare model size for different compression types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "42c7b254-1ce4-4f23-813a-9bdc23aed327",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Size of model with INT4 compressed weights is 1739.13 MB\n"
     ]
    }
   ],
   "source": [
    "fp16_weights = fp16_model_dir / \"openvino_model.bin\"\n",
    "int8_weights = int8_model_dir / \"openvino_model.bin\"\n",
    "int4_weights = int4_model_dir / \"openvino_model.bin\"\n",
    "\n",
    "if fp16_weights.exists():\n",
    "    print(f\"Size of FP16 model is {fp16_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n",
    "for precision, compressed_weights in zip([8, 4], [int8_weights, int4_weights]):\n",
    "    if compressed_weights.exists():\n",
    "        print(f\"Size of model with INT{precision} compressed weights is {compressed_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n",
    "    if compressed_weights.exists() and fp16_weights.exists():\n",
    "        print(f\"Compression rate for INT{precision} model: {fp16_weights.stat().st_size / compressed_weights.stat().st_size:.3f}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "3df73379-bccc-41b1-9c94-c3040819805b",
   "metadata": {},
   "source": [
    "## Select device for inference and model variant\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    ">**Note**: There may be no speedup for INT4/INT8 compressed models on dGPU."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d2d7bf5b-8a05-4c3b-a36b-631af5c197e9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9c395bc265ed44de84d2369262ae8610",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Device:', options=('CPU', 'GPU', 'AUTO'), value='CPU')"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "core = ov.Core()\n",
    "\n",
    "support_devices = core.available_devices\n",
    "if \"NPU\" in support_devices:\n",
    "    support_devices.remove(\"NPU\")\n",
    "\n",
    "device = widgets.Dropdown(\n",
    "    options=support_devices + [\"AUTO\"],\n",
    "    value=\"CPU\",\n",
    "    description=\"Device:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "device"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "24532480-80a5-4953-9cd6-78ac51a1cd8f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c5d8f2038f1247dc98723fa891aa7c4e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Model to run:', options=('INT4',), value='INT4')"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "available_models = []\n",
    "if int4_model_dir.exists():\n",
    "    available_models.append(\"INT4\")\n",
    "if int8_model_dir.exists():\n",
    "    available_models.append(\"INT8\")\n",
    "if fp16_model_dir.exists():\n",
    "    available_models.append(\"FP16\")\n",
    "\n",
    "model_to_run = widgets.Dropdown(\n",
    "    options=available_models,\n",
    "    value=available_models[0],\n",
    "    description=\"Model to run:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "model_to_run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5259c1c5-4128-4210-9ad2-faf33ee40e86",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading model from phi-2\\INT4_compressed_weights\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
      "Compiling the model to CPU ...\n"
     ]
    }
   ],
   "source": [
    "from transformers import AutoTokenizer\n",
    "\n",
    "if model_to_run.value == \"INT4\":\n",
    "    model_dir = int4_model_dir\n",
    "elif model_to_run.value == \"INT8\":\n",
    "    model_dir = int8_model_dir\n",
    "else:\n",
    "    model_dir = fp16_model_dir\n",
    "print(f\"Loading model from {model_dir}\")\n",
    "\n",
    "model_name = model_configuration[\"model_id\"]\n",
    "ov_config = {\"PERFORMANCE_HINT\": \"LATENCY\", \"NUM_STREAMS\": \"1\", \"CACHE_DIR\": \"\"}\n",
    "\n",
    "tok = AutoTokenizer.from_pretrained(model_name)\n",
    "\n",
    "ov_model = OVModelForCausalLM.from_pretrained(\n",
    "    model_dir,\n",
    "    device=device.value,\n",
    "    ov_config=ov_config,\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "bf13f6c3-6671-408e-ae0e-aaa3d8a6eaac",
   "metadata": {},
   "source": [
    "## Create an instruction-following inference pipeline\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    " \n",
    " The `run_generation` function accepts user-provided text input, tokenizes it, and runs the generation process. Text generation is an iterative process, where each next token depends on previously generated until a maximum number of tokens or stop generation condition is not reached. To obtain intermediate generation results without waiting until when generation is finished, we will use [`TextIteratorStreamer`](https://huggingface.co/docs/transformers/main/en/internal/generation_utils#transformers.TextIteratorStreamer), provided as part of HuggingFace [Streaming API](https://huggingface.co/docs/transformers/main/en/generation_strategies#streaming).\n",
    " \n",
    "The diagram below illustrates how the instruction-following pipeline works\n",
    "\n",
    "![generation pipeline)](https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/e881f4a4-fcc8-427a-afe1-7dd80aebd66e)\n",
    "\n",
    "As can be seen, on the first iteration, the user provided instructions converted to token ids using a tokenizer, then prepared input provided to the model. The model generates probabilities for all tokens in logits format  The way the next token will be selected over predicted probabilities is driven by the selected decoding methodology. You can find more information about the most popular decoding methods in this [blog](https://huggingface.co/blog/how-to-generate).\n",
    "\n",
    "There are several parameters that can control text generation quality:\n",
    "\n",
    "  * `Temperature` is a parameter used to control the level of creativity in AI-generated text. By adjusting the `temperature`, you can influence the AI model's probability distribution, making the text more focused or diverse.  \n",
    "  Consider the following example: The AI model has to complete the sentence \"The cat is ____.\" with the following token probabilities:  \n",
    "\n",
    "    playing: 0.5  \n",
    "    sleeping: 0.25  \n",
    "    eating: 0.15  \n",
    "    driving: 0.05  \n",
    "    flying: 0.05  \n",
    "\n",
    "    - **Low temperature** (e.g., 0.2): The AI model becomes more focused and deterministic, choosing tokens with the highest probability, such as \"playing.\"  \n",
    "    - **Medium temperature** (e.g., 1.0): The AI model maintains a balance between creativity and focus, selecting tokens based on their probabilities without significant bias, such as \"playing,\" \"sleeping,\" or \"eating.\"  \n",
    "    - **High temperature** (e.g., 2.0): The AI model becomes more adventurous, increasing the chances of selecting less likely tokens, such as \"driving\" and \"flying.\"\n",
    "  * `Top-p`, also known as nucleus sampling, is a parameter used to control the range of tokens considered by the AI model based on their cumulative probability. By adjusting the `top-p` value, you can influence the AI model's token selection, making it more focused or diverse.\n",
    "  Using the same example with the cat, consider the following top_p settings:  \n",
    "    - **Low top_p** (e.g., 0.5): The AI model considers only tokens with the highest cumulative probability, such as \"playing.\"  \n",
    "    - **Medium top_p** (e.g., 0.8): The AI model considers tokens with a higher cumulative probability, such as \"playing,\" \"sleeping,\" and \"eating.\"  \n",
    "    - **High top_p** (e.g., 1.0): The AI model considers all tokens, including those with lower probabilities, such as \"driving\" and \"flying.\" \n",
    "  * `Top-k` is another popular sampling strategy. In comparison with Top-P, which chooses from the smallest possible set of words whose cumulative probability exceeds the probability P, in Top-K sampling K most likely next words are filtered and the probability mass is redistributed among only those K next words. In our example with cat, if k=3, then only \"playing\", \"sleeping\" and \"eating\" will be taken into account as possible next word.\n",
    "\n",
    "To optimize the generation process and use memory more efficiently, the `use_cache=True` option is enabled. Since the output side is auto-regressive, an output token hidden state remains the same once computed for every further generation step. Therefore, recomputing it every time you want to generate a new token seems wasteful. With the cache, the model saves the hidden state once it has been computed. The model only computes the one for the most recently generated output token at each time step, re-using the saved ones for hidden tokens. This reduces the generation complexity from O(n^3) to O(n^2) for a transformer model. More details about how it works can be found in this [article](https://scale.com/blog/pytorch-improvements#Text%20Translation). With this option, the model gets the previous step's hidden states (cached attention keys and values) as input and additionally provides hidden states for the current step as output. It means for all next iterations, it is enough to provide only a new token obtained from the previous step and cached key values to get the next token prediction. \n",
    "\n",
    "The generation cycle repeats until the end of the sequence token is reached or it also can be interrupted when maximum tokens will be generated. As already mentioned before, we can enable printing current generated tokens without waiting until when the whole generation is finished using Streaming API, it adds a new token to the output queue and then prints them when they are ready."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "eb7af692-0a15-4493-86ef-a80cda21551c",
   "metadata": {},
   "source": [
    "### Setup imports\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "19d23a99-3284-42db-b7dc-5805d219f70d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from threading import Thread\n",
    "from time import perf_counter\n",
    "from typing import List\n",
    "import gradio as gr\n",
    "from transformers import AutoTokenizer, TextIteratorStreamer\n",
    "import numpy as np"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b341a9e6-290d-4780-90da-1ee64cee436d",
   "metadata": {},
   "source": [
    "### Prepare template for user prompt\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "For effective generation, model expects to have input in specific format. The code below prepare template for passing user instruction into model with providing additional context."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e2638c5b-47ad-4213-80da-8cfc2659b3aa",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n"
     ]
    }
   ],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
    "tokenizer_kwargs = model_configuration.get(\"toeknizer_kwargs\", {})\n",
    "\n",
    "\n",
    "def get_special_token_id(tokenizer: AutoTokenizer, key: str) -> int:\n",
    "    \"\"\"\n",
    "    Gets the token ID for a given string that has been added to the tokenizer as a special token.\n",
    "\n",
    "    Args:\n",
    "        tokenizer (PreTrainedTokenizer): the tokenizer\n",
    "        key (str): the key to convert to a single token\n",
    "\n",
    "    Raises:\n",
    "        RuntimeError: if more than one ID was generated\n",
    "\n",
    "    Returns:\n",
    "        int: the token ID for the given key\n",
    "    \"\"\"\n",
    "    token_ids = tokenizer.encode(key)\n",
    "    if len(token_ids) > 1:\n",
    "        raise ValueError(f\"Expected only a single token for '{key}' but found {token_ids}\")\n",
    "    return token_ids[0]\n",
    "\n",
    "\n",
    "response_key = model_configuration.get(\"response_key\")\n",
    "tokenizer_response_key = None\n",
    "\n",
    "if response_key is not None:\n",
    "    tokenizer_response_key = next(\n",
    "        (token for token in tokenizer.additional_special_tokens if token.startswith(response_key)),\n",
    "        None,\n",
    "    )\n",
    "\n",
    "end_key_token_id = None\n",
    "if tokenizer_response_key:\n",
    "    try:\n",
    "        end_key = model_configuration.get(\"end_key\")\n",
    "        if end_key:\n",
    "            end_key_token_id = get_special_token_id(tokenizer, end_key)\n",
    "        # Ensure generation stops once it generates \"### End\"\n",
    "    except ValueError:\n",
    "        pass\n",
    "\n",
    "prompt_template = model_configuration.get(\"prompt_template\", \"{instruction}\")\n",
    "end_key_token_id = end_key_token_id or tokenizer.eos_token_id\n",
    "pad_token_id = end_key_token_id or tokenizer.pad_token_id"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "55dbc4ae-da28-4be8-b928-3dd68c197937",
   "metadata": {},
   "source": [
    "### Main generation function\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "As it was discussed above, `run_generation` function is the entry point for starting generation. It gets provided input instruction as parameter and returns model response."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "27802e81-9d42-4d71-99ea-5f76db5237f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_generation(\n",
    "    user_text: str,\n",
    "    top_p: float,\n",
    "    temperature: float,\n",
    "    top_k: int,\n",
    "    max_new_tokens: int,\n",
    "    perf_text: str,\n",
    "):\n",
    "    \"\"\"\n",
    "    Text generation function\n",
    "\n",
    "    Parameters:\n",
    "      user_text (str): User-provided instruction for a generation.\n",
    "      top_p (float):  Nucleus sampling. If set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for a generation.\n",
    "      temperature (float): The value used to module the logits distribution.\n",
    "      top_k (int): The number of highest probability vocabulary tokens to keep for top-k-filtering.\n",
    "      max_new_tokens (int): Maximum length of generated sequence.\n",
    "      perf_text (str): Content of text field for printing performance results.\n",
    "    Returns:\n",
    "      model_output (str) - model-generated text\n",
    "      perf_text (str) - updated perf text filed content\n",
    "    \"\"\"\n",
    "\n",
    "    # Prepare input prompt according to model expected template\n",
    "    prompt_text = prompt_template.format(instruction=user_text)\n",
    "\n",
    "    # Tokenize the user text.\n",
    "    model_inputs = tokenizer(prompt_text, return_tensors=\"pt\", **tokenizer_kwargs)\n",
    "\n",
    "    # Start generation on a separate thread, so that we don't block the UI. The text is pulled from the streamer\n",
    "    # in the main thread. Adds timeout to the streamer to handle exceptions in the generation thread.\n",
    "    streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)\n",
    "    generate_kwargs = dict(\n",
    "        model_inputs,\n",
    "        streamer=streamer,\n",
    "        max_new_tokens=max_new_tokens,\n",
    "        do_sample=True,\n",
    "        top_p=top_p,\n",
    "        temperature=float(temperature),\n",
    "        top_k=top_k,\n",
    "        eos_token_id=end_key_token_id,\n",
    "        pad_token_id=pad_token_id,\n",
    "    )\n",
    "    t = Thread(target=ov_model.generate, kwargs=generate_kwargs)\n",
    "    t.start()\n",
    "\n",
    "    # Pull the generated text from the streamer, and update the model output.\n",
    "    model_output = \"\"\n",
    "    per_token_time = []\n",
    "    num_tokens = 0\n",
    "    start = perf_counter()\n",
    "    for new_text in streamer:\n",
    "        current_time = perf_counter() - start\n",
    "        model_output += new_text\n",
    "        perf_text, num_tokens = estimate_latency(current_time, perf_text, new_text, per_token_time, num_tokens)\n",
    "        yield model_output, perf_text\n",
    "        start = perf_counter()\n",
    "    return model_output, perf_text"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "6d7b7182-1d9b-485b-81f2-1a9fab6d5cd4",
   "metadata": {},
   "source": [
    "### Helpers for application\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "For making interactive user interface we will use Gradio library. The code bellow provides useful functions used for communication with UI elements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c9b2a2b7-5a91-470f-98d7-7355664bc1be",
   "metadata": {},
   "outputs": [],
   "source": [
    "def estimate_latency(\n",
    "    current_time: float,\n",
    "    current_perf_text: str,\n",
    "    new_gen_text: str,\n",
    "    per_token_time: List[float],\n",
    "    num_tokens: int,\n",
    "):\n",
    "    \"\"\"\n",
    "    Helper function for performance estimation\n",
    "\n",
    "    Parameters:\n",
    "      current_time (float): This step time in seconds.\n",
    "      current_perf_text (str): Current content of performance UI field.\n",
    "      new_gen_text (str): New generated text.\n",
    "      per_token_time (List[float]): history of performance from previous steps.\n",
    "      num_tokens (int): Total number of generated tokens.\n",
    "\n",
    "    Returns:\n",
    "      update for performance text field\n",
    "      update for a total number of tokens\n",
    "    \"\"\"\n",
    "    num_current_toks = len(tokenizer.encode(new_gen_text))\n",
    "    num_tokens += num_current_toks\n",
    "    per_token_time.append(num_current_toks / current_time)\n",
    "    if len(per_token_time) > 10 and len(per_token_time) % 4 == 0:\n",
    "        current_bucket = per_token_time[:-10]\n",
    "        return (\n",
    "            f\"Average generation speed: {np.mean(current_bucket):.2f} tokens/s. Total generated tokens: {num_tokens}\",\n",
    "            num_tokens,\n",
    "        )\n",
    "    return current_perf_text, num_tokens\n",
    "\n",
    "\n",
    "def reset_textbox(instruction: str, response: str, perf: str):\n",
    "    \"\"\"\n",
    "    Helper function for resetting content of all text fields\n",
    "\n",
    "    Parameters:\n",
    "      instruction (str): Content of user instruction field.\n",
    "      response (str): Content of model response field.\n",
    "      perf (str): Content of performance info filed\n",
    "\n",
    "    Returns:\n",
    "      empty string for each placeholder\n",
    "    \"\"\"\n",
    "    return \"\", \"\", \"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "d56f95e1-d2c5-4fd1-a6c2-757e46e6ccaf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " * Serving Flask app '__main__'\n",
      " * Debug mode: on\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.\n",
      " * Running on http://127.0.0.1:5000\n",
      "Press CTRL+C to quit\n",
      " * Restarting with stat\n"
     ]
    },
    {
     "ename": "SystemExit",
     "evalue": "1",
     "output_type": "error",
     "traceback": [
      "An exception has occurred, use %tb to see the full traceback.\n",
      "\u001b[1;31mSystemExit\u001b[0m\u001b[1;31m:\u001b[0m 1\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3585: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.\n",
      "  warn(\"To exit: use 'exit', 'quit', or Ctrl-D.\", stacklevel=1)\n"
     ]
    }
   ],
   "source": [
    "from flask import Flask, request, jsonify\n",
    "from werkzeug.security import generate_password_hash, check_password_hash\n",
    "import jwt\n",
    "import datetime\n",
    "\n",
    "app = Flask(__name__)\n",
    "app.config['SECRET_KEY'] = 'your_secret_key'\n",
    "\n",
    "# In-memory user storage (replace with a database in a real application)\n",
    "users = {}\n",
    "\n",
    "# User registration endpoint\n",
    "@app.route('/register', methods=['POST'])\n",
    "def register():\n",
    "    data = request.get_json()\n",
    "    username = data.get('username')\n",
    "    password = data.get('password')\n",
    "    \n",
    "    if username in users:\n",
    "        return jsonify({'message': 'User already exists'}), 400\n",
    "    \n",
    "    hashed_password = generate_password_hash(password, method='sha256')\n",
    "    users[username] = hashed_password\n",
    "    return jsonify({'message': 'User registered successfully'}), 201\n",
    "\n",
    "# User login endpoint\n",
    "@app.route('/login', methods=['POST'])\n",
    "def login():\n",
    "    data = request.get_json()\n",
    "    username = data.get('username')\n",
    "    password = data.get('password')\n",
    "    \n",
    "    if username not in users or not check_password_hash(users[username], password):\n",
    "        return jsonify({'message': 'Invalid credentials'}), 401\n",
    "    \n",
    "    token = jwt.encode({\n",
    "        'username': username,\n",
    "        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)\n",
    "    }, app.config['SECRET_KEY'])\n",
    "    \n",
    "    return jsonify({'token': token})\n",
    "\n",
    "# Token validation decorator\n",
    "def token_required(f):\n",
    "    def decorator(*args, **kwargs):\n",
    "        token = request.headers.get('x-access-token')\n",
    "        \n",
    "        if not token:\n",
    "            return jsonify({'message': 'Token is missing'}), 401\n",
    "        \n",
    "        try:\n",
    "            data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=[\"HS256\"])\n",
    "            current_user = data['username']\n",
    "        except:\n",
    "            return jsonify({'message': 'Token is invalid'}), 401\n",
    "        \n",
    "        return f(current_user, *args, **kwargs)\n",
    "    return decorator\n",
    "\n",
    "# Example chatbot logic\n",
    "def chatbot_response(question):\n",
    "    # Placeholder for LLM response (replace with actual chatbot logic)\n",
    "    return f\"Answering the question: {question}\"\n",
    "\n",
    "# Protected route for question answering\n",
    "@app.route('/qa', methods=['POST'])\n",
    "@token_required\n",
    "def question_answer(current_user):\n",
    "    data = request.get_json()\n",
    "    question = data.get('question')\n",
    "    answer = chatbot_response(question)\n",
    "    \n",
    "    return jsonify({'user': current_user, 'question': question, 'answer': answer})\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    app.run(debug=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "6022618f-cca2-41d9-8404-f9f2c4fe8adb",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.\n",
      " * Running on http://localhost:5000\n",
      "Press CTRL+C to quit\n",
      "127.0.0.1 - - [26/Jun/2024 18:18:04] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:18:07] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:18:10] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:18:13] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:22:02] \"GET / HTTP/1.1\" 404 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:26:56] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:26:57] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:27:10] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:27:11] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:32:03] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:32:55] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:32:55] \"GET / HTTP/1.1\" 404 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:33:53] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:33:53] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:33:53] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:33:53] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:33:53] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:33:53] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:34:35] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:34:38] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:34:49] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:34:51] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:34:51] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:37:39] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:37:40] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:37:40] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:37:41] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:37:47] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:37:55] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:38:00] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:38:20] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:39:51] \"GET / HTTP/1.1\" 404 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:41:46] \"GET / HTTP/1.1\" 404 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:42:29] \"GET / HTTP/1.1\" 404 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:44:30] \"GET / HTTP/1.1\" 404 -\n",
      "127.0.0.1 - - [26/Jun/2024 18:46:11] \"GET / HTTP/1.1\" 404 -\n",
      "127.0.0.1 - - [26/Jun/2024 19:34:21] \"GET / HTTP/1.1\" 404 -\n",
      "127.0.0.1 - - [26/Jun/2024 19:37:09] \"GET / HTTP/1.1\" 404 -\n",
      "127.0.0.1 - - [26/Jun/2024 19:44:34] \"GET / HTTP/1.1\" 404 -\n",
      "127.0.0.1 - - [26/Jun/2024 21:19:23] \"OPTIONS /register HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 21:19:32] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [26/Jun/2024 21:19:36] \"OPTIONS /login HTTP/1.1\" 200 -\n",
      "127.0.0.1 - - [27/Jun/2024 00:39:16] \"GET / HTTP/1.1\" 404 -\n"
     ]
    }
   ],
   "source": [
    "import threading\n",
    "\n",
    "def run_flask():\n",
    "    from werkzeug.serving import run_simple\n",
    "    run_simple('localhost', 5000, app)\n",
    "\n",
    "flask_thread = threading.Thread(target=run_flask)\n",
    "flask_thread.start()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "e42a1655-72b1-4600-b114-08dad5a21841",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Failed to decode JSON response\n",
      "Response status code: 500\n",
      "Response content: <!doctype html>\n",
      "<html lang=en>\n",
      "  <head>\n",
      "    <title>ValueError: Invalid hash method &#39;sha256&#39;.\n",
      " // Werkzeug Debugger</title>\n",
      "    <link rel=\"stylesheet\" href=\"?__debugger__=yes&amp;cmd=resource&amp;f=style.css\">\n",
      "    <link rel=\"shortcut icon\"\n",
      "        href=\"?__debugger__=yes&amp;cmd=resource&amp;f=console.png\">\n",
      "    <script src=\"?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js\"></script>\n",
      "    <script>\n",
      "      var CONSOLE_MODE = false,\n",
      "          EVALEX = true,\n",
      "          EVALEX_TRUSTED = false,\n",
      "          SECRET = \"z1FWOfqsTGEN9DnRn99M\";\n",
      "    </script>\n",
      "  </head>\n",
      "  <body style=\"background-color: #fff\">\n",
      "    <div class=\"debugger\">\n",
      "<h1>ValueError</h1>\n",
      "<div class=\"detail\">\n",
      "  <p class=\"errormsg\">ValueError: Invalid hash method &#39;sha256&#39;.\n",
      "</p>\n",
      "</div>\n",
      "<h2 class=\"traceback\">Traceback <em>(most recent call last)</em></h2>\n",
      "<div class=\"traceback\">\n",
      "  <h3></h3>\n",
      "  <ul><li><div class=\"frame\" id=\"frame-2062545657904\">\n",
      "  <h4>File <cite class=\"filename\">\"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\"</cite>,\n",
      "      line <em class=\"line\">1498</em>,\n",
      "      in <code class=\"function\">__call__</code></h4>\n",
      "  <div class=\"source library\"><pre class=\"line before\"><span class=\"ws\">    </span>) -&gt; cabc.Iterable[bytes]:</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>&#34;&#34;&#34;The WSGI server calls the Flask application object as the</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>WSGI application. This calls :meth:`wsgi_app`, which can be</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>wrapped to apply middleware.</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>&#34;&#34;&#34;</pre>\n",
      "<pre class=\"line current\"><span class=\"ws\">        </span>return self.wsgi_app(environ, start_response)</pre></div>\n",
      "</div>\n",
      "\n",
      "<li><div class=\"frame\" id=\"frame-2062545654992\">\n",
      "  <h4>File <cite class=\"filename\">\"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\"</cite>,\n",
      "      line <em class=\"line\">1476</em>,\n",
      "      in <code class=\"function\">wsgi_app</code></h4>\n",
      "  <div class=\"source library\"><pre class=\"line before\"><span class=\"ws\">            </span>try:</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">                </span>ctx.push()</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">                </span>response = self.full_dispatch_request()</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">            </span>except Exception as e:</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">                </span>error = e</pre>\n",
      "<pre class=\"line current\"><span class=\"ws\">                </span>response = self.handle_exception(e)</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">            </span>except:  # noqa: B001</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">                </span>error = sys.exc_info()[1]</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">                </span>raise</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">            </span>return response(environ, start_response)</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">        </span>finally:</pre></div>\n",
      "</div>\n",
      "\n",
      "<li><div class=\"frame\" id=\"frame-2062545660704\">\n",
      "  <h4>File <cite class=\"filename\">\"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\"</cite>,\n",
      "      line <em class=\"line\">1473</em>,\n",
      "      in <code class=\"function\">wsgi_app</code></h4>\n",
      "  <div class=\"source library\"><pre class=\"line before\"><span class=\"ws\">        </span>ctx = self.request_context(environ)</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>error: BaseException | None = None</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>try:</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">            </span>try:</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">                </span>ctx.push()</pre>\n",
      "<pre class=\"line current\"><span class=\"ws\">                </span>response = self.full_dispatch_request()</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">            </span>except Exception as e:</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">                </span>error = e</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">                </span>response = self.handle_exception(e)</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">            </span>except:  # noqa: B001</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">                </span>error = sys.exc_info()[1]</pre></div>\n",
      "</div>\n",
      "\n",
      "<li><div class=\"frame\" id=\"frame-2062545654880\">\n",
      "  <h4>File <cite class=\"filename\">\"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\"</cite>,\n",
      "      line <em class=\"line\">882</em>,\n",
      "      in <code class=\"function\">full_dispatch_request</code></h4>\n",
      "  <div class=\"source library\"><pre class=\"line before\"><span class=\"ws\">            </span>request_started.send(self, _async_wrapper=self.ensure_sync)</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">            </span>rv = self.preprocess_request()</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">            </span>if rv is None:</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">                </span>rv = self.dispatch_request()</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>except Exception as e:</pre>\n",
      "<pre class=\"line current\"><span class=\"ws\">            </span>rv = self.handle_user_exception(e)</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">        </span>return self.finalize_request(rv)</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">    </span>def finalize_request(</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">        </span>self,</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">        </span>rv: ft.ResponseReturnValue | HTTPException,</pre></div>\n",
      "</div>\n",
      "\n",
      "<li><div class=\"frame\" id=\"frame-2062545658352\">\n",
      "  <h4>File <cite class=\"filename\">\"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\"</cite>,\n",
      "      line <em class=\"line\">880</em>,\n",
      "      in <code class=\"function\">full_dispatch_request</code></h4>\n",
      "  <div class=\"source library\"><pre class=\"line before\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>try:</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">            </span>request_started.send(self, _async_wrapper=self.ensure_sync)</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">            </span>rv = self.preprocess_request()</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">            </span>if rv is None:</pre>\n",
      "<pre class=\"line current\"><span class=\"ws\">                </span>rv = self.dispatch_request()</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">        </span>except Exception as e:</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">            </span>rv = self.handle_user_exception(e)</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">        </span>return self.finalize_request(rv)</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">    </span>def finalize_request(</pre></div>\n",
      "</div>\n",
      "\n",
      "<li><div class=\"frame\" id=\"frame-2062545664288\">\n",
      "  <h4>File <cite class=\"filename\">\"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\"</cite>,\n",
      "      line <em class=\"line\">865</em>,\n",
      "      in <code class=\"function\">dispatch_request</code></h4>\n",
      "  <div class=\"source library\"><pre class=\"line before\"><span class=\"ws\">            </span>and req.method == &#34;OPTIONS&#34;</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>):</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">            </span>return self.make_default_options_response()</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span># otherwise dispatch to the handler for that endpoint</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>view_args: dict[str, t.Any] = req.view_args  # type: ignore[assignment]</pre>\n",
      "<pre class=\"line current\"><span class=\"ws\">        </span>return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">    </span>def full_dispatch_request(self) -&gt; Response:</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">        </span>&#34;&#34;&#34;Dispatches the request and on top of that performs request</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">        </span>pre and postprocessing as well as HTTP exception catching and</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">        </span>error handling.</pre></div>\n",
      "</div>\n",
      "\n",
      "<li><div class=\"frame\" id=\"frame-2062545663728\">\n",
      "  <h4>File <cite class=\"filename\">\"C:\\Users\\KIIT\\app.py\"</cite>,\n",
      "      line <em class=\"line\">22</em>,\n",
      "      in <code class=\"function\">register</code></h4>\n",
      "  <div class=\"source \"><pre class=\"line before\"><span class=\"ws\">    </span>password = data.get(&#39;password&#39;)</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">    </span>if username in users:</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>return jsonify({&#39;message&#39;: &#39;User already exists&#39;}), 400</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line current\"><span class=\"ws\">    </span>hashed_password = generate_password_hash(password, method=&#39;sha256&#39;)</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">    </span>users[username] = hashed_password</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">    </span>return jsonify({&#39;message&#39;: &#39;User registered successfully&#39;}), 201</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span># User login endpoint</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span>@app.route(&#39;/login&#39;, methods=[&#39;POST&#39;])</pre></div>\n",
      "</div>\n",
      "\n",
      "<li><div class=\"frame\" id=\"frame-2062545665856\">\n",
      "  <h4>File <cite class=\"filename\">\"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\werkzeug\\security.py\"</cite>,\n",
      "      line <em class=\"line\">105</em>,\n",
      "      in <code class=\"function\">generate_password_hash</code></h4>\n",
      "  <div class=\"source library\"><pre class=\"line before\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">    </span>.. versionchanged:: 2.3</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>All plain hashes are deprecated and will not be supported in Werkzeug 3.0.</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">    </span>&#34;&#34;&#34;</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">    </span>salt = gen_salt(salt_length)</pre>\n",
      "<pre class=\"line current\"><span class=\"ws\">    </span>h, actual_method = _hash_internal(method, salt, password)</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">    </span>return f&#34;{actual_method}${salt}${h}&#34;</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span>def check_password_hash(pwhash: str, password: str) -&gt; bool:</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">    </span>&#34;&#34;&#34;Securely check that the given stored password hash, previously generated using</pre></div>\n",
      "</div>\n",
      "\n",
      "<li><div class=\"frame\" id=\"frame-2062545656784\">\n",
      "  <h4>File <cite class=\"filename\">\"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\werkzeug\\security.py\"</cite>,\n",
      "      line <em class=\"line\">70</em>,\n",
      "      in <code class=\"function\">_hash_internal</code></h4>\n",
      "  <div class=\"source library\"><pre class=\"line before\"><span class=\"ws\">                </span>hash_name, password_bytes, salt_bytes, iterations</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">            </span>).hex(),</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">            </span>f&#34;pbkdf2:{hash_name}:{iterations}&#34;,</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">        </span>)</pre>\n",
      "<pre class=\"line before\"><span class=\"ws\">    </span>else:</pre>\n",
      "<pre class=\"line current\"><span class=\"ws\">        </span>raise ValueError(f&#34;Invalid hash method &#39;{method}&#39;.&#34;)</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span> </pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span>def generate_password_hash(</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\">    </span>password: str, method: str = &#34;scrypt&#34;, salt_length: int = 16</pre>\n",
      "<pre class=\"line after\"><span class=\"ws\"></span>) -&gt; str:</pre></div>\n",
      "</div>\n",
      "</ul>\n",
      "  <blockquote>ValueError: Invalid hash method &#39;sha256&#39;.\n",
      "</blockquote>\n",
      "</div>\n",
      "\n",
      "<div class=\"plain\">\n",
      "    <p>\n",
      "      This is the Copy/Paste friendly version of the traceback.\n",
      "    </p>\n",
      "    <textarea cols=\"50\" rows=\"10\" name=\"code\" readonly>Traceback (most recent call last):\n",
      "  File &#34;C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py&#34;, line 1498, in __call__\n",
      "    return self.wsgi_app(environ, start_response)\n",
      "  File &#34;C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py&#34;, line 1476, in wsgi_app\n",
      "    response = self.handle_exception(e)\n",
      "  File &#34;C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py&#34;, line 1473, in wsgi_app\n",
      "    response = self.full_dispatch_request()\n",
      "  File &#34;C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py&#34;, line 882, in full_dispatch_request\n",
      "    rv = self.handle_user_exception(e)\n",
      "  File &#34;C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py&#34;, line 880, in full_dispatch_request\n",
      "    rv = self.dispatch_request()\n",
      "  File &#34;C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py&#34;, line 865, in dispatch_request\n",
      "    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n",
      "  File &#34;C:\\Users\\KIIT\\app.py&#34;, line 22, in register\n",
      "    hashed_password = generate_password_hash(password, method=&#39;sha256&#39;)\n",
      "  File &#34;C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\werkzeug\\security.py&#34;, line 105, in generate_password_hash\n",
      "    h, actual_method = _hash_internal(method, salt, password)\n",
      "  File &#34;C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\werkzeug\\security.py&#34;, line 70, in _hash_internal\n",
      "    raise ValueError(f&#34;Invalid hash method &#39;{method}&#39;.&#34;)\n",
      "ValueError: Invalid hash method &#39;sha256&#39;.\n",
      "</textarea>\n",
      "</div>\n",
      "<div class=\"explanation\">\n",
      "  The debugger caught an exception in your WSGI application.  You can now\n",
      "  look at the traceback which led to the error.  <span class=\"nojavascript\">\n",
      "  If you enable JavaScript you can also use additional features such as code\n",
      "  execution (if the evalex feature is enabled), automatic pasting of the\n",
      "  exceptions and much more.</span>\n",
      "</div>\n",
      "      <div class=\"footer\">\n",
      "        Brought to you by <strong class=\"arthur\">DON'T PANIC</strong>, your\n",
      "        friendly Werkzeug powered traceback interpreter.\n",
      "      </div>\n",
      "    </div>\n",
      "\n",
      "    <div class=\"pin-prompt\">\n",
      "      <div class=\"inner\">\n",
      "        <h3>Console Locked</h3>\n",
      "        <p>\n",
      "          The console is locked and needs to be unlocked by entering the PIN.\n",
      "          You can find the PIN printed out on the standard output of your\n",
      "          shell that runs the server.\n",
      "        <form>\n",
      "          <p>PIN:\n",
      "            <input type=text name=pin size=14>\n",
      "            <input type=submit name=btn value=\"Confirm Pin\">\n",
      "        </form>\n",
      "      </div>\n",
      "    </div>\n",
      "  </body>\n",
      "</html>\n",
      "\n",
      "<!--\n",
      "\n",
      "Traceback (most recent call last):\n",
      "  File \"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\", line 1498, in __call__\n",
      "    return self.wsgi_app(environ, start_response)\n",
      "  File \"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\", line 1476, in wsgi_app\n",
      "    response = self.handle_exception(e)\n",
      "  File \"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\", line 1473, in wsgi_app\n",
      "    response = self.full_dispatch_request()\n",
      "  File \"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\", line 882, in full_dispatch_request\n",
      "    rv = self.handle_user_exception(e)\n",
      "  File \"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\", line 880, in full_dispatch_request\n",
      "    rv = self.dispatch_request()\n",
      "  File \"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\flask\\app.py\", line 865, in dispatch_request\n",
      "    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]\n",
      "  File \"C:\\Users\\KIIT\\app.py\", line 22, in register\n",
      "    hashed_password = generate_password_hash(password, method='sha256')\n",
      "  File \"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\werkzeug\\security.py\", line 105, in generate_password_hash\n",
      "    h, actual_method = _hash_internal(method, salt, password)\n",
      "  File \"C:\\Users\\KIIT\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\werkzeug\\security.py\", line 70, in _hash_internal\n",
      "    raise ValueError(f\"Invalid hash method '{method}'.\")\n",
      "ValueError: Invalid hash method 'sha256'.\n",
      "\n",
      "\n",
      "-->\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "url = \"http://localhost:5000/register\"\n",
    "payload = {\n",
    "    \"username\": \"testuser\",\n",
    "    \"password\": \"testpassword\"\n",
    "}\n",
    "\n",
    "response = requests.post(url, json=payload)\n",
    "\n",
    "try:\n",
    "    response_json = response.json()\n",
    "    print(response_json)\n",
    "except requests.JSONDecodeError:\n",
    "    print(\"Failed to decode JSON response\")\n",
    "    print(\"Response status code:\", response.status_code)\n",
    "    print(\"Response content:\", response.text)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "a5a0ae65-34f5-4a23-8ded-dcd56f1dfaa2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "url = \"http://localhost:5000/login\"\n",
    "payload = {\n",
    "    \"username\": \"testuser\",\n",
    "    \"password\": \"testpassword\"\n",
    "}\n",
    "response = requests.post(url, json=payload)\n",
    "token = response.json().get(\"token\")\n",
    "print(token)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "f0ab4eb7-0c2d-467f-8b64-59e7a7ac983f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'message': 'Token is missing'}\n"
     ]
    }
   ],
   "source": [
    "url = \"http://localhost:5000/qa\"\n",
    "headers = {\n",
    "    \"x-access-token\": token\n",
    "}\n",
    "payload = {\n",
    "    \"question\": \"What is the capital of France?\"\n",
    "}\n",
    "response = requests.post(url, headers=headers, json=payload)\n",
    "print(response.json())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "08070293-37d4-44d8-a899-788a018c48c1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " * Serving Flask app '__main__'\n",
      " * Debug mode: on\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.\n",
      " * Running on http://127.0.0.1:5000\n",
      "Press CTRL+C to quit\n"
     ]
    }
   ],
   "source": [
    "import threading\n",
    "from flask import Flask, request, jsonify\n",
    "from werkzeug.security import generate_password_hash, check_password_hash\n",
    "import jwt\n",
    "import datetime\n",
    "\n",
    "app = Flask(__name__)\n",
    "app.config['SECRET_KEY'] = 'your_secret_key'\n",
    "\n",
    "users = {}\n",
    "\n",
    "@app.route('/register', methods=['POST'])\n",
    "def register():\n",
    "    data = request.get_json()\n",
    "    username = data.get('username')\n",
    "    password = data.get('password')\n",
    "    \n",
    "    if username in users:\n",
    "        return jsonify({'message': 'User already exists'}), 400\n",
    "    \n",
    "    hashed_password = generate_password_hash(password, method='sha256')\n",
    "    users[username] = hashed_password\n",
    "    return jsonify({'message': 'User registered successfully'}), 201\n",
    "\n",
    "@app.route('/login', methods=['POST'])\n",
    "def login():\n",
    "    data = request.get_json()\n",
    "    username = data.get('username')\n",
    "    password = data.get('password')\n",
    "    \n",
    "    if username not in users or not check_password_hash(users[username], password):\n",
    "        return jsonify({'message': 'Invalid credentials'}), 401\n",
    "    \n",
    "    token = jwt.encode({\n",
    "        'username': username,\n",
    "        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)\n",
    "    }, app.config['SECRET_KEY'])\n",
    "    \n",
    "    return jsonify({'token': token})\n",
    "\n",
    "def run_flask():\n",
    "    app.run(debug=True, use_reloader=False)\n",
    "\n",
    "flask_thread = threading.Thread(target=run_flask)\n",
    "flask_thread.start()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "5972b591-14fd-4568-9a01-eae9f0729c68",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<flask_cors.extension.CORS at 0x1df7c842bc0>"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from flask_cors import CORS\n",
    "\n",
    "app = Flask(__name__)\n",
    "CORS(app)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "0f0398a5-4801-42c2-bc49-52f3034b83c9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " * Serving Flask app '__main__'\n",
      " * Debug mode: on\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.\n",
      " * Running on http://127.0.0.1:5000\n",
      "Press CTRL+C to quit\n",
      " * Restarting with stat\n"
     ]
    },
    {
     "ename": "SystemExit",
     "evalue": "1",
     "output_type": "error",
     "traceback": [
      "An exception has occurred, use %tb to see the full traceback.\n",
      "\u001b[1;31mSystemExit\u001b[0m\u001b[1;31m:\u001b[0m 1\n"
     ]
    }
   ],
   "source": [
    "from flask import Flask, request, jsonify\n",
    "from flask_cors import CORS\n",
    "from werkzeug.security import generate_password_hash, check_password_hash\n",
    "import jwt\n",
    "import datetime\n",
    "\n",
    "app = Flask(__name__)\n",
    "app.config['SECRET_KEY'] = 'your_secret_key'\n",
    "CORS(app)\n",
    "\n",
    "users = {}\n",
    "\n",
    "@app.route('/register', methods=['POST'])\n",
    "def register():\n",
    "    data = request.get_json()\n",
    "    username = data.get('username')\n",
    "    password = data.get('password')\n",
    "\n",
    "    if username in users:\n",
    "        return jsonify({'message': 'User already exists'}), 400\n",
    "\n",
    "    hashed_password = generate_password_hash(password, method='sha256')\n",
    "    users[username] = hashed_password\n",
    "    return jsonify({'message': 'User registered successfully'}), 201\n",
    "\n",
    "@app.route('/login', methods=['POST'])\n",
    "def login():\n",
    "    data = request.get_json()\n",
    "    username = data.get('username')\n",
    "    password = data.get('password')\n",
    "\n",
    "    user = users.get(username)\n",
    "    if not user or not check_password_hash(user, password):\n",
    "        return jsonify({'message': 'Login failed. Check your username and/or password'}), 401\n",
    "\n",
    "    token = jwt.encode({'username': username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)}, app.config['SECRET_KEY'])\n",
    "    return jsonify({'token': token.decode('UTF-8')}), 200\n",
    "\n",
    "@app.route('/qa', methods=['POST'])\n",
    "def qa():\n",
    "    token = request.headers.get('x-access-token')\n",
    "    if not token:\n",
    "        return jsonify({'message': 'Token is missing!'}), 401\n",
    "\n",
    "    try:\n",
    "        data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=[\"HS256\"])\n",
    "        username = data['username']\n",
    "    except jwt.ExpiredSignatureError:\n",
    "        return jsonify({'message': 'Token is expired!'}), 401\n",
    "    except jwt.InvalidTokenError:\n",
    "        return jsonify({'message': 'Invalid token!'}), 401\n",
    "\n",
    "    question = request.get_json().get('question')\n",
    "    answer = f\"Answer to '{question}'\"\n",
    "    return jsonify({'question': question, 'answer': answer}), 200\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    app.run(debug=True)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "31ebb167-0e55-4271-aedd-13814c2356d2",
   "metadata": {},
   "source": [
    "## Run instruction-following pipeline\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Now, we are ready to explore model capabilities. This demo provides a simple interface that allows communication with a model using text instruction. Type your instruction into the `User instruction` field or select one from predefined examples and click on the `Submit` button to start generation. Additionally, you can modify advanced generation parameters:\n",
    "\n",
    "* `Device` - allows switching inference device. Please note, every time when new device is selected, model will be recompiled and this takes some time.\n",
    "* `Max New Tokens` - maximum size of generated text.\n",
    "* `Top-p (nucleus sampling)` -  if set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for a generation.\n",
    "* `Top-k` - the number of highest probability vocabulary tokens to keep for top-k-filtering.\n",
    "* `Temperature` - the value used to module the logits distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "53f6eeea-d9e4-4f12-83e0-b8ffb54c0434",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4c617885e1bd41378e382f4ad62c1d49",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Label(value='Please login to access the demo:'), Text(value='', placeholder='Username'), Passwo…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import gradio as gr\n",
    "import ipywidgets as widgets\n",
    "from IPython.display import display, clear_output\n",
    "\n",
    "# Define your examples and other setup here\n",
    "examples = [\n",
    "    \"Give me a recipe for pizza with pineapple\",\n",
    "    \"Write me a tweet about the new OpenVINO release\",\n",
    "    \"Explain the difference between CPU and GPU\",\n",
    "    \"Give five ideas for a great weekend with family\",\n",
    "    \"Do Androids dream of Electric sheep?\",\n",
    "    \"Who is Dolly?\",\n",
    "    \"Please give me advice on how to write resume?\",\n",
    "    \"Name 3 advantages to being a cat\",\n",
    "    \"Write instructions on how to become a good AI engineer\",\n",
    "    \"Write a love letter to my best friend\",\n",
    "]\n",
    "\n",
    "# Function to check user credentials\n",
    "def authenticate(username, password):\n",
    "    # Replace with actual authentication logic\n",
    "    if username == \"user\" and password == \"password\":\n",
    "        return True\n",
    "    else:\n",
    "        return False\n",
    "\n",
    "# Function to handle submission\n",
    "def handle_submit(button):\n",
    "    clear_output()\n",
    "    if authenticate(username.value, password.value):\n",
    "        launch_demo()\n",
    "    else:\n",
    "        print(\"Authentication failed. Please try again.\")\n",
    "\n",
    "# Function to launch the Gradio demo\n",
    "def launch_demo():\n",
    "    with gr.Blocks() as demo:\n",
    "        gr.Markdown(\n",
    "            \"# Question Answering with \" + model_id.value + \" and OpenVINO.\\n\"\n",
    "            \"Provide instruction which describes a task below or select among predefined examples and model writes response that performs requested task.\"\n",
    "        )\n",
    "\n",
    "        with gr.Row():\n",
    "            with gr.Column(scale=4):\n",
    "                user_text = gr.Textbox(\n",
    "                    placeholder=\"Write an email about an alpaca that likes flan\",\n",
    "                    label=\"User instruction\",\n",
    "                )\n",
    "                model_output = gr.Textbox(label=\"Model response\", interactive=False)\n",
    "                performance = gr.Textbox(label=\"Performance\", lines=1, interactive=False)\n",
    "                with gr.Column(scale=1):\n",
    "                    button_clear = gr.Button(value=\"Clear\")\n",
    "                    button_submit = gr.Button(value=\"Submit\")\n",
    "                gr.Examples(examples, user_text)\n",
    "            with gr.Column(scale=1):\n",
    "                max_new_tokens = gr.Slider(\n",
    "                    minimum=1,\n",
    "                    maximum=1000,\n",
    "                    value=256,\n",
    "                    step=1,\n",
    "                    interactive=True,\n",
    "                    label=\"Max New Tokens\",\n",
    "                )\n",
    "                top_p = gr.Slider(\n",
    "                    minimum=0.05,\n",
    "                    maximum=1.0,\n",
    "                    value=0.92,\n",
    "                    step=0.05,\n",
    "                    interactive=True,\n",
    "                    label=\"Top-p (nucleus sampling)\",\n",
    "                )\n",
    "                top_k = gr.Slider(\n",
    "                    minimum=0,\n",
    "                    maximum=50,\n",
    "                    value=0,\n",
    "                    step=1,\n",
    "                    interactive=True,\n",
    "                    label=\"Top-k\",\n",
    "                )\n",
    "                temperature = gr.Slider(\n",
    "                    minimum=0.1,\n",
    "                    maximum=5.0,\n",
    "                    value=0.8,\n",
    "                    step=0.1,\n",
    "                    interactive=True,\n",
    "                    label=\"Temperature\",\n",
    "                )\n",
    "\n",
    "        user_text.submit(\n",
    "            run_generation,\n",
    "            [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
    "            [model_output, performance],\n",
    "        )\n",
    "        button_submit.click(\n",
    "            run_generation,\n",
    "            [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
    "            [model_output, performance],\n",
    "        )\n",
    "        button_clear.click(\n",
    "            reset_textbox,\n",
    "            [user_text, model_output, performance],\n",
    "            [user_text, model_output, performance],\n",
    "        )\n",
    "\n",
    "    demo.launch(height=800,share=True)\n",
    "\n",
    "# Define widgets for authentication\n",
    "username = widgets.Text(placeholder=\"Username\")\n",
    "password = widgets.Password(placeholder=\"Password\")\n",
    "submit_button = widgets.Button(description=\"Login\")\n",
    "submit_button.on_click(handle_submit)\n",
    "\n",
    "# Layout for login page\n",
    "login_page = widgets.VBox([\n",
    "    widgets.Label(\"Please login to access the demo:\"),\n",
    "    username,\n",
    "    password,\n",
    "    submit_button\n",
    "])\n",
    "\n",
    "# Display login page initially\n",
    "display(login_page)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "d330b060-e78e-40ee-836e-71a17ddfe324",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "62bda9fd258944a8be6de4afad6e12a1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(Label(value='Please login to access the demo:'), Text(value='', placeholder='Username'), Passwo…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import gradio as gr\n",
    "import ipywidgets as widgets\n",
    "from IPython.display import display, clear_output\n",
    "\n",
    "# Define your examples and other setup here\n",
    "examples = [\n",
    "    \"Give me a recipe for pizza with pineapple\",\n",
    "    \"Write me a tweet about the new OpenVINO release\",\n",
    "    \"Explain the difference between CPU and GPU\",\n",
    "    \"Give five ideas for a great weekend with family\",\n",
    "    \"Do Androids dream of Electric sheep?\",\n",
    "    \"Who is Dolly?\",\n",
    "    \"Please give me advice on how to write resume?\",\n",
    "    \"Name 3 advantages to being a cat\",\n",
    "    \"Write instructions on how to become a good AI engineer\",\n",
    "    \"Write a love letter to my best friend\",\n",
    "]\n",
    "\n",
    "# Function to check user credentials\n",
    "def authenticate(username, password):\n",
    "    # Replace with actual authentication logic\n",
    "    if username == \"user\" and password == \"password\":\n",
    "        return True\n",
    "    else:\n",
    "        return False\n",
    "\n",
    "# Function to handle submission\n",
    "def handle_submit(button):\n",
    "    clear_output()\n",
    "    if authenticate(username.value, password.value):\n",
    "        display_interface()\n",
    "    else:\n",
    "        print(\"Authentication failed. Please try again.\")\n",
    "\n",
    "# Function to display Gradio interface\n",
    "def display_interface():\n",
    "    with gr.Blocks() as demo:\n",
    "        gr.Markdown(\n",
    "            \"# Question Answering with \" + model_id.value + \" and OpenVINO.\\n\"\n",
    "            \"Provide instruction which describes a task below or select among predefined examples and model writes response that performs requested task.\"\n",
    "        )\n",
    "\n",
    "        with gr.Row():\n",
    "            with gr.Column(scale=4):\n",
    "                user_text = gr.Textbox(\n",
    "                    placeholder=\"Write an email about an alpaca that likes flan\",\n",
    "                    label=\"User instruction\",\n",
    "                )\n",
    "                model_output = gr.Textbox(label=\"Model response\", interactive=False)\n",
    "                performance = gr.Textbox(label=\"Performance\", lines=1, interactive=False)\n",
    "                with gr.Column(scale=1):\n",
    "                    button_clear = gr.Button(value=\"Clear\")\n",
    "                    button_submit = gr.Button(value=\"Submit\")\n",
    "                gr.Examples(examples, user_text)\n",
    "            with gr.Column(scale=1):\n",
    "                max_new_tokens = gr.Slider(\n",
    "                    minimum=1,\n",
    "                    maximum=1000,\n",
    "                    value=256,\n",
    "                    step=1,\n",
    "                    interactive=True,\n",
    "                    label=\"Max New Tokens\",\n",
    "                )\n",
    "                top_p = gr.Slider(\n",
    "                    minimum=0.05,\n",
    "                    maximum=1.0,\n",
    "                    value=0.92,\n",
    "                    step=0.05,\n",
    "                    interactive=True,\n",
    "                    label=\"Top-p (nucleus sampling)\",\n",
    "                )\n",
    "                top_k = gr.Slider(\n",
    "                    minimum=0,\n",
    "                    maximum=50,\n",
    "                    value=0,\n",
    "                    step=1,\n",
    "                    interactive=True,\n",
    "                    label=\"Top-k\",\n",
    "                )\n",
    "                temperature = gr.Slider(\n",
    "                    minimum=0.1,\n",
    "                    maximum=5.0,\n",
    "                    value=0.8,\n",
    "                    step=0.1,\n",
    "                    interactive=True,\n",
    "                    label=\"Temperature\",\n",
    "                )\n",
    "\n",
    "        user_text.submit(\n",
    "            run_generation,\n",
    "            [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
    "            [model_output, performance],\n",
    "        )\n",
    "        button_submit.click(\n",
    "            run_generation,\n",
    "            [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
    "            [model_output, performance],\n",
    "        )\n",
    "        button_clear.click(\n",
    "            reset_textbox,\n",
    "            [user_text, model_output, performance],\n",
    "            [user_text, model_output, performance],\n",
    "        )\n",
    "\n",
    "    display(demo.launch(height=800,share=True))\n",
    "\n",
    "# Define widgets for authentication\n",
    "username = widgets.Text(placeholder=\"Username\")\n",
    "password = widgets.Password(placeholder=\"Password\")\n",
    "submit_button = widgets.Button(description=\"Login\")\n",
    "submit_button.on_click(handle_submit)\n",
    "\n",
    "# Layout for login page\n",
    "login_page = widgets.VBox([\n",
    "    widgets.Label(\"Please login to access the demo:\"),\n",
    "    username,\n",
    "    password,\n",
    "    submit_button\n",
    "])\n",
    "\n",
    "# Display login page initially\n",
    "display(login_page)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a64908da-3afa-4a0e-953a-5e262fdb4a76",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gradio as gr\n",
    "import ipywidgets as widgets\n",
    "from IPython.display import display, clear_output\n",
    "\n",
    "# Define your examples and other setup here\n",
    "examples = [\n",
    "    \"Give me a recipe for pizza with pineapple\",\n",
    "    \"Write me a tweet about the new OpenVINO release\",\n",
    "    \"Explain the difference between CPU and GPU\",\n",
    "    \"Give five ideas for a great weekend with family\",\n",
    "    \"Do Androids dream of Electric sheep?\",\n",
    "    \"Who is Dolly?\",\n",
    "    \"Please give me advice on how to write resume?\",\n",
    "    \"Name 3 advantages to being a cat\",\n",
    "    \"Write instructions on how to become a good AI engineer\",\n",
    "    \"Write a love letter to my best friend\",\n",
    "]\n",
    "\n",
    "# Function to check user credentials\n",
    "def authenticate(username, password):\n",
    "    # Replace with actual authentication logic\n",
    "    if username == \"user\" and password == \"password\":\n",
    "        return True\n",
    "    else:\n",
    "        return False\n",
    "\n",
    "# Function to handle submission\n",
    "def handle_submit(button):\n",
    "    clear_output()\n",
    "    if authenticate(username.value, password.value):\n",
    "        display_interface()\n",
    "    else:\n",
    "        print(\"Authentication failed. Please try again.\")\n",
    "\n",
    "# Function to display Gradio interface\n",
    "def display_interface():\n",
    "    with gr.Blocks() as demo:\n",
    "        gr.Markdown(\n",
    "            \"# Question Answering with \" + model_id.value + \" and OpenVINO.\\n\"\n",
    "            \"Provide instruction which describes a task below or select among predefined examples and model writes response that performs requested task.\"\n",
    "        )\n",
    "\n",
    "        with gr.Row():\n",
    "            with gr.Column(scale=4):\n",
    "                user_text = gr.Textbox(\n",
    "                    placeholder=\"Write an email about an alpaca that likes flan\",\n",
    "                    label=\"User instruction\",\n",
    "                )\n",
    "                model_output = gr.Textbox(label=\"Model response\", interactive=False)\n",
    "                performance = gr.Textbox(label=\"Performance\", lines=1, interactive=False)\n",
    "                with gr.Column(scale=1):\n",
    "                    button_clear = gr.Button(value=\"Clear\")\n",
    "                    button_submit = gr.Button(value=\"Submit\")\n",
    "                gr.Examples(examples, user_text)\n",
    "            with gr.Column(scale=1):\n",
    "                max_new_tokens = gr.Slider(\n",
    "                    minimum=1,\n",
    "                    maximum=1000,\n",
    "                    value=256,\n",
    "                    step=1,\n",
    "                    interactive=True,\n",
    "                    label=\"Max New Tokens\",\n",
    "                )\n",
    "                top_p = gr.Slider(\n",
    "                    minimum=0.05,\n",
    "                    maximum=1.0,\n",
    "                    value=0.92,\n",
    "                    step=0.05,\n",
    "                    interactive=True,\n",
    "                    label=\"Top-p (nucleus sampling)\",\n",
    "                )\n",
    "                top_k = gr.Slider(\n",
    "                    minimum=0,\n",
    "                    maximum=50,\n",
    "                    value=0,\n",
    "                    step=1,\n",
    "                    interactive=True,\n",
    "                    label=\"Top-k\",\n",
    "                )\n",
    "                temperature = gr.Slider(\n",
    "                    minimum=0.1,\n",
    "                    maximum=5.0,\n",
    "                    value=0.8,\n",
    "                    step=0.1,\n",
    "                    interactive=True,\n",
    "                    label=\"Temperature\",\n",
    "                )\n",
    "\n",
    "        user_text.submit(\n",
    "            run_generation,\n",
    "            [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
    "            [model_output, performance],\n",
    "        )\n",
    "        button_submit.click(\n",
    "            run_generation,\n",
    "            [user_text, top_p, temperature, top_k, max_new_tokens, performance],\n",
    "            [model_output, performance],\n",
    "        )\n",
    "        button_clear.click(\n",
    "            reset_textbox,\n",
    "            [user_text, model_output, performance],\n",
    "            [user_text, model_output, performance],\n",
    "        )\n",
    "\n",
    "    display(demo.launch(height=800,share=True))\n",
    "\n",
    "# Define widgets for authentication\n",
    "username = widgets.Text(placeholder=\"Username\")\n",
    "password = widgets.Password(placeholder=\"Password\")\n",
    "submit_button = widgets.Button(description=\"Login\")\n",
    "submit_button.on_click(handle_submit)\n",
    "\n",
    "# Layout for login page\n",
    "login_page = widgets.VBox([\n",
    "    widgets.Label(\"Please login to access the demo:\"),\n",
    "    username,\n",
    "    password,\n",
    "    submit_button\n",
    "])\n",
    "\n",
    "# Display login page initially\n",
    "display(login_page)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "9af95d72-931c-45f3-a4f0-d417fc426a30",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: flask in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (3.0.3)\n",
      "Requirement already satisfied: gradio in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (4.36.1)\n",
      "Collecting flask-ngrok\n",
      "  Downloading flask_ngrok-0.0.25-py3-none-any.whl.metadata (1.8 kB)\n",
      "Requirement already satisfied: Werkzeug>=3.0.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from flask) (3.0.3)\n",
      "Requirement already satisfied: Jinja2>=3.1.2 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from flask) (3.1.4)\n",
      "Requirement already satisfied: itsdangerous>=2.1.2 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from flask) (2.2.0)\n",
      "Requirement already satisfied: click>=8.1.3 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from flask) (8.1.7)\n",
      "Requirement already satisfied: blinker>=1.6.2 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from flask) (1.8.2)\n",
      "Requirement already satisfied: aiofiles<24.0,>=22.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (23.2.1)\n",
      "Requirement already satisfied: altair<6.0,>=4.2.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (5.3.0)\n",
      "Requirement already satisfied: fastapi in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (0.111.0)\n",
      "Requirement already satisfied: ffmpy in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (0.3.2)\n",
      "Requirement already satisfied: gradio-client==1.0.1 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (1.0.1)\n",
      "Requirement already satisfied: httpx>=0.24.1 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (0.27.0)\n",
      "Requirement already satisfied: huggingface-hub>=0.19.3 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (0.23.4)\n",
      "Requirement already satisfied: importlib-resources<7.0,>=1.3 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (6.4.0)\n",
      "Requirement already satisfied: markupsafe~=2.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (2.1.5)\n",
      "Requirement already satisfied: matplotlib~=3.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (3.6.3)\n",
      "Requirement already satisfied: numpy<3.0,>=1.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (1.25.2)\n",
      "Requirement already satisfied: orjson~=3.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (3.10.5)\n",
      "Requirement already satisfied: packaging in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (24.0)\n",
      "Requirement already satisfied: pandas<3.0,>=1.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (2.2.2)\n",
      "Requirement already satisfied: pillow<11.0,>=8.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (10.3.0)\n",
      "Requirement already satisfied: pydantic>=2.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (2.7.4)\n",
      "Requirement already satisfied: pydub in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (0.25.1)\n",
      "Requirement already satisfied: python-multipart>=0.0.9 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (0.0.9)\n",
      "Requirement already satisfied: pyyaml<7.0,>=5.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (6.0.1)\n",
      "Requirement already satisfied: ruff>=0.2.2 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (0.4.9)\n",
      "Requirement already satisfied: semantic-version~=2.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (2.10.0)\n",
      "Requirement already satisfied: tomlkit==0.12.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (0.12.0)\n",
      "Requirement already satisfied: typer<1.0,>=0.12 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (0.12.3)\n",
      "Requirement already satisfied: typing-extensions~=4.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (4.12.0)\n",
      "Requirement already satisfied: urllib3~=2.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (2.2.1)\n",
      "Requirement already satisfied: uvicorn>=0.14.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio) (0.30.1)\n",
      "Requirement already satisfied: fsspec in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio-client==1.0.1->gradio) (2024.5.0)\n",
      "Requirement already satisfied: websockets<12.0,>=10.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from gradio-client==1.0.1->gradio) (11.0.3)\n",
      "Requirement already satisfied: requests in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from flask-ngrok) (2.32.2)\n",
      "Requirement already satisfied: jsonschema>=3.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from altair<6.0,>=4.2.0->gradio) (4.22.0)\n",
      "Requirement already satisfied: toolz in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from altair<6.0,>=4.2.0->gradio) (0.12.1)\n",
      "Requirement already satisfied: colorama in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from click>=8.1.3->flask) (0.4.6)\n",
      "Requirement already satisfied: anyio in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from httpx>=0.24.1->gradio) (4.4.0)\n",
      "Requirement already satisfied: certifi in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from httpx>=0.24.1->gradio) (2024.2.2)\n",
      "Requirement already satisfied: httpcore==1.* in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from httpx>=0.24.1->gradio) (1.0.5)\n",
      "Requirement already satisfied: idna in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from httpx>=0.24.1->gradio) (3.7)\n",
      "Requirement already satisfied: sniffio in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from httpx>=0.24.1->gradio) (1.3.1)\n",
      "Requirement already satisfied: h11<0.15,>=0.13 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from httpcore==1.*->httpx>=0.24.1->gradio) (0.14.0)\n",
      "Requirement already satisfied: filelock in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from huggingface-hub>=0.19.3->gradio) (3.15.3)\n",
      "Requirement already satisfied: tqdm>=4.42.1 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from huggingface-hub>=0.19.3->gradio) (4.66.4)\n",
      "Requirement already satisfied: contourpy>=1.0.1 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from matplotlib~=3.0->gradio) (1.2.1)\n",
      "Requirement already satisfied: cycler>=0.10 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from matplotlib~=3.0->gradio) (0.12.1)\n",
      "Requirement already satisfied: fonttools>=4.22.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from matplotlib~=3.0->gradio) (4.52.1)\n",
      "Requirement already satisfied: kiwisolver>=1.0.1 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from matplotlib~=3.0->gradio) (1.4.5)\n",
      "Requirement already satisfied: pyparsing>=2.2.1 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from matplotlib~=3.0->gradio) (3.1.2)\n",
      "Requirement already satisfied: python-dateutil>=2.7 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from matplotlib~=3.0->gradio) (2.9.0.post0)\n",
      "Requirement already satisfied: pytz>=2020.1 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from pandas<3.0,>=1.0->gradio) (2024.1)\n",
      "Requirement already satisfied: tzdata>=2022.7 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from pandas<3.0,>=1.0->gradio) (2024.1)\n",
      "Requirement already satisfied: annotated-types>=0.4.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from pydantic>=2.0->gradio) (0.7.0)\n",
      "Requirement already satisfied: pydantic-core==2.18.4 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from pydantic>=2.0->gradio) (2.18.4)\n",
      "Requirement already satisfied: shellingham>=1.3.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from typer<1.0,>=0.12->gradio) (1.5.4)\n",
      "Requirement already satisfied: rich>=10.11.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from typer<1.0,>=0.12->gradio) (13.7.1)\n",
      "Requirement already satisfied: starlette<0.38.0,>=0.37.2 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from fastapi->gradio) (0.37.2)\n",
      "Requirement already satisfied: fastapi-cli>=0.0.2 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from fastapi->gradio) (0.0.4)\n",
      "Requirement already satisfied: ujson!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0,>=4.0.1 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from fastapi->gradio) (5.10.0)\n",
      "Requirement already satisfied: email_validator>=2.0.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from fastapi->gradio) (2.1.2)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from requests->flask-ngrok) (3.3.2)\n",
      "Requirement already satisfied: dnspython>=2.0.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from email_validator>=2.0.0->fastapi->gradio) (2.6.1)\n",
      "Requirement already satisfied: attrs>=22.2.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from jsonschema>=3.0->altair<6.0,>=4.2.0->gradio) (23.2.0)\n",
      "Requirement already satisfied: jsonschema-specifications>=2023.03.6 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from jsonschema>=3.0->altair<6.0,>=4.2.0->gradio) (2023.12.1)\n",
      "Requirement already satisfied: referencing>=0.28.4 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from jsonschema>=3.0->altair<6.0,>=4.2.0->gradio) (0.35.1)\n",
      "Requirement already satisfied: rpds-py>=0.7.1 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from jsonschema>=3.0->altair<6.0,>=4.2.0->gradio) (0.18.1)\n",
      "Requirement already satisfied: six>=1.5 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from python-dateutil>=2.7->matplotlib~=3.0->gradio) (1.16.0)\n",
      "Requirement already satisfied: markdown-it-py>=2.2.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from rich>=10.11.0->typer<1.0,>=0.12->gradio) (3.0.0)\n",
      "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from rich>=10.11.0->typer<1.0,>=0.12->gradio) (2.18.0)\n",
      "Requirement already satisfied: exceptiongroup>=1.0.2 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from anyio->httpx>=0.24.1->gradio) (1.2.1)\n",
      "Requirement already satisfied: httptools>=0.5.0 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from uvicorn[standard]>=0.12.0->fastapi->gradio) (0.6.1)\n",
      "Requirement already satisfied: python-dotenv>=0.13 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from uvicorn[standard]>=0.12.0->fastapi->gradio) (1.0.1)\n",
      "Requirement already satisfied: watchfiles>=0.13 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from uvicorn[standard]>=0.12.0->fastapi->gradio) (0.22.0)\n",
      "Requirement already satisfied: mdurl~=0.1 in c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (from markdown-it-py>=2.2.0->rich>=10.11.0->typer<1.0,>=0.12->gradio) (0.1.2)\n",
      "Downloading flask_ngrok-0.0.25-py3-none-any.whl (3.1 kB)\n",
      "Installing collected packages: flask-ngrok\n",
      "Successfully installed flask-ngrok-0.0.25\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -ptimum (c:\\users\\kiit\\appdata\\local\\programs\\python\\python310\\lib\\site-packages)\n"
     ]
    }
   ],
   "source": [
    "!pip install flask gradio flask-ngrok\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "925a8d0f-234c-4993-9e01-26a159800b7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from flask_ngrok import run_with_ngrok\n",
    "from app import app\n",
    "\n",
    "run_with_ngrok(app)\n",
    "app.run()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9166086f-648c-49bb-ac19-bfb2d53b4c5a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "openvino_env",
   "language": "python",
   "name": "openvino_env"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  },
  "openvino_notebooks": {
   "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/daafd702-5a42-4f54-ae72-2e4480d73501",
   "tags": {
    "categories": [
     "Model Demos",
     "AI Trends"
    ],
    "libraries": [],
    "other": [
     "LLM"
    ],
    "tasks": [
     "Text Generation"
    ]
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}