File size: 13,357 Bytes
8fa04cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f49ec35
 
 
 
 
 
 
 
 
 
 
8fa04cd
f49ec35
 
8fa04cd
f49ec35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa04cd
f49ec35
8fa04cd
 
f49ec35
 
 
 
8fa04cd
f49ec35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa04cd
f49ec35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa04cd
 
 
f49ec35
 
 
 
 
 
8fa04cd
 
 
f49ec35
 
 
 
 
 
 
 
 
8fa04cd
f49ec35
 
 
 
 
c944402
8fa04cd
 
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
# import os
# os.environ["KERAS_BACKEND"] = "jax"
# os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
# import logging
# from pathlib import Path
# import numpy as np
# import librosa
# import tensorflow_hub as hub
# from flask import Flask, render_template, request, jsonify, session
# from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
# import keras
# import torch
# from werkzeug.utils import secure_filename
# import traceback

# # Configure logging
# logging.basicConfig(
#     level=logging.INFO,
#     format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
#     handlers=[
#         logging.FileHandler('app.log'),
#         logging.StreamHandler()
#     ]
# )
# logger = logging.getLogger(__name__)

# # Environment setup


# class AudioProcessor:
#     _instance = None
#     _initialized = False

#     def __new__(cls):
#         if cls._instance is None:
#             cls._instance = super(AudioProcessor, cls).__new__(cls)
#         return cls._instance

#     def __init__(self):
#         if not AudioProcessor._initialized:
#             self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
#             self.torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
#             self.initialize_models()
#             AudioProcessor._initialized = True

#     def initialize_models(self):
#         try:
#             logger.info("Initializing models...")
#             # Initialize transcription model
#             model_id = "distil-whisper/distil-large-v3"
#             self.transcription_model = AutoModelForSpeechSeq2Seq.from_pretrained(
#                 model_id, torch_dtype=self.torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
#             )
#             self.transcription_model.to(self.device)
#             self.processor = AutoProcessor.from_pretrained(model_id)
            
#             # Initialize classification model
#             self.classification_model = keras.saving.load_model("hf://datasciencesage/attentionaudioclassification")
            
#             # Initialize pipeline
#             self.pipe = pipeline(
#                 "automatic-speech-recognition",
#                 model=self.transcription_model,
#                 tokenizer=self.processor.tokenizer,
#                 feature_extractor=self.processor.feature_extractor,
#                 max_new_tokens=128,
#                 chunk_length_s=25,
#                 batch_size=16,
#                 torch_dtype=self.torch_dtype,
#                 device=self.device,
#             )
            
#             # Initialize YAMNet model
#             self.yamnet_model = hub.load('https://tfhub.dev/google/yamnet/1')
            
#             logger.info("Models initialized successfully")
#         except Exception as e:
#             logger.error(f"Error initializing models: {str(e)}")
#             raise

#     def load_wav_16k_mono(self, filename):
#         try:
#             wav, sr = librosa.load(filename, mono=True, sr=None)
#             if sr != 16000:
#                 wav = librosa.resample(wav, orig_sr=sr, target_sr=16000)
#             return wav
#         except Exception as e:
#             logger.error(f"Error loading audio file: {str(e)}")
#             raise

#     def get_features_yamnet_extract_embedding(self, wav_data):
#         try:
#             scores, embeddings, spectrogram = self.yamnet_model(wav_data)
#             return np.mean(embeddings.numpy(), axis=0)
#         except Exception as e:
#             logger.error(f"Error extracting YAMNet embeddings: {str(e)}")
#             raise

# # Initialize Flask application
# app = Flask(__name__)
# app.secret_key = 'your_secret_key_here'
# app.config['UPLOAD_FOLDER'] = Path('uploads')
# app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

# # Create upload folder
# app.config['UPLOAD_FOLDER'].mkdir(exist_ok=True)

# # Initialize audio processor (will only happen once)
# audio_processor = AudioProcessor()

