File size: 50,280 Bytes
34aa1cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# Machine Translation Project (English to French)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Fetching 30 files: 100%|██████████| 30/30 [00:00<?, ?it/s]\n"
     ]
    },
    {
     "ename": "OSError",
     "evalue": "SavedModel file does not exist at: C:\\Users\\prajw\\.cache\\huggingface\\hub\\models--prajwath--NullClass_Task-1\\snapshots\\db56a5e525e47ee9bde30fd099bea336bba3908f\\{saved_model.pbtxt|saved_model.pb}",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mOSError\u001b[0m                                   Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[6], line 3\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mhuggingface_hub\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m from_pretrained_keras\n\u001b[1;32m----> 3\u001b[0m model \u001b[38;5;241m=\u001b[39m \u001b[43mfrom_pretrained_keras\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mprajwath/NullClass_Task-1\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n",
      "File \u001b[1;32mc:\\Users\\prajw\\anaconda3\\envs\\TestNullClass\\lib\\site-packages\\huggingface_hub\\keras_mixin.py:293\u001b[0m, in \u001b[0;36mfrom_pretrained_keras\u001b[1;34m(*args, **kwargs)\u001b[0m\n\u001b[0;32m    240\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mfrom_pretrained_keras\u001b[39m(\u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mKerasModelHubMixin\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n\u001b[0;32m    241\u001b[0m \u001b[38;5;250m    \u001b[39m\u001b[38;5;124mr\u001b[39m\u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m    242\u001b[0m \u001b[38;5;124;03m    Instantiate a pretrained Keras model from a pre-trained model from the Hub.\u001b[39;00m\n\u001b[0;32m    243\u001b[0m \u001b[38;5;124;03m    The model is expected to be in `SavedModel` format.\u001b[39;00m\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m    291\u001b[0m \u001b[38;5;124;03m    </Tip>\u001b[39;00m\n\u001b[0;32m    292\u001b[0m \u001b[38;5;124;03m    \"\"\"\u001b[39;00m\n\u001b[1;32m--> 293\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m KerasModelHubMixin\u001b[38;5;241m.\u001b[39mfrom_pretrained(\u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n",
      "File \u001b[1;32mc:\\Users\\prajw\\anaconda3\\envs\\TestNullClass\\lib\\site-packages\\huggingface_hub\\utils\\_validators.py:114\u001b[0m, in \u001b[0;36mvalidate_hf_hub_args.<locals>._inner_fn\u001b[1;34m(*args, **kwargs)\u001b[0m\n\u001b[0;32m    111\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m check_use_auth_token:\n\u001b[0;32m    112\u001b[0m     kwargs \u001b[38;5;241m=\u001b[39m smoothly_deprecate_use_auth_token(fn_name\u001b[38;5;241m=\u001b[39mfn\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__name__\u001b[39m, has_token\u001b[38;5;241m=\u001b[39mhas_token, kwargs\u001b[38;5;241m=\u001b[39mkwargs)\n\u001b[1;32m--> 114\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m fn(\u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n",
      "File \u001b[1;32mc:\\Users\\prajw\\anaconda3\\envs\\TestNullClass\\lib\\site-packages\\huggingface_hub\\hub_mixin.py:558\u001b[0m, in \u001b[0;36mModelHubMixin.from_pretrained\u001b[1;34m(cls, pretrained_model_name_or_path, force_download, resume_download, proxies, token, cache_dir, local_files_only, revision, **model_kwargs)\u001b[0m\n\u001b[0;32m    555\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mcls\u001b[39m\u001b[38;5;241m.\u001b[39m_hub_mixin_inject_config \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mconfig\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m model_kwargs:\n\u001b[0;32m    556\u001b[0m         model_kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mconfig\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m config\n\u001b[1;32m--> 558\u001b[0m instance \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mcls\u001b[39m\u001b[38;5;241m.\u001b[39m_from_pretrained(\n\u001b[0;32m    559\u001b[0m     model_id\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mstr\u001b[39m(model_id),\n\u001b[0;32m    560\u001b[0m     revision\u001b[38;5;241m=\u001b[39mrevision,\n\u001b[0;32m    561\u001b[0m     cache_dir\u001b[38;5;241m=\u001b[39mcache_dir,\n\u001b[0;32m    562\u001b[0m     force_download\u001b[38;5;241m=\u001b[39mforce_download,\n\u001b[0;32m    563\u001b[0m     proxies\u001b[38;5;241m=\u001b[39mproxies,\n\u001b[0;32m    564\u001b[0m     resume_download\u001b[38;5;241m=\u001b[39mresume_download,\n\u001b[0;32m    565\u001b[0m     local_files_only\u001b[38;5;241m=\u001b[39mlocal_files_only,\n\u001b[0;32m    566\u001b[0m     token\u001b[38;5;241m=\u001b[39mtoken,\n\u001b[0;32m    567\u001b[0m     \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mmodel_kwargs,\n\u001b[0;32m    568\u001b[0m )\n\u001b[0;32m    570\u001b[0m \u001b[38;5;66;03m# Implicitly set the config as instance attribute if not already set by the class\u001b[39;00m\n\u001b[0;32m    571\u001b[0m \u001b[38;5;66;03m# This way `config` will be available when calling `save_pretrained` or `push_to_hub`.\u001b[39;00m\n\u001b[0;32m    572\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m config \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m (\u001b[38;5;28mgetattr\u001b[39m(instance, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m_hub_mixin_config\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m) \u001b[38;5;129;01min\u001b[39;00m (\u001b[38;5;28;01mNone\u001b[39;00m, {})):\n",
      "File \u001b[1;32mc:\\Users\\prajw\\anaconda3\\envs\\TestNullClass\\lib\\site-packages\\huggingface_hub\\keras_mixin.py:494\u001b[0m, in \u001b[0;36mKerasModelHubMixin._from_pretrained\u001b[1;34m(cls, model_id, revision, cache_dir, force_download, proxies, resume_download, local_files_only, token, config, **model_kwargs)\u001b[0m\n\u001b[0;32m    491\u001b[0m     storage_folder \u001b[38;5;241m=\u001b[39m model_id\n\u001b[0;32m    493\u001b[0m \u001b[38;5;66;03m# TODO: change this in a future PR. We are not returning a KerasModelHubMixin instance here...\u001b[39;00m\n\u001b[1;32m--> 494\u001b[0m model \u001b[38;5;241m=\u001b[39m \u001b[43mkeras\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmodels\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mload_model\u001b[49m\u001b[43m(\u001b[49m\u001b[43mstorage_folder\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m    496\u001b[0m \u001b[38;5;66;03m# For now, we add a new attribute, config, to store the config loaded from the hub/a local dir.\u001b[39;00m\n\u001b[0;32m    497\u001b[0m model\u001b[38;5;241m.\u001b[39mconfig \u001b[38;5;241m=\u001b[39m config\n",
      "File \u001b[1;32mc:\\Users\\prajw\\anaconda3\\envs\\TestNullClass\\lib\\site-packages\\keras\\utils\\traceback_utils.py:70\u001b[0m, in \u001b[0;36mfilter_traceback.<locals>.error_handler\u001b[1;34m(*args, **kwargs)\u001b[0m\n\u001b[0;32m     67\u001b[0m     filtered_tb \u001b[38;5;241m=\u001b[39m _process_traceback_frames(e\u001b[38;5;241m.\u001b[39m__traceback__)\n\u001b[0;32m     68\u001b[0m     \u001b[38;5;66;03m# To get the full stack trace, call:\u001b[39;00m\n\u001b[0;32m     69\u001b[0m     \u001b[38;5;66;03m# `tf.debugging.disable_traceback_filtering()`\u001b[39;00m\n\u001b[1;32m---> 70\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m e\u001b[38;5;241m.\u001b[39mwith_traceback(filtered_tb) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[0;32m     71\u001b[0m \u001b[38;5;28;01mfinally\u001b[39;00m:\n\u001b[0;32m     72\u001b[0m     \u001b[38;5;28;01mdel\u001b[39;00m filtered_tb\n",
      "File \u001b[1;32mc:\\Users\\prajw\\anaconda3\\envs\\TestNullClass\\lib\\site-packages\\tensorflow\\python\\saved_model\\loader_impl.py:115\u001b[0m, in \u001b[0;36mparse_saved_model\u001b[1;34m(export_dir)\u001b[0m\n\u001b[0;32m    113\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mIOError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCannot parse file \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpath_to_pbtxt\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mstr\u001b[39m(e)\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m    114\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m--> 115\u001b[0m   \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mIOError\u001b[39;00m(\n\u001b[0;32m    116\u001b[0m       \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mSavedModel file does not exist at: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mexport_dir\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;132;01m{\u001b[39;00mos\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39msep\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m    117\u001b[0m       \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m{{\u001b[39;00m\u001b[38;5;132;01m{\u001b[39;00mconstants\u001b[38;5;241m.\u001b[39mSAVED_MODEL_FILENAME_PBTXT\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m|\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m    118\u001b[0m       \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mconstants\u001b[38;5;241m.\u001b[39mSAVED_MODEL_FILENAME_PB\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;130;01m}}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
      "\u001b[1;31mOSError\u001b[0m: SavedModel file does not exist at: C:\\Users\\prajw\\.cache\\huggingface\\hub\\models--prajwath--NullClass_Task-1\\snapshots\\db56a5e525e47ee9bde30fd099bea336bba3908f\\{saved_model.pbtxt|saved_model.pb}"
     ]
    }
   ],
   "source": [
    "from huggingface_hub import from_pretrained_keras\n",
    "\n",
    "model = from_pretrained_keras(\"prajwath/NullClass_Task-1\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting huggingface_hub\n",
      "  Using cached huggingface_hub-0.23.4-py3-none-any.whl.metadata (12 kB)\n",
      "Collecting filelock (from huggingface_hub)\n",
      "  Using cached filelock-3.15.4-py3-none-any.whl.metadata (2.9 kB)\n",
      "Collecting fsspec>=2023.5.0 (from huggingface_hub)\n",
      "  Using cached fsspec-2024.6.1-py3-none-any.whl.metadata (11 kB)\n",
      "Requirement already satisfied: packaging>=20.9 in c:\\users\\prajw\\anaconda3\\envs\\testnullclass\\lib\\site-packages (from huggingface_hub) (24.0)\n",
      "Collecting pyyaml>=5.1 (from huggingface_hub)\n",
      "  Using cached PyYAML-6.0.1-cp39-cp39-win_amd64.whl.metadata (2.1 kB)\n",
      "Requirement already satisfied: requests in c:\\users\\prajw\\anaconda3\\envs\\testnullclass\\lib\\site-packages (from huggingface_hub) (2.32.3)\n",
      "Collecting tqdm>=4.42.1 (from huggingface_hub)\n",
      "  Using cached tqdm-4.66.4-py3-none-any.whl.metadata (57 kB)\n",
      "Requirement already satisfied: typing-extensions>=3.7.4.3 in c:\\users\\prajw\\anaconda3\\envs\\testnullclass\\lib\\site-packages (from huggingface_hub) (4.12.2)\n",
      "Requirement already satisfied: colorama in c:\\users\\prajw\\anaconda3\\envs\\testnullclass\\lib\\site-packages (from tqdm>=4.42.1->huggingface_hub) (0.4.6)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in c:\\users\\prajw\\anaconda3\\envs\\testnullclass\\lib\\site-packages (from requests->huggingface_hub) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\prajw\\anaconda3\\envs\\testnullclass\\lib\\site-packages (from requests->huggingface_hub) (2.10)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\users\\prajw\\anaconda3\\envs\\testnullclass\\lib\\site-packages (from requests->huggingface_hub) (2.2.1)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\prajw\\anaconda3\\envs\\testnullclass\\lib\\site-packages (from requests->huggingface_hub) (2024.6.2)\n",
      "Downloading huggingface_hub-0.23.4-py3-none-any.whl (402 kB)\n",
      "   ---------------------------------------- 0.0/402.6 kB ? eta -:--:--\n",
      "   - -------------------------------------- 10.2/402.6 kB ? eta -:--:--\n",
      "   --- ----------------------------------- 41.0/402.6 kB 393.8 kB/s eta 0:00:01\n",
      "   ----------- -------------------------- 122.9/402.6 kB 798.9 kB/s eta 0:00:01\n",
      "   ---------------------- ----------------- 225.3/402.6 kB 1.1 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ------------ 276.5/402.6 kB 1.4 MB/s eta 0:00:01\n",
      "   --------------------------- ---------- 286.7/402.6 kB 221.2 kB/s eta 0:00:01\n",
      "   --------------------------- ---------- 286.7/402.6 kB 221.2 kB/s eta 0:00:01\n",
      "   ---------------------------- --------- 307.2/402.6 kB 221.0 kB/s eta 0:00:01\n",
      "   ---------------------------- --------- 307.2/402.6 kB 221.0 kB/s eta 0:00:01\n",
      "   ----------------------------- -------- 317.4/402.6 kB 216.0 kB/s eta 0:00:01\n",
      "   --------------------------------- ---- 358.4/402.6 kB 234.5 kB/s eta 0:00:01\n",
      "   -------------------------------------- 402.6/402.6 kB 253.6 kB/s eta 0:00:00\n",
      "Downloading fsspec-2024.6.1-py3-none-any.whl (177 kB)\n",
      "   ---------------------------------------- 0.0/177.6 kB ? eta -:--:--\n",
      "   ---------------------------------------- 177.6/177.6 kB 5.4 MB/s eta 0:00:00\n",
      "Downloading PyYAML-6.0.1-cp39-cp39-win_amd64.whl (152 kB)\n",
      "   ---------------------------------------- 0.0/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ---------------- ----------------------- 61.4/152.8 kB ? eta -:--:--\n",
      "   ------------------ --------------------- 71.7/152.8 kB 58.7 kB/s eta 0:00:02\n",
      "   ------------------------ --------------- 92.2/152.8 kB 74.9 kB/s eta 0:00:01\n",
      "   ---------------------------- ---------- 112.6/152.8 kB 91.0 kB/s eta 0:00:01\n",
      "   ------------------------------- ------- 122.9/152.8 kB 94.8 kB/s eta 0:00:01\n",
      "   -------------------------------------- 152.8/152.8 kB 115.4 kB/s eta 0:00:00\n",
      "Downloading tqdm-4.66.4-py3-none-any.whl (78 kB)\n",
      "   ---------------------------------------- 0.0/78.3 kB ? eta -:--:--\n",
      "   ---------------------------------------- 78.3/78.3 kB 4.3 MB/s eta 0:00:00\n",
      "Downloading filelock-3.15.4-py3-none-any.whl (16 kB)\n",
      "Installing collected packages: tqdm, pyyaml, fsspec, filelock, huggingface_hub\n",
      "Successfully installed filelock-3.15.4 fsspec-2024.6.1 huggingface_hub-0.23.4 pyyaml-6.0.1 tqdm-4.66.4\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install huggingface_hub\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "import numpy as np\n",
    "import json\n",
    "\n",
    "from keras.preprocessing.text import Tokenizer\n",
    "from keras.utils import pad_sequences\n",
    "from keras.models import Model, Sequential\n",
    "from keras.layers import Input, Dense, Embedding, GRU, LSTM, Bidirectional, Dropout, Activation, TimeDistributed, RepeatVector\n",
    "from keras.optimizers import Adam\n",
    "from keras.losses import sparse_categorical_crossentropy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Verify access to the GPU"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[name: \"/device:CPU:0\"\n",
      "device_type: \"CPU\"\n",
      "memory_limit: 268435456\n",
      "locality {\n",
      "}\n",
      "incarnation: 753238729468120299\n",
      "xla_global_id: -1\n",
      ", name: \"/device:GPU:0\"\n",
      "device_type: \"GPU\"\n",
      "memory_limit: 1733715559\n",
      "locality {\n",
      "  bus_id: 1\n",
      "  links {\n",
      "  }\n",
      "}\n",
      "incarnation: 17911561745832575813\n",
      "physical_device_desc: \"device: 0, name: NVIDIA GeForce RTX 2050, pci bus id: 0000:01:00.0, compute capability: 8.6\"\n",
      "xla_global_id: 416903419\n",
      "]\n"
     ]
    }
   ],
   "source": [
    "from tensorflow.python.client import device_lib\n",
    "print(device_lib.list_local_devices())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dataset\n",
    "For our machine translation project, we opt for a dataset featuring a limited vocabulary, specifically designed to facilitate a more manageable and efficient training process. Unlike the extensive [WMT](http://www.statmt.org/) datasets, our chosen dataset ensures a quicker training time and demands fewer computational resources. This strategic decision aims to balance the learning experience while still achieving meaningful results within practical time constraints.\n",
    "### Load Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_data(path):\n",
    "    input_file = path\n",
    "    with open(input_file, \"r\") as f:\n",
    "        data = f.read()\n",
    "    return data.split('\\n')\n",
    "\n",
    "english_sentences = load_data('data/english')\n",
    "french_sentences = load_data('data/french')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sample Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['new jersey is sometimes quiet during autumn , and it is snowy in april .',\n",
       " 'the united states is usually chilly during july , and it is usually freezing in november .',\n",
       " 'california is usually quiet during march , and it is usually hot in june .',\n",
       " 'the united states is sometimes mild during june , and it is cold in september .',\n",
       " 'your least liked fruit is the grape , but my least liked is the apple .']"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "english_sentences[:5]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By examining the sentences, it's apparent that they have undergone preprocessing: punctuation has been delimited with spaces, and all the text has been converted to lowercase. This preprocessing serves a crucial purpose in text preparation. Firstly, delimiting punctuation with spaces ensures that each punctuation mark is treated as a separate token, aiding the model in understanding sentence structure. Secondly, converting the entire text to lowercase standardizes the input, preventing the model from distinguishing between words solely based on their casing. This uniformity facilitates more effective training and generalization, enhancing the model's ability to grasp patterns and generate accurate translations."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Structure of the Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1823250 English words.\n",
      "227 unique English words.\n",
      "10 Most common words in the English dataset:\n",
      "\"is\" \",\" \".\" \"in\" \"it\" \"during\" \"the\" \"but\" \"and\" \"sometimes\"\n",
      "\n",
      "1961295 French words.\n",
      "355 unique French words.\n",
      "10 Most common words in the French dataset:\n",
      "\"est\" \".\" \",\" \"en\" \"il\" \"les\" \"mais\" \"et\" \"la\" \"parfois\"\n"
     ]
    }
   ],
   "source": [
    "english_words_counter = collections.Counter([word for sentence in english_sentences for word in sentence.split()])\n",
    "french_words_counter = collections.Counter([word for sentence in french_sentences for word in sentence.split()])\n",
    "\n",
    "print('{} English words.'.format(len([word for sentence in english_sentences for word in sentence.split()])))\n",
    "print('{} unique English words.'.format(len(english_words_counter)))\n",
    "print('10 Most common words in the English dataset:')\n",
    "print('\"' + '\" \"'.join(list(zip(*english_words_counter.most_common(10)))[0]) + '\"')\n",
    "\n",
    "print()\n",
    "print('{} French words.'.format(len([word for sentence in french_sentences for word in sentence.split()])))\n",
    "print('{} unique French words.'.format(len(french_words_counter)))\n",
    "print('10 Most common words in the French dataset:')\n",
    "print('\"' + '\" \"'.join(list(zip(*french_words_counter.most_common(10)))[0]) + '\"')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Preprocess\n",
    "1. Tokenize the words into ids\n",
    "2. Add padding to make all the sequences the same length."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'the': 1, 'quick': 2, 'a': 3, 'brown': 4, 'fox': 5, 'jumps': 6, 'over': 7, 'lazy': 8, 'dog': 9, 'by': 10, 'jove': 11, 'my': 12, 'study': 13, 'of': 14, 'lexicography': 15, 'won': 16, 'prize': 17, 'this': 18, 'is': 19, 'short': 20, 'sentence': 21}\n",
      "\n",
      "Sequence 1 in x\n",
      "  Input:  The quick brown fox jumps over the lazy dog .\n",
      "  Output: [1, 2, 4, 5, 6, 7, 1, 8, 9]\n",
      "Sequence 2 in x\n",
      "  Input:  By Jove , my quick study of lexicography won a prize .\n",
      "  Output: [10, 11, 12, 2, 13, 14, 15, 16, 3, 17]\n",
      "Sequence 3 in x\n",
      "  Input:  This is a short sentence .\n",
      "  Output: [18, 19, 3, 20, 21]\n"
     ]
    }
   ],
   "source": [
    "def tokenize(x):\n",
    "    tokenizer = Tokenizer()\n",
    "    tokenizer.fit_on_texts(x)\n",
    "    return tokenizer.texts_to_sequences(x), tokenizer\n",
    "\n",
    "text_sentences = [\n",
    "    'The quick brown fox jumps over the lazy dog .',\n",
    "    'By Jove , my quick study of lexicography won a prize .',\n",
    "    'This is a short sentence .']\n",
    "\n",
    "text_tokenized, text_tokenizer = tokenize(text_sentences)\n",
    "print(text_tokenizer.word_index)\n",
    "print()\n",
    "for sample_i, (sent, token_sent) in enumerate(zip(text_sentences, text_tokenized)):\n",
    "    print('Sequence {} in x'.format(sample_i + 1))\n",
    "    print('  Input:  {}'.format(sent))\n",
    "    print('  Output: {}'.format(token_sent))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sequence 1 in x\n",
      "  Input:  [1 2 4 5 6 7 1 8 9]\n",
      "  Output: [1 2 4 5 6 7 1 8 9 0]\n",
      "Sequence 2 in x\n",
      "  Input:  [10 11 12  2 13 14 15 16  3 17]\n",
      "  Output: [10 11 12  2 13 14 15 16  3 17]\n",
      "Sequence 3 in x\n",
      "  Input:  [18 19  3 20 21]\n",
      "  Output: [18 19  3 20 21  0  0  0  0  0]\n"
     ]
    }
   ],
   "source": [
    "def pad(x, length=None):\n",
    "    if length is None:\n",
    "        length = max([len(sentence) for sentence in x])\n",
    "    return pad_sequences(x, maxlen=length, padding='post')\n",
    "\n",
    "test_pad = pad(text_tokenized)\n",
    "for sample_i, (token_sent, pad_sent) in enumerate(zip(text_tokenized, test_pad)):\n",
    "    print('Sequence {} in x'.format(sample_i + 1))\n",
    "    print('  Input:  {}'.format(np.array(token_sent)))\n",
    "    print('  Output: {}'.format(pad_sent))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data Preprocessed\n",
      "Max English sentence length: 15\n",
      "Max French sentence length: 21\n",
      "English vocabulary size: 199\n",
      "French vocabulary size: 344\n"
     ]
    }
   ],
   "source": [
    "def preprocess(x,y):\n",
    "    preprocess_x, x_tk = tokenize(x)\n",
    "    preprocess_y, y_tk = tokenize(y)\n",
    "    \n",
    "    preprocess_x = pad(preprocess_x)\n",
    "    preprocess_y = pad(preprocess_y)\n",
    "    \n",
    "    preprocess_y = preprocess_y.reshape(*preprocess_y.shape, 1)\n",
    "    \n",
    "    return preprocess_x, preprocess_y, x_tk, y_tk\n",
    "\n",
    "preproc_english_sentences, preproc_french_sentences, english_tokenizer, french_tokenizer = preprocess(english_sentences, french_sentences)\n",
    "\n",
    "max_english_sequence_length = preproc_english_sentences.shape[1]\n",
    "max_french_sequence_length = preproc_french_sentences.shape[1]\n",
    "english_vocab_size = len(english_tokenizer.word_index)\n",
    "french_vocab_size = len(french_tokenizer.word_index)\n",
    "\n",
    "print('Data Preprocessed')\n",
    "print(\"Max English sentence length:\", max_english_sequence_length)\n",
    "print(\"Max French sentence length:\", max_french_sequence_length)\n",
    "print(\"English vocabulary size:\", english_vocab_size)\n",
    "print(\"French vocabulary size:\", french_vocab_size)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Models\n",
    "- Model 1 is a simple RNN\n",
    "- Model 2 is a Bidirectional RNN\n",
    "- Model 3 is an Embedding RNN\n",
    "\n",
    "### Ids Back to Text\n",
    "The neural network will be translating the input to words ids, which isn't the final form we want.  We want the French translation.  The function `logits_to_text` will bridge the gab between the logits from the neural network to the French translation.  You'll be using this function to better understand the output of the neural network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def logits_to_text(logits, tokenizer):\n",
    "    index_to_words = {id: word for word, id in tokenizer.word_index.items()}\n",
    "    index_to_words[0] = '<PAD>'\n",
    "    \n",
    "    return ' '.join([index_to_words[prediction] for prediction in np.argmax(logits, 1)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model 1: RNN\n",
    "![RNN](images/rnn.png)\n",
    "A basic RNN model is a good baseline for sequence data.  In this model, you'll build a RNN that translates English to French."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/10\n",
      "108/108 [==============================] - 21s 132ms/step - loss: 1.9204 - accuracy: 0.5445 - val_loss: nan - val_accuracy: 0.6271\n",
      "Epoch 2/10\n",
      "108/108 [==============================] - 13s 119ms/step - loss: 1.2280 - accuracy: 0.6415 - val_loss: nan - val_accuracy: 0.6736\n",
      "Epoch 3/10\n",
      "108/108 [==============================] - 13s 119ms/step - loss: 1.0781 - accuracy: 0.6701 - val_loss: nan - val_accuracy: 0.7027\n",
      "Epoch 4/10\n",
      "108/108 [==============================] - 13s 122ms/step - loss: 0.9893 - accuracy: 0.6861 - val_loss: nan - val_accuracy: 0.7056\n",
      "Epoch 5/10\n",
      "108/108 [==============================] - 13s 122ms/step - loss: 0.9328 - accuracy: 0.6960 - val_loss: nan - val_accuracy: 0.7206\n",
      "Epoch 6/10\n",
      "108/108 [==============================] - 12s 113ms/step - loss: 0.8917 - accuracy: 0.7037 - val_loss: nan - val_accuracy: 0.7074\n",
      "Epoch 7/10\n",
      "108/108 [==============================] - 12s 109ms/step - loss: 0.8539 - accuracy: 0.7123 - val_loss: nan - val_accuracy: 0.7419\n",
      "Epoch 8/10\n",
      "108/108 [==============================] - 12s 114ms/step - loss: 0.8136 - accuracy: 0.7258 - val_loss: nan - val_accuracy: 0.7366\n",
      "Epoch 9/10\n",
      "108/108 [==============================] - 13s 117ms/step - loss: 0.7947 - accuracy: 0.7312 - val_loss: nan - val_accuracy: 0.7469\n",
      "Epoch 10/10\n",
      "108/108 [==============================] - 13s 117ms/step - loss: 0.7671 - accuracy: 0.7396 - val_loss: nan - val_accuracy: 0.7694\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x1d1836779d0>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def simple_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n",
    "    \n",
    "    #Hyperparameters\n",
    "    learning_rate = 0.005\n",
    "    \n",
    "    # Build the layers\n",
    "    model = Sequential()\n",
    "    model.add(GRU(256, input_shape=input_shape[1:], return_sequences=True))\n",
    "    model.add(TimeDistributed(Dense(1024, activation='relu')))\n",
    "    model.add(Dropout(0.5))\n",
    "    model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax')))\n",
    "    \n",
    "    # Compile model\n",
    "    model.compile(loss = sparse_categorical_crossentropy,\n",
    "                  optimizer = Adam(learning_rate),\n",
    "                  metrics = ['accuracy'])\n",
    "    \n",
    "    return model\n",
    "\n",
    "tmp_x = pad(preproc_english_sentences, max_french_sequence_length)\n",
    "tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))\n",
    "\n",
    "#Train the neural network\n",
    "simple_rnn_model = simple_model(\n",
    "    tmp_x.shape,\n",
    "    max_french_sequence_length,\n",
    "    english_vocab_size,\n",
    "    french_vocab_size)\n",
    "\n",
    "simple_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Prediciton:\n",
      "1/1 [==============================] - 0s 278ms/step\n",
      "new jersey est parfois calme en mois de il et il est en en <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>\n",
      "\n",
      "Correct Translation:\n",
      "[\"new jersey est parfois calme pendant l' automne , et il est neigeux en avril .\"]\n",
      "\n",
      "Original text:\n",
      "['new jersey is sometimes quiet during autumn , and it is snowy in april .']\n"
     ]
    }
   ],
   "source": [
    "# Print prediction(s)\n",
    "print(\"Prediciton:\")\n",
    "print(logits_to_text(simple_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))\n",
    "\n",
    "print(\"\\nCorrect Translation:\")\n",
    "print(french_sentences[:1])\n",
    "\n",
    "print('\\nOriginal text:')\n",
    "print(english_sentences[:1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model 2: Bidirectional RNNs\n",
    "![RNN](images/bidirectional.png)\n",
    "One restriction of a RNN is that it can't see the future input, only the past.  This is where bidirectional recurrent neural networks come in.  They are able to see the future data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_1\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " bidirectional (Bidirectiona  (None, 21, 256)          100608    \n",
      " l)                                                              \n",
      "                                                                 \n",
      " time_distributed_2 (TimeDis  (None, 21, 1024)         263168    \n",
      " tributed)                                                       \n",
      "                                                                 \n",
      " dropout_1 (Dropout)         (None, 21, 1024)          0         \n",
      "                                                                 \n",
      " time_distributed_3 (TimeDis  (None, 21, 344)          352600    \n",
      " tributed)                                                       \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 716,376\n",
      "Trainable params: 716,376\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "None\n",
      "Epoch 1/10\n",
      "108/108 [==============================] - 15s 121ms/step - loss: 1.7581 - accuracy: 0.5748 - val_loss: nan - val_accuracy: 0.6500\n",
      "Epoch 2/10\n",
      "108/108 [==============================] - 13s 117ms/step - loss: 1.1684 - accuracy: 0.6552 - val_loss: nan - val_accuracy: 0.6823\n",
      "Epoch 3/10\n",
      "108/108 [==============================] - 13s 118ms/step - loss: 1.0394 - accuracy: 0.6766 - val_loss: nan - val_accuracy: 0.6961\n",
      "Epoch 4/10\n",
      "108/108 [==============================] - 13s 118ms/step - loss: 0.9543 - accuracy: 0.6900 - val_loss: nan - val_accuracy: 0.7073\n",
      "Epoch 5/10\n",
      "108/108 [==============================] - 13s 118ms/step - loss: 0.8969 - accuracy: 0.6993 - val_loss: nan - val_accuracy: 0.7155\n",
      "Epoch 6/10\n",
      "108/108 [==============================] - 13s 118ms/step - loss: 0.8589 - accuracy: 0.7062 - val_loss: nan - val_accuracy: 0.7109\n",
      "Epoch 7/10\n",
      "108/108 [==============================] - 13s 118ms/step - loss: 0.8371 - accuracy: 0.7107 - val_loss: nan - val_accuracy: 0.7233\n",
      "Epoch 8/10\n",
      "108/108 [==============================] - 13s 118ms/step - loss: 0.7975 - accuracy: 0.7195 - val_loss: nan - val_accuracy: 0.7446\n",
      "Epoch 9/10\n",
      "108/108 [==============================] - 13s 118ms/step - loss: 0.7670 - accuracy: 0.7282 - val_loss: nan - val_accuracy: 0.7498\n",
      "Epoch 10/10\n",
      "108/108 [==============================] - 13s 117ms/step - loss: 0.7318 - accuracy: 0.7401 - val_loss: nan - val_accuracy: 0.7604\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x1d184e5adf0>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def bd_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n",
    "    \n",
    "    #Hyperparameters\n",
    "    learning_rate = 0.005\n",
    "    \n",
    "    # Build the layers\n",
    "    model = Sequential()\n",
    "    model.add(Bidirectional(GRU(128, return_sequences=True), input_shape=input_shape[1:]))\n",
    "    model.add(TimeDistributed(Dense(1024, activation='relu')))\n",
    "    model.add(Dropout(0.5))\n",
    "    model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax')))\n",
    "    \n",
    "    # Compile model\n",
    "    model.compile(loss = sparse_categorical_crossentropy,\n",
    "                  optimizer = Adam(learning_rate),\n",
    "                  metrics = ['accuracy'])\n",
    "    \n",
    "    return model\n",
    "\n",
    "tmp_x = pad(preproc_english_sentences, max_french_sequence_length)\n",
    "tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))\n",
    "\n",
    "# Train the neural network\n",
    "bd_rnn_model = bd_model(\n",
    "    tmp_x.shape,\n",
    "    max_french_sequence_length,\n",
    "    english_vocab_size,\n",
    "    french_vocab_size)\n",
    "\n",
    "print(bd_rnn_model.summary())\n",
    "\n",
    "bd_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Prediciton:\n",
      "1/1 [==============================] - 1s 569ms/step\n",
      "new jersey est parfois chaud en mois de il et est est en en <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>\n",
      "\n",
      "Correct Translation:\n",
      "[\"new jersey est parfois calme pendant l' automne , et il est neigeux en avril .\"]\n",
      "\n",
      "Original text:\n",
      "['new jersey is sometimes quiet during autumn , and it is snowy in april .']\n"
     ]
    }
   ],
   "source": [
    "# Print prediction(s)\n",
    "print(\"Prediciton:\")\n",
    "print(logits_to_text(bd_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))\n",
    "\n",
    "print(\"\\nCorrect Translation:\")\n",
    "print(french_sentences[:1])\n",
    "\n",
    "print('\\nOriginal text:')\n",
    "print(english_sentences[:1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model 3: Embedding\n",
    "![RNN](images/embedding-words.png)\n",
    "You've turned the words into ids, but there's a better representation of a word.  This is called word embeddings.  An embedding is a vector representation of the word that is close to similar words in n-dimensional space, where the n represents the size of the embedding vectors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_2\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " embedding (Embedding)       (None, 21, 256)           50944     \n",
      "                                                                 \n",
      " bidirectional_1 (Bidirectio  (None, 21, 512)          789504    \n",
      " nal)                                                            \n",
      "                                                                 \n",
      " time_distributed_4 (TimeDis  (None, 21, 1024)         525312    \n",
      " tributed)                                                       \n",
      "                                                                 \n",
      " dropout_2 (Dropout)         (None, 21, 1024)          0         \n",
      "                                                                 \n",
      " time_distributed_5 (TimeDis  (None, 21, 344)          352600    \n",
      " tributed)                                                       \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 1,718,360\n",
      "Trainable params: 1,718,360\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "None\n",
      "Epoch 1/10\n",
      "108/108 [==============================] - 21s 168ms/step - loss: 1.3566 - accuracy: 0.6890 - val_loss: nan - val_accuracy: 0.8730\n",
      "Epoch 2/10\n",
      "108/108 [==============================] - 16s 151ms/step - loss: 0.3153 - accuracy: 0.9007 - val_loss: nan - val_accuracy: 0.9377\n",
      "Epoch 3/10\n",
      "108/108 [==============================] - 17s 154ms/step - loss: 0.1827 - accuracy: 0.9428 - val_loss: nan - val_accuracy: 0.9572\n",
      "Epoch 4/10\n",
      "108/108 [==============================] - 17s 154ms/step - loss: 0.1322 - accuracy: 0.9589 - val_loss: nan - val_accuracy: 0.9685\n",
      "Epoch 5/10\n",
      "108/108 [==============================] - 17s 154ms/step - loss: 0.1035 - accuracy: 0.9680 - val_loss: nan - val_accuracy: 0.9734\n",
      "Epoch 6/10\n",
      "108/108 [==============================] - 17s 156ms/step - loss: 0.0864 - accuracy: 0.9734 - val_loss: nan - val_accuracy: 0.9764\n",
      "Epoch 7/10\n",
      "108/108 [==============================] - 17s 156ms/step - loss: 0.0755 - accuracy: 0.9767 - val_loss: nan - val_accuracy: 0.9774\n",
      "Epoch 8/10\n",
      "108/108 [==============================] - 17s 157ms/step - loss: 0.0659 - accuracy: 0.9795 - val_loss: nan - val_accuracy: 0.9805\n",
      "Epoch 9/10\n",
      "108/108 [==============================] - 17s 159ms/step - loss: 0.0604 - accuracy: 0.9812 - val_loss: nan - val_accuracy: 0.9813\n",
      "Epoch 10/10\n",
      "108/108 [==============================] - 17s 158ms/step - loss: 0.0559 - accuracy: 0.9827 - val_loss: nan - val_accuracy: 0.9825\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x1d183c75460>"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def bidirectional_embed_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n",
    "    \n",
    "    # Hyperparameters\n",
    "    learning_rate = 0.005\n",
    "    \n",
    "    # Build the layers\n",
    "    model = Sequential()\n",
    "    model.add(Embedding(english_vocab_size, 256, input_length=input_shape[1], input_shape=input_shape[1:]))\n",
    "    model.add(Bidirectional(GRU(256, return_sequences=True)))\n",
    "    model.add(TimeDistributed(Dense(1024, activation='relu')))\n",
    "    model.add(Dropout(0.5))\n",
    "    model.add(TimeDistributed(Dense(french_vocab_size, activation='softmax')))\n",
    "    \n",
    "    # Compile model\n",
    "    model.compile(loss = sparse_categorical_crossentropy,\n",
    "                  optimizer = Adam(learning_rate),\n",
    "                  metrics = ['accuracy'])\n",
    "    \n",
    "    return model\n",
    "\n",
    "tmp_x = pad(preproc_english_sentences, max_french_sequence_length)\n",
    "tmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2]))\n",
    "\n",
    "# Build the model\n",
    "embed_rnn_model = bidirectional_embed_model(\n",
    "    tmp_x.shape,\n",
    "    max_french_sequence_length,\n",
    "    english_vocab_size,\n",
    "    french_vocab_size)\n",
    "\n",
    "print(embed_rnn_model.summary())\n",
    "\n",
    "embed_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Prediciton:\n",
      "1/1 [==============================] - 0s 479ms/step\n",
      "new jersey est parfois calme pendant l' automne et il est neigeux en avril <PAD> <PAD> <PAD> <PAD> <PAD> <PAD> <PAD>\n",
      "\n",
      "Correct Translation:\n",
      "[\"new jersey est parfois calme pendant l' automne , et il est neigeux en avril .\"]\n",
      "\n",
      "Original text:\n",
      "['new jersey is sometimes quiet during autumn , and it is snowy in april .']\n"
     ]
    }
   ],
   "source": [
    "# Print prediction(s)\n",
    "print(\"Prediciton:\")\n",
    "print(logits_to_text(embed_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))\n",
    "\n",
    "print(\"\\nCorrect Translation:\")\n",
    "print(french_sentences[:1])\n",
    "\n",
    "print('\\nOriginal text:')\n",
    "print(english_sentences[:1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING:absl:Found untraced functions such as gru_cell_5_layer_call_fn, gru_cell_5_layer_call_and_return_conditional_losses, gru_cell_6_layer_call_fn, gru_cell_6_layer_call_and_return_conditional_losses while saving (showing 4 of 4). These functions will not be directly callable after loading.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: english_to_french_model\\assets\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: english_to_french_model\\assets\n"
     ]
    }
   ],
   "source": [
    "embed_rnn_model.save('english_to_french_model')\n",
    "# Serialize English Tokenizer to JSON\n",
    "with open('english_tokenizer.json', 'w', encoding='utf8') as f:\n",
    "    f.write(json.dumps(english_tokenizer.to_json(), ensure_ascii=False))\n",
    "    \n",
    "# Serialize French Tokenizer to JSON\n",
    "with open('french_tokenizer.json', 'w', encoding='utf8') as f:\n",
    "    f.write(json.dumps(french_tokenizer.to_json(), ensure_ascii=False))\n",
    "    \n",
    "# Save max lengths\n",
    "max_french_sequence_length_json = max_french_sequence_length\n",
    "with open('sequence_length.json', 'w', encoding='utf8') as f:\n",
    "    f.write(json.dumps(max_french_sequence_length_json, ensure_ascii=False))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.9.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}