File size: 40,783 Bytes
f4ec5ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "09eb5ef2",
   "metadata": {},
   "source": [
    "#### Gradio Comparing Transfer Learning Models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f3f83569",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.12.0\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "print(tf.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c1ca8b20",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting gradio==1.6.0\n",
      "  Downloading gradio-1.6.0-py3-none-any.whl (1.1 MB)\n",
      "                                              0.0/1.1 MB ? eta -:--:--\n",
      "     ----                                     0.1/1.1 MB 3.2 MB/s eta 0:00:01\n",
      "     ------------                             0.3/1.1 MB 4.2 MB/s eta 0:00:01\n",
      "     ----------------------                   0.6/1.1 MB 5.6 MB/s eta 0:00:01\n",
      "     -------------------------------          0.9/1.1 MB 5.6 MB/s eta 0:00:01\n",
      "     -------------------------------------    1.0/1.1 MB 5.1 MB/s eta 0:00:01\n",
      "     -------------------------------------    1.0/1.1 MB 5.1 MB/s eta 0:00:01\n",
      "     ---------------------------------------- 1.1/1.1 MB 3.8 MB/s eta 0:00:00\n",
      "Requirement already satisfied: numpy in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (1.24.3)\n",
      "Requirement already satisfied: requests in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (2.28.1)\n",
      "Requirement already satisfied: Flask>=1.1.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (2.1.2)\n",
      "Requirement already satisfied: Flask-Cors>=3.0.8 in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (3.0.10)\n",
      "Collecting flask-cachebuster (from gradio==1.6.0)\n",
      "  Downloading Flask-CacheBuster-1.0.0.tar.gz (3.1 kB)\n",
      "  Preparing metadata (setup.py): started\n",
      "  Preparing metadata (setup.py): finished with status 'done'\n",
      "Requirement already satisfied: Flask-BasicAuth in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (0.2.0)\n",
      "Requirement already satisfied: paramiko in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (2.8.1)\n",
      "Requirement already satisfied: scipy in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (1.10.0)\n",
      "Requirement already satisfied: IPython in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (8.10.0)\n",
      "Requirement already satisfied: scikit-image in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (0.19.3)\n",
      "Collecting analytics-python (from gradio==1.6.0)\n",
      "  Downloading analytics_python-1.4.post1-py2.py3-none-any.whl (23 kB)\n",
      "Requirement already satisfied: pandas in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (1.5.3)\n",
      "Requirement already satisfied: ffmpy in c:\\users\\user\\anaconda3\\lib\\site-packages (from gradio==1.6.0) (0.3.0)\n",
      "Collecting markdown2 (from gradio==1.6.0)\n",
      "  Downloading markdown2-2.4.8-py2.py3-none-any.whl (38 kB)\n",
      "Requirement already satisfied: Werkzeug>=2.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from Flask>=1.1.1->gradio==1.6.0) (2.3.4)\n",
      "Requirement already satisfied: Jinja2>=3.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from Flask>=1.1.1->gradio==1.6.0) (3.1.2)\n",
      "Requirement already satisfied: itsdangerous>=2.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from Flask>=1.1.1->gradio==1.6.0) (2.1.2)\n",
      "Requirement already satisfied: click>=8.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from Flask>=1.1.1->gradio==1.6.0) (8.1.3)\n",
      "Requirement already satisfied: Six in c:\\users\\user\\anaconda3\\lib\\site-packages (from Flask-Cors>=3.0.8->gradio==1.6.0) (1.16.0)\n",
      "Collecting monotonic>=1.5 (from analytics-python->gradio==1.6.0)\n",
      "  Downloading monotonic-1.6-py2.py3-none-any.whl (8.2 kB)\n",
      "Collecting backoff==1.10.0 (from analytics-python->gradio==1.6.0)\n",
      "  Downloading backoff-1.10.0-py2.py3-none-any.whl (31 kB)\n",
      "Requirement already satisfied: python-dateutil>2.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from analytics-python->gradio==1.6.0) (2.8.2)\n",
      "Requirement already satisfied: charset-normalizer<3,>=2 in c:\\users\\user\\anaconda3\\lib\\site-packages (from requests->gradio==1.6.0) (2.0.4)\n",
      "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\user\\anaconda3\\lib\\site-packages (from requests->gradio==1.6.0) (3.4)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from requests->gradio==1.6.0) (1.26.14)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\user\\anaconda3\\lib\\site-packages (from requests->gradio==1.6.0) (2022.12.7)\n",
      "Requirement already satisfied: backcall in c:\\users\\user\\anaconda3\\lib\\site-packages (from IPython->gradio==1.6.0) (0.2.0)\n",
      "Requirement already satisfied: decorator in c:\\users\\user\\anaconda3\\lib\\site-packages (from IPython->gradio==1.6.0) (5.1.1)\n",
      "Requirement already satisfied: jedi>=0.16 in c:\\users\\user\\anaconda3\\lib\\site-packages (from IPython->gradio==1.6.0) (0.18.1)\n",
      "Requirement already satisfied: matplotlib-inline in c:\\users\\user\\anaconda3\\lib\\site-packages (from IPython->gradio==1.6.0) (0.1.6)\n",
      "Requirement already satisfied: pickleshare in c:\\users\\user\\anaconda3\\lib\\site-packages (from IPython->gradio==1.6.0) (0.7.5)\n",
      "Requirement already satisfied: prompt-toolkit<3.1.0,>=3.0.30 in c:\\users\\user\\anaconda3\\lib\\site-packages (from IPython->gradio==1.6.0) (3.0.36)\n",
      "Requirement already satisfied: pygments>=2.4.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from IPython->gradio==1.6.0) (2.15.1)\n",
      "Requirement already satisfied: stack-data in c:\\users\\user\\anaconda3\\lib\\site-packages (from IPython->gradio==1.6.0) (0.2.0)\n",
      "Requirement already satisfied: traitlets>=5 in c:\\users\\user\\anaconda3\\lib\\site-packages (from IPython->gradio==1.6.0) (5.7.1)\n",
      "Requirement already satisfied: colorama in c:\\users\\user\\anaconda3\\lib\\site-packages (from IPython->gradio==1.6.0) (0.4.6)\n",
      "Requirement already satisfied: pytz>=2020.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from pandas->gradio==1.6.0) (2022.7)\n",
      "Requirement already satisfied: bcrypt>=3.1.3 in c:\\users\\user\\anaconda3\\lib\\site-packages (from paramiko->gradio==1.6.0) (3.2.0)\n",
      "Requirement already satisfied: cryptography>=2.5 in c:\\users\\user\\anaconda3\\lib\\site-packages (from paramiko->gradio==1.6.0) (39.0.1)\n",
      "Requirement already satisfied: pynacl>=1.0.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from paramiko->gradio==1.6.0) (1.5.0)\n",
      "Requirement already satisfied: networkx>=2.2 in c:\\users\\user\\anaconda3\\lib\\site-packages (from scikit-image->gradio==1.6.0) (2.8.4)\n",
      "Requirement already satisfied: pillow!=7.1.0,!=7.1.1,!=8.3.0,>=6.1.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from scikit-image->gradio==1.6.0) (9.4.0)\n",
      "Requirement already satisfied: imageio>=2.4.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from scikit-image->gradio==1.6.0) (2.26.0)\n",
      "Requirement already satisfied: tifffile>=2019.7.26 in c:\\users\\user\\anaconda3\\lib\\site-packages (from scikit-image->gradio==1.6.0) (2021.7.2)\n",
      "Requirement already satisfied: PyWavelets>=1.1.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from scikit-image->gradio==1.6.0) (1.4.1)\n",
      "Requirement already satisfied: packaging>=20.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from scikit-image->gradio==1.6.0) (22.0)\n",
      "Requirement already satisfied: cffi>=1.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from bcrypt>=3.1.3->paramiko->gradio==1.6.0) (1.15.1)\n",
      "Requirement already satisfied: parso<0.9.0,>=0.8.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from jedi>=0.16->IPython->gradio==1.6.0) (0.8.3)\n",
      "Requirement already satisfied: MarkupSafe>=2.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from Jinja2>=3.0->Flask>=1.1.1->gradio==1.6.0) (2.1.1)\n",
      "Requirement already satisfied: wcwidth in c:\\users\\user\\anaconda3\\lib\\site-packages (from prompt-toolkit<3.1.0,>=3.0.30->IPython->gradio==1.6.0) (0.2.5)\n",
      "Requirement already satisfied: executing in c:\\users\\user\\anaconda3\\lib\\site-packages (from stack-data->IPython->gradio==1.6.0) (0.8.3)\n",
      "Requirement already satisfied: asttokens in c:\\users\\user\\anaconda3\\lib\\site-packages (from stack-data->IPython->gradio==1.6.0) (2.0.5)\n",
      "Requirement already satisfied: pure-eval in c:\\users\\user\\anaconda3\\lib\\site-packages (from stack-data->IPython->gradio==1.6.0) (0.2.2)\n",
      "Requirement already satisfied: pycparser in c:\\users\\user\\anaconda3\\lib\\site-packages (from cffi>=1.1->bcrypt>=3.1.3->paramiko->gradio==1.6.0) (2.21)\n",
      "Building wheels for collected packages: flask-cachebuster\n",
      "  Building wheel for flask-cachebuster (setup.py): started\n",
      "  Building wheel for flask-cachebuster (setup.py): finished with status 'done'\n",
      "  Created wheel for flask-cachebuster: filename=Flask_CacheBuster-1.0.0-py3-none-any.whl size=3372 sha256=c1b85a8b017ca7784ce61eec4714ca9dd7e500dc251835ef6f9820731268b2c5\n",
      "  Stored in directory: c:\\users\\user\\appdata\\local\\pip\\cache\\wheels\\22\\35\\5e\\088242cb16f309a4ff4e94ce97f1ef8a469983fdde92b45f50\n",
      "Successfully built flask-cachebuster\n",
      "Installing collected packages: monotonic, markdown2, backoff, analytics-python, flask-cachebuster, gradio\n",
      "  Attempting uninstall: gradio\n",
      "    Found existing installation: gradio 3.33.1\n",
      "    Uninstalling gradio-3.33.1:\n",
      "      Successfully uninstalled gradio-3.33.1\n",
      "Successfully installed analytics-python-1.4.post1 backoff-1.10.0 flask-cachebuster-1.0.0 gradio-1.6.0 markdown2-2.4.8 monotonic-1.6\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Ignoring invalid distribution -orch (c:\\users\\user\\anaconda3\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -rotobuf (c:\\users\\user\\anaconda3\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -orch (c:\\users\\user\\anaconda3\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -rotobuf (c:\\users\\user\\anaconda3\\lib\\site-packages)\n"
     ]
    }
   ],
   "source": [
    "pip install gradio==1.6.0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "70ec40a3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting MarkupSafe==2.1.1\n",
      "  Downloading MarkupSafe-2.1.1-cp310-cp310-win_amd64.whl (17 kB)\n",
      "Installing collected packages: MarkupSafe\n",
      "  Attempting uninstall: MarkupSafe\n",
      "    Found existing installation: MarkupSafe 2.0.1\n",
      "    Uninstalling MarkupSafe-2.0.1:\n",
      "      Successfully uninstalled MarkupSafe-2.0.1\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Ignoring invalid distribution -orch (c:\\users\\user\\anaconda3\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -rotobuf (c:\\users\\user\\anaconda3\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -orch (c:\\users\\user\\anaconda3\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -rotobuf (c:\\users\\user\\anaconda3\\lib\\site-packages)\n",
      "ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\\\\Users\\\\User\\\\anaconda3\\\\Lib\\\\site-packages\\\\~arkupsafe\\\\_speedups.cp310-win_amd64.pyd'\n",
      "Consider using the `--user` option or check the permissions.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "pip install MarkupSafe==2.1.1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "961a6510",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\User\\anaconda3\\lib\\site-packages\\paramiko\\transport.py:219: CryptographyDeprecationWarning: Blowfish has been deprecated\n",
      "  \"class\": algorithms.Blowfish,\n"
     ]
    }
   ],
   "source": [
    "import gradio as gr\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import requests\n",
    "\n",
    "\n",
    "# Download human-readable labels for ImageNet.\n",
    "response = requests.get(\"https://git.io/JJkYN\")\n",
    "labels = response.text.split(\"\\n\")\n",
    "\n",
    "mobile_net = tf.keras.applications.MobileNetV2()\n",
    "inception_net = tf.keras.applications.InceptionV3()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "44d83e7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def classify_image_with_mobile_net(im):\n",
    "    im = Image.fromarray(im.astype('uint8'), 'RGB')\n",
    "    im = im.resize((224, 224))\n",
    "    arr = np.array(im).reshape((-1, 224, 224, 3))\n",
    "    arr = tf.keras.applications.mobilenet.preprocess_input(arr)\n",
    "    prediction = mobile_net.predict(arr).flatten()\n",
    "    return {labels[i]: float(prediction[i]) for i in range(1000)}\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5e77912e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def classify_image_with_inception_net(im):\n",
    "    # Resize the image to\n",
    "    im = Image.fromarray(im.astype('uint8'), 'RGB')\n",
    "    im = im.resize((299, 299))\n",
    "    arr = np.array(im).reshape((-1, 299, 299, 3))\n",
    "    arr = tf.keras.applications.inception_v3.preprocess_input(arr)\n",
    "    prediction = inception_net.predict(arr).flatten()\n",
    "    return {labels[i]: float(prediction[i]) for i in range(1000)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f6a9e5fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "imagein = gr.inputs.Image()\n",
    "label = gr.outputs.Label(num_top_classes=3)\n",
    "sample_images = [\n",
    "                 [\"monkey.jpg\"],\n",
    "                 [\"sailboat.jpg\"],\n",
    "                 [\"bicycle.jpg\"],\n",
    "                 [\"download.jpg\"],\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "61c325d0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "IMPORTANT: You are using gradio version 1.6.0, however version 3.14.0 is available, please upgrade.\n",
      "--------\n",
      "Running locally at: http://127.0.0.1:7861/\n",
      "To create a public link, set `share=True` in `launch()`.\n",
      "Interface loading below...\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"1000\"\n",
       "            height=\"500\"\n",
       "            src=\"http://127.0.0.1:7861/\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "            \n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x1f4f8fe2830>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[2023-06-05 22:40:39,347] ERROR in app: Exception on /file/monkey.jpg [GET]\n",
      "Traceback (most recent call last):\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 2077, in wsgi_app\n",
      "    response = self.full_dispatch_request()\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1525, in full_dispatch_request\n",
      "    rv = self.handle_user_exception(e)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask_cors\\extension.py\", line 165, in wrapped_function\n",
      "    return cors_after_request(app.make_response(f(*args, **kwargs)))\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1523, in full_dispatch_request\n",
      "    rv = self.dispatch_request()\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1509, in dispatch_request\n",
      "    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\gradio\\networking.py\", line 269, in file\n",
      "    return send_file(os.path.join(app.cwd, path))\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\helpers.py\", line 610, in send_file\n",
      "    return werkzeug.utils.send_file(\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\werkzeug\\utils.py\", line 427, in send_file\n",
      "    stat = os.stat(path)\n",
      "FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\\\Users\\\\User\\\\Downloads\\\\monkey.jpg'\n",
      "[2023-06-05 22:40:39,356] ERROR in app: Exception on /file/sailboat.jpg [GET]\n",
      "Traceback (most recent call last):\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 2077, in wsgi_app\n",
      "    response = self.full_dispatch_request()\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1525, in full_dispatch_request\n",
      "    rv = self.handle_user_exception(e)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask_cors\\extension.py\", line 165, in wrapped_function\n",
      "    return cors_after_request(app.make_response(f(*args, **kwargs)))\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1523, in full_dispatch_request\n",
      "    rv = self.dispatch_request()\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1509, in dispatch_request\n",
      "    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\gradio\\networking.py\", line 269, in file\n",
      "    return send_file(os.path.join(app.cwd, path))\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\helpers.py\", line 610, in send_file\n",
      "    return werkzeug.utils.send_file(\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\werkzeug\\utils.py\", line 427, in send_file\n",
      "    stat = os.stat(path)\n",
      "FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\\\Users\\\\User\\\\Downloads\\\\sailboat.jpg'\n",
      "[2023-06-05 22:40:39,357] ERROR in app: Exception on /file/bicycle.jpg [GET]\n",
      "Traceback (most recent call last):\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 2077, in wsgi_app\n",
      "    response = self.full_dispatch_request()\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1525, in full_dispatch_request\n",
      "    rv = self.handle_user_exception(e)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask_cors\\extension.py\", line 165, in wrapped_function\n",
      "    return cors_after_request(app.make_response(f(*args, **kwargs)))\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1523, in full_dispatch_request\n",
      "    rv = self.dispatch_request()\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1509, in dispatch_request\n",
      "    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\gradio\\networking.py\", line 269, in file\n",
      "    return send_file(os.path.join(app.cwd, path))\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\helpers.py\", line 610, in send_file\n",
      "    return werkzeug.utils.send_file(\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\werkzeug\\utils.py\", line 427, in send_file\n",
      "    stat = os.stat(path)\n",
      "FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\\\Users\\\\User\\\\Downloads\\\\bicycle.jpg'\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(<Flask 'gradio.networking'>, 'http://127.0.0.1:7861/', None)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gr.Interface(\n",
    "    [classify_image_with_mobile_net, classify_image_with_inception_net],\n",
    "    imagein,\n",
    "    label,\n",
    "    title=\"MobileNet vs. InceptionNet\",\n",
    "    description=\"\"\"Let's compare 2 state-of-the-art machine learning models that classify images into one of 1,000 categories: MobileNet (top),\n",
    "          a lightweight model that has an accuracy of 0.704, vs. InceptionNet\n",
    "          (bottom), a much heavier model that has an accuracy of 0.779.\"\"\",\n",
    "    examples=sample_images).launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3dbc1cab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: transformers in c:\\users\\user\\anaconda3\\lib\\site-packages (4.27.0)\n",
      "Requirement already satisfied: filelock in c:\\users\\user\\anaconda3\\lib\\site-packages (from transformers) (3.12.0)\n",
      "Requirement already satisfied: huggingface-hub<1.0,>=0.11.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from transformers) (0.14.1)\n",
      "Requirement already satisfied: numpy>=1.17 in c:\\users\\user\\anaconda3\\lib\\site-packages (from transformers) (1.24.3)\n",
      "Requirement already satisfied: packaging>=20.0 in c:\\users\\user\\anaconda3\\lib\\site-packages (from transformers) (22.0)\n",
      "Requirement already satisfied: pyyaml>=5.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from transformers) (6.0)\n",
      "Requirement already satisfied: regex!=2019.12.17 in c:\\users\\user\\anaconda3\\lib\\site-packages (from transformers) (2022.7.9)\n",
      "Requirement already satisfied: requests in c:\\users\\user\\anaconda3\\lib\\site-packages (from transformers) (2.28.1)\n",
      "Requirement already satisfied: tokenizers!=0.11.3,<0.14,>=0.11.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from transformers) (0.11.4)\n",
      "Requirement already satisfied: tqdm>=4.27 in c:\\users\\user\\anaconda3\\lib\\site-packages (from transformers) (4.64.1)\n",
      "Requirement already satisfied: fsspec in c:\\users\\user\\anaconda3\\lib\\site-packages (from huggingface-hub<1.0,>=0.11.0->transformers) (2022.11.0)\n",
      "Requirement already satisfied: typing-extensions>=3.7.4.3 in c:\\users\\user\\anaconda3\\lib\\site-packages (from huggingface-hub<1.0,>=0.11.0->transformers) (4.4.0)\n",
      "Requirement already satisfied: colorama in c:\\users\\user\\anaconda3\\lib\\site-packages (from tqdm>=4.27->transformers) (0.4.6)\n",
      "Requirement already satisfied: charset-normalizer<3,>=2 in c:\\users\\user\\anaconda3\\lib\\site-packages (from requests->transformers) (2.0.4)\n",
      "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\user\\anaconda3\\lib\\site-packages (from requests->transformers) (3.4)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\user\\anaconda3\\lib\\site-packages (from requests->transformers) (1.26.14)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\user\\anaconda3\\lib\\site-packages (from requests->transformers) (2022.12.7)\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Ignoring invalid distribution -orch (c:\\users\\user\\anaconda3\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -rotobuf (c:\\users\\user\\anaconda3\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -orch (c:\\users\\user\\anaconda3\\lib\\site-packages)\n",
      "WARNING: Ignoring invalid distribution -rotobuf (c:\\users\\user\\anaconda3\\lib\\site-packages)\n"
     ]
    }
   ],
   "source": [
    "pip install transformers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7deaaac7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "IMPORTANT: You are using gradio version 1.6.0, however version 3.14.0 is available, please upgrade.\n",
      "--------\n",
      "Running locally at: http://127.0.0.1:7861/\n",
      "To create a public link, set `share=True` in `launch()`.\n",
      "Interface loading below...\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"1000\"\n",
       "            height=\"500\"\n",
       "            src=\"http://127.0.0.1:7861/\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "            \n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x22af27eb940>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "(<Flask 'gradio.networking'>, 'http://127.0.0.1:7861/', None)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gradio as gr\n",
    "from transformers import AutoTokenizer, AutoModelForSequenceClassification\n",
    "\n",
    "# Load the models and tokenizers\n",
    "from transformers import AutoTokenizer, AutoModelForSequenceClassification\n",
    "\n",
    "tokenizer1 = AutoTokenizer.from_pretrained(\"textattack/bert-base-uncased-imdb\")\n",
    "tokenizer2 = AutoTokenizer.from_pretrained(\"nlptown/bert-base-multilingual-uncased-sentiment\")\n",
    "model1 = AutoModelForSequenceClassification.from_pretrained(\"textattack/bert-base-uncased-imdb\")\n",
    "model2 = AutoModelForSequenceClassification.from_pretrained(\"nlptown/bert-base-multilingual-uncased-sentiment\")\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "# Define the sentiment prediction functions\n",
    "def predict_sentiment(text):\n",
    "    # Predict sentiment using model 1\n",
    "    inputs1 = tokenizer1.encode_plus(text, padding=\"longest\", truncation=True, return_tensors=\"pt\")\n",
    "    outputs1 = model1(**inputs1)\n",
    "    predicted_label1 = outputs1.logits.argmax().item()\n",
    "    sentiment1 = \"Positive\" if predicted_label1 == 1 else \"Negative\" if predicted_label1 == 0 else \"Neutral\"\n",
    "\n",
    "    # Predict sentiment using model 2\n",
    "    inputs2 = tokenizer2.encode_plus(text, padding=\"longest\", truncation=True, return_tensors=\"pt\")\n",
    "    outputs2 = model2(**inputs2)\n",
    "    predicted_label2 = outputs2.logits.argmax().item()\n",
    "    sentiment2 = \"Positive\" if predicted_label2 == 1 else \"Negative\" if predicted_label2 == 0 else \"Neutral\"\n",
    "\n",
    "    return sentiment1, sentiment2\n",
    "\n",
    "# Create the Gradio interface\n",
    "iface = gr.Interface(\n",
    "    fn=predict_sentiment,\n",
    "    inputs=\"text\",\n",
    "    outputs=[\"text\", \"text\"],\n",
    "    title=\"Sentiment Analysis (Model 1 vs Model 2)\",\n",
    "    description=\"Compare sentiment predictions from two models.\",\n",
    ")\n",
    "\n",
    "# Launch the interface\n",
    "iface.launch()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "bd93f2a5",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Some weights of the model checkpoint at bert-base-uncased were not used when initializing BertForSequenceClassification: ['cls.seq_relationship.weight', 'cls.predictions.transform.LayerNorm.bias', 'cls.seq_relationship.bias', 'cls.predictions.transform.dense.bias', 'cls.predictions.decoder.weight', 'cls.predictions.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.LayerNorm.weight']\n",
      "- This IS expected if you are initializing BertForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
      "- This IS NOT expected if you are initializing BertForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n",
      "Some weights of BertForSequenceClassification were not initialized from the model checkpoint at bert-base-uncased and are newly initialized: ['classifier.bias', 'classifier.weight']\n",
      "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n",
      "Some weights of the model checkpoint at distilbert-base-uncased were not used when initializing DistilBertForSequenceClassification: ['vocab_projector.bias', 'vocab_layer_norm.weight', 'vocab_transform.weight', 'vocab_transform.bias', 'vocab_layer_norm.bias', 'vocab_projector.weight']\n",
      "- This IS expected if you are initializing DistilBertForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
      "- This IS NOT expected if you are initializing DistilBertForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n",
      "Some weights of DistilBertForSequenceClassification were not initialized from the model checkpoint at distilbert-base-uncased and are newly initialized: ['classifier.bias', 'classifier.weight', 'pre_classifier.bias', 'pre_classifier.weight']\n",
      "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "IMPORTANT: You are using gradio version 1.6.0, however version 3.14.0 is available, please upgrade.\n",
      "--------\n",
      "Running locally at: http://127.0.0.1:7871/\n",
      "To create a public link, set `share=True` in `launch()`.\n",
      "Interface loading below...\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"1000\"\n",
       "            height=\"500\"\n",
       "            src=\"http://127.0.0.1:7871/\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "            \n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x22a82329c30>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "(<Flask 'gradio.networking'>, 'http://127.0.0.1:7871/', None)"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[2023-06-05 21:25:10,327] ERROR in app: Exception on /api/predict/ [POST]\n",
      "Traceback (most recent call last):\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 2077, in wsgi_app\n",
      "    response = self.full_dispatch_request()\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1525, in full_dispatch_request\n",
      "    rv = self.handle_user_exception(e)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask_cors\\extension.py\", line 165, in wrapped_function\n",
      "    return cors_after_request(app.make_response(f(*args, **kwargs)))\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1523, in full_dispatch_request\n",
      "    rv = self.dispatch_request()\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1509, in dispatch_request\n",
      "    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\gradio\\networking.py\", line 133, in predict\n",
      "    prediction, durations = app.interface.process(raw_input)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\gradio\\interface.py\", line 272, in process\n",
      "    predictions, durations = self.run_prediction(processed_input, return_duration=True)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\gradio\\interface.py\", line 246, in run_prediction\n",
      "    prediction = predict_fn(*processed_input)\n",
      "  File \"C:\\Users\\User\\AppData\\Local\\Temp\\ipykernel_9376\\3704131587.py\", line 80, in classify_image\n",
      "    prediction = predict(image_file=image_file, model_key=model_key)\n",
      "  File \"C:\\Users\\User\\AppData\\Local\\Temp\\ipykernel_9376\\3704131587.py\", line 67, in predict\n",
      "    image = preprocess(image_file)\n",
      "  File \"C:\\Users\\User\\AppData\\Local\\Temp\\ipykernel_9376\\3704131587.py\", line 51, in preprocess\n",
      "    image = Image.open(BytesIO(image_file.read())).convert(\"RGB\")\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\PIL\\Image.py\", line 3283, in open\n",
      "    raise UnidentifiedImageError(msg)\n",
      "PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x0000022ABA1C10D0>\n",
      "[2023-06-05 21:39:36,773] ERROR in app: Exception on /api/predict/ [POST]\n",
      "Traceback (most recent call last):\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 2077, in wsgi_app\n",
      "    response = self.full_dispatch_request()\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1525, in full_dispatch_request\n",
      "    rv = self.handle_user_exception(e)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask_cors\\extension.py\", line 165, in wrapped_function\n",
      "    return cors_after_request(app.make_response(f(*args, **kwargs)))\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1523, in full_dispatch_request\n",
      "    rv = self.dispatch_request()\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\flask\\app.py\", line 1509, in dispatch_request\n",
      "    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\gradio\\networking.py\", line 133, in predict\n",
      "    prediction, durations = app.interface.process(raw_input)\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\gradio\\interface.py\", line 270, in process\n",
      "    processed_input = [input_interface.preprocess(raw_input[i])\n",
      "  File \"C:\\Users\\User\\anaconda3\\lib\\site-packages\\gradio\\interface.py\", line 270, in <listcomp>\n",
      "    processed_input = [input_interface.preprocess(raw_input[i])\n",
      "IndexError: list index out of range\n"
     ]
    }
   ],
   "source": [
    "import gradio as gr\n",
    "from transformers import AutoTokenizer, AutoModelForSequenceClassification\n",
    "import torch\n",
    "from torchvision import transforms\n",
    "from io import BytesIO\n",
    "from PIL import Image\n",
    "\n",
    "# Define the available models and datasets\n",
    "models = {\n",
    "    \"Model 1\": {\n",
    "        \"model_name\": \"bert-base-uncased\",\n",
    "        \"tokenizer\": None,\n",
    "        \"model\": None\n",
    "    },\n",
    "    \"Model 2\": {\n",
    "        \"model_name\": \"distilbert-base-uncased\",\n",
    "        \"tokenizer\": None,\n",
    "        \"model\": None\n",
    "    },\n",
    "    # Add more models as needed\n",
    "}\n",
    "\n",
    "datasets = {\n",
    "    \"Dataset 1\": {\n",
    "        \"name\": \"imdb\",\n",
    "        \"split\": \"test\",\n",
    "        \"features\": [\"text\"],\n",
    "    },\n",
    "    \"Dataset 2\": {\n",
    "        \"name\": \"ag_news\",\n",
    "        \"split\": \"test\",\n",
    "        \"features\": [\"text\"],\n",
    "    },\n",
    "    # Add more datasets as needed\n",
    "}\n",
    "\n",
    "# Load models\n",
    "for model_key, model_info in models.items():\n",
    "    tokenizer = AutoTokenizer.from_pretrained(model_info[\"model_name\"])\n",
    "    model = AutoModelForSequenceClassification.from_pretrained(model_info[\"model_name\"])\n",
    "    model_info[\"tokenizer\"] = tokenizer\n",
    "    model_info[\"model\"] = model\n",
    "\n",
    "# Set the device to GPU if available\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "for model_info in models.values():\n",
    "    model_info[\"model\"].to(device)\n",
    "\n",
    "# Define the preprocessing function\n",
    "def preprocess(image_file):\n",
    "    image = Image.open(BytesIO(image_file.read())).convert(\"RGB\")\n",
    "    preprocess_transform = transforms.Compose([\n",
    "        transforms.Resize((224, 224)),\n",
    "        transforms.ToTensor(),\n",
    "        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n",
    "    ])\n",
    "    image = preprocess_transform(image)\n",
    "    image = image.unsqueeze(0)\n",
    "    return image.to(device)\n",
    "\n",
    "# Define the prediction function\n",
    "def predict(image_file, model_key):\n",
    "    model_info = models[model_key]\n",
    "    tokenizer = model_info[\"tokenizer\"]\n",
    "    model = model_info[\"model\"]\n",
    "\n",
    "    image = preprocess(image_file)\n",
    "\n",
    "    with torch.no_grad():\n",
    "        outputs = model(image)\n",
    "\n",
    "    predictions = outputs.logits.argmax(dim=1)\n",
    "\n",
    "    return predictions.item()\n",
    "\n",
    "def classify_image(image, model_key):\n",
    "    image = Image.fromarray(image.astype('uint8'), 'RGB')\n",
    "    image_file = BytesIO()\n",
    "    image.save(image_file, format=\"JPEG\")\n",
    "    prediction = predict(image_file=image_file, model_key=model_key)\n",
    "    return prediction\n",
    "\n",
    "iface = gr.Interface(fn=classify_image,\n",
    "                     inputs=[\"image\", gr.inputs.Dropdown(list(models.keys()), label=\"Model\")],\n",
    "                     outputs=\"text\",\n",
    "                     title=\"Image Classification\",\n",
    "                     description=\"Classify images using Hugging Face models\")\n",
    "\n",
    "iface.launch()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c25d39b5",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "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"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}