File size: 3,455 Bytes
228b6ea
 
1e7a231
228b6ea
 
 
 
1e7a231
 
 
 
228b6ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdc6979
1e7a231
228b6ea
1e7a231
 
 
 
228b6ea
1e7a231
 
 
 
f70a604
1e7a231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f70a604
1e7a231
cdc6979
1e7a231
 
cdc6979
 
 
 
f70a604
cdc6979
 
 
 
228b6ea
 
1e7a231
 
228b6ea
 
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
import os
import warnings
import tempfile
from basic_pitch.inference import predict_and_save
from basic_pitch import ICASSP_2022_MODEL_PATH
import tensorflow as tf

# Configurar TensorFlow para evitar problemas de GPU
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'  # Forzar uso de CPU
tf.config.set_visible_devices([], 'GPU')  # Desabilitar GPU


# Suprime warnings de runtime (p.ej. invalid value encountered in divide)
warnings.filterwarnings("ignore", category=RuntimeWarning)

# Carpeta ra铆z donde guardamos archivos midi
BASE_MIDI_DIR = "data/midi"


def inferir_basic_pitch(input_file: str) -> str:
    """
    Procesa un archivo de audio y genera un archivo MIDI usando Basic Pitch.
    
    Args:
        input_file: Ruta al archivo de audio de entrada
        
    Returns:
        Ruta al archivo MIDI generado
    """
    # Crear directorio de salida si no existe
    os.makedirs(BASE_MIDI_DIR, exist_ok=True)
    
    try:
        print(f"Procesando archivo: {input_file}")
        print(f"Directorio de salida: {BASE_MIDI_DIR}")
        
        # Verificar que el archivo de entrada existe
        if not os.path.exists(input_file):
            print(f"Error: El archivo de entrada no existe: {input_file}")
            return None
        
        # Limpiar el directorio de salida antes del procesamiento
        for f in os.listdir(BASE_MIDI_DIR):
            if f.endswith('.mid'):
                os.remove(os.path.join(BASE_MIDI_DIR, f))
        
        # Realizar predicci贸n y guardar archivo MIDI
        try:
            predict_and_save(
                model_or_model_path=ICASSP_2022_MODEL_PATH,
                audio_path_list=[input_file],
                output_directory=BASE_MIDI_DIR,
                save_midi=True,
                sonify_midi=False,
                save_model_outputs=False,
                save_notes=False,
            )
            print("Predicci贸n completada")
        except Exception as model_error:
            print(f"Error espec铆fico del modelo: {model_error}")
            # Intentar con una configuraci贸n alternativa
            try:
                print("Intentando configuraci贸n alternativa...")
                predict_and_save(
                    audio_path_list=[input_file],
                    output_directory=BASE_MIDI_DIR,
                    save_midi=True,
                    sonify_midi=False,
                    save_model_outputs=False,
                    save_notes=False,
                )
                print("Predicci贸n alternativa completada")
            except Exception as alt_error:
                print(f"Error en configuraci贸n alternativa: {alt_error}")
                return None
        
        # Buscar archivos MIDI generados
        generated_files = [f for f in os.listdir(BASE_MIDI_DIR) if f.endswith('.mid')]
        print(f"Archivos generados: {generated_files}")
        
        if generated_files:
            # Tomar el archivo m谩s reciente
            latest_file = max([os.path.join(BASE_MIDI_DIR, f) for f in generated_files], 
                            key=os.path.getctime)
            print(f"Archivo MIDI encontrado: {latest_file}")
            return latest_file
        else:
            print("No se gener贸 ning煤n archivo MIDI")
            return None
        
    except Exception as e:
        print(f"Error general durante la inferencia: {e}")
        print(f"Tipo de error: {type(e).__name__}")
        return None