File size: 1,252 Bytes
68f7e32
636c045
98ddfa5
68f7e32
636c045
 
 
 
 
 
98ddfa5
 
 
 
 
 
636c045
68f7e32
 
636c045
 
 
 
 
 
 
 
 
 
 
 
 
575cc76
a4dc28d
98ddfa5
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
from faster_whisper import WhisperModel
import os
import torch # Lägg till import av torch för att kontrollera GPU

# Globalt model för att undvika återladdning
model = None

def get_model():
    global model
    if model is None:
        # Kontrollera om GPU är tillgänglig och använd den
        device = "cuda" if torch.cuda.is_available() else "cpu"
        # Använd float16 för att dra nytta av GPU:n, int8_float16 är också ett alternativ
        compute_type = "float16" if device == "cuda" else "int8" 
        print(f"Laddar Whisper-modell på {device} med compute_type={compute_type}")
        model = WhisperModel("base", device=device, compute_type=compute_type)
    return model

def transcribe_audio(audio_path: str) -> str:
    """Transkribera ljudfil till text"""
    try:
        if not os.path.exists(audio_path):
            return f"Audio file not found: {audio_path}"
        
        model = get_model()
        segments, info = model.transcribe(audio_path, beam_size=5)
        
        transcription = " ".join(segment.text for segment in segments)
        return transcription.strip() or "No transcription found."
    
    except Exception as e:
        return f"Error transcribing audio: {str(e)}"