# @app.route('/')
# def index():
#     session.clear()
#     return render_template('terminal.html')

# @app.route('/process', methods=['POST'])
# def process():
#     try:
#         data = request.json
#         command = data.get('command', '').strip().lower()

#         if command in ['classify', 'transcribe']:
#             session['operation'] = command
#             return jsonify({
#                 'result': f'root@math:~$ Upload a .mp3 file for {command} operation.',
#                 'upload': True
#             })
#         else:
#             return jsonify({
#                 'result': 'root@math:~$ Please specify an operation: "classify" or "transcribe".'
#             })
#     except Exception as e:
#         logger.error(f"Error in process route: {str(e)}\n{traceback.format_exc()}")
#         session.pop('operation', None)
#         return jsonify({'result': f'root@math:~$ Error: {str(e)}'})

# @app.route('/upload', methods=['POST'])
# def upload():
#     filepath = None
#     try:
#         operation = session.get('operation')
#         if not operation:
#             return jsonify({
#                 'result': 'root@math:~$ Please specify an operation first: "classify" or "transcribe".'
#             })

#         if 'file' not in request.files:
#             return jsonify({'result': 'root@math:~$ No file uploaded.'})

#         file = request.files['file']
#         if file.filename == '' or not file.filename.lower().endswith('.mp3'):
#             return jsonify({'result': 'root@math:~$ Please upload a valid .mp3 file.'})

#         filename = secure_filename(file.filename)
#         filepath = app.config['UPLOAD_FOLDER'] / filename
        
#         file.save(filepath)
#         wav_data = audio_processor.load_wav_16k_mono(filepath)
        
#         if operation == 'classify':
#             embeddings = audio_processor.get_features_yamnet_extract_embedding(wav_data)
#             embeddings = np.reshape(embeddings, (-1, 1024))
#             result = np.argmax(audio_processor.classification_model.predict(embeddings))
#         elif operation == 'transcribe':
#             result = audio_processor.pipe(str(filepath))['text']
#         else:
#             result = 'Invalid operation'

#         return jsonify({
#             'result': f'root@math:~$ Result is: {result}\nroot@math:~$ Please specify an operation: "classify" or "transcribe".',
#             'upload': False
#         })

#     except Exception as e:
#         logger.error(f"Error in upload route: {str(e)}\n{traceback.format_exc()}")
#         return jsonify({
#             'result': f'root@math:~$ Error: {str(e)}\nroot@math:~$ Please specify an operation: "classify" or "transcribe".'
#         })
#     finally:
#         session.pop('operation', None)
#         if filepath and Path(filepath).exists():
#             try:
#                 Path(filepath).unlink()
#             except Exception as e:
#                 logger.error(f"Error deleting file {filepath}: {str(e)}")

import os
os.environ["KERAS_BACKEND"] = "jax"
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
import logging
import numpy as np
import librosa
import tensorflow_hub as hub
from flask import Flask, render_template, request, jsonify, session
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
import keras
import torch
import io
import traceback

# Configure logging to print to terminal only
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class AudioProcessor:
    _instance = None
    _initialized = False

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(AudioProcessor, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if not AudioProcessor._initialized:
            self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
            self.torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
            self.initialize_models()
            AudioProcessor._initialized = True

    def initialize_models(self):
        try:
            logger.info("Initializing models...")
            # Initialize transcription model
            model_id = "distil-whisper/distil-large-v3"
            self.transcription_model = AutoModelForSpeechSeq2Seq.from_pretrained(
                model_id, torch_dtype=self.torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
            )
            self.transcription_model.to(self.device)
            self.processor = AutoProcessor.from_pretrained(model_id)
            
            # Initialize classification model
            self.classification_model = keras.saving.load_model("hf://datasciencesage/attentionaudioclassification")
            
            # Initialize pipeline
            self.pipe = pipeline(
                "automatic-speech-recognition",
                model=self.transcription_model,
                tokenizer=self.processor.tokenizer,
                feature_extractor=self.processor.feature_extractor,
                max_new_tokens=128,
                chunk_length_s=25,
                batch_size=16,
                torch_dtype=self.torch_dtype,
                device=self.device,
            )
            
            # Initialize YAMNet model
            self.yamnet_model = hub.load('https://tfhub.dev/google/yamnet/1')
            
            logger.info("Models initialized successfully")
        except Exception as e:
            logger.error(f"Error initializing models: {str(e)}")
            raise

    def load_wav_16k_mono(self, audio_data):
        try:
            # Load audio from bytes buffer instead of file
            wav, sr = librosa.load(io.BytesIO(audio_data), mono=True, sr=None)
            if sr != 16000:
                wav = librosa.resample(wav, orig_sr=sr, target_sr=16000)
            return wav
        except Exception as e:
            logger.error(f"Error loading audio data: {str(e)}")
            raise

    def get_features_yamnet_extract_embedding(self, wav_data):
        try:
            scores, embeddings, spectrogram = self.yamnet_model(wav_data)
            return np.mean(embeddings.numpy(), axis=0)
        except Exception as e:
            logger.error(f"Error extracting YAMNet embeddings: {str(e)}")
            raise

# Initialize Flask application
app = Flask(__name__)
app.secret_key = 'your_secret_key_here'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

# Initialize audio processor (will only happen once)
audio_processor = AudioProcessor()

@app.route('/')
def index():
    session.clear()
    return render_template('terminal.html')

@app.route('/process', methods=['POST'])
def process():
    try:
        data = request.json
        command = data.get('command', '').strip().lower()

        if command in ['classify', 'transcribe']:
            session['operation'] = command
            return jsonify({
                'result': f'root@math:~$ Upload a .mp3 file for {command} operation.',
                'upload': True
            })
        else:
            return jsonify({
                'result': 'root@math:~$ Please specify an operation: "classify" or "transcribe".'
            })
    except Exception as e:
        logger.error(f"Error in process route: {str(e)}")
        session.pop('operation', None)
        return jsonify({'result': f'root@math:~$ Error: {str(e)}'})

@app.route('/upload', methods=['POST'])
def upload():
    try:
        operation = session.get('operation')
        if not operation:
            return jsonify({
                'result': 'root@math:~$ Please specify an operation first: "classify" or "transcribe".'
            })

        if 'file' not in request.files:
            return jsonify({'result': 'root@math:~$ No file uploaded.'})

        file = request.files['file']
        if file.filename == '' or not file.filename.lower().endswith('.mp3'):
            return jsonify({'result': 'root@math:~$ Please upload a valid .mp3 file.'})

        # Read file content into memory
        audio_data = file.read()
        wav_data = audio_processor.load_wav_16k_mono(audio_data)
        
        if operation == 'classify':
            embeddings = audio_processor.get_features_yamnet_extract_embedding(wav_data)
            embeddings = np.reshape(embeddings, (-1, 1024))
            result = np.argmax(audio_processor.classification_model.predict(embeddings))
        elif operation == 'transcribe':
            # Create temporary buffer for transcription
            audio_buffer = io.BytesIO(audio_data)
            result = audio_processor.pipe(audio_buffer)['text']
        else:
            result = 'Invalid operation'

        return jsonify({
            'result': f'root@math:~$ Result is: {result}\nroot@math:~$ Please specify an operation: "classify" or "transcribe".',
            'upload': False
        })

    except Exception as e:
        logger.error(f"Error in upload route: {str(e)}")
        return jsonify({
            'result': f'root@math:~$ Error: {str(e)}\nroot@math:~$ Please specify an operation: "classify" or "transcribe".'
        })
    finally:
        session.pop('operation', None)

# if __name__ == '__main__':
#     app.run(host='0.0.0.0', port=7860)