File size: 48,516 Bytes
0d989cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
051d665
0d989cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
051d665
0d989cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# πŸ”„ TensorFlow β†’ PyTorch Conversion\n",
    "\n",
    "This section guides you through converting the PatentBERT model from TensorFlow to PyTorch and uploading it to Hugging Face Hub.\n",
    "\n",
    "## πŸ“‹ Conversion Plan:\n",
    "\n",
    "1. **TensorFlow Model Download** (previous cells)\n",
    "2. **Weight Extraction** - Extract parameters from TensorFlow checkpoint\n",
    "3. **PyTorch Conversion** - Create equivalent PyTorch model\n",
    "4. **Model Testing** - Verify that the conversion works\n",
    "5. **Hugging Face Upload** - Publish to Hub for public use\n",
    "\n",
    "## ⚠️ Prerequisites:\n",
    "- PatentBERT model downloaded (run previous cells first)\n",
    "- Python 3.7+ with TensorFlow 1.15\n",
    "- Separate environment with PyTorch to avoid conflicts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸ” Environment verification...\n",
      "Python: 3.7.16 (default, Jan 17 2023, 22:20:44) \n",
      "[GCC 11.2.0]\n",
      "TensorFlow: 1.15.0\n",
      "NumPy: 1.21.5\n",
      "\n",
      "πŸ“‚ Checking model files in ./:\n",
      "βœ… model.ckpt-181172.data-00000-of-00001\n",
      "βœ… model.ckpt-181172.index\n",
      "βœ… model.ckpt-181172.meta\n",
      "βœ… bert_config.json\n",
      "βœ… vocab.txt\n",
      "\n",
      "βœ… All model files are present!\n",
      "πŸ“ Created: /tmp/patentbert_conversion\n",
      "πŸ“ Created: /tmp/patentbert_conversion/tf_weights\n",
      "πŸ“ Created: /tmp/patentbert_conversion/pytorch_model\n",
      "\n",
      "🎯 Ready for conversion!\n",
      "πŸ“Š Working directories configured\n"
     ]
    }
   ],
   "source": [
    "# Step 1: Environment verification and preparation\n",
    "\n",
    "import os\n",
    "import sys\n",
    "import json\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "\n",
    "print(\"πŸ” Environment verification...\")\n",
    "print(f\"Python: {sys.version}\")\n",
    "print(f\"TensorFlow: {tf.__version__}\")\n",
    "print(f\"NumPy: {np.__version__}\")\n",
    "\n",
    "# Verify that PatentBERT model has been downloaded\n",
    "model_folder = './'\n",
    "required_files = [\n",
    "    'model.ckpt-181172.data-00000-of-00001',\n",
    "    'model.ckpt-181172.index',\n",
    "    'model.ckpt-181172.meta',\n",
    "    'bert_config.json',\n",
    "    'vocab.txt'\n",
    "]\n",
    "\n",
    "print(f\"\\nπŸ“‚ Checking model files in {model_folder}:\")\n",
    "missing_files = []\n",
    "for file in required_files:\n",
    "    filepath = os.path.join(model_folder, file)\n",
    "    if os.path.exists(filepath):\n",
    "        print(f\"βœ… {file}\")\n",
    "    else:\n",
    "        print(f\"❌ {file} - MISSING\")\n",
    "        missing_files.append(file)\n",
    "\n",
    "if missing_files:\n",
    "    print(f\"\\n⚠️  Missing files: {missing_files}\")\n",
    "    print(\"πŸ’‘ Please run the previous cells first to download the model\")\n",
    "else:\n",
    "    print(\"\\nβœ… All model files are present!\")\n",
    "\n",
    "# Create working directories for conversion\n",
    "conversion_dir = \"/tmp/patentbert_conversion\"\n",
    "tf_weights_dir = os.path.join(conversion_dir, \"tf_weights\")\n",
    "pytorch_dir = os.path.join(conversion_dir, \"pytorch_model\")\n",
    "\n",
    "for dir_path in [conversion_dir, tf_weights_dir, pytorch_dir]:\n",
    "    os.makedirs(dir_path, exist_ok=True)\n",
    "    print(f\"πŸ“ Created: {dir_path}\")\n",
    "\n",
    "print(f\"\\n🎯 Ready for conversion!\")\n",
    "print(f\"πŸ“Š Working directories configured\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸ”„ Extracting weights from TensorFlow PatentBERT model...\n",
      "πŸ“– Model configuration:\n",
      "  β€’ Hidden size: 768\n",
      "  β€’ Number of layers: 12\n",
      "  β€’ Attention heads: 12\n",
      "  β€’ Vocabulary size: 30522\n",
      "πŸ” Found 604 variables in checkpoint\n",
      "πŸ“Š 176 important variables to extract\n",
      "πŸ”„ Extraction in progress...\n",
      "  Progress: 20/176 (11.4%)\n",
      "  Progress: 20/176 (11.4%)\n",
      "  Progress: 40/176 (22.7%)\n",
      "  Progress: 40/176 (22.7%)\n",
      "  Progress: 60/176 (34.1%)\n",
      "  Progress: 60/176 (34.1%)\n",
      "  Progress: 80/176 (45.5%)\n",
      "  Progress: 80/176 (45.5%)\n",
      "  Progress: 100/176 (56.8%)\n",
      "  Progress: 100/176 (56.8%)\n",
      "  Progress: 120/176 (68.2%)\n",
      "  Progress: 120/176 (68.2%)\n",
      "  Progress: 140/176 (79.5%)\n",
      "  Progress: 140/176 (79.5%)\n",
      "  Progress: 160/176 (90.9%)\n",
      "  Progress: 160/176 (90.9%)\n",
      "  Progress: 176/176 (100.0%)\n",
      "βœ… Extraction completed!\n",
      "πŸ“ Weights saved in: /tmp/patentbert_conversion/tf_weights\n",
      "πŸ“Š 176 weights extracted\n",
      "πŸ’Ύ Total size: 419.5 MB\n",
      "\n",
      "πŸ“‚ Examples of created files:\n",
      "  β€’ bert_config.json\n",
      "  β€’ bert_embeddings_LayerNorm_gamma.npy\n",
      "  β€’ bert_embeddings_position_embeddings.npy\n",
      "  β€’ bert_embeddings_token_type_embeddings.npy\n",
      "  β€’ bert_embeddings_word_embeddings.npy\n",
      "  ... and 174 other files\n",
      "\n",
      "πŸŽ‰ Extraction successful!\n",
      "  Progress: 176/176 (100.0%)\n",
      "βœ… Extraction completed!\n",
      "πŸ“ Weights saved in: /tmp/patentbert_conversion/tf_weights\n",
      "πŸ“Š 176 weights extracted\n",
      "πŸ’Ύ Total size: 419.5 MB\n",
      "\n",
      "πŸ“‚ Examples of created files:\n",
      "  β€’ bert_config.json\n",
      "  β€’ bert_embeddings_LayerNorm_gamma.npy\n",
      "  β€’ bert_embeddings_position_embeddings.npy\n",
      "  β€’ bert_embeddings_token_type_embeddings.npy\n",
      "  β€’ bert_embeddings_word_embeddings.npy\n",
      "  ... and 174 other files\n",
      "\n",
      "πŸŽ‰ Extraction successful!\n"
     ]
    }
   ],
   "source": [
    "# Step 2: TensorFlow model weights extraction\n",
    "\n",
    "print(\"πŸ”„ Extracting weights from TensorFlow PatentBERT model...\")\n",
    "\n",
    "def extract_tf_weights():\n",
    "    \"\"\"Extract all weights from TensorFlow checkpoint\"\"\"\n",
    "    \n",
    "    # File paths\n",
    "    checkpoint_path = \"./model.ckpt-181172\"\n",
    "    config_path = \"./bert_config.json\"\n",
    "    vocab_path = \"./vocab.txt\"\n",
    "    \n",
    "    # Read BERT configuration\n",
    "    with open(config_path, 'r') as f:\n",
    "        config = json.load(f)\n",
    "    \n",
    "    print(f\"πŸ“– Model configuration:\")\n",
    "    print(f\"  β€’ Hidden size: {config.get('hidden_size', 768)}\")\n",
    "    print(f\"  β€’ Number of layers: {config.get('num_hidden_layers', 12)}\")\n",
    "    print(f\"  β€’ Attention heads: {config.get('num_attention_heads', 12)}\")\n",
    "    print(f\"  β€’ Vocabulary size: {config.get('vocab_size', 30522)}\")\n",
    "    \n",
    "    # List all variables in checkpoint\n",
    "    var_list = tf.train.list_variables(checkpoint_path)\n",
    "    print(f\"πŸ” Found {len(var_list)} variables in checkpoint\")\n",
    "    \n",
    "    # Filter important variables (ignore optimization variables)\n",
    "    skip_patterns = ['adam', 'beta', 'global_step', 'learning_rate']\n",
    "    important_vars = []\n",
    "    \n",
    "    for name, shape in var_list:\n",
    "        if not any(pattern in name.lower() for pattern in skip_patterns):\n",
    "            important_vars.append((name, shape))\n",
    "    \n",
    "    print(f\"πŸ“Š {len(important_vars)} important variables to extract\")\n",
    "    \n",
    "    # Extract and save weights\n",
    "    weights_info = {}\n",
    "    total_size = 0\n",
    "    \n",
    "    print(\"πŸ”„ Extraction in progress...\")\n",
    "    for i, (name, shape) in enumerate(important_vars):\n",
    "        try:\n",
    "            # Load variable\n",
    "            weight = tf.train.load_variable(checkpoint_path, name)\n",
    "            \n",
    "            # Create safe filename\n",
    "            safe_name = name.replace('/', '_').replace(':', '_').replace(' ', '_')\n",
    "            filename = f\"{safe_name}.npy\"\n",
    "            \n",
    "            # Save in NumPy format\n",
    "            filepath = os.path.join(tf_weights_dir, filename)\n",
    "            np.save(filepath, weight)\n",
    "            \n",
    "            # Record metadata\n",
    "            weights_info[name] = {\n",
    "                'filename': filename,\n",
    "                'shape': list(shape),\n",
    "                'dtype': str(weight.dtype),\n",
    "                'size_mb': weight.nbytes / (1024 * 1024)\n",
    "            }\n",
    "            \n",
    "            total_size += weight.nbytes\n",
    "            \n",
    "            # Show progress\n",
    "            if (i + 1) % 20 == 0 or (i + 1) == len(important_vars):\n",
    "                print(f\"  Progress: {i + 1}/{len(important_vars)} ({(i+1)/len(important_vars)*100:.1f}%)\")\n",
    "                \n",
    "        except Exception as e:\n",
    "            print(f\"⚠️  Error for {name}: {e}\")\n",
    "            continue\n",
    "    \n",
    "    # Create complete metadata\n",
    "    metadata = {\n",
    "        'model_info': {\n",
    "            'name': 'PatentBERT',\n",
    "            'source': 'TensorFlow',\n",
    "            'checkpoint_path': checkpoint_path,\n",
    "            'extraction_date': '2025-07-20'\n",
    "        },\n",
    "        'config': config,\n",
    "        'weights_info': weights_info,\n",
    "        'statistics': {\n",
    "            'total_weights': len(weights_info),\n",
    "            'total_size_mb': total_size / (1024 * 1024),\n",
    "            'original_variables': len(var_list),\n",
    "            'extracted_variables': len(weights_info)\n",
    "        }\n",
    "    }\n",
    "    \n",
    "    # Save metadata\n",
    "    metadata_path = os.path.join(tf_weights_dir, 'extraction_metadata.json')\n",
    "    with open(metadata_path, 'w') as f:\n",
    "        json.dump(metadata, f, indent=2)\n",
    "    \n",
    "    # Copy configuration files\n",
    "    import shutil\n",
    "    shutil.copy(config_path, os.path.join(tf_weights_dir, 'bert_config.json'))\n",
    "    shutil.copy(vocab_path, os.path.join(tf_weights_dir, 'vocab.txt'))\n",
    "    \n",
    "    print(f\"βœ… Extraction completed!\")\n",
    "    print(f\"πŸ“ Weights saved in: {tf_weights_dir}\")\n",
    "    print(f\"πŸ“Š {len(weights_info)} weights extracted\")\n",
    "    print(f\"πŸ’Ύ Total size: {total_size / (1024 * 1024):.1f} MB\")\n",
    "    \n",
    "    # Show some examples of extracted weights\n",
    "    print(f\"\\nπŸ“‚ Examples of created files:\")\n",
    "    files = sorted(os.listdir(tf_weights_dir))\n",
    "    for i, file in enumerate(files[:5]):\n",
    "        print(f\"  β€’ {file}\")\n",
    "    if len(files) > 5:\n",
    "        print(f\"  ... and {len(files) - 5} other files\")\n",
    "    \n",
    "    return tf_weights_dir, metadata\n",
    "\n",
    "# Execute extraction\n",
    "try:\n",
    "    weights_dir, metadata = extract_tf_weights()\n",
    "    print(\"\\nπŸŽ‰ Extraction successful!\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"❌ Error during extraction: {e}\")\n",
    "    import traceback\n",
    "    traceback.print_exc()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🎯 Converting TensorFlow weights to PyTorch format...\n",
      "βœ… CORRECTED upload script created!\n",
      "\n",
      "πŸ”§ Key corrections:\n",
      "   βœ… Accepts BOTH model.safetensors AND pytorch_model.bin\n",
      "   βœ… Automatically detects model format\n",
      "   βœ… Improved error messages\n",
      "   βœ… Better commit message with format info\n",
      "   βœ… Proper torch import for testing\n",
      "\n",
      "πŸš€ NOW RUN THIS CORRECTED COMMAND:\n",
      "   python /tmp/upload_to_hf.py patentbert_conversion/pytorch_model ZoeYou/patentbert-pytorch xxxxx\n",
      "\n",
      "πŸ’‘ Or use the new corrected script:\n",
      "   python /tmp/upload_to_hf_corrected.py patentbert_conversion/pytorch_model ZoeYou/patentbert-pytorch xxxxx\n"
     ]
    }
   ],
   "source": [
    "# Step 3: Convert TensorFlow weights to PyTorch format\n",
    "\n",
    "print(\"🎯 Converting TensorFlow weights to PyTorch format...\")\n",
    "\n",
    "corrected_upload_script = \"\"\"#!/usr/bin/env python3\n",
    "import os\n",
    "import sys\n",
    "from huggingface_hub import HfApi, create_repo, upload_folder\n",
    "from transformers import BertForSequenceClassification, BertTokenizer\n",
    "\n",
    "def check_model_files(model_dir):\n",
    "    \\\"\\\"\\\"Check for required model files with support for both formats.\\\"\\\"\\\"\n",
    "    \n",
    "    # Required base files\n",
    "    required_base = ['config.json', 'vocab.txt', 'tokenizer_config.json']\n",
    "    \n",
    "    # Model files (at least one of these)\n",
    "    model_files = ['model.safetensors', 'pytorch_model.bin']\n",
    "    \n",
    "    missing_base = []\n",
    "    for file in required_base:\n",
    "        if not os.path.exists(os.path.join(model_dir, file)):\n",
    "            missing_base.append(file)\n",
    "    \n",
    "    # Check for at least one model file\n",
    "    found_model_files = []\n",
    "    for f in model_files:\n",
    "        if os.path.exists(os.path.join(model_dir, f)):\n",
    "            found_model_files.append(f)\n",
    "    \n",
    "    if missing_base:\n",
    "        print(f\"❌ Missing required files: {missing_base}\")\n",
    "        return False\n",
    "    \n",
    "    if not found_model_files:\n",
    "        print(f\"❌ No model file found. Expected one of: {model_files}\")\n",
    "        return False\n",
    "    \n",
    "    # Show found files\n",
    "    all_files = os.listdir(model_dir)\n",
    "    print(f\"βœ… Model files found: {all_files}\")\n",
    "    print(f\"βœ… Model weights format: {found_model_files[0]}\")\n",
    "    return True\n",
    "\n",
    "def test_model_loading(model_dir):\n",
    "    \\\"\\\"\\\"Test model loading to verify it works.\\\"\\\"\\\"\n",
    "    try:\n",
    "        print(\"πŸ§ͺ Model loading test...\")\n",
    "        \n",
    "        # Load model and tokenizer\n",
    "        model = BertForSequenceClassification.from_pretrained(model_dir)\n",
    "        tokenizer = BertTokenizer.from_pretrained(model_dir)\n",
    "        \n",
    "        print(f\"βœ… Model loaded: {model.config.num_labels} classes, {model.config.hidden_size} hidden\")\n",
    "        print(f\"βœ… Tokenizer loaded: {len(tokenizer)} tokens\")\n",
    "        \n",
    "        # Quick inference test\n",
    "        text = \"A method for producing synthetic materials\"\n",
    "        inputs = tokenizer(text, return_tensors=\"pt\", max_length=512, truncation=True, padding=True)\n",
    "        \n",
    "        import torch\n",
    "        with torch.no_grad():\n",
    "            outputs = model(**inputs)\n",
    "            predictions = outputs.logits.softmax(dim=-1)\n",
    "        \n",
    "        print(f\"βœ… Inference test successful: shape {predictions.shape}\")\n",
    "        return True\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"❌ Test error: {e}\")\n",
    "        return False\n",
    "\n",
    "def upload_to_huggingface(model_dir, repo_name, token, private=False):\n",
    "    \\\"\\\"\\\"Upload model to Hugging Face Hub with support for all formats.\\\"\\\"\\\"\n",
    "    \n",
    "    print(\"πŸš€ Upload to Hugging Face Hub\")\n",
    "    print(f\"πŸ“‚ Model: {model_dir}\")\n",
    "    print(f\"🏷️  Repository: {repo_name}\")\n",
    "    print(f\"πŸ”’ Private: {private}\")\n",
    "    \n",
    "    # File verification\n",
    "    if not check_model_files(model_dir):\n",
    "        return False\n",
    "    \n",
    "    # Loading test\n",
    "    if not test_model_loading(model_dir):\n",
    "        print(\"⚠️  Warning: Model doesn't load correctly, but continuing upload...\")\n",
    "    \n",
    "    try:\n",
    "        # Initialize API\n",
    "        api = HfApi(token=token)\n",
    "        \n",
    "        # Check connection\n",
    "        user_info = api.whoami()\n",
    "        print(f\"βœ… Connected as: {user_info['name']}\")\n",
    "        \n",
    "        # Create or verify repository\n",
    "        try:\n",
    "            create_repo(repo_name, token=token, private=private, exist_ok=True)\n",
    "            print(f\"βœ… Repository created/verified: https://huggingface.co/{repo_name}\")\n",
    "        except Exception as e:\n",
    "            print(f\"⚠️  Repository warning: {e}\")\n",
    "        \n",
    "        # Upload complete folder\n",
    "        print(\"πŸ“€ Uploading files...\")\n",
    "        \n",
    "        # Determine model format\n",
    "        model_format = \"SafeTensors\" if os.path.exists(os.path.join(model_dir, 'model.safetensors')) else \"PyTorch\"\n",
    "        \n",
    "        # Create informative commit message\n",
    "        commit_message = f\\\"\\\"\\\"Upload PatentBERT PyTorch model\n",
    "\n",
    "BERT model fine-tuned for patent classification, converted from TensorFlow to PyTorch.\n",
    "\n",
    "Specifications:\n",
    "- Format: {model_format}\n",
    "- Classes: Auto-detected from config.json  \n",
    "- Conversion: TensorFlow 1.15 β†’ PyTorch via transformers\n",
    "- CPC Labels: Real Cooperative Patent Classification labels included\n",
    "\n",
    "Included files:\n",
    "{', '.join(sorted(os.listdir(model_dir)))}\n",
    "\\\"\\\"\\\"\n",
    "        \n",
    "        upload_folder(\n",
    "            folder_path=model_dir,\n",
    "            repo_id=repo_name,\n",
    "            token=token,\n",
    "            commit_message=commit_message,\n",
    "            ignore_patterns=[\".git\", \".gitattributes\", \"*.tmp\"]\n",
    "        )\n",
    "        \n",
    "        print(\"πŸŽ‰ Upload completed successfully!\")\n",
    "        print(f\"🌐 Model available at: https://huggingface.co/{repo_name}\")\n",
    "        \n",
    "        # Usage instructions\n",
    "        print(\"\\\\nπŸ“‹ Usage instructions:\")\n",
    "        print(f\"from transformers import BertForSequenceClassification, BertTokenizer\")\n",
    "        print(f\"model = BertForSequenceClassification.from_pretrained('{repo_name}')\")\n",
    "        print(f\"tokenizer = BertTokenizer.from_pretrained('{repo_name}')\")\n",
    "        \n",
    "        return True\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"❌ Upload error: {e}\")\n",
    "        import traceback\n",
    "        traceback.print_exc()\n",
    "        return False\n",
    "\n",
    "def main():\n",
    "    if len(sys.argv) != 4:\n",
    "        print(\"Usage: python upload_to_hf.py <model_dir> <repo_name> <hf_token>\")\n",
    "        print(\"Example: python upload_to_hf.py ./pytorch_model ZoeYou/patentbert-pytorch hf_xxx...\")\n",
    "        sys.exit(1)\n",
    "    \n",
    "    model_dir = sys.argv[1]\n",
    "    repo_name = sys.argv[2]\n",
    "    token = sys.argv[3]\n",
    "    \n",
    "    if not os.path.exists(model_dir):\n",
    "        print(f\"❌ Directory not found: {model_dir}\")\n",
    "        sys.exit(1)\n",
    "    \n",
    "    success = upload_to_huggingface(model_dir, repo_name, token, private=False)\n",
    "    \n",
    "    if success:\n",
    "        print(\"\\\\nβœ… UPLOAD SUCCESSFUL!\")\n",
    "    else:\n",
    "        print(\"\\\\n❌ UPLOAD FAILED!\")\n",
    "        sys.exit(1)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # Import torch for loading test\n",
    "    try:\n",
    "        import torch\n",
    "    except ImportError:\n",
    "        print(\"⚠️  torch not available, loading test skipped\")\n",
    "        \n",
    "    main()\n",
    "\"\"\"\n",
    "\n",
    "# Save the corrected upload script\n",
    "with open('/tmp/upload_to_hf_corrected.py', 'w', encoding='utf-8') as f:\n",
    "    f.write(corrected_upload_script)\n",
    "\n",
    "# Also overwrite the original script\n",
    "with open('/tmp/upload_to_hf.py', 'w', encoding='utf-8') as f:\n",
    "    f.write(corrected_upload_script)\n",
    "\n",
    "print(\"βœ… CORRECTED upload script created!\")\n",
    "print(\"\\nπŸ”§ Key corrections:\")\n",
    "print(\"   βœ… Accepts BOTH model.safetensors AND pytorch_model.bin\")\n",
    "print(\"   βœ… Automatically detects model format\")\n",
    "print(\"   βœ… Improved error messages\")\n",
    "print(\"   βœ… Better commit message with format info\")\n",
    "print(\"   βœ… Proper torch import for testing\")\n",
    "\n",
    "print(\"\\nπŸš€ NOW RUN THIS CORRECTED COMMAND:\")\n",
    "print(\"   python /tmp/upload_to_hf.py patentbert_conversion/pytorch_model ZoeYou/patentbert-pytorch xxxxx\")\n",
    "\n",
    "print(\"\\nπŸ’‘ Or use the new corrected script:\")\n",
    "print(\"   python /tmp/upload_to_hf_corrected.py patentbert_conversion/pytorch_model ZoeYou/patentbert-pytorch xxxxx\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# πŸŽ‰ UPLOAD SUCCESS! Let's test the uploaded model\n",
    "\n",
    "print(\"πŸŽ‰ Upload successful! Testing the uploaded model from Hugging Face...\")\n",
    "\n",
    "# Test the uploaded model\n",
    "\n",
    "from transformers import BertForSequenceClassification, BertTokenizer\n",
    "import torch\n",
    "\n",
    "print(\"πŸ” Testing uploaded PatentBERT model from Hugging Face...\")\n",
    "\n",
    "try:\n",
    "    # Load model and tokenizer from Hugging Face Hub\n",
    "    model = BertForSequenceClassification.from_pretrained('ZoeYou/patentbert-pytorch')\n",
    "    tokenizer = BertTokenizer.from_pretrained('ZoeYou/patentbert-pytorch')\n",
    "    \n",
    "    print(f\"βœ… Model loaded: {model.config.num_labels} classes\")\n",
    "    print(f\"βœ… Tokenizer loaded: {len(tokenizer)} tokens\")\n",
    "    \n",
    "    # Test inference\n",
    "    text = \"A method for producing synthetic materials with enhanced properties\"\n",
    "    inputs = tokenizer(text, return_tensors=\"pt\", max_length=512, truncation=True, padding=True)\n",
    "    \n",
    "    with torch.no_grad():\n",
    "        outputs = model(**inputs)\n",
    "        predictions = outputs.logits.softmax(dim=-1)\n",
    "    \n",
    "    # Get top prediction\n",
    "    predicted_class_id = predictions.argmax().item()\n",
    "    confidence = predictions.max().item()\n",
    "    \n",
    "    # Use real CPC labels if available\n",
    "    if hasattr(model.config, 'id2label') and model.config.id2label:\n",
    "        predicted_label = model.config.id2label[predicted_class_id]\n",
    "        print(f\"βœ… Predicted CPC class: {predicted_label} (ID: {predicted_class_id})\")\n",
    "    else:\n",
    "        print(f\"βœ… Predicted class ID: {predicted_class_id}\")\n",
    "    \n",
    "    print(f\"βœ… Confidence: {confidence:.2%}\")\n",
    "    print(\"πŸŽ‰ Model works perfectly from Hugging Face!\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"❌ Error: {e}\")\n",
    "\n",
    "\n",
    "print(\"πŸ“ Model test code ready. Your model is now live at:\")\n",
    "print(\"🌐 https://huggingface.co/ZoeYou/patentbert-pytorch\")\n",
    "\n",
    "print(\"\\\\nπŸ“‹ Quick usage example:\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "πŸŽ‰ CONVERSION SUCCESSFUL! Upload script correction...\n",
      "βœ… CORRECTED upload script created!\n",
      "\n",
      "πŸ”§ Applied corrections:\n",
      "   βœ… Accepts model.safetensors AND pytorch_model.bin\n",
      "   βœ… Model loading test before upload\n",
      "   βœ… Robust file verification\n",
      "   βœ… Informative commit message\n",
      "   βœ… Usage instructions included\n",
      "\n",
      "πŸš€ CORRECTED COMMAND:\n",
      "   python upload_to_hf.py patentbert_conversion/pytorch_model ZoeYou/patentbert-pytorch xxxxx\n"
     ]
    }
   ],
   "source": [
    "# step 4: Provide usage example for the uploaded model\n",
    "\n",
    "# πŸŽ‰ CONVERSION SUCCESS! Upload script correction\n",
    "\n",
    "print(\"πŸŽ‰ CONVERSION SUCCESSFUL! Upload script correction...\")\n",
    "\n",
    "upload_script = \"\"\"#!/usr/bin/env python3\n",
    "import os\n",
    "import sys\n",
    "from huggingface_hub import HfApi, create_repo, upload_folder\n",
    "from transformers import BertForSequenceClassification, BertTokenizer\n",
    "\n",
    "def check_model_files(model_dir):\n",
    "    \\\"\\\"\\\"Check for required model files.\\\"\\\"\\\"\n",
    "    \n",
    "    # Required base files\n",
    "    required_base = ['config.json', 'vocab.txt', 'tokenizer_config.json']\n",
    "    \n",
    "    # Model files (at least one of these)\n",
    "    model_files = ['model.safetensors', 'pytorch_model.bin']\n",
    "    \n",
    "    missing_base = []\n",
    "    for file in required_base:\n",
    "        if not os.path.exists(os.path.join(model_dir, file)):\n",
    "            missing_base.append(file)\n",
    "    \n",
    "    # Check for at least one model file\n",
    "    has_model_file = any(os.path.exists(os.path.join(model_dir, f)) for f in model_files)\n",
    "    \n",
    "    if missing_base:\n",
    "        print(f\"❌ Missing required files: {missing_base}\")\n",
    "        return False\n",
    "    \n",
    "    if not has_model_file:\n",
    "        print(f\"❌ No model file found. Expected: {model_files}\")\n",
    "        return False\n",
    "    \n",
    "    # Show found files\n",
    "    found_files = []\n",
    "    for file in os.listdir(model_dir):\n",
    "        if os.path.isfile(os.path.join(model_dir, file)):\n",
    "            found_files.append(file)\n",
    "    \n",
    "    print(f\"βœ… Model files found: {found_files}\")\n",
    "    return True\n",
    "\n",
    "def test_model_loading(model_dir):\n",
    "    \\\"\\\"\\\"Test model loading to verify it works.\\\"\\\"\\\"\n",
    "    try:\n",
    "        print(\"πŸ§ͺ Model loading test...\")\n",
    "        \n",
    "        # Load model and tokenizer\n",
    "        model = BertForSequenceClassification.from_pretrained(model_dir)\n",
    "        tokenizer = BertTokenizer.from_pretrained(model_dir)\n",
    "        \n",
    "        print(f\"βœ… Model loaded: {model.config.num_labels} classes, {model.config.hidden_size} hidden\")\n",
    "        print(f\"βœ… Tokenizer loaded: {len(tokenizer)} tokens\")\n",
    "        \n",
    "        # Quick inference test\n",
    "        text = \"A method for producing synthetic materials\"\n",
    "        inputs = tokenizer(text, return_tensors=\"pt\", max_length=512, truncation=True, padding=True)\n",
    "        \n",
    "        with torch.no_grad():\n",
    "            outputs = model(**inputs)\n",
    "            predictions = outputs.logits.softmax(dim=-1)\n",
    "        \n",
    "        print(f\"βœ… Inference test successful: shape {predictions.shape}\")\n",
    "        return True\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"❌ Test error: {e}\")\n",
    "        return False\n",
    "\n",
    "def upload_to_huggingface(model_dir, repo_name, token, private=False):\n",
    "    \\\"\\\"\\\"Upload model to Hugging Face Hub.\\\"\\\"\\\"\n",
    "    \n",
    "    print(\"πŸš€ Upload to Hugging Face Hub\")\n",
    "    print(f\"πŸ“‚ Model: {model_dir}\")\n",
    "    print(f\"🏷️  Repository: {repo_name}\")\n",
    "    print(f\"πŸ”’ Private: {private}\")\n",
    "    \n",
    "    # File verification\n",
    "    if not check_model_files(model_dir):\n",
    "        return False\n",
    "    \n",
    "    # Loading test\n",
    "    if not test_model_loading(model_dir):\n",
    "        print(\"⚠️  Warning: Model doesn't load correctly, but continuing upload...\")\n",
    "    \n",
    "    try:\n",
    "        # Initialize API\n",
    "        api = HfApi(token=token)\n",
    "        \n",
    "        # Check connection\n",
    "        user_info = api.whoami()\n",
    "        print(f\"βœ… Connected as: {user_info['name']}\")\n",
    "        \n",
    "        # Create or verify repository\n",
    "        try:\n",
    "            create_repo(repo_name, token=token, private=private, exist_ok=True)\n",
    "            print(f\"βœ… Repository created/verified: https://huggingface.co/{repo_name}\")\n",
    "        except Exception as e:\n",
    "            print(f\"⚠️  Repository warning: {e}\")\n",
    "        \n",
    "        # Upload complete folder\n",
    "        print(\"πŸ“€ Uploading files...\")\n",
    "        \n",
    "        # Create informative commit message\n",
    "        commit_message = f\\\"\\\"\\\"Upload PatentBERT PyTorch model\n",
    "\n",
    "BERT model fine-tuned for patent classification, converted from TensorFlow to PyTorch.\n",
    "\n",
    "Specifications:\n",
    "- Format: {'SafeTensors' if os.path.exists(os.path.join(model_dir, 'model.safetensors')) else 'PyTorch'}\n",
    "- Classes: Auto-detected from config.json\n",
    "- Conversion: TensorFlow 1.15 β†’ PyTorch via transformers\n",
    "\n",
    "Included files:\n",
    "{', '.join(os.listdir(model_dir))}\n",
    "\\\"\\\"\\\"\n",
    "        \n",
    "        upload_folder(\n",
    "            folder_path=model_dir,\n",
    "            repo_id=repo_name,\n",
    "            token=token,\n",
    "            commit_message=commit_message,\n",
    "            ignore_patterns=[\".git\", \".gitattributes\", \"*.tmp\"]\n",
    "        )\n",
    "        \n",
    "        print(\"πŸŽ‰ Upload completed successfully!\")\n",
    "        print(f\"🌐 Model available at: https://huggingface.co/{repo_name}\")\n",
    "        \n",
    "        # Usage instructions\n",
    "        print(\"\\\\nπŸ“‹ Usage instructions:\")\n",
    "        print(f\"from transformers import BertForSequenceClassification, BertTokenizer\")\n",
    "        print(f\"model = BertForSequenceClassification.from_pretrained('{repo_name}')\")\n",
    "        print(f\"tokenizer = BertTokenizer.from_pretrained('{repo_name}')\")\n",
    "        \n",
    "        return True\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"❌ Upload error: {e}\")\n",
    "        return False\n",
    "\n",
    "def main():\n",
    "    if len(sys.argv) != 4:\n",
    "        print(\"Usage: python upload_to_hf.py <model_dir> <repo_name> <hf_token>\")\n",
    "        print(\"Example: python upload_to_hf.py ./pytorch_model ZoeYou/patentbert-pytorch hf_xxx...\")\n",
    "        sys.exit(1)\n",
    "    \n",
    "    model_dir = sys.argv[1]\n",
    "    repo_name = sys.argv[2]\n",
    "    token = sys.argv[3]\n",
    "    \n",
    "    if not os.path.exists(model_dir):\n",
    "        print(f\"❌ Directory not found: {model_dir}\")\n",
    "        sys.exit(1)\n",
    "    \n",
    "    success = upload_to_huggingface(model_dir, repo_name, token, private=False)\n",
    "    \n",
    "    if success:\n",
    "        print(\"\\\\nβœ… UPLOAD SUCCESSFUL!\")\n",
    "    else:\n",
    "        print(\"\\\\n❌ UPLOAD FAILED!\")\n",
    "        sys.exit(1)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # Import torch for loading test\n",
    "    try:\n",
    "        import torch\n",
    "    except ImportError:\n",
    "        print(\"⚠️  torch not available, loading test skipped\")\n",
    "        \n",
    "    main()\n",
    "\"\"\"\n",
    "\n",
    "# Save corrected upload script\n",
    "with open('/tmp/upload_to_hf.py', 'w', encoding='utf-8') as f:\n",
    "    f.write(upload_script)\n",
    "\n",
    "print(\"βœ… CORRECTED upload script created!\")\n",
    "print(\"\\nπŸ”§ Applied corrections:\")\n",
    "print(\"   βœ… Accepts model.safetensors AND pytorch_model.bin\")\n",
    "print(\"   βœ… Model loading test before upload\")\n",
    "print(\"   βœ… Robust file verification\")\n",
    "print(\"   βœ… Informative commit message\")\n",
    "print(\"   βœ… Usage instructions included\")\n",
    "\n",
    "print(\"\\nπŸš€ CORRECTED COMMAND:\")\n",
    "print(\"   python upload_to_hf.py patentbert_conversion/pytorch_model ZoeYou/patentbert-pytorch xxxxx\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "🎯 COMPLETE TENSORFLOW β†’ PYTORCH CONVERSION GUIDE\n",
    "\n",
    "πŸ“‹ 4-step process:\n",
    "\n",
    "1️⃣  **DOWNLOAD** (in this notebook)\n",
    "   β€’ Run previous cells to download PatentBERT\n",
    "   β€’ Model will be in ./\n",
    "\n",
    "2️⃣  **EXTRACTION** (in this notebook)\n",
    "   β€’ Run TensorFlow weight extraction cell\n",
    "   β€’ Weights will be extracted to /tmp/patentbert_conversion/tf_weights/\n",
    "\n",
    "3️⃣  **CONVERSION** (Python 3.8+ environment)\n",
    "   ```\n",
    "   bash /tmp/install_pytorch_env.sh\n",
    "   source patentbert_pytorch/bin/activate\n",
    "   python /tmp/convert_patentbert.py /tmp/patentbert_conversion/tf_weights /tmp/patentbert_conversion/pytorch_model\n",
    "   ```\n",
    "\n",
    "4️⃣  **TEST AND UPLOAD**\n",
    "\n",
    "   `python /tmp/test_patentbert.py /tmp/patentbert_conversion/pytorch_model`\n",
    "\n",
    "   `python /tmp/upload_to_hf.py /tmp/patentbert_conversion/pytorch_model username/patentbert-pytorch your_hf_token`\n",
    "\n",
    "πŸŽ‰ RESULT:\n",
    "β€’ PyTorch model ready for production\n",
    "β€’ Compatible with Hugging Face Transformers\n",
    "β€’ Publicly available on Hub\n",
    "β€’ Documentation and examples included\n",
    "\n",
    "πŸ’‘ TIP:\n",
    "First create an account at https://huggingface.co/ and get your access token\n",
    "from https://huggingface.co/settings/tokens\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🏷️ Creating and adding CPC class labels...\n",
      "βœ… Loaded 656 real CPC labels from PatentBERT\n",
      "πŸ“ Example labels from the real data:\n",
      "     0: A01B - SOIL WORKING IN AGRICULTURE OR FORESTRY; PARTS, DETAILS, OR ACCESSORIES OF AGRIC...\n",
      "    50: A46B - BRUSHES ...\n",
      "   100: B07B - SEPERATING SOLIDS FROM SOLIDS BY SIEVING, SCREENING, OR SIFTING OR BY USING GAS ...\n",
      "   200: B60Q - ARRANGEMENT OF SIGNALLING OR LIGHTING DEVICES, THE MOUNTING OR SUPPORTING THEREO...\n",
      "   300: C10F - DRYING OR WORKING-UP OF PEAT...\n",
      "   400: E04G - SCAFFOLDING; FORMS; SHUTTERING; BUILDING IMPLEMENTS OR OTHER BUILDING AIDS, OR T...\n",
      "   500: F28B - STEAM OR VAPOUR CONDENSERS ...\n",
      "   600: H01H - ELECTRIC SWITCHES; RELAYS; SELECTORS...\n",
      "   655: Y10T - TECHNICAL SUBJECTS COVERED BY FORMER US CLASSIFICATION...\n",
      "\n",
      "βœ… Real CPC system structure:\n",
      "   πŸ“Š Total classes: 656\n",
      "   πŸ“ˆ Distribution by section:\n",
      "      A: 84 classes\n",
      "      B: 171 classes\n",
      "      C: 88 classes\n",
      "      D: 40 classes\n",
      "      E: 31 classes\n",
      "      F: 101 classes\n",
      "      G: 81 classes\n",
      "      H: 51 classes\n",
      "      Y: 9 classes\n",
      "βœ… Labels saved to: /tmp/patentbert_conversion/pytorch_model/labels.json\n",
      "βœ… Configuration updated with real CPC labels\n",
      "βœ… README updated with REAL CPC label documentation\n",
      "\n",
      "πŸ“ Added/updated files:\n",
      "   β€’ labels.json - Complete mapping of 656 REAL CPC labels\n",
      "   β€’ config.json - Updated configuration with authentic id2label/label2id\n",
      "   β€’ README.md - Complete documentation with real CPC distribution\n",
      "\n",
      "🎯 Model is now ready for upload with AUTHENTIC CPC labels!\n"
     ]
    }
   ],
   "source": [
    "# 🏷️ ADDING CLASS LABELS - Essential for prediction interpretation\n",
    "\n",
    "print(\"🏷️ Creating and adding CPC class labels...\")\n",
    "\n",
    "# Load the REAL CPC labels from the original PatentBERT label file\n",
    "import pandas as pd\n",
    "import json\n",
    "import os\n",
    "\n",
    "# Load the real CPC labels\n",
    "label_file_path = \"./labels_group_id.tsv\"\n",
    "cpc_df = pd.read_csv(label_file_path, sep='\\t')\n",
    "\n",
    "print(f\"βœ… Loaded {len(cpc_df)} real CPC labels from PatentBERT\")\n",
    "print(f\"πŸ“ Example labels from the real data:\")\n",
    "for i in [0, 50, 100, 200, 300, 400, 500, 600, 655]:\n",
    "    if i < len(cpc_df):\n",
    "        row = cpc_df.iloc[i]\n",
    "        print(f\"   {i:3d}: {row['id']} - {row['title'][:80]}...\")\n",
    "\n",
    "# Extract labels and descriptions\n",
    "cpc_labels = cpc_df['id'].tolist()\n",
    "cpc_descriptions = [f\"{row['id']}: {row['title']}\" for _, row in cpc_df.iterrows()]\n",
    "\n",
    "print(f\"\\nβœ… Real CPC system structure:\")\n",
    "print(f\"   πŸ“Š Total classes: {len(cpc_labels)}\")\n",
    "\n",
    "# Analyze the actual distribution by section\n",
    "section_counts = {}\n",
    "for label in cpc_labels:\n",
    "    section = label[0]\n",
    "    section_counts[section] = section_counts.get(section, 0) + 1\n",
    "\n",
    "print(f\"   πŸ“ˆ Distribution by section:\")\n",
    "for section, count in sorted(section_counts.items()):\n",
    "    print(f\"      {section}: {count} classes\")\n",
    "\n",
    "# Create label configuration file\n",
    "label_config = {\n",
    "    \"id2label\": {str(i): label for i, label in enumerate(cpc_labels)},\n",
    "    \"label2id\": {label: i for i, label in enumerate(cpc_labels)},\n",
    "    \"num_labels\": len(cpc_labels),\n",
    "    \"classification_type\": \"CPC\",\n",
    "    \"description\": \"Real Cooperative Patent Classification (CPC) labels from PatentBERT training data\"\n",
    "}\n",
    "\n",
    "# Save to model directory\n",
    "model_dir = \"/tmp/patentbert_conversion/pytorch_model\"\n",
    "labels_file = os.path.join(model_dir, \"labels.json\")\n",
    "\n",
    "with open(labels_file, 'w', encoding='utf-8') as f:\n",
    "    json.dump(label_config, f, indent=2, ensure_ascii=False)\n",
    "\n",
    "print(f\"βœ… Labels saved to: {labels_file}\")\n",
    "\n",
    "# Update model configuration to include labels\n",
    "config_file = os.path.join(model_dir, \"config.json\")\n",
    "\n",
    "if os.path.exists(config_file):\n",
    "    with open(config_file, 'r') as f:\n",
    "        config = json.load(f)\n",
    "    \n",
    "    # Add labels to config\n",
    "    config[\"id2label\"] = label_config[\"id2label\"]\n",
    "    config[\"label2id\"] = label_config[\"label2id\"]\n",
    "    \n",
    "    # Save updated config\n",
    "    with open(config_file, 'w', encoding='utf-8') as f:\n",
    "        json.dump(config, f, indent=2, ensure_ascii=False)\n",
    "    \n",
    "    print(\"βœ… Configuration updated with real CPC labels\")\n",
    "else:\n",
    "    print(\"⚠️ config.json file not found\")\n",
    "\n",
    "# Create detailed README with REAL CPC labels and distribution\n",
    "section_descriptions = {\n",
    "    'A': 'Human Necessities - Agriculture, Food, Health, Sports',\n",
    "    'B': 'Performing Operations; Transporting - Manufacturing, Transport',\n",
    "    'C': 'Chemistry; Metallurgy - Chemical processes, Materials',\n",
    "    'D': 'Textiles; Paper - Fibers, Fabrics, Paper-making',\n",
    "    'E': 'Fixed Constructions - Building, Mining, Roads',\n",
    "    'F': 'Mechanical Engineering; Lightning; Heating; Weapons; Blasting',\n",
    "    'G': 'Physics - Optics, Acoustics, Computing, Measuring',\n",
    "    'H': 'Electricity - Electronics, Power generation, Communication',\n",
    "    'Y': 'General Tagging of New Technological Developments'\n",
    "}\n",
    "\n",
    "readme_with_labels = f\"\"\"# PatentBERT - PyTorch\n",
    "\n",
    "BERT model specialized for patent classification using the **real CPC (Cooperative Patent Classification) system** from the original PatentBERT training data.\n",
    "\n",
    "## πŸ“Š Specifications\n",
    "\n",
    "- **Output classes**: {len(cpc_labels)} (real CPC labels)\n",
    "- **Classification system**: CPC (Cooperative Patent Classification)\n",
    "- **Architecture**: BERT-base (768 hidden, 12 layers, 12 attention heads)\n",
    "- **Vocabulary**: 30,522 tokens\n",
    "- **Format**: SafeTensors\n",
    "\n",
    "## 🏷️ CPC Classes (Real Distribution)\n",
    "\n",
    "The model predicts classes according to the authentic CPC system used in PatentBERT training:\n",
    "\n",
    "### Main Sections (Actual Counts)\n",
    "\"\"\"\n",
    "\n",
    "# Add real distribution to README\n",
    "for section in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'Y']:\n",
    "    if section in section_counts:\n",
    "        count = section_counts[section]\n",
    "        desc = section_descriptions.get(section, f'Section {section}')\n",
    "        readme_with_labels += f\"- **{section} ({count} classes)**: {desc}\\n\"\n",
    "\n",
    "readme_with_labels += f\"\"\"\n",
    "### Example Real Classes\n",
    "\n",
    "- `A01B`: SOIL WORKING IN AGRICULTURE OR FORESTRY\n",
    "- `B25J`: MANIPULATORS; CHAMBERS PROVIDED WITH MANIPULATION DEVICES\n",
    "- `C07D`: HETEROCYCLIC COMPOUNDS\n",
    "- `G06F`: ELECTRIC DIGITAL DATA PROCESSING\n",
    "- `H04L`: TRANSMISSION OF DIGITAL INFORMATION\n",
    "\n",
    "## πŸš€ Usage\n",
    "\n",
    "```python\n",
    "from transformers import BertForSequenceClassification, BertTokenizer\n",
    "import json\n",
    "import torch\n",
    "\n",
    "# Load model and tokenizer\n",
    "model = BertForSequenceClassification.from_pretrained('ZoeYou/patentbert-pytorch')\n",
    "tokenizer = BertTokenizer.from_pretrained('ZoeYou/patentbert-pytorch')\n",
    "\n",
    "# Inference example\n",
    "text = \"A method for producing synthetic materials with enhanced thermal properties...\"\n",
    "inputs = tokenizer(text, return_tensors=\"pt\", max_length=512, truncation=True, padding=True)\n",
    "\n",
    "with torch.no_grad():\n",
    "    outputs = model(**inputs)\n",
    "    predictions = outputs.logits.softmax(dim=-1)\n",
    "\n",
    "# Get prediction\n",
    "predicted_class_id = predictions.argmax().item()\n",
    "confidence = predictions.max().item()\n",
    "\n",
    "# Use model labels (real CPC codes)\n",
    "predicted_label = model.config.id2label[predicted_class_id]\n",
    "\n",
    "\n",
    "print(f\"Predicted CPC class: {{predicted_label}} (ID: {{predicted_class_id}})\")\n",
    "print(f\"Confidence: {{confidence:.2%}}\")\n",
    "```\n",
    "\n",
    "## πŸ“ Included Files\n",
    "\n",
    "- `model.safetensors`: Model weights (420 MB)\n",
    "- `config.json`: Configuration with integrated real CPC labels\n",
    "- `vocab.txt`: Tokenizer vocabulary\n",
    "- `tokenizer_config.json`: Tokenizer configuration\n",
    "- `labels.json`: Complete real CPC label mapping ({len(cpc_labels)} authentic labels)\n",
    "- `README.md`: This documentation\n",
    "\n",
    "## πŸ”¬ Performance\n",
    "\n",
    "This model was trained on a large patent corpus to automatically classify documents according to the real CPC system, using the exact same {len(cpc_labels)} CPC codes from the original PatentBERT training data.\n",
    "\n",
    "## πŸ“– References\n",
    "\n",
    "- [Cooperative Patent Classification (CPC)](https://www.cooperativepatentclassification.org/)\n",
    "- [Original PatentBERT Paper](https://arxiv.org/abs/2103.02557)\n",
    "\n",
    "## πŸ“ Citation\n",
    "\n",
    "If you use this model, please cite the original PatentBERT work and mention this PyTorch conversion.\n",
    "\"\"\"\n",
    "\n",
    "# Save updated README\n",
    "readme_file = os.path.join(model_dir, \"README.md\")\n",
    "with open(readme_file, 'w', encoding='utf-8') as f:\n",
    "    f.write(readme_with_labels)\n",
    "\n",
    "print(\"βœ… README updated with REAL CPC label documentation\")\n",
    "\n",
    "# Summary of created/updated files\n",
    "print(\"\\nπŸ“ Added/updated files:\")\n",
    "print(f\"   β€’ labels.json - Complete mapping of {len(cpc_labels)} REAL CPC labels\")\n",
    "print(f\"   β€’ config.json - Updated configuration with authentic id2label/label2id\")\n",
    "print(f\"   β€’ README.md - Complete documentation with real CPC distribution\")\n",
    "\n",
    "print(\"\\n🎯 Model is now ready for upload with AUTHENTIC CPC labels!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Predicted CPC class: A63B (ID: 76)\n",
      "Confidence: 99.51%\n"
     ]
    }
   ],
   "source": [
    "from transformers import BertForSequenceClassification, BertTokenizer\n",
    "import torch\n",
    "\n",
    "# Load model and tokenizer\n",
    "model = BertForSequenceClassification.from_pretrained('ZoeYou/patentbert-pytorch')\n",
    "tokenizer = BertTokenizer.from_pretrained('ZoeYou/patentbert-pytorch')\n",
    "\n",
    "# Inference example\n",
    "text = \"A device designed to spin in a user's hands may include a body with a centrally mounted ball bearing positioned within a center orifice of the body, wherein an outer race of the ball bearing is attached to the frame; a button made of a pair of bearing caps attached to one another through the ball bearing and clamped against an inner race of the ball bearing, such that when the button is held between a user's thumb and finger, the body freely rotates about the ball bearing; and a plurality of weights distributed at opposite ends of the body, creating at least a bipolar weight distribution.\"\n",
    "inputs = tokenizer(text, return_tensors=\"pt\", max_length=512, truncation=True, padding=True)\n",
    "\n",
    "with torch.no_grad():\n",
    "    outputs = model(**inputs)\n",
    "    predictions = outputs.logits.softmax(dim=-1)\n",
    "\n",
    "# Get prediction\n",
    "predicted_class_id = predictions.argmax().item()\n",
    "confidence = predictions.max().item()\n",
    "\n",
    "# Use model labels (real CPC codes)\n",
    "predicted_label = model.config.id2label[predicted_class_id]\n",
    "\n",
    "print(f\"Predicted CPC class: {predicted_label} (ID: {predicted_class_id})\")\n",
    "print(f\"Confidence: {confidence:.2%}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'A63B'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.config.id2label[76]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "PatentBERT",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "simcse",
   "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.23"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}