File size: 42,624 Bytes
6051ae2
3921dd6
 
6051ae2
777b2a0
6051ae2
 
777b2a0
3921dd6
6051ae2
 
 
 
 
3921dd6
 
 
 
 
 
 
 
 
 
 
 
 
6051ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3921dd6
 
 
 
 
 
 
 
 
 
6051ae2
 
 
3921dd6
6051ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3921dd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6051ae2
 
 
 
 
 
3921dd6
6051ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3921dd6
 
 
 
 
 
 
6051ae2
 
 
3921dd6
 
 
 
 
 
 
 
 
63c9215
6051ae2
 
 
 
 
 
777b2a0
6051ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3921dd6
6051ae2
 
 
3921dd6
6051ae2
 
 
 
 
 
3921dd6
6051ae2
 
 
3921dd6
 
 
 
 
 
6051ae2
 
 
 
 
 
 
 
 
 
777b2a0
6051ae2
 
3921dd6
 
 
 
 
 
 
 
 
6051ae2
 
 
3921dd6
 
 
6051ae2
 
3921dd6
6051ae2
 
 
 
 
 
 
 
 
 
 
3921dd6
 
 
6051ae2
 
 
 
3921dd6
6051ae2
 
 
 
3921dd6
 
 
6051ae2
 
 
 
3921dd6
 
 
 
 
 
 
 
 
 
6051ae2
 
 
3921dd6
 
 
 
 
 
6051ae2
3921dd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6051ae2
 
777b2a0
6051ae2
777b2a0
 
 
6051ae2
 
 
 
 
 
 
 
 
 
3921dd6
 
 
 
 
 
 
 
 
 
 
 
 
 
6051ae2
 
 
 
 
 
 
777b2a0
 
6051ae2
3921dd6
6051ae2
3921dd6
 
 
 
 
 
 
 
 
 
 
6051ae2
 
 
3921dd6
 
6051ae2
3921dd6
6051ae2
 
 
3921dd6
 
6051ae2
 
 
 
 
 
 
 
 
 
 
 
3921dd6
 
 
6051ae2
 
 
 
3921dd6
6051ae2
 
 
 
 
3921dd6
 
 
6051ae2
 
 
 
3921dd6
 
 
 
 
 
 
 
 
 
 
6051ae2
3921dd6
 
 
 
 
 
 
 
 
 
 
 
 
 
6051ae2
3921dd6
 
 
 
 
 
 
 
6051ae2
 
777b2a0
6051ae2
777b2a0
 
 
 
 
 
 
 
 
 
 
 
 
6051ae2
3921dd6
 
 
 
 
 
 
 
 
 
 
 
 
6051ae2
 
 
3921dd6
 
6051ae2
3921dd6
6051ae2
 
 
 
3921dd6
6051ae2
 
 
 
 
 
 
 
 
 
 
 
3921dd6
 
 
6051ae2
 
 
 
3921dd6
6051ae2
 
 
 
 
3921dd6
 
 
6051ae2
 
 
 
3921dd6
 
 
 
 
 
 
 
 
 
6051ae2
 
3921dd6
 
 
 
 
 
 
6051ae2
 
 
3921dd6
 
 
 
 
 
 
 
6051ae2
63c9215
6051ae2
 
 
 
 
 
777b2a0
6051ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3921dd6
6051ae2
 
 
3921dd6
6051ae2
 
 
 
 
 
3921dd6
6051ae2
 
 
3921dd6
 
 
 
 
 
6051ae2
 
 
 
 
 
 
 
 
 
777b2a0
6051ae2
 
3921dd6
 
 
 
 
 
 
 
 
6051ae2
3921dd6
 
 
6051ae2
 
3921dd6
6051ae2
 
 
 
 
 
 
 
 
 
 
3921dd6
 
 
6051ae2
 
 
 
3921dd6
6051ae2
 
 
 
3921dd6
 
 
6051ae2
 
 
 
3921dd6
 
 
 
 
 
 
 
 
 
 
6051ae2
 
 
3921dd6
6051ae2
 
 
 
 
 
 
777b2a0
6051ae2
3921dd6
 
 
 
 
 
6051ae2
3921dd6
 
 
 
 
 
 
 
6051ae2
 
777b2a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6051ae2
3921dd6
6051ae2
 
3921dd6
6051ae2
 
 
 
 
 
 
3921dd6
 
 
 
 
 
6051ae2
3921dd6
 
6051ae2
3921dd6
6051ae2
 
 
 
 
3921dd6
6051ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3921dd6
 
 
6051ae2
 
 
 
3921dd6
6051ae2
 
 
 
 
3921dd6
 
 
6051ae2
 
 
 
3921dd6
 
 
 
 
 
 
 
 
 
 
6051ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
777b2a0
 
6051ae2
777b2a0
3921dd6
 
 
 
 
 
 
6051ae2
 
3921dd6
 
 
 
 
6051ae2
 
3921dd6
 
 
 
 
 
 
6051ae2
 
777b2a0
6051ae2
 
3921dd6
6051ae2
 
 
3921dd6
 
 
6051ae2
 
3921dd6
 
 
 
 
 
6051ae2
 
 
3921dd6
 
 
 
 
 
6051ae2
 
3921dd6
 
 
6051ae2
 
 
3921dd6
6051ae2
 
 
 
 
 
 
777b2a0
6051ae2
 
3921dd6
 
 
 
 
6051ae2
 
 
3921dd6
 
 
 
 
 
6051ae2
 
 
 
 
 
3921dd6
 
 
 
 
 
6051ae2
 
 
 
 
 
 
 
 
 
 
 
 
777b2a0
 
6051ae2
777b2a0
3921dd6
 
 
 
 
 
 
 
777b2a0
6051ae2
 
3921dd6
6051ae2
777b2a0
6051ae2
 
3921dd6
6051ae2
 
3921dd6
 
 
6051ae2
 
3921dd6
6051ae2
 
 
3921dd6
6051ae2
 
3921dd6
 
 
6051ae2
 
 
3921dd6
6051ae2
 
 
 
 
 
 
 
 
 
3921dd6
6051ae2
 
 
 
 
 
 
 
408ec97
 
6051ae2
 
 
 
 
 
 
 
 
 
 
adedf8e
6051ae2
 
 
 
 
 
3921dd6
6051ae2
3921dd6
 
 
 
 
810f572
 
 
 
3921dd6
 
6051ae2
 
6c0d667
 
 
3921dd6
 
6c0d667
 
 
 
 
3921dd6
6c0d667
 
3921dd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c0d667
 
 
 
6051ae2
810f572
 
 
 
 
 
 
6051ae2
 
3921dd6
 
6051ae2
 
3921dd6
 
6051ae2
 
 
 
 
4dbcda2
6051ae2
 
 
eded98b
 
6051ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3921dd6
6051ae2
 
 
 
 
 
3921dd6
6051ae2
 
 
 
 
 
3921dd6
6051ae2
 
 
 
 
3921dd6
6051ae2
 
 
 
 
3921dd6
6051ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb9117f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
from enum import Enum
from functools import lru_cache, partial
import json
from pathlib import Path
from typing import Optional, Tuple
import gradio as gr
from gradio_huggingfacehub_search import HuggingfaceHubSearch
import huggingface_hub
from sentence_transformers import CrossEncoder, SentenceTransformer, SparseEncoder
from sentence_transformers import (
    export_dynamic_quantized_onnx_model as st_export_dynamic_quantized_onnx_model,
    export_optimized_onnx_model as st_export_optimized_onnx_model,
    export_static_quantized_openvino_model as st_export_static_quantized_openvino_model,
)
from huggingface_hub import (
    model_info,
    upload_folder,
    get_repo_discussions,
    list_repo_commits,
    HfFileSystem,
    hf_hub_download,
)
from huggingface_hub.errors import (
    RepositoryNotFoundError,
    HFValidationError,
    EntryNotFoundError,
)
from optimum.intel import OVQuantizationConfig
from tempfile import TemporaryDirectory


class Backend(Enum):
    # TORCH = "PyTorch"
    ONNX = "ONNX"
    ONNX_DYNAMIC_QUANTIZATION = "ONNX (Dynamic Quantization)"
    ONNX_OPTIMIZATION = "ONNX (Optimization)"
    OPENVINO = "OpenVINO"
    OPENVINO_STATIC_QUANTIZATION = "OpenVINO (Static Quantization)"

    def __str__(self):
        return self.value


class Archetype(Enum):
    SENTENCE_TRANSFORMER = "SentenceTransformer"
    SPARSE_ENCODER = "SparseEncoder"
    CROSS_ENCODER = "CrossEncoder"
    OTHER = "Other"

    def __str__(self):
        return self.value


backends = [str(backend) for backend in Backend]
FILE_SYSTEM = HfFileSystem()


def is_new_model(model_id: str) -> bool:
    """
    Check if the model ID exists on the Hugging Face Hub. If we get a request error, then we
    assume the model *does* exist.
    """
    try:
        model_info(model_id)
    except RepositoryNotFoundError:
        return True
    except Exception:
        pass
    return False


def is_sentence_transformer_model(model_id: str) -> bool:
    return "sentence-transformers" in model_info(model_id).tags


@lru_cache()
def get_archetype(model_id: str) -> Archetype:
    if "/" not in model_id:
        return Archetype.OTHER

    try:
        config_sentence_transformers_path = hf_hub_download(
            model_id, filename="config_sentence_transformers.json"
        )
    except (RepositoryNotFoundError, HFValidationError):
        return Archetype.OTHER
    except EntryNotFoundError:
        config_sentence_transformers_path = None

    try:
        config_path = hf_hub_download(model_id, filename="config.json")
    except (RepositoryNotFoundError, HFValidationError):
        return Archetype.OTHER
    except EntryNotFoundError:
        config_path = None

    if config_sentence_transformers_path is None and config_path is None:
        return Archetype.OTHER

    if config_sentence_transformers_path is not None:
        with open(config_sentence_transformers_path, "r", encoding="utf8") as f:
            st_config = json.load(f)
            model_type = st_config.get("model_type", "SentenceTransformer")
            if model_type == "SentenceTransformer":
                return Archetype.SENTENCE_TRANSFORMER
            elif model_type == "SparseEncoder":
                return Archetype.SPARSE_ENCODER
            else:
                return Archetype.OTHER

    if config_path is not None:
        with open(config_path, "r", encoding="utf8") as f:
            config = json.load(f)
            if "sentence_transformers" in config or config["architectures"][0].endswith(
                "ForSequenceClassification"
            ):
                return Archetype.CROSS_ENCODER

    return Archetype.OTHER


def get_last_commit(model_id: str) -> str:
    """
    Get the last commit hash of the model ID.
    """
    return f"https://huggingface.co/{model_id}/commit/{list_repo_commits(model_id)[0].commit_id}"


def get_last_pr(model_id: str) -> Tuple[str, int]:
    last_pr = next(get_repo_discussions(model_id))
    return last_pr.url, last_pr.num


def does_file_glob_exist(repo_id: str, glob: str) -> bool:
    """
    Check if a file glob exists in the repository.
    """
    try:
        return bool(FILE_SYSTEM.glob(f"{repo_id}/{glob}", detail=False))
    except FileNotFoundError:
        return False


def export_to_torch(model_id, create_pr, output_model_id):
    model = SentenceTransformer(model_id, backend="torch")
    model.push_to_hub(
        repo_id=output_model_id,
        create_pr=create_pr,
        exist_ok=True,
    )


def export_to_onnx(
    model_id: str,
    archetype: Archetype,
    create_pr: bool,
    output_model_id: str,
    token: Optional[str] = None,
) -> None:
    if does_file_glob_exist(output_model_id, "**/model.onnx"):
        raise FileExistsError("An ONNX model already exists in the repository")

    if archetype == Archetype.SENTENCE_TRANSFORMER:
        model = SentenceTransformer(model_id, backend="onnx")
    elif archetype == Archetype.SPARSE_ENCODER:
        model = SparseEncoder(model_id, backend="onnx")
    elif archetype == Archetype.CROSS_ENCODER:
        model = CrossEncoder(model_id, backend="onnx")
    else:
        return

    commit_message = "Add exported onnx model 'model.onnx'"

    if is_new_model(output_model_id):
        model.push_to_hub(
            repo_id=output_model_id,
            commit_message=commit_message,
            create_pr=create_pr,
            token=token,
        )
    else:
        with TemporaryDirectory() as tmp_dir:
            model.save_pretrained(tmp_dir)

            commit_description = f"""
Hello!

*This pull request has been automatically generated from the [Sentence Transformers backend-export](https://huggingface.co/spaces/sentence-transformers/backend-export) Space.*

## Pull Request overview
* Add exported ONNX model `model.onnx`.

## Tip:
Consider testing this pull request before merging by loading the model from this PR with the `revision` argument:
```python
from sentence_transformers import {archetype}

# TODO: Fill in the PR number
pr_number = 2
model = {archetype}(
    "{output_model_id}",
    revision=f"refs/pr/{{pr_number}}",
    backend="onnx",
)

# Verify that everything works as expected
{'''embeddings = model.encode(["The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium."])
print(embeddings.shape)

similarities = model.similarity(embeddings, embeddings)
print(similarities)''' if archetype in {Archetype.SENTENCE_TRANSFORMER, Archetype.SPARSE_ENCODER} else
'''predictions = model.predict([
    ["Which planet is known as the Red Planet?", "Mars, known for its reddish appearance, is often referred to as the Red Planet."],
    ["Which planet is known as the Red Planet?", "Jupiter, the largest planet in our solar system, has a prominent red spot."],
])
print(predictions)'''}
```
"""

            upload_folder(
                repo_id=output_model_id,
                folder_path=Path(tmp_dir) / "onnx",
                path_in_repo="onnx",
                commit_message=commit_message,
                commit_description=commit_description if create_pr else None,
                create_pr=create_pr,
                token=token,
            )


def export_to_onnx_snippet(
    model_id: str, archetype: Archetype, create_pr: bool, output_model_id: str
) -> Tuple[str, str, str]:
    if archetype == Archetype.OTHER:
        return "", "", ""

    return (
        """\
pip install sentence_transformers[onnx-gpu]
# or
pip install sentence_transformers[onnx]
""",
        f"""\
from sentence_transformers import {archetype}

# 1. Load the model to be exported with the ONNX backend
model = {archetype}(
    "{model_id}",
    backend="onnx",
)

# 2. Push the model to the Hugging Face Hub
{f'model.push_to_hub("{output_model_id}")'
 if not create_pr
 else f'''model.push_to_hub(
    "{output_model_id}",
    create_pr=True,
)'''}
""",
        f"""\
from sentence_transformers import {archetype}

# 1. Load the model from the Hugging Face Hub
# (until merged) Use the `revision` argument to load the model from the PR
pr_number = 2
model = {archetype}(
    "{output_model_id}",
    revision=f"refs/pr/{{pr_number}}",
    backend="onnx",
)
"""
        + (
            """
# 2. Inference works as normal
embeddings = model.encode(["The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium."])
similarities = model.similarity(embeddings, embeddings)
"""
            if archetype in {Archetype.SENTENCE_TRANSFORMER, Archetype.SPARSE_ENCODER}
            else """
# 2. Inference works as normal
predictions = model.predict([
    ["Which planet is known as the Red Planet?", "Mars, known for its reddish appearance, is often referred to as the Red Planet."],
    ["Which planet is known as the Red Planet?", "Jupiter, the largest planet in our solar system, has a prominent red spot."],
])
"""
        ),
    )


def export_to_onnx_dynamic_quantization(
    model_id: str,
    archetype: Archetype,
    create_pr: bool,
    output_model_id: str,
    onnx_quantization_config: str,
    token: Optional[str] = None,
) -> None:
    if does_file_glob_exist(
        output_model_id, f"onnx/model_qint8_{onnx_quantization_config}.onnx"
    ):
        raise FileExistsError(
            "The quantized ONNX model already exists in the repository"
        )

    if archetype == Archetype.SENTENCE_TRANSFORMER:
        model = SentenceTransformer(model_id, backend="onnx")
    elif archetype == Archetype.SPARSE_ENCODER:
        model = SparseEncoder(model_id, backend="onnx")
    elif archetype == Archetype.CROSS_ENCODER:
        model = CrossEncoder(model_id, backend="onnx")
    else:
        return

    if not create_pr and is_new_model(output_model_id):
        model.push_to_hub(repo_id=output_model_id, token=token)

    # Monkey-patch the upload_folder function to include the token, as it's not used in export_dynamic_quantized_onnx_model
    original_upload_folder = huggingface_hub.upload_folder
    huggingface_hub.upload_folder = partial(original_upload_folder, token=token)
    try:
        st_export_dynamic_quantized_onnx_model(
            model,
            quantization_config=onnx_quantization_config,
            model_name_or_path=output_model_id,
            push_to_hub=True,
            create_pr=create_pr,
        )
    except ValueError:
        # Currently, quantization with optimum has some issues if there's already an ONNX model in a subfolder
        if archetype == Archetype.SENTENCE_TRANSFORMER:
            model = SentenceTransformer(
                model_id, backend="onnx", model_kwargs={"export": True}
            )
        elif archetype == Archetype.SPARSE_ENCODER:
            model = SparseEncoder(
                model_id, backend="onnx", model_kwargs={"export": True}
            )
        elif archetype == Archetype.CROSS_ENCODER:
            model = CrossEncoder(
                model_id, backend="onnx", model_kwargs={"export": True}
            )
        else:
            return
        st_export_dynamic_quantized_onnx_model(
            model,
            quantization_config=onnx_quantization_config,
            model_name_or_path=output_model_id,
            push_to_hub=True,
            create_pr=create_pr,
        )
    finally:
        huggingface_hub.upload_folder = original_upload_folder


def export_to_onnx_dynamic_quantization_snippet(
    model_id: str,
    archetype: Archetype,
    create_pr: bool,
    output_model_id: str,
    onnx_quantization_config: str,
) -> Tuple[str, str, str]:
    if archetype == Archetype.OTHER:
        return "", "", ""

    return (
        """\
pip install sentence_transformers[onnx-gpu]
# or
pip install sentence_transformers[onnx]
""",
        f"""\
from sentence_transformers import (
    {archetype},
    export_dynamic_quantized_onnx_model,
)

# 1. Load the model to be exported with the ONNX backend
model = {archetype}(
    "{model_id}",
    backend="onnx",
)

# 2. Export the model with {onnx_quantization_config} dynamic quantization
export_dynamic_quantized_onnx_model(
    model,
    quantization_config="{onnx_quantization_config}",
    model_name_or_path="{output_model_id}",
    push_to_hub=True,
{'''    create_pr=True,
''' if create_pr else ''})
""",
        f"""\
from sentence_transformers import {archetype}

# 1. Load the model from the Hugging Face Hub
# (until merged) Use the `revision` argument to load the model from the PR
pr_number = 2
model = {archetype}(
    "{output_model_id}",
    revision=f"refs/pr/{{pr_number}}",
    backend="onnx",
    model_kwargs={{"file_name": "model_qint8_{onnx_quantization_config}.onnx"}},
)
"""
        + (
            """
# 2. Inference works as normal
embeddings = model.encode(["The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium."])
similarities = model.similarity(embeddings, embeddings)
"""
            if archetype in {Archetype.SENTENCE_TRANSFORMER, Archetype.SPARSE_ENCODER}
            else """
# 2. Inference works as normal
predictions = model.predict([
    ["Which planet is known as the Red Planet?", "Mars, known for its reddish appearance, is often referred to as the Red Planet."],
    ["Which planet is known as the Red Planet?", "Jupiter, the largest planet in our solar system, has a prominent red spot."],
])
"""
        ),
    )


def export_to_onnx_optimization(
    model_id: str,
    archetype: Archetype,
    create_pr: bool,
    output_model_id: str,
    onnx_optimization_config: str,
    token: Optional[str] = None,
) -> None:
    if does_file_glob_exist(
        output_model_id, f"onnx/model_{onnx_optimization_config}.onnx"
    ):
        raise FileExistsError(
            "The optimized ONNX model already exists in the repository"
        )

    if archetype == Archetype.SENTENCE_TRANSFORMER:
        model = SentenceTransformer(model_id, backend="onnx")
    elif archetype == Archetype.SPARSE_ENCODER:
        model = SparseEncoder(model_id, backend="onnx")
    elif archetype == Archetype.CROSS_ENCODER:
        model = CrossEncoder(model_id, backend="onnx")
    else:
        return

    if not create_pr and is_new_model(output_model_id):
        model.push_to_hub(repo_id=output_model_id, token=token)

    # Monkey-patch the upload_folder function to include the token, as it's not used in export_optimized_onnx_model
    original_upload_folder = huggingface_hub.upload_folder
    huggingface_hub.upload_folder = partial(original_upload_folder, token=token)
    try:
        st_export_optimized_onnx_model(
            model,
            optimization_config=onnx_optimization_config,
            model_name_or_path=output_model_id,
            push_to_hub=True,
            create_pr=create_pr,
        )
    finally:
        huggingface_hub.upload_folder = original_upload_folder


def export_to_onnx_optimization_snippet(
    model_id: str,
    archetype: Archetype,
    create_pr: bool,
    output_model_id: str,
    onnx_optimization_config: str,
) -> Tuple[str, str, str]:
    if archetype == Archetype.OTHER:
        return "", "", ""

    return (
        """\
pip install sentence_transformers[onnx-gpu]
# or
pip install sentence_transformers[onnx]
""",
        f"""\
from sentence_transformers import (
    {archetype},
    export_optimized_onnx_model,
)

# 1. Load the model to be optimized with the ONNX backend
model = {archetype}(
    "{model_id}",
    backend="onnx",
)

# 2. Export the model with {onnx_optimization_config} optimization level
export_optimized_onnx_model(
    model,
    optimization_config="{onnx_optimization_config}",
    model_name_or_path="{output_model_id}",
    push_to_hub=True,
{'''    create_pr=True,
''' if create_pr else ''})
""",
        f"""\
from sentence_transformers import {archetype}

# 1. Load the model from the Hugging Face Hub
# (until merged) Use the `revision` argument to load the model from the PR
pr_number = 2
model = {archetype}(
    "{output_model_id}",
    revision=f"refs/pr/{{pr_number}}",
    backend="onnx",
    model_kwargs={{"file_name": "model_{onnx_optimization_config}.onnx"}},
)
"""
        + (
            """
# 2. Inference works as normal
embeddings = model.encode(["The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium."])
similarities = model.similarity(embeddings, embeddings)
"""
            if archetype in {Archetype.SENTENCE_TRANSFORMER, Archetype.SPARSE_ENCODER}
            else """
# 2. Inference works as normal
predictions = model.predict([
    ["Which planet is known as the Red Planet?", "Mars, known for its reddish appearance, is often referred to as the Red Planet."],
    ["Which planet is known as the Red Planet?", "Jupiter, the largest planet in our solar system, has a prominent red spot."],
])
"""
        ),
    )


def export_to_openvino(
    model_id: str,
    archetype: Archetype,
    create_pr: bool,
    output_model_id: str,
    token: Optional[str] = None,
) -> None:
    if does_file_glob_exist(output_model_id, "**/openvino_model.xml"):
        raise FileExistsError("The OpenVINO model already exists in the repository")

    if archetype == Archetype.SENTENCE_TRANSFORMER:
        model = SentenceTransformer(model_id, backend="openvino")
    elif archetype == Archetype.SPARSE_ENCODER:
        model = SparseEncoder(model_id, backend="openvino")
    elif archetype == Archetype.CROSS_ENCODER:
        model = CrossEncoder(model_id, backend="openvino")
    else:
        return

    commit_message = "Add exported openvino model 'openvino_model.xml'"

    if is_new_model(output_model_id):
        model.push_to_hub(
            repo_id=output_model_id,
            commit_message=commit_message,
            create_pr=create_pr,
            token=token,
        )
    else:
        with TemporaryDirectory() as tmp_dir:
            model.save_pretrained(tmp_dir)

            commit_description = f"""
Hello!

*This pull request has been automatically generated from the [Sentence Transformers backend-export](https://huggingface.co/spaces/sentence-transformers/backend-export) Space.*

## Pull Request overview
* Add exported OpenVINO model `openvino_model.xml`.

## Tip:
Consider testing this pull request before merging by loading the model from this PR with the `revision` argument:
```python
from sentence_transformers import {archetype}

# TODO: Fill in the PR number
pr_number = 2
model = {archetype}(
    "{output_model_id}",
    revision=f"refs/pr/{{pr_number}}",
    backend="openvino",
)

# Verify that everything works as expected
{'''embeddings = model.encode(["The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium."])
print(embeddings.shape)

similarities = model.similarity(embeddings, embeddings)
print(similarities)''' if archetype in {Archetype.SENTENCE_TRANSFORMER, Archetype.SPARSE_ENCODER} else
'''predictions = model.predict([
    ["Which planet is known as the Red Planet?", "Mars, known for its reddish appearance, is often referred to as the Red Planet."],
    ["Which planet is known as the Red Planet?", "Jupiter, the largest planet in our solar system, has a prominent red spot."],
])
print(predictions)'''}
```
"""

            upload_folder(
                repo_id=output_model_id,
                folder_path=Path(tmp_dir) / "openvino",
                path_in_repo="openvino",
                commit_message=commit_message,
                commit_description=commit_description if create_pr else None,
                create_pr=create_pr,
                token=token,
            )


def export_to_openvino_snippet(
    model_id: str, archetype: Archetype, create_pr: bool, output_model_id: str
) -> Tuple[str, str, str]:
    if archetype == Archetype.OTHER:
        return "", "", ""

    return (
        """\
pip install sentence_transformers[openvino]
""",
        f"""\
from sentence_transformers import {archetype}

# 1. Load the model to be exported with the OpenVINO backend
model = {archetype}(
    "{model_id}",
    backend="openvino",
)

# 2. Push the model to the Hugging Face Hub
{f'model.push_to_hub("{output_model_id}")'
 if not create_pr
 else f'''model.push_to_hub(
    "{output_model_id}",
    create_pr=True,
)'''}
""",
        f"""\
from sentence_transformers import {archetype}

# 1. Load the model from the Hugging Face Hub
# (until merged) Use the `revision` argument to load the model from the PR
pr_number = 2
model = {archetype}(
    "{output_model_id}",
    revision=f"refs/pr/{{pr_number}}",
    backend="openvino",
)
"""
        + (
            """
# 2. Inference works as normal
embeddings = model.encode(["The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium."])
similarities = model.similarity(embeddings, embeddings)
"""
            if archetype in {Archetype.SENTENCE_TRANSFORMER, Archetype.SPARSE_ENCODER}
            else """
# 2. Inference works as normal
predictions = model.predict([
    ["Which planet is known as the Red Planet?", "Mars, known for its reddish appearance, is often referred to as the Red Planet."],
    ["Which planet is known as the Red Planet?", "Jupiter, the largest planet in our solar system, has a prominent red spot."],
])
"""
        ),
    )


def export_to_openvino_static_quantization(
    model_id: str,
    archetype: Archetype,
    create_pr: bool,
    output_model_id: str,
    ov_quant_dataset_name: str,
    ov_quant_dataset_subset: str,
    ov_quant_dataset_split: str,
    ov_quant_dataset_column_name: str,
    ov_quant_dataset_num_samples: int,
    token: Optional[str] = None,
) -> None:
    if does_file_glob_exist(
        output_model_id, "openvino/openvino_model_qint8_quantized.xml"
    ):
        raise FileExistsError(
            "The quantized OpenVINO model already exists in the repository"
        )

    if archetype == Archetype.SENTENCE_TRANSFORMER:
        model = SentenceTransformer(model_id, backend="openvino")
    elif archetype == Archetype.SPARSE_ENCODER:
        model = SparseEncoder(model_id, backend="openvino")
    elif archetype == Archetype.CROSS_ENCODER:
        model = CrossEncoder(model_id, backend="openvino")
    else:
        return

    if not create_pr and is_new_model(output_model_id):
        model.push_to_hub(repo_id=output_model_id, token=token)

    # Monkey-patch the upload_folder function to include the token, as it's not used in export_static_quantized_openvino_model
    original_upload_folder = huggingface_hub.upload_folder
    huggingface_hub.upload_folder = partial(original_upload_folder, token=token)
    try:
        st_export_static_quantized_openvino_model(
            model,
            quantization_config=OVQuantizationConfig(
                num_samples=ov_quant_dataset_num_samples,
            ),
            model_name_or_path=output_model_id,
            dataset_name=ov_quant_dataset_name,
            dataset_config_name=ov_quant_dataset_subset,
            dataset_split=ov_quant_dataset_split,
            column_name=ov_quant_dataset_column_name,
            push_to_hub=True,
            create_pr=create_pr,
        )
    finally:
        huggingface_hub.upload_folder = original_upload_folder


def export_to_openvino_static_quantization_snippet(
    model_id: str,
    archetype: Archetype,
    create_pr: bool,
    output_model_id: str,
    ov_quant_dataset_name: str,
    ov_quant_dataset_subset: str,
    ov_quant_dataset_split: str,
    ov_quant_dataset_column_name: str,
    ov_quant_dataset_num_samples: int,
) -> Tuple[str, str, str]:
    if archetype == Archetype.OTHER:
        return "", "", ""

    return (
        """\
pip install sentence_transformers[openvino]
""",
        f"""\
from sentence_transformers import (
    {archetype},
    export_static_quantized_openvino_model,
)
from optimum.intel import OVQuantizationConfig

# 1. Load the model to be quantized with the OpenVINO backend
model = {archetype}(
    "{model_id}",
    backend="openvino",
)

# 2. Export the model with int8 static quantization
export_static_quantized_openvino_model(
    model,
    quantization_config=OVQuantizationConfig(
        num_samples={ov_quant_dataset_num_samples},
    ),
    model_name_or_path="{output_model_id}",
    dataset_name="{ov_quant_dataset_name}",
    dataset_config_name="{ov_quant_dataset_subset}",
    dataset_split="{ov_quant_dataset_split}",
    column_name="{ov_quant_dataset_column_name}",
    push_to_hub=True,
{'''    create_pr=True,
''' if create_pr else ''})
""",
        f"""\
from sentence_transformers import {archetype}

# 1. Load the model from the Hugging Face Hub
# (until merged) Use the `revision` argument to load the model from the PR
pr_number = 2
model = {archetype}(
    "{output_model_id}",
    revision=f"refs/pr/{{pr_number}}",
    backend="openvino",
    model_kwargs={{"file_name": "openvino_model_qint8_quantized.xml"}},
)
"""
        + (
            """
# 2. Inference works as normal
embeddings = model.encode(["The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium."])
similarities = model.similarity(embeddings, embeddings)
"""
            if archetype in {Archetype.SENTENCE_TRANSFORMER, Archetype.SPARSE_ENCODER}
            else """
# 2. Inference works as normal
predictions = model.predict([
    ["Which planet is known as the Red Planet?", "Mars, known for its reddish appearance, is often referred to as the Red Planet."],
    ["Which planet is known as the Red Planet?", "Jupiter, the largest planet in our solar system, has a prominent red spot."],
])
"""
        ),
    )


def on_submit(
    model_id,
    create_pr,
    output_model_id,
    backend,
    onnx_quantization_config,
    onnx_optimization_config,
    ov_quant_dataset_name,
    ov_quant_dataset_subset,
    ov_quant_dataset_split,
    ov_quant_dataset_column_name,
    ov_quant_dataset_num_samples,
    inference_snippet: str,
    oauth_token: Optional[gr.OAuthToken] = None,
    profile: Optional[gr.OAuthProfile] = None,
):
    if oauth_token is None or profile is None:
        return (
            "Commit or PR url:<br>...",
            inference_snippet,
            gr.Textbox(
                "Please sign in with Hugging Face to use this Space", visible=True
            ),
        )

    if not model_id:
        return (
            "Commit or PR url:<br>...",
            inference_snippet,
            gr.Textbox("Please enter a model ID", visible=True),
        )

    if not is_sentence_transformer_model(model_id):
        return (
            "Commit or PR url:<br>...",
            inference_snippet,
            gr.Textbox(
                "The source model must have a Sentence Transformers tag", visible=True
            ),
        )

    if output_model_id and "/" not in output_model_id:
        output_model_id = f"{profile.name}/{output_model_id}"

    output_model_id = output_model_id if not create_pr else model_id
    archetype = get_archetype(model_id)

    try:
        if backend == Backend.ONNX.value:
            export_to_onnx(
                model_id, archetype, create_pr, output_model_id, token=oauth_token.token
            )
        elif backend == Backend.ONNX_DYNAMIC_QUANTIZATION.value:
            export_to_onnx_dynamic_quantization(
                model_id,
                archetype,
                create_pr,
                output_model_id,
                onnx_quantization_config,
                token=oauth_token.token,
            )
        elif backend == Backend.ONNX_OPTIMIZATION.value:
            export_to_onnx_optimization(
                model_id,
                archetype,
                create_pr,
                output_model_id,
                onnx_optimization_config,
                token=oauth_token.token,
            )
        elif backend == Backend.OPENVINO.value:
            export_to_openvino(
                model_id, archetype, create_pr, output_model_id, token=oauth_token.token
            )
        elif backend == Backend.OPENVINO_STATIC_QUANTIZATION.value:
            export_to_openvino_static_quantization(
                model_id,
                archetype,
                create_pr,
                output_model_id,
                ov_quant_dataset_name,
                ov_quant_dataset_subset,
                ov_quant_dataset_split,
                ov_quant_dataset_column_name,
                ov_quant_dataset_num_samples,
                token=oauth_token.token,
            )
    except FileExistsError as exc:
        return (
            "Commit or PR url:<br>...",
            inference_snippet,
            gr.Textbox(str(exc), visible=True),
        )

    if create_pr:
        url, num = get_last_pr(output_model_id)
        return (
            f"PR url:<br>{url}",
            inference_snippet.replace("pr_number = 2", f"pr_number = {num}"),
            gr.Textbox(visible=False),
        )

    # Remove the lines that refer to the revision argument
    lines = inference_snippet.splitlines()
    del lines[7]
    del lines[4]
    del lines[3]
    inference_snippet = "\n".join(lines)
    return (
        f"Commit url:<br>{get_last_commit(output_model_id)}",
        inference_snippet,
        gr.Textbox(visible=False),
    )


def on_change(
    model_id,
    create_pr,
    output_model_id,
    backend,
    onnx_quantization_config,
    onnx_optimization_config,
    ov_quant_dataset_name,
    ov_quant_dataset_subset,
    ov_quant_dataset_split,
    ov_quant_dataset_column_name,
    ov_quant_dataset_num_samples,
    oauth_token: Optional[gr.OAuthToken] = None,
    profile: Optional[gr.OAuthProfile] = None,
) -> str:
    if oauth_token is None or profile is None:
        return (
            "",
            "",
            "",
            gr.Textbox(
                "Please sign in with Hugging Face to use this Space", visible=True
            ),
        )

    if not model_id:
        return "", "", "", gr.Textbox("Please enter a model ID", visible=True)

    if output_model_id and "/" not in output_model_id:
        output_model_id = f"{profile.username}/{output_model_id}"

    output_model_id = output_model_id if not create_pr else model_id
    archetype = get_archetype(model_id)

    if backend == Backend.ONNX.value:
        snippets = export_to_onnx_snippet(
            model_id, archetype, create_pr, output_model_id
        )
    elif backend == Backend.ONNX_DYNAMIC_QUANTIZATION.value:
        snippets = export_to_onnx_dynamic_quantization_snippet(
            model_id, archetype, create_pr, output_model_id, onnx_quantization_config
        )
    elif backend == Backend.ONNX_OPTIMIZATION.value:
        snippets = export_to_onnx_optimization_snippet(
            model_id, archetype, create_pr, output_model_id, onnx_optimization_config
        )
    elif backend == Backend.OPENVINO.value:
        snippets = export_to_openvino_snippet(
            model_id, archetype, create_pr, output_model_id
        )
    elif backend == Backend.OPENVINO_STATIC_QUANTIZATION.value:
        snippets = export_to_openvino_static_quantization_snippet(
            model_id,
            archetype,
            create_pr,
            output_model_id,
            ov_quant_dataset_name,
            ov_quant_dataset_subset,
            ov_quant_dataset_split,
            ov_quant_dataset_column_name,
            ov_quant_dataset_num_samples,
        )
    else:
        return "", "", "", gr.Textbox("Unexpected backend!", visible=True)

    return *snippets, gr.Textbox(visible=False)


css = """
.container {
    padding-left: 0;
}

div:has(> div.text-error) {
    border-color: var(--error-border-color);
}

.small-text * {
    font-size: var(--block-info-text-size);
}
"""

with gr.Blocks(
    css=css,
    theme=gr.themes.Base(),
) as demo:
    gr.LoginButton(min_width=250)

    with gr.Row():
        # Left Input Column
        with gr.Column(scale=2):
            gr.Markdown(
                value="""\
### Export a SentenceTransformer, SparseEncoder, or CrossEncoder model to accelerated backends

Sentence Transformers models can be optimized for **faster inference** on CPU and GPU devices by exporting, quantizing, and optimizing them in ONNX and OpenVINO formats.
Observe the Speeding up Inference documentation for more information:
* [SentenceTransformer > Speeding up Inference](https://sbert.net/docs/sentence_transformer/usage/efficiency.html)
* [SparseEncoder > Speeding up Inference](https://sbert.net/docs/sparse_encoder/usage/efficiency.html)
* [CrossEncoder > Speeding up Inference](https://sbert.net/docs/cross_encoder/usage/efficiency.html)
""",
                label="",
                container=True,
            )
            gr.HTML(
                value="""\
<details><summary>Click to see performance benchmarks</summary>

<table>
  <thead>
    <tr>
      <th>SentenceTransformer GPU</th>
      <th>SentenceTransformer CPU</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <img src="https://sbert.net/_images/backends_benchmark_gpu.png" alt="">
      </td>
      <td>
        <img src="https://sbert.net/_images/backends_benchmark_cpu.png" alt="">
      </td>
    </tr>
  </tbody>
</table>

<table>
  <thead>
    <tr>
      <th>SparseEncoder GPU</th>
      <th>SparseEncoder CPU</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <img src="https://sbert.net/_images/se_backends_benchmark_gpu.png" alt="">
      </td>
      <td>
        <img src="https://sbert.net/_images/se_backends_benchmark_cpu.png" alt="">
      </td>
    </tr>
  </tbody>
</table>

<table>
  <thead>
    <tr>
      <th>CrossEncoder GPU</th>
      <th>CrossEncoder CPU</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <img src="https://sbert.net/_images/ce_backends_benchmark_gpu.png" alt="">
      </td>
      <td>
        <img src="https://sbert.net/_images/ce_backends_benchmark_cpu.png" alt="">
      </td>
    </tr>
  </tbody>
</table>

<ul>
  <li><code>onnx</code> refers to the ONNX backend</li>
  <li><code>onnx-qint8</code> refers to ONNX (Dynamic Quantization)</li>
  <li><code>onnx-O1</code> to <code>onnx-O4</code> refers to ONNX (Optimization)</li>
  <li><code>openvino</code> refers to the OpenVINO backend</li>
  <li><code>openvino-qint8</code> refers to OpenVINO (Static Quantization)</li>
</ul>

</details>
"""
            )

            model_id = HuggingfaceHubSearch(
                label="SentenceTransformer, SparseEncoder, or CrossEncoder model to export",
                placeholder="Search for SentenceTransformer, SparseEncoder, or CrossEncoder models on Hugging Face",
                search_type="model",
            )
            create_pr = gr.Checkbox(
                value=True,
                label="Create PR",
                info="Create a pull request instead of pushing directly to a repository",
            )
            output_model_id = gr.Textbox(
                value="",
                label="Model repository to write to",
                placeholder="Model ID",
                type="text",
                visible=False,
            )
            create_pr.change(
                lambda create_pr: gr.Textbox(visible=not create_pr),
                inputs=[create_pr],
                outputs=[output_model_id],
            )

            backend = gr.Radio(
                choices=backends,
                value=Backend.ONNX,
                label="Backend",
            )

            with gr.Group(visible=True) as onnx_group:
                gr.Markdown(
                    value="[ONNX Documentation](https://sbert.net/docs/sentence_transformer/usage/efficiency.html#onnx)",
                    container=True,
                    elem_classes=["small-text"],
                )
            with gr.Group(visible=False) as onnx_dynamic_quantization_group:
                onnx_quantization_config = gr.Radio(
                    choices=["arm64", "avx2", "avx512", "avx512_vnni"],
                    value="avx512_vnni",
                    label="Quantization config",
                    info="[ONNX Quantization Documentation](https://sbert.net/docs/sentence_transformer/usage/efficiency.html#quantizing-onnx-models)",
                )
            with gr.Group(visible=False) as onnx_optimization_group:
                onnx_optimization_config = gr.Radio(
                    choices=["O1", "O2", "O3", "O4"],
                    value="O4",
                    label="Optimization config",
                    info="[ONNX Optimization Documentation](https://sbert.net/docs/sentence_transformer/usage/efficiency.html#optimizing-onnx-models)",
                )
            with gr.Group(visible=False) as openvino_group:
                gr.Markdown(
                    value="[OpenVINO Documentation](https://sbert.net/docs/sentence_transformer/usage/efficiency.html#openvino)",
                    container=True,
                    elem_classes=["small-text"],
                )
            with gr.Group(visible=False) as openvino_static_quantization_group:
                gr.Markdown(
                    value="[OpenVINO Quantization Documentation](https://sbert.net/docs/sentence_transformer/usage/efficiency.html#quantizing-openvino-models)",
                    container=True,
                    elem_classes=["small-text"],
                )
                ov_quant_dataset_name = HuggingfaceHubSearch(
                    value="nyu-mll/glue",
                    label="Calibration Dataset Name",
                    placeholder="Search for Sentence Transformer datasets on Hugging Face",
                    search_type="dataset",
                )
                ov_quant_dataset_subset = gr.Textbox(
                    value="sst2",
                    label="Calibration Dataset Subset",
                    placeholder="Calibration Dataset Subset",
                    type="text",
                    max_lines=1,
                )
                ov_quant_dataset_split = gr.Textbox(
                    value="train",
                    label="Calibration Dataset Split",
                    placeholder="Calibration Dataset Split",
                    type="text",
                    max_lines=1,
                )
                ov_quant_dataset_column_name = gr.Textbox(
                    value="sentence",
                    label="Calibration Dataset Column Name",
                    placeholder="Calibration Dataset Column Name",
                    type="text",
                    max_lines=1,
                )
                ov_quant_dataset_num_samples = gr.Number(
                    value=300,
                    label="Calibration Dataset Num Samples",
                )

            backend.change(
                lambda backend: (
                    (
                        gr.Group(visible=True)
                        if backend == Backend.ONNX.value
                        else gr.Group(visible=False)
                    ),
                    (
                        gr.Group(visible=True)
                        if backend == Backend.ONNX_DYNAMIC_QUANTIZATION.value
                        else gr.Group(visible=False)
                    ),
                    (
                        gr.Group(visible=True)
                        if backend == Backend.ONNX_OPTIMIZATION.value
                        else gr.Group(visible=False)
                    ),
                    (
                        gr.Group(visible=True)
                        if backend == Backend.OPENVINO.value
                        else gr.Group(visible=False)
                    ),
                    (
                        gr.Group(visible=True)
                        if backend == Backend.OPENVINO_STATIC_QUANTIZATION.value
                        else gr.Group(visible=False)
                    ),
                ),
                inputs=[backend],
                outputs=[
                    onnx_group,
                    onnx_dynamic_quantization_group,
                    onnx_optimization_group,
                    openvino_group,
                    openvino_static_quantization_group,
                ],
            )

            submit_button = gr.Button(
                "Export Model",
                variant="primary",
            )

        # Right Input Column
        with gr.Column(scale=1):
            error = gr.Textbox(
                value="",
                label="Error",
                type="text",
                visible=False,
                max_lines=1,
                interactive=False,
                elem_classes=["text-error"],
            )

            requirements = gr.Code(
                value="",
                language="shell",
                label="Requirements",
                lines=1,
            )
            export_snippet = gr.Code(
                value="",
                language="python",
                label="Export Snippet",
            )
            inference_snippet = gr.Code(
                value="",
                language="python",
                label="Inference Snippet",
            )
            url = gr.Markdown(
                value="Commit or PR url:<br>...",
                label="",
                container=True,
                visible=True,
            )

    submit_button.click(
        on_submit,
        inputs=[
            model_id,
            create_pr,
            output_model_id,
            backend,
            onnx_quantization_config,
            onnx_optimization_config,
            ov_quant_dataset_name,
            ov_quant_dataset_subset,
            ov_quant_dataset_split,
            ov_quant_dataset_column_name,
            ov_quant_dataset_num_samples,
            inference_snippet,
        ],
        outputs=[url, inference_snippet, error],
    )
    for input_component in [
        model_id,
        create_pr,
        output_model_id,
        backend,
        onnx_quantization_config,
        onnx_optimization_config,
        ov_quant_dataset_name,
        ov_quant_dataset_subset,
        ov_quant_dataset_split,
        ov_quant_dataset_column_name,
        ov_quant_dataset_num_samples,
    ]:
        input_component.change(
            on_change,
            inputs=[
                model_id,
                create_pr,
                output_model_id,
                backend,
                onnx_quantization_config,
                onnx_optimization_config,
                ov_quant_dataset_name,
                ov_quant_dataset_subset,
                ov_quant_dataset_split,
                ov_quant_dataset_column_name,
                ov_quant_dataset_num_samples,
            ],
            outputs=[requirements, export_snippet, inference_snippet, error],
        )

if __name__ == "__main__":
    demo.launch(ssr_mode=False)