File size: 56,615 Bytes
82b88b7
 
 
 
 
28ea4d1
82b88b7
7d296d1
 
 
3a5e154
82b88b7
 
 
28ea4d1
7d296d1
 
28ea4d1
 
 
 
 
3a5e154
 
 
 
 
 
 
 
 
 
28ea4d1
 
0768555
3a5e154
0768555
 
 
 
 
 
 
 
3a5e154
0768555
 
 
 
 
 
 
 
 
 
 
28ea4d1
3a5e154
28ea4d1
3a5e154
 
 
 
ced977b
 
3a5e154
ced977b
 
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ced977b
3a5e154
28ea4d1
ced977b
 
 
0768555
3a5e154
ced977b
 
 
 
 
3a5e154
ced977b
 
 
 
3a5e154
ced977b
 
 
 
 
 
 
 
 
 
 
 
 
3a5e154
 
 
 
 
 
 
 
 
 
ced977b
 
 
 
3a5e154
 
 
7d296d1
 
28ea4d1
 
 
 
 
 
 
7d296d1
 
 
3a5e154
82b88b7
 
28ea4d1
 
 
0768555
 
 
 
82b88b7
 
28ea4d1
 
 
82b88b7
 
3a5e154
28ea4d1
 
3a5e154
28ea4d1
82b88b7
 
3a5e154
28ea4d1
0768555
3a5e154
 
 
28ea4d1
 
 
 
 
3a5e154
28ea4d1
 
 
3a5e154
28ea4d1
3a5e154
28ea4d1
 
 
82b88b7
 
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b88b7
3a5e154
82b88b7
 
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b88b7
28ea4d1
 
82b88b7
 
 
 
0768555
28ea4d1
82b88b7
28ea4d1
 
7d296d1
28ea4d1
 
0768555
 
3a5e154
0768555
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a5e154
0768555
 
 
 
 
 
 
 
 
3a5e154
82b88b7
0768555
 
82b88b7
 
28ea4d1
82b88b7
 
3a5e154
82b88b7
7d296d1
82b88b7
28ea4d1
82b88b7
 
7d296d1
82b88b7
 
 
28ea4d1
 
 
 
7d296d1
 
82b88b7
28ea4d1
3a5e154
 
82b88b7
28ea4d1
 
82b88b7
28ea4d1
 
0768555
 
28ea4d1
82b88b7
28ea4d1
 
0768555
 
28ea4d1
7d296d1
28ea4d1
 
 
 
 
 
 
 
 
 
 
 
 
3a5e154
7d296d1
82b88b7
28ea4d1
7d296d1
 
 
3a5e154
28ea4d1
0768555
 
28ea4d1
82b88b7
28ea4d1
7d296d1
28ea4d1
 
 
 
 
 
 
 
 
7d296d1
82b88b7
28ea4d1
7d296d1
28ea4d1
7d296d1
28ea4d1
 
7d296d1
28ea4d1
 
 
7d296d1
 
82b88b7
28ea4d1
7d296d1
28ea4d1
7d296d1
28ea4d1
 
 
7d296d1
82b88b7
28ea4d1
7d296d1
 
28ea4d1
 
7d296d1
82b88b7
28ea4d1
7d296d1
28ea4d1
82b88b7
28ea4d1
 
 
 
 
7d296d1
82b88b7
28ea4d1
7d296d1
28ea4d1
82b88b7
0768555
28ea4d1
3a5e154
28ea4d1
7d296d1
82b88b7
3a5e154
 
 
 
 
 
 
 
28ea4d1
7d296d1
82b88b7
28ea4d1
3a5e154
 
28ea4d1
7d296d1
82b88b7
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28ea4d1
7d296d1
3a5e154
28ea4d1
0768555
 
28ea4d1
0768555
28ea4d1
7d296d1
28ea4d1
7d296d1
 
 
82b88b7
 
3a5e154
82b88b7
 
28ea4d1
3a5e154
28ea4d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a5e154
28ea4d1
3a5e154
 
28ea4d1
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d296d1
 
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28ea4d1
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28ea4d1
7d296d1
3a5e154
 
 
7d296d1
3a5e154
0768555
 
3a5e154
 
0768555
 
3a5e154
 
7d296d1
 
3a5e154
 
 
7d296d1
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b88b7
 
 
3a5e154
82b88b7
 
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
82b88b7
28ea4d1
3a5e154
82b88b7
7d296d1
 
 
3a5e154
7d296d1
3a5e154
28ea4d1
 
 
 
3a5e154
28ea4d1
 
 
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28ea4d1
 
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28ea4d1
3a5e154
 
 
 
 
28ea4d1
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28ea4d1
 
3a5e154
 
 
28ea4d1
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28ea4d1
3a5e154
28ea4d1
3a5e154
0768555
3a5e154
 
 
 
 
 
 
 
 
 
28ea4d1
3a5e154
28ea4d1
3a5e154
28ea4d1
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b88b7
3a5e154
82b88b7
3a5e154
7d296d1
3a5e154
 
 
 
 
 
 
 
 
82b88b7
3a5e154
0768555
3a5e154
28ea4d1
3a5e154
 
7d296d1
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b88b7
 
28ea4d1
3a5e154
28ea4d1
7d296d1
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b88b7
3a5e154
 
 
 
 
 
 
82b88b7
 
 
3a5e154
 
 
 
 
 
 
 
 
 
82b88b7
 
 
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b88b7
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28ea4d1
3a5e154
28ea4d1
3a5e154
7d296d1
3a5e154
7d296d1
3a5e154
7d296d1
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b88b7
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d296d1
3a5e154
 
82b88b7
7d296d1
28ea4d1
3a5e154
28ea4d1
3a5e154
 
 
 
0768555
3a5e154
 
 
0768555
3a5e154
 
 
 
 
 
 
 
 
 
 
28ea4d1
3a5e154
28ea4d1
3a5e154
28ea4d1
 
3a5e154
 
 
 
 
 
28ea4d1
 
3a5e154
 
 
 
 
 
 
 
 
 
 
 
28ea4d1
3a5e154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82b88b7
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
import gradio as gr
import struct
import os
import tempfile
import io
import re
import zipfile
import numpy as np
import soundfile as sf
import traceback
from collections import defaultdict


###############################################################################
# MAPEO DE NOTAS
###############################################################################

NOTE_NAMES = {
    'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11
}

MIDI_TO_NAME = {}
for _octave in range(-1, 10):
    for _name, _semitone in NOTE_NAMES.items():
        _midi = (_octave + 1) * 12 + _semitone
        if 0 <= _midi <= 127:
            MIDI_TO_NAME[_midi] = f"{_name}{_octave}"
        _midi_sharp = _midi + 1
        if 0 <= _midi_sharp <= 127:
            _sharp_names = {0: 'C#', 2: 'D#', 5: 'F#', 7: 'G#', 9: 'A#'}
            if _semitone in _sharp_names:
                MIDI_TO_NAME[_midi_sharp] = f"{_sharp_names[_semitone]}{_octave}"


def _parse_single_note(note_str):
    pattern = r'^([A-Ga-g])(#|b|β™―|β™­)?(-?\d+)$'
    m = re.match(pattern, note_str.strip())
    if not m:
        return None
    note_letter = m.group(1).upper()
    accidental = m.group(2) or ''
    octave = int(m.group(3))
    if note_letter not in NOTE_NAMES:
        return None
    if octave > 9 or octave < -1:
        return None
    midi = (octave + 1) * 12 + NOTE_NAMES[note_letter]
    if accidental in ('#', 'β™―'):
        midi += 1
    elif accidental in ('b', 'β™­'):
        midi -= 1
    if 0 <= midi <= 127:
        return midi
    return None


def parse_note_name(filename):
    """Extrae nota MIDI y velocidad del nombre del archivo."""
    name = os.path.splitext(filename)[0]
    
    # Formato: Nombre_Nota_Velocidad (e.g., Piano_C3_127, Nylon+Steel_E4_127)
    vel_pattern = r'[_\-\+]([A-Ga-g](?:#|b|β™―|β™­)?(?:-?\d+))[_\-](\d+)$'
    vel_match = re.search(vel_pattern, name)
    if vel_match:
        note_str = vel_match.group(1)
        velocity = int(vel_match.group(2))
        midi = _parse_single_note(note_str)
        if midi is not None:
            return midi, min(127, max(1, velocity))
    
    # Formato: Nombre_Nota (e.g., Piano_C3)
    vel_pattern2 = r'[_\-\+]([A-Ga-g](?:#|b|β™―|β™­)?(?:-?\d+))$'
    vel_match2 = re.search(vel_pattern2, name)
    if vel_match2:
        note_str = vel_match2.group(1)
        midi = _parse_single_note(note_str)
        if midi is not None:
            return midi, 127
    
    # Nota al inicio con velocidad: C3_127
    init_vel = re.match(r'^([A-Ga-g](?:#|b|β™―|β™­)?(?:-?\d+))[_\-](\d+)$', name)
    if init_vel:
        midi = _parse_single_note(init_vel.group(1))
        velocity = int(init_vel.group(2))
        if midi is not None:
            return midi, min(127, max(1, velocity))
    
    # Nota musical con octava en cualquier parte
    pattern = r'([A-Ga-g])(#|b|β™―|β™­)?(-?\d+)'
    matches = list(re.finditer(pattern, name))
    
    if matches:
        valid_matches = []
        for m in matches:
            note_letter = m.group(1).upper()
            octave = int(m.group(3))
            if octave > 9 or octave < -1:
                continue
            start = m.start()
            if start > 0 and name[start - 1].isdigit():
                continue
            valid_matches.append(m)
        
        if valid_matches:
            preferred = None
            for m in valid_matches:
                start = m.start()
                if start == 0 or (start > 0 and name[start - 1] in ('_', '-', ' ', '+')):
                    preferred = m
                    break
            best = preferred if preferred else valid_matches[0]
            note_letter = best.group(1).upper()
            accidental = best.group(2) or ''
            octave = int(best.group(3))
            if note_letter in NOTE_NAMES:
                midi = (octave + 1) * 12 + NOTE_NAMES[note_letter]
                if accidental in ('#', 'β™―'):
                    midi += 1
                elif accidental in ('b', 'β™­'):
                    midi -= 1
                if 0 <= midi <= 127:
                    # Buscar velocidad despuΓ©s de la nota
                    after = name[best.end():]
                    vel_after = re.match(r'[_\-](\d+)', after)
                    if vel_after:
                        vel = int(vel_after.group(1))
                        if 1 <= vel <= 127:
                            return midi, vel
                    return midi, 127
    
    # NΓΊmero MIDI directo
    num_match = re.search(r'(?<!\d)(\d{2,3})(?!\d)', name)
    if num_match:
        num = int(num_match.group(1))
        if 0 <= num <= 127:
            return num, 127
    
    return None, None


def midi_to_note_name(midi):
    if midi in MIDI_TO_NAME:
        return MIDI_TO_NAME[midi]
    note_names = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
    octave = (midi // 12) - 1
    note = note_names[midi % 12]
    return f"{note}{octave}"


###############################################################################
# AUDIO PROCESSING
###############################################################################

def read_audio_file(audio_bytes):
    try:
        data, sr = sf.read(io.BytesIO(audio_bytes), dtype='float32', always_2d=True)
        num_channels = data.shape[1]
        return data, sr, num_channels
    except Exception:
        return None, None, None


def float_to_pcm16(audio):
    clipped = np.clip(audio, -1.0, 1.0)
    return (clipped * 32767).astype(np.int16).tobytes()


def normalize_audio(audio, target_peak=0.95):
    max_val = np.max(np.abs(audio))
    if max_val > 0.0001:
        return audio * (target_peak / max_val)
    return audio


def trim_silence(audio, sr, threshold_db=-50, margin_ms=5, tail_ms=100):
    threshold = 10 ** (threshold_db / 20.0)
    abs_audio = np.max(np.abs(audio), axis=1)
    margin_samples = int(sr * margin_ms / 1000)
    tail_samples = int(sr * tail_ms / 1000)
    
    start = 0
    for i in range(len(abs_audio)):
        if abs_audio[i] > threshold:
            start = max(0, i - margin_samples)
            break
    
    end = len(abs_audio)
    for i in range(len(abs_audio) - 1, -1, -1):
        if abs_audio[i] > threshold:
            end = min(len(abs_audio), i + tail_samples)
            break
    
    if start >= end:
        return audio
    return audio[start:end]


def apply_fade_in(audio, sr, fade_ms=5):
    """Aplica fade-in suave al inicio."""
    fade_samples = int(sr * fade_ms / 1000)
    fade_samples = min(fade_samples, len(audio))
    if fade_samples > 0:
        fade = np.linspace(0, 1, fade_samples)
        result = audio.copy()
        result[:fade_samples] *= fade[:, np.newaxis]
        return result
    return audio


def apply_fade_out(audio, sr, fade_ms=200):
    """Aplica fade-out suave al final (simula release)."""
    fade_samples = int(sr * fade_ms / 1000)
    fade_samples = min(fade_samples, len(audio))
    if fade_samples > 0:
        fade = np.linspace(1, 0, fade_samples)
        result = audio.copy()
        result[-fade_samples:] *= fade[:, np.newaxis]
        return result
    return audio


###############################################################################
# SF2 WRITER β€” SOPORTE COMPLETO STEREO + VELOCIDADES + RELEASE
###############################################################################

# Generadores SF2
SF2_GEN_START_ADDRS_OFFSET = 0
SF2_GEN_END_ADDRS_OFFSET = 1
SF2_GEN_STARTLOOP_ADDRS_OFFSET = 2
SF2_GEN_ENDLOOP_ADDRS_OFFSET = 3
SF2_GEN_MOD_LFO_TO_PITCH = 5
SF2_GEN_VIB_LFO_TO_PITCH = 6
SF2_GEN_MOD_ENV_TO_PITCH = 7
SF2_GEN_INITIAL_FILTER_FC = 8
SF2_GEN_INITIAL_FILTER_Q = 9
SF2_GEN_MOD_LFO_TO_FILTER_FC = 10
SF2_GEN_MOD_ENV_TO_FILTER_FC = 11
SF2_GEN_END_ADDRS_COARSE_OFFSET = 12
SF2_GEN_MOD_LFO_TO_VOLUME = 13
SF2_GEN_CHORUS_EFFECTS_SEND = 15
SF2_GEN_REVERB_EFFECTS_SEND = 16
SF2_GEN_PAN = 17
SF2_GEN_DELAY_MOD_LFO = 21
SF2_GEN_FREQ_MOD_LFO = 22
SF2_GEN_DELAY_VIB_LFO = 23
SF2_GEN_FREQ_VIB_LFO = 24
SF2_GEN_DELAY_MOD_ENV = 25
SF2_GEN_ATTACK_MOD_ENV = 26
SF2_GEN_HOLD_MOD_ENV = 27
SF2_GEN_DECAY_MOD_ENV = 28
SF2_GEN_SUSTAIN_MOD_ENV = 29
SF2_GEN_RELEASE_MOD_ENV = 30
SF2_GEN_DELAY_VOL_ENV = 33
SF2_GEN_ATTACK_VOL_ENV = 34
SF2_GEN_HOLD_VOL_ENV = 35
SF2_GEN_DECAY_VOL_ENV = 36
SF2_GEN_SUSTAIN_VOL_ENV = 37
SF2_GEN_RELEASE_VOL_ENV = 38
SF2_GEN_KEY_RANGE = 43
SF2_GEN_VEL_RANGE = 44
SF2_GEN_INITIAL_ATTENUATION = 48
SF2_GEN_SAMPLE_MODES = 54
SF2_GEN_SCALE_TUNING = 56
SF2_GEN_OVERRIDING_ROOT_KEY = 58
SF2_GEN_SAMPLE_ID = 53


def timecents(seconds):
    """Convierte segundos a timecents para SF2."""
    if seconds <= 0:
        return -12000
    tc = int(1200 * np.log2(max(seconds, 0.001)))
    return max(-12000, min(8000, tc))


def centibels(db):
    """Convierte dB a centibels para SF2 attenuation."""
    return int(db * 10)


class SF2Writer:
    def __init__(self, name="SoundFont"):
        self.name = name
        self.samples = []
        self.instruments = []
        self.presets = []

    def add_sample_mono(self, name, pcm_16bit, sample_rate, root_key=60):
        num_points = len(pcm_16bit) // 2
        self.samples.append({
            'name': self._clean(name, 20),
            'pcm': pcm_16bit,
            'num_points': num_points,
            'sr': sample_rate,
            'root': min(127, max(0, root_key)),
            'type': 'mono',
            'link': 0,
            'sf_type': 1,
        })
        return len(self.samples) - 1

    def add_sample_stereo(self, name, pcm_left, pcm_right, sample_rate, root_key=60):
        num_points_l = len(pcm_left) // 2
        num_points_r = len(pcm_right) // 2
        left_idx = len(self.samples)
        right_idx = left_idx + 1
        self.samples.append({
            'name': self._clean(name + '_L', 20),
            'pcm': pcm_left,
            'num_points': num_points_l,
            'sr': sample_rate,
            'root': min(127, max(0, root_key)),
            'type': 'stereo_left',
            'link': right_idx,
            'sf_type': 4,
        })
        self.samples.append({
            'name': self._clean(name + '_R', 20),
            'pcm': pcm_right,
            'num_points': num_points_r,
            'sr': sample_rate,
            'root': min(127, max(0, root_key)),
            'type': 'stereo_right',
            'link': left_idx,
            'sf_type': 8,
        })
        return left_idx, right_idx

    def add_instrument(self, name, zones):
        self.instruments.append({
            'name': self._clean(name, 20),
            'zones': zones,
        })
        return len(self.instruments) - 1

    def add_preset(self, name, preset_num, bank, inst_idx):
        self.presets.append({
            'name': self._clean(name, 20),
            'preset': preset_num,
            'bank': bank,
            'inst_idx': inst_idx,
        })

    def build(self):
        self._calc_offsets()
        info = self._mk_info()
        sdta = self._mk_sdta()
        pdta = self._mk_pdta()
        body = b'sfbk' + info + sdta + pdta
        return b'RIFF' + struct.pack('<I', len(body)) + body

    def _clean(self, s, n):
        cleaned = ''.join(c if 32 <= ord(c) < 127 else '_' for c in str(s))
        return cleaned[:n]

    def _fstr(self, s, n):
        return s.encode('ascii', errors='replace')[:n].ljust(n, b'\x00')

    def _schunk(self, tag, s):
        b = s.encode('ascii', errors='replace') + b'\x00'
        if len(b) % 2:
            b += b'\x00'
        return tag + struct.pack('<I', len(b)) + b

    def _chunk(self, tag, data):
        r = tag + struct.pack('<I', len(data)) + data
        if len(data) % 2:
            r += b'\x00'
        return r

    def _calc_offsets(self):
        off = 0
        for s in self.samples:
            s['start'] = off
            s['end'] = off + s['num_points']
            s['loop_s'] = off
            s['loop_e'] = off + s['num_points'] - 1
            off += s['num_points'] + 46

    def _mk_info(self):
        sub = b'ifil' + struct.pack('<I', 4) + struct.pack('<HH', 2, 4)
        sub += self._schunk(b'isng', 'EMU8000')
        sub += self._schunk(b'INAM', self.name)
        sub += self._schunk(b'ISFT', 'SF2 Creator Pro v2.0')
        return b'LIST' + struct.pack('<I', len(sub) + 4) + b'INFO' + sub

    def _mk_sdta(self):
        smpl = b''
        for s in self.samples:
            smpl += s['pcm']
            smpl += b'\x00' * 92
        sc = b'smpl' + struct.pack('<I', len(smpl)) + smpl
        if len(smpl) % 2:
            sc += b'\x00'
        return b'LIST' + struct.pack('<I', len(sc) + 4) + b'sdta' + sc

    def _mk_pdta(self):
        sub = b''
        sub += self._chunk(b'phdr', self._mk_phdr())
        sub += self._chunk(b'pbag', self._mk_pbag())
        sub += self._chunk(b'pmod', b'\x00' * 10)
        sub += self._chunk(b'pgen', self._mk_pgen())
        sub += self._chunk(b'inst', self._mk_inst())
        sub += self._chunk(b'ibag', self._mk_ibag())
        sub += self._chunk(b'imod', b'\x00' * 10)
        sub += self._chunk(b'igen', self._mk_igen())
        sub += self._chunk(b'shdr', self._mk_shdr())
        return b'LIST' + struct.pack('<I', len(sub) + 4) + b'pdta' + sub

    def _mk_phdr(self):
        d = b''
        bi = 0
        for p in self.presets:
            d += self._fstr(p['name'], 20)
            d += struct.pack('<HHH', p['preset'], p['bank'], bi)
            d += struct.pack('<III', 0, 0, 0)
            bi += 1
        d += self._fstr('EOP', 20)
        d += struct.pack('<HHH', 255, 255, bi)
        d += struct.pack('<III', 0, 0, 0)
        return d

    def _mk_pbag(self):
        d = b''
        gi = 0
        for _ in self.presets:
            d += struct.pack('<HH', gi, 0)
            gi += 1
        d += struct.pack('<HH', gi, 0)
        return d

    def _mk_pgen(self):
        d = b''
        for p in self.presets:
            d += struct.pack('<HH', 41, p['inst_idx'])
        d += struct.pack('<HH', 0, 0)
        return d

    def _mk_inst(self):
        d = b''
        bi = 0
        for inst in self.instruments:
            d += self._fstr(inst['name'], 20)
            d += struct.pack('<H', bi)
            bi += len(inst['zones'])
        d += self._fstr('EOI', 20)
        d += struct.pack('<H', bi)
        return d

    def _mk_ibag(self):
        d = b''
        gi = 0
        for inst in self.instruments:
            for z in inst['zones']:
                d += struct.pack('<HH', gi, 0)
                gi += z.get('num_gens', 1)
        d += struct.pack('<HH', gi, 0)
        return d

    def _encode_gen(self, gen_op, value):
        """Encoda un generador SF2."""
        return struct.pack('<Hh', gen_op, value)

    def _encode_gen_u(self, gen_op, value):
        """Encoda un generador SF2 sin signo."""
        return struct.pack('<HH', gen_op, value)

    def _mk_igen(self):
        d = b''
        for inst in self.instruments:
            for z in inst['zones']:
                gens = self._build_zone_gens(z)
                d += gens
        d += struct.pack('<HH', 0, 0)
        return d

    def _build_zone_gens(self, z):
        """Construye los generadores para una zona del instrumento."""
        d = b''
        
        # Key range
        kr = (z['key_hi'] & 0x7F) << 8 | (z['key_lo'] & 0x7F)
        d += self._encode_gen_u(SF2_GEN_KEY_RANGE, kr)
        
        # Velocity range
        vel_lo = z.get('vel_lo', 0)
        vel_hi = z.get('vel_hi', 127)
        vr = (vel_hi & 0x7F) << 8 | (vel_lo & 0x7F)
        d += self._encode_gen_u(SF2_GEN_VEL_RANGE, vr)
        
        # Attenuation (volumen basado en velocidad)
        attenuation = z.get('attenuation', 0)
        d += self._encode_gen(SF2_GEN_INITIAL_ATTENUATION, attenuation)
        
        # Release volume envelope
        release_tc = z.get('release_tc', timecents(0.3))
        d += self._encode_gen(SF2_GEN_RELEASE_VOL_ENV, release_tc)
        
        # Decay
        decay_tc = z.get('decay_tc', timecents(1.0))
        d += self._encode_gen(SF2_GEN_DECAY_VOL_ENV, decay_tc)
        
        # Sustain (en centibels, 0 = sin atenuaciΓ³n)
        sustain_cb = z.get('sustain_cb', 0)
        d += self._encode_gen(SF2_GEN_SUSTAIN_VOL_ENV, sustain_cb)
        
        # Pan (si stereo, -500 para left, +500 para right; 0 para mono o left de pair)
        pan = z.get('pan', 0)
        d += self._encode_gen(SF2_GEN_PAN, pan)
        
        # Reverb send
        reverb = z.get('reverb', 150)
        d += self._encode_gen(SF2_GEN_REVERB_EFFECTS_SEND, reverb)
        
        # Sample modes (0 = no loop)
        d += self._encode_gen_u(SF2_GEN_SAMPLE_MODES, 0)
        
        # Scale tuning (100 = normal semitone)
        d += self._encode_gen(SF2_GEN_SCALE_TUNING, 100)
        
        # Override root key
        d += self._encode_gen_u(SF2_GEN_OVERRIDING_ROOT_KEY, z['root_key'])
        
        # Sample ID β€” siempre el ΓΊltimo
        d += self._encode_gen_u(SF2_GEN_SAMPLE_ID, z['sample_idx'])
        
        # Si es stereo izquierdo, agregar zona derecha
        if z.get('is_stereo_left', False) and 'right_sample_idx' in z:
            d += self._build_zone_gens_right(z)
        
        return d

    def _build_zone_gens_right(self, z):
        """Construye los generadores para el canal derecho de un par stereo."""
        d = b''
        kr = (z['key_hi'] & 0x7F) << 8 | (z['key_lo'] & 0x7F)
        d += self._encode_gen_u(SF2_GEN_KEY_RANGE, kr)
        
        vel_lo = z.get('vel_lo', 0)
        vel_hi = z.get('vel_hi', 127)
        vr = (vel_hi & 0x7F) << 8 | (vel_lo & 0x7F)
        d += self._encode_gen_u(SF2_GEN_VEL_RANGE, vr)
        
        attenuation = z.get('attenuation', 0)
        d += self._encode_gen(SF2_GEN_INITIAL_ATTENUATION, attenuation)
        
        release_tc = z.get('release_tc', timecents(0.3))
        d += self._encode_gen(SF2_GEN_RELEASE_VOL_ENV, release_tc)
        
        decay_tc = z.get('decay_tc', timecents(1.0))
        d += self._encode_gen(SF2_GEN_DECAY_VOL_ENV, decay_tc)
        
        sustain_cb = z.get('sustain_cb', 0)
        d += self._encode_gen(SF2_GEN_SUSTAIN_VOL_ENV, sustain_cb)
        
        # Pan derecho
        d += self._encode_gen(SF2_GEN_PAN, 500)
        
        reverb = z.get('reverb', 150)
        d += self._encode_gen(SF2_GEN_REVERB_EFFECTS_SEND, reverb)
        
        d += self._encode_gen_u(SF2_GEN_SAMPLE_MODES, 0)
        d += self._encode_gen(SF2_GEN_SCALE_TUNING, 100)
        d += self._encode_gen_u(SF2_GEN_OVERRIDING_ROOT_KEY, z['root_key'])
        d += self._encode_gen_u(SF2_GEN_SAMPLE_ID, z['right_sample_idx'])
        
        return d

    def _mk_shdr(self):
        d = b''
        for s in self.samples:
            d += self._fstr(s['name'], 20)
            d += struct.pack('<IIIII', s['start'], s['end'],
                             s['loop_s'], s['loop_e'], s['sr'])
            d += struct.pack('<Bb', s['root'], 0)
            d += struct.pack('<HH', s['link'], s['sf_type'])
        d += self._fstr('EOS', 20)
        d += struct.pack('<IIIII', 0, 0, 0, 0, 0)
        d += struct.pack('<Bb', 0, 0)
        d += struct.pack('<HH', 0, 0)
        return d


###############################################################################
# LΓ“GICA DE ZONAS Y SF2
###############################################################################

def calculate_key_zones(midi_notes):
    """Calcula zonas de teclas basadas en notas MIDI."""
    if len(midi_notes) == 1:
        return [(0, 127)]
    zones = []
    sorted_notes = sorted(midi_notes)
    for i, note in enumerate(sorted_notes):
        if i == 0:
            lo = 0
        else:
            lo = (sorted_notes[i - 1] + note) // 2 + 1
        if i == len(sorted_notes) - 1:
            hi = 127
        else:
            hi = (note + sorted_notes[i + 1]) // 2
        zones.append((lo, hi))
    return zones


def calculate_velocity_layers(velocity_samples):
    """
    Dado un dict {velocity: sample_data}, calcula rangos de velocidad.
    Retorna lista de (vel_lo, vel_hi, velocity, sample_data).
    """
    velocities = sorted(velocity_samples.keys())
    result = []
    for i, vel in enumerate(velocities):
        if i == 0:
            lo = 1
        else:
            prev_vel = velocities[i - 1]
            lo = (prev_vel + vel) // 2 + 1
        if i == len(velocities) - 1:
            hi = 127
        else:
            next_vel = velocities[i + 1]
            hi = (vel + next_vel) // 2
        result.append((lo, hi, vel, velocity_samples[vel]))
    return result


def process_samples_to_sf2(writer, sample_list, instrument_name,
                            do_normalize, do_trim,
                            release_ms, reverb_amount,
                            fade_in_ms=3):
    """
    Procesa una lista de samples y los aΓ±ade al writer SF2.
    Soporta velocidades mΓΊltiples por nota.
    
    sample_list: lista de (name, audio_2d, sr, midi_note, velocity, num_channels)
    """
    if not sample_list:
        return []
    
    # Agrupar por nota MIDI -> {midi: {velocity: (name, audio, sr, num_channels)}}
    notes_dict = defaultdict(dict)
    for name, audio, sr, midi_note, velocity, num_channels in sample_list:
        if velocity not in notes_dict[midi_note]:
            notes_dict[midi_note][velocity] = []
        notes_dict[midi_note][velocity].append((name, audio, sr, num_channels))
    
    # Para cada nota y velocidad, tomar el primer sample
    notes_flat = {}
    for midi_note, vel_dict in notes_dict.items():
        notes_flat[midi_note] = {}
        for vel, samples in vel_dict.items():
            notes_flat[midi_note][vel] = samples[0]  # tomar el primero
    
    # Calcular zonas de teclas
    midi_notes = sorted(notes_flat.keys())
    key_zones = calculate_key_zones(midi_notes)
    key_zone_map = dict(zip(midi_notes, key_zones))
    
    zone_list = []
    
    for midi_note in midi_notes:
        key_lo, key_hi = key_zone_map[midi_note]
        vel_dict = notes_flat[midi_note]
        
        # Calcular capas de velocidad
        vel_layers = calculate_velocity_layers(vel_dict)
        
        for vel_lo, vel_hi, velocity, (name, audio, sr, num_channels) in vel_layers:
            # Procesar audio
            if do_normalize:
                audio = normalize_audio(audio)
            if do_trim:
                audio = trim_silence(audio, sr)
            
            # Aplicar fade-in suave
            if fade_in_ms > 0:
                audio = apply_fade_in(audio, sr, fade_in_ms)
            
            # Aplicar fade-out (release natural)
            if release_ms > 0:
                audio = apply_fade_out(audio, sr, release_ms)
            
            if len(audio) < 10:
                continue
            
            # Calcular atenuaciΓ³n por velocidad (mΓ‘s grave = mΓ‘s silencioso)
            # Escala de 0 (127) a ~120 cb (~12 dB quieter, para vel=1)
            # SF2 attenuation: 0 = max volume, 1440 = silent
            vel_ratio = velocity / 127.0
            # Curva suave
            attenuation = int((1.0 - vel_ratio ** 0.5) * 200)
            
            # Release en timecents
            release_seconds = max(0.05, release_ms / 1000.0)
            release_tc = timecents(release_seconds)
            
            reverb_val = min(1000, max(0, int(reverb_amount * 10)))
            
            sample_name = f"{midi_to_note_name(midi_note)}_{velocity}"
            sample_name = sample_name[:20]
            
            if num_channels >= 2:
                left_channel = np.ascontiguousarray(audio[:, 0])
                right_channel = np.ascontiguousarray(audio[:, 1])
                pcm_left = float_to_pcm16(left_channel)
                pcm_right = float_to_pcm16(right_channel)
                
                left_idx, right_idx = writer.add_sample_stereo(
                    sample_name, pcm_left, pcm_right, sr, root_key=midi_note
                )
                
                # Zona izquierda con referencia a derecha
                num_gens = 12 + 12  # 12 gens por canal
                zone_list.append({
                    'key_lo': key_lo,
                    'key_hi': key_hi,
                    'vel_lo': vel_lo,
                    'vel_hi': vel_hi,
                    'root_key': midi_note,
                    'sample_idx': left_idx,
                    'right_sample_idx': right_idx,
                    'is_stereo_left': True,
                    'pan': -500,
                    'attenuation': attenuation,
                    'release_tc': release_tc,
                    'decay_tc': timecents(2.0),
                    'sustain_cb': 0,
                    'reverb': reverb_val,
                    'num_gens': num_gens,
                })
            else:
                mono_data = np.ascontiguousarray(audio[:, 0])
                pcm = float_to_pcm16(mono_data)
                
                sample_idx = writer.add_sample_mono(
                    sample_name, pcm, sr, root_key=midi_note
                )
                
                num_gens = 12
                zone_list.append({
                    'key_lo': key_lo,
                    'key_hi': key_hi,
                    'vel_lo': vel_lo,
                    'vel_hi': vel_hi,
                    'root_key': midi_note,
                    'sample_idx': sample_idx,
                    'is_stereo_left': False,
                    'pan': 0,
                    'attenuation': attenuation,
                    'release_tc': release_tc,
                    'decay_tc': timecents(2.0),
                    'sustain_cb': 0,
                    'reverb': reverb_val,
                    'num_gens': num_gens,
                })
    
    return zone_list, key_zone_map, midi_notes


def count_zones(zone_list):
    """Cuenta el nΓΊmero total de generadores en una lista de zonas."""
    return sum(z.get('num_gens', 12) for z in zone_list)


###############################################################################
# AUDIO EXTENSIONS
###############################################################################

AUDIO_EXTENSIONS = ('.wav', '.wave', '.flac', '.ogg', '.aiff', '.aif')


def is_audio_file(filename):
    return filename.lower().endswith(AUDIO_EXTENSIONS)


def should_skip(basename):
    return basename.startswith('.') or basename.startswith('__') or basename.startswith('~')


###############################################################################
# PROCESADORES PRINCIPALES
###############################################################################

def process_single_instrument_zip(zf, sf2_name, preset_name, do_normalize, do_trim,
                                   release_ms, reverb_amount):
    """Procesa un ZIP con samples en la raΓ­z (un solo instrumento)."""
    sample_list = []
    skipped = []
    errors = []
    stereo_count = 0
    mono_count = 0
    
    for entry in sorted(zf.namelist()):
        if entry.endswith('/'):
            continue
        basename = os.path.basename(entry)
        if should_skip(basename):
            continue
        if not is_audio_file(basename):
            continue
        
        midi_note, velocity = parse_note_name(basename)
        if midi_note is None:
            skipped.append(f"⚠️ `{basename}` β€” nota no detectada")
            continue
        
        try:
            audio_data = zf.read(entry)
            audio_float, sr, num_channels = read_audio_file(audio_data)
            if audio_float is None:
                errors.append(f"❌ `{basename}` β€” error de lectura")
                continue
            if len(audio_float) < 100:
                errors.append(f"❌ `{basename}` β€” audio muy corto")
                continue
            
            if num_channels >= 2:
                stereo_count += 1
            else:
                mono_count += 1
            
            clean_name = os.path.splitext(basename)[0]
            sample_list.append((clean_name, audio_float, sr, midi_note, velocity or 127, num_channels))
        
        except Exception as e:
            errors.append(f"❌ `{basename}` β€” {str(e)}")
    
    return sample_list, skipped, errors, stereo_count, mono_count


def process_multi_instrument_zip(zf, do_normalize, do_trim, release_ms, reverb_amount):
    """Procesa un ZIP con carpetas (cada carpeta = un instrumento)."""
    # Organizar entries por carpeta
    folder_samples = defaultdict(list)
    skipped = []
    errors = []
    
    for entry in sorted(zf.namelist()):
        if entry.endswith('/'):
            continue
        
        parts = entry.split('/')
        
        # Ignorar archivos en la raΓ­z sin carpeta
        if len(parts) < 2:
            continue
        
        # Carpeta de primer nivel = nombre del instrumento
        instrument_folder = parts[0]
        basename = parts[-1]
        
        if should_skip(basename):
            continue
        if not is_audio_file(basename):
            continue
        
        midi_note, velocity = parse_note_name(basename)
        if midi_note is None:
            skipped.append(f"⚠️ [{instrument_folder}] `{basename}` β€” nota no detectada")
            continue
        
        try:
            audio_data = zf.read(entry)
            audio_float, sr, num_channels = read_audio_file(audio_data)
            if audio_float is None:
                errors.append(f"❌ [{instrument_folder}] `{basename}` β€” error de lectura")
                continue
            if len(audio_float) < 100:
                errors.append(f"❌ [{instrument_folder}] `{basename}` β€” audio muy corto")
                continue
            
            clean_name = os.path.splitext(basename)[0]
            folder_samples[instrument_folder].append(
                (clean_name, audio_float, sr, midi_note, velocity or 127, num_channels)
            )
        
        except Exception as e:
            errors.append(f"❌ [{instrument_folder}] `{basename}` β€” {str(e)}")
    
    return folder_samples, skipped, errors


###############################################################################
# GRADIO HANDLERS
###############################################################################

def format_size(b):
    if b < 1024:
        return f"{b} B"
    if b < 1_048_576:
        return f"{b / 1024:.1f} KB"
    if b < 1_073_741_824:
        return f"{b / 1_048_576:.1f} MB"
    return f"{b / 1_073_741_824:.1f} GB"


def process_single_zip(file, sf2_name, preset_name, do_normalize, do_trim,
                        release_ms, reverb_amount):
    """Handler para la pestaΓ±a de instrumento ΓΊnico."""
    if file is None:
        return None, "❌ Sube un archivo ZIP con los WAVs."
    
    try:
        filepath = file if isinstance(file, str) else file.name
        with open(filepath, 'rb') as f:
            data = f.read()
        
        original_size = len(data)
        
        if not sf2_name or not sf2_name.strip():
            sf2_name = os.path.splitext(os.path.basename(filepath))[0]
        if not preset_name or not preset_name.strip():
            preset_name = sf2_name
        
        try:
            zf = zipfile.ZipFile(io.BytesIO(data))
        except Exception:
            return None, "❌ No se pudo abrir como ZIP."
        
        sample_list, skipped, errors, stereo_count, mono_count = process_single_instrument_zip(
            zf, sf2_name, preset_name, do_normalize, do_trim, release_ms, reverb_amount
        )
        
        if not sample_list:
            msg = build_error_msg(skipped, errors)
            return None, msg
        
        writer = SF2Writer(sf2_name)
        
        result = process_samples_to_sf2(
            writer, sample_list, preset_name,
            do_normalize, do_trim, release_ms, reverb_amount
        )
        
        if not result:
            return None, "❌ No se pudieron procesar los samples."
        
        zone_list, key_zone_map, midi_notes = result
        
        if not zone_list:
            return None, "❌ Ninguna zona vÑlida generada."
        
        writer.add_instrument(preset_name[:20], zone_list)
        writer.add_preset(preset_name[:20], 0, 0, 0)
        
        sf2_bytes = writer.build()
        
        out_name = (sf2_name.replace(' ', '_') or 'output') + '.sf2'
        tmp = tempfile.mkdtemp()
        out_path = os.path.join(tmp, out_name)
        with open(out_path, 'wb') as f:
            f.write(sf2_bytes)
        
        info = build_success_info_single(
            out_name, original_size, sf2_bytes,
            sample_list, stereo_count, mono_count,
            zone_list, key_zone_map, midi_notes,
            skipped, errors, release_ms
        )
        
        return out_path, info
    
    except Exception as e:
        tb = traceback.format_exc()
        return None, f"❌ **Error inesperado:** {str(e)}\n\n```\n{tb}\n```"


def process_multi_zip(file, sf2_name, do_normalize, do_trim,
                       release_ms, reverb_amount):
    """Handler para la pestaΓ±a de mΓΊltiples instrumentos."""
    if file is None:
        return None, "❌ Sube un archivo ZIP con carpetas de instrumentos."
    
    try:
        filepath = file if isinstance(file, str) else file.name
        with open(filepath, 'rb') as f:
            data = f.read()
        
        original_size = len(data)
        
        if not sf2_name or not sf2_name.strip():
            sf2_name = os.path.splitext(os.path.basename(filepath))[0]
        
        try:
            zf = zipfile.ZipFile(io.BytesIO(data))
        except Exception:
            return None, "❌ No se pudo abrir como ZIP."
        
        folder_samples, skipped, errors = process_multi_instrument_zip(
            zf, do_normalize, do_trim, release_ms, reverb_amount
        )
        
        if not folder_samples:
            msg = "❌ **No se encontraron carpetas con samples vÑlidos.**\n\n"
            msg += "AsegΓΊrate de que el ZIP tenga esta estructura:\n```\nMiSoundFont.zip\nβ”œβ”€β”€ Piano/\nβ”‚   β”œβ”€β”€ C3.wav\nβ”‚   β”œβ”€β”€ F3.wav\nβ”‚   └── C4.wav\nβ”œβ”€β”€ Strings/\nβ”‚   β”œβ”€β”€ C3.wav\nβ”‚   └── G3.wav\n└── Bass/\n    β”œβ”€β”€ E1.wav\n    └── A1.wav\n```\n"
            if skipped:
                msg += f"\n**Archivos ignorados:** {len(skipped)}\n"
                for s in skipped[:10]:
                    msg += f"- {s}\n"
            return None, msg
        
        writer = SF2Writer(sf2_name)
        instruments_info = []
        total_stereo = 0
        total_mono = 0
        
        for preset_num, (instrument_name, sample_list) in enumerate(sorted(folder_samples.items())):
            result = process_samples_to_sf2(
                writer, sample_list, instrument_name,
                do_normalize, do_trim, release_ms, reverb_amount
            )
            
            if not result:
                errors.append(f"❌ [{instrument_name}] β€” no se pudo procesar")
                continue
            
            zone_list, key_zone_map, midi_notes = result
            
            if not zone_list:
                errors.append(f"❌ [{instrument_name}] β€” ninguna zona vΓ‘lida")
                continue
            
            inst_idx = writer.add_instrument(instrument_name[:20], zone_list)
            writer.add_preset(instrument_name[:20], preset_num, 0, inst_idx)
            
            stereo = sum(1 for s in sample_list if s[5] >= 2)
            mono = sum(1 for s in sample_list if s[5] < 2)
            total_stereo += stereo
            total_mono += mono
            
            instruments_info.append({
                'name': instrument_name,
                'preset': preset_num,
                'sample_count': len(set((s[3], s[4]) for s in sample_list)),
                'note_count': len(midi_notes),
                'stereo': stereo,
                'mono': mono,
                'midi_notes': midi_notes,
                'key_zone_map': key_zone_map,
            })
        
        if not instruments_info:
            return None, "❌ No se pudo crear ningún instrumento vÑlido.\n\n" + "\n".join(errors[:20])
        
        sf2_bytes = writer.build()
        
        out_name = (sf2_name.replace(' ', '_') or 'output') + '.sf2'
        tmp = tempfile.mkdtemp()
        out_path = os.path.join(tmp, out_name)
        with open(out_path, 'wb') as f:
            f.write(sf2_bytes)
        
        info = build_success_info_multi(
            out_name, original_size, sf2_bytes,
            instruments_info, total_stereo, total_mono,
            skipped, errors, release_ms
        )
        
        return out_path, info
    
    except Exception as e:
        tb = traceback.format_exc()
        return None, f"❌ **Error inesperado:** {str(e)}\n\n```\n{tb}\n```"


###############################################################################
# INFO BUILDERS
###############################################################################

def build_error_msg(skipped, errors):
    msg = "❌ **No se encontraron samples vÑlidos.**\n\n"
    msg += "AsegΓΊrate de que los WAVs tengan la nota en el nombre:\n"
    msg += "`C3.wav`, `F#4.wav`, `Piano_A3_127.wav`, `060.wav`, etc.\n\n"
    if skipped:
        msg += f"**Archivos sin nota detectada ({len(skipped)}):**\n"
        for s in skipped[:15]:
            msg += f"- {s}\n"
        msg += "\n"
    if errors:
        msg += f"**Errores ({len(errors)}):**\n"
        for e in errors[:15]:
            msg += f"- {e}\n"
    return msg


def build_success_info_single(out_name, original_size, sf2_bytes,
                               sample_list, stereo_count, mono_count,
                               zone_list, key_zone_map, midi_notes,
                               skipped, errors, release_ms):
    # Contar capas de velocidad ΓΊnicas
    vel_layers = defaultdict(set)
    for name, _, sr, midi, vel, nch in sample_list:
        vel_layers[midi].add(vel)
    max_vel_layers = max(len(v) for v in vel_layers.values()) if vel_layers else 1
    
    info = f"""βœ… **Β‘SF2 creado exitosamente!**

---

### πŸ“Š EstadΓ­sticas

| ParΓ‘metro | Valor |
|-----------|-------|
| πŸ“ ZIP entrada | {format_size(original_size)} |
| πŸ’Ύ SF2 salida | {format_size(len(sf2_bytes))} |
| 🎡 Total samples | {len(sample_list)} |
| πŸ”Š Stereo | {stereo_count} |
| πŸ”ˆ Mono | {mono_count} |
| 🎹 Notas cubiertas | {len(midi_notes)} |
| 🎚️ MÑx. capas velocidad | {max_vel_layers} |
| πŸ”” Release | {release_ms} ms |

---

### 🎹 Mapa del teclado

| Nota | MIDI | Zona (MIDI) | Zona (Notas) | Capas Vel. | Tipo |
|------|------|-------------|--------------|------------|------|
"""
    
    sample_by_note = defaultdict(list)
    for name, _, sr, midi, vel, nch in sample_list:
        sample_by_note[midi].append((vel, nch))
    
    for midi in sorted(midi_notes):
        if midi in key_zone_map:
            lo, hi = key_zone_map[midi]
            lo_name = midi_to_note_name(lo)
            hi_name = midi_to_note_name(hi)
            samples_for_note = sample_by_note[midi]
            vel_count = len(set(v for v, _ in samples_for_note))
            has_stereo = any(nch >= 2 for _, nch in samples_for_note)
            ch_type = "πŸ”Š Stereo" if has_stereo else "πŸ”ˆ Mono"
            info += f"| **{midi_to_note_name(midi)}** | {midi} | {lo}–{hi} | {lo_name}–{hi_name} | {vel_count} | {ch_type} |\n"
    
    if skipped:
        info += f"\n---\n### ⚠️ Ignorados ({len(skipped)})\n"
        for s in skipped[:10]:
            info += f"- {s}\n"
    
    if errors:
        info += f"\n---\n### ❌ Errores ({len(errors)})\n"
        for e in errors[:10]:
            info += f"- {e}\n"
    
    return info


def build_success_info_multi(out_name, original_size, sf2_bytes,
                              instruments_info, total_stereo, total_mono,
                              skipped, errors, release_ms):
    total_samples = sum(i['sample_count'] for i in instruments_info)
    
    info = f"""βœ… **Β‘SF2 Multi-instrumento creado!**

---

### πŸ“Š Resumen General

| ParΓ‘metro | Valor |
|-----------|-------|
| πŸ“ ZIP entrada | {format_size(original_size)} |
| πŸ’Ύ SF2 salida | {format_size(len(sf2_bytes))} |
| 🎸 Instrumentos | {len(instruments_info)} |
| 🎡 Total samples | {total_samples} |
| πŸ”Š Stereo | {total_stereo} |
| πŸ”ˆ Mono | {total_mono} |
| πŸ”” Release | {release_ms} ms |

---

### 🎸 Instrumentos

| # | Instrumento | Preset | Notas | Samples | S/M |
|---|-------------|--------|-------|---------|-----|
"""
    
    for inst in instruments_info:
        sm = f"{'πŸ”Š' if inst['stereo'] > 0 else ''}{'πŸ”ˆ' if inst['mono'] > 0 else ''}"
        info += f"| {inst['preset']} | **{inst['name']}** | P{inst['preset']} | {inst['note_count']} | {inst['sample_count']} | {sm} |\n"
    
    info += "\n---\n"
    
    for inst in instruments_info:
        info += f"\n### 🎡 {inst['name']} (Preset {inst['preset']})\n"
        info += f"| Nota | MIDI | Rango |\n|------|------|-------|\n"
        for midi in sorted(inst['midi_notes'])[:15]:  # Limitar para no saturar
            if midi in inst['key_zone_map']:
                lo, hi = inst['key_zone_map'][midi]
                info += f"| {midi_to_note_name(midi)} | {midi} | {midi_to_note_name(lo)}–{midi_to_note_name(hi)} |\n"
        if len(inst['midi_notes']) > 15:
            info += f"| ... | ... | ({len(inst['midi_notes']) - 15} mΓ‘s) |\n"
    
    if skipped:
        info += f"\n---\n### ⚠️ Ignorados ({len(skipped)})\n"
        for s in skipped[:10]:
            info += f"- {s}\n"
    
    if errors:
        info += f"\n---\n### ❌ Errores ({len(errors)})\n"
        for e in errors[:10]:
            info += f"- {e}\n"
    
    return info


###############################################################################
# INTERFAZ GRADIO
###############################################################################

CSS = """
.gradio-container { font-family: 'Inter', sans-serif; }
.main-header { 
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
    padding: 2rem;
    border-radius: 12px;
    margin-bottom: 1.5rem;
    text-align: center;
    box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}
.main-header h1 { 
    color: #e2e8f0; 
    font-size: 2.2rem; 
    margin: 0;
    text-shadow: 0 2px 4px rgba(0,0,0,0.5);
}
.main-header p { color: #94a3b8; margin: 0.5rem 0 0 0; font-size: 1rem; }
.badge {
    display: inline-block;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.8rem;
    margin: 0.25rem;
    font-weight: 600;
}
.badge-blue { background: #1e3a5f; color: #60a5fa; }
.badge-green { background: #1a3a2a; color: #4ade80; }
.badge-purple { background: #2d1b4e; color: #c084fc; }
"""

with gr.Blocks(
    title="SF2 Creator Pro",
    theme=gr.themes.Soft(
        primary_hue="blue",
        secondary_hue="violet",
        neutral_hue="slate",
    ),
    css=CSS,
) as demo:

    gr.HTML("""
    <div class="main-header">
        <h1>🎹 SF2 SoundFont Creator Pro</h1>
        <p>Convierte colecciones de WAV en SoundFonts SF2 profesionales</p>
        <div style="margin-top:1rem;">
            <span class="badge badge-blue">πŸ”Š Stereo Nativo</span>
            <span class="badge badge-green">🎚️ Capas de Velocidad</span>
            <span class="badge badge-purple">🎸 Multi-Instrumento</span>
            <span class="badge badge-blue">πŸ”” Release Natural</span>
            <span class="badge badge-green">πŸ“€ Sin CompresiΓ³n</span>
        </div>
    </div>
    """)

    with gr.Tabs():
        
        # ══════════════════════════════════════════════════════════════════════
        # TAB 1: INSTRUMENTO ÚNICO
        # ══════════════════════════════════════════════════════════════════════
        with gr.TabItem("🎡 Un Instrumento", id="single"):
            with gr.Row():
                with gr.Column(scale=1, min_width=340):
                    gr.Markdown("## πŸ“€ ConfiguraciΓ³n")
                    
                    s_input_file = gr.File(
                        label="ZIP con WAVs",
                        file_types=[".zip"],
                        type="filepath",
                    )
                    
                    with gr.Row():
                        s_sf2_name = gr.Textbox(
                            label="Nombre del SoundFont",
                            placeholder="Mi Piano",
                            value="MySoundFont",
                        )
                        s_preset_name = gr.Textbox(
                            label="Nombre del Preset",
                            placeholder="Piano AcΓΊstico",
                            value="Preset 1",
                        )
                    
                    gr.Markdown("### βš™οΈ Procesamiento de Audio")
                    
                    with gr.Row():
                        s_do_normalize = gr.Checkbox(
                            label="πŸ”Š Normalizar",
                            value=True,
                            info="Normaliza el volumen al pico",
                        )
                        s_do_trim = gr.Checkbox(
                            label="βœ‚οΈ Recortar silencio",
                            value=True,
                            info="Elimina silencio al inicio/final",
                        )
                    
                    gr.Markdown("### πŸ”” Envelope (ADSR)")
                    
                    s_release_ms = gr.Slider(
                        minimum=50,
                        maximum=5000,
                        value=500,
                        step=50,
                        label="Release (ms)",
                        info="DuraciΓ³n del fade-out al soltar la tecla",
                    )
                    
                    s_reverb = gr.Slider(
                        minimum=0,
                        maximum=100,
                        value=15,
                        step=5,
                        label="Reverb Send (%)",
                        info="Cantidad de reverb incorporada en el SF2",
                    )
                    
                    s_convert_btn = gr.Button(
                        "🎡 Crear SF2",
                        variant="primary",
                        size="lg",
                    )
                    
                    with gr.Accordion("πŸ“ Formatos de nombre soportados", open=False):
                        gr.Markdown("""
```
C3.wav                     β†’ Do3 (MIDI 48)
F#4.wav                    β†’ Fa#4 (MIDI 66)  
Ab3.wav                    β†’ Lab3 (bemol)
Bb2.wav                    β†’ Sib2
Piano_G4.wav               β†’ Sol4
Piano_C3_127.wav           β†’ Do3, vel=127
Piano_C3_64.wav            β†’ Do3, vel=64
Nylon+Steel_E4_127.wav     β†’ Mi4, vel=127
Guitar_F#3_64.wav          β†’ Fa#3, vel=64
060.wav                    β†’ MIDI 60
```
**Capas de velocidad:** pon mΓΊltiples archivos de la misma nota con diferentes velocidades:
```
Piano_C3_32.wav   β†’ Do3 suave
Piano_C3_64.wav   β†’ Do3 medio
Piano_C3_127.wav  β†’ Do3 fuerte
```
                        """)
                
                with gr.Column(scale=1):
                    gr.Markdown("## πŸ“₯ Resultado")
                    s_output_file = gr.File(label="Archivo SF2 generado")
                    s_output_info = gr.Markdown("*Sube un ZIP para comenzar...*")
            
            s_convert_btn.click(
                fn=process_single_zip,
                inputs=[
                    s_input_file, s_sf2_name, s_preset_name,
                    s_do_normalize, s_do_trim,
                    s_release_ms, s_reverb,
                ],
                outputs=[s_output_file, s_output_info],
            )
        
        # ══════════════════════════════════════════════════════════════════════
        # TAB 2: MULTI-INSTRUMENTO
        # ══════════════════════════════════════════════════════════════════════
        with gr.TabItem("🎸 Multi-Instrumento", id="multi"):
            with gr.Row():
                with gr.Column(scale=1, min_width=340):
                    gr.Markdown("## πŸ“€ ConfiguraciΓ³n Multi-Instrumento")
                    
                    m_input_file = gr.File(
                        label="ZIP con carpetas de instrumentos",
                        file_types=[".zip"],
                        type="filepath",
                    )
                    
                    gr.Markdown("""
                    **πŸ“ Estructura requerida:**
                    ```
                    MiSoundFont.zip
                    β”œβ”€β”€ Piano/
                    β”‚   β”œβ”€β”€ C2.wav
                    β”‚   β”œβ”€β”€ C2_64.wav   ← vel layer
                    β”‚   β”œβ”€β”€ F2.wav
                    β”‚   └── C3.wav
                    β”œβ”€β”€ Strings/
                    β”‚   β”œβ”€β”€ C3.wav
                    β”‚   └── G3.wav
                    └── Bass/
                        β”œβ”€β”€ E1.wav
                        └── A1.wav
                    ```
                    Cada carpeta = un instrumento/preset.
                    El nombre de la carpeta = nombre del instrumento.
                    """)
                    
                    m_sf2_name = gr.Textbox(
                        label="Nombre del SoundFont",
                        placeholder="Mi Orquesta",
                        value="MySoundFont",
                    )
                    
                    gr.Markdown("### βš™οΈ Procesamiento de Audio")
                    
                    with gr.Row():
                        m_do_normalize = gr.Checkbox(
                            label="πŸ”Š Normalizar",
                            value=True,
                        )
                        m_do_trim = gr.Checkbox(
                            label="βœ‚οΈ Recortar silencio",
                            value=True,
                        )
                    
                    gr.Markdown("### πŸ”” Envelope")
                    
                    m_release_ms = gr.Slider(
                        minimum=50,
                        maximum=5000,
                        value=500,
                        step=50,
                        label="Release (ms)",
                        info="Release aplicado a todos los instrumentos",
                    )
                    
                    m_reverb = gr.Slider(
                        minimum=0,
                        maximum=100,
                        value=15,
                        step=5,
                        label="Reverb Send (%)",
                    )
                    
                    m_convert_btn = gr.Button(
                        "🎸 Crear SF2 Multi-Instrumento",
                        variant="primary",
                        size="lg",
                    )
                
                with gr.Column(scale=1):
                    gr.Markdown("## πŸ“₯ Resultado")
                    m_output_file = gr.File(label="Archivo SF2 multi-instrumento")
                    m_output_info = gr.Markdown("*Sube un ZIP con carpetas para comenzar...*")
            
            m_convert_btn.click(
                fn=process_multi_zip,
                inputs=[
                    m_input_file, m_sf2_name,
                    m_do_normalize, m_do_trim,
                    m_release_ms, m_reverb,
                ],
                outputs=[m_output_file, m_output_info],
            )
        
        # ══════════════════════════════════════════════════════════════════════
        # TAB 3: DOCUMENTACIΓ“N
        # ══════════════════════════════════════════════════════════════════════
        with gr.TabItem("πŸ“š GuΓ­a de Uso", id="docs"):
            gr.Markdown("""
## 🎹 SF2 Creator Pro β€” GuΓ­a Completa

### ΒΏQuΓ© es un SoundFont SF2?

Un archivo SF2 es una colecciΓ³n de samples de audio organizados para ser reproducidos por un sintetizador. Cada sample se asigna a una o mΓ‘s notas del teclado MIDI, y el sintetizador ajusta el pitch automΓ‘ticamente para las notas intermedias.

---

### 🎡 Pestaña: Un Instrumento

Ideal para crear un SF2 con un solo instrumento (piano, guitarra, etc.).

**Flujo de trabajo:**
1. ReΓΊne tus WAVs grabados/sampleados
2. NΓ³mbralos con la nota que representan (ver formatos)
3. ComprΓ­melos en un ZIP
4. Sube el ZIP y configura las opciones
5. Descarga tu SF2

**Capas de velocidad:** Para tener samples diferentes segΓΊn la fuerza de pulsaciΓ³n:
```
Piano_C4_32.wav   β†’ suave (vel 1-48)
Piano_C4_64.wav   β†’ medio (vel 49-96)  
Piano_C4_127.wav  β†’ fuerte (vel 97-127)
```

---

### 🎸 Pestaña: Multi-Instrumento

Crea un SF2 con mΓΊltiples instrumentos en un solo archivo.

**Estructura del ZIP:**
```
MiOrquesta.zip
β”œβ”€β”€ 00_Grand_Piano/
β”‚   β”œβ”€β”€ C1.wav, C2.wav, C3.wav, C4.wav, C5.wav
β”‚   β”œβ”€β”€ C2_64.wav  ← capa de velocidad
β”‚   └── C2_32.wav  ← capa de velocidad
β”œβ”€β”€ 01_Strings/
β”‚   β”œβ”€β”€ C2.wav, G2.wav, D3.wav
β”œβ”€β”€ 02_Brass/
β”‚   β”œβ”€β”€ C3.wav, F3.wav
└── 03_Bass/
    β”œβ”€β”€ E1.wav, A1.wav, D2.wav
```

Los nombres de carpetas se convierten en nombres de presets.
El prefijo numΓ©rico (`00_`, `01_`) controla el orden.

---

### πŸ”” Envelope (ADSR)

| ParΓ‘metro | DescripciΓ³n | Recomendado |
|-----------|-------------|-------------|
| **Release** | CuΓ‘nto tarda en silenciarse al soltar la tecla | 300-800ms piano, 1000-3000ms strings |
| **Reverb Send** | Reverb incorporado en el SF2 | 10-20% para uso general |

---

### πŸ“ Formatos de nombre de archivo

| Formato | Ejemplo | Resultado |
|---------|---------|-----------|
| Nota simple | `C4.wav` | MIDI 60, vel 127 |
| Con sostenido | `F#3.wav` | MIDI 54, vel 127 |
| Con bemol | `Bb2.wav` | MIDI 46, vel 127 |
| Con instrumento | `Piano_A3.wav` | MIDI 57, vel 127 |
| Con velocidad | `Piano_C3_64.wav` | MIDI 48, vel 64 |
| Vel. compleja | `Nylon+Steel_E4_127.wav` | MIDI 64, vel 127 |
| MIDI directo | `060.wav` | MIDI 60, vel 127 |

---

### 🎼 Distribución automÑtica del teclado

Si subes: `C3`, `F3`, `A#3`, `D#4`, `G4`, `C5`

```
C3  (48) β†’ teclas 0–50    (graves + hasta D#3)
F3  (53) β†’ teclas 51–55   (E3 hasta G#3)
A#3 (58) β†’ teclas 56–60   (A3 hasta C4)
D#4 (63) β†’ teclas 61–65   (C#4 hasta F4)
G4  (67) β†’ teclas 66–73   (F#4 hasta B4)
C5  (72) β†’ teclas 74–127  (C5 hasta lo mΓ‘s agudo)
```

---

### πŸ”§ Compatibilidad

El SF2 generado es compatible con:
- **FluidSynth** (Linux, multiplataforma)
- **Polyphone** (editor SF2)
- **MuseScore** (notaciΓ³n)
- **LMMS** (DAW gratuito)
- **Reason, Cubase, FL Studio, Ableton** (con plugins SF2)
- **Soundblaster** y hardware compatible con SF2
- **Sitios web** que usen WebAudio + sf2-player

---

### πŸ’‘ Consejos para mejores resultados

1. **Graba cada muestra en su nota natural** β€” el pitch shifting degrada la calidad
2. **MΓ‘s muestras = mejor calidad** β€” para piano: cada 3-4 semitonos es ideal
3. **Para instrumentos con sustain** (cuerdas, pad): release alto (2000-5000ms)
4. **Para instrumentos percusivos** (piano, marimba): release bajo (200-600ms)
5. **Normaliza antes de exportar** β€” muestras balanceadas entre capas de velocidad
6. **WAV 24-bit 44.1kHz o 48kHz** β€” el SF2 usa 16-bit internamente
7. **Stereo** β†’ mΓ‘s realismo pero archivo mΓ‘s grande; **Mono** β†’ mΓ‘s eficiente
            """)

    gr.HTML("""
    <div style="text-align:center; margin-top:2rem; padding:1rem; 
                border-top: 1px solid #334155; color:#64748b; font-size:0.85rem;">
        <strong>SF2 Creator Pro v2.0</strong> β€” Compatible con FluidSynth, Polyphone, MuseScore, LMMS y mΓ‘s
    </div>
    """)


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