File size: 2,118 Bytes
ebf7fba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import torch
import tempfile
import os
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
from audiorecorder import audiorecorder
from pydub import AudioSegment

# Setup model
device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
model_id = "KBLab/kb-whisper-tiny"

@st.cache_resource
def load_model():
    model = AutoModelForSpeechSeq2Seq.from_pretrained(
        model_id, torch_dtype=torch_dtype, use_safetensors=True, cache_dir="cache"
    )
    model.to(device)
    processor = AutoProcessor.from_pretrained(model_id)
    return pipeline(
        "automatic-speech-recognition",
        model=model,
        tokenizer=processor.tokenizer,
        feature_extractor=processor.feature_extractor,
        torch_dtype=torch_dtype,
        device=device,
    )

pipe = load_model()

def transcribe_audio(audio_path):
    return pipe(audio_path, chunk_length_s=30, generate_kwargs={"task": "transcribe", "language": "sv"})

st.title("Speech-to-Text Transcription")

# Audio recording
st.subheader("Record Audio")
recorded_audio = audiorecorder("Start Recording", "Stop Recording")

if recorded_audio:
    with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_file:
        temp_file.write(recorded_audio.tobytes())
        temp_file_path = temp_file.name
    st.audio(temp_file_path, format="audio/wav")
    result = transcribe_audio(temp_file_path)
    st.write("### Transcription:")
    st.write(result["text"])
    os.remove(temp_file_path)

# File upload
st.subheader("Upload Audio File")
uploaded_file = st.file_uploader("Choose an audio file", type=["wav", "mp3", "ogg", "flac"])

if uploaded_file:
    with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[-1]) as temp_file:
        temp_file.write(uploaded_file.read())
        temp_file_path = temp_file.name
    st.audio(temp_file_path)
    result = transcribe_audio(temp_file_path)
    st.write("### Transcription:")
    st.write(result["text"])
    os.remove(temp_file_path)