Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import torchfrom transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipelineimport gradio as grfrom pydub import AudioSegmentimport os# Set device and precision for CPUdevice = "cpu"torch_dtype = torch.float32# Load KB-Whisper model (Large variant)model_id = "KBLab/kb-whisper-large"model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)processor = AutoProcessor.from_pretrained(model_id)pipe = pipeline("automatic-speech-recognition",model=model,tokenizer=processor.tokenizer,feature_extractor=processor.feature_extractor,device=device,torch_dtype=torch_dtype,)def transcribe(audio_path):# Handle m4a or other formats by converting to wavbase, ext = os.path.splitext(audio_path)if ext.lower() != ".wav":try:sound = AudioSegment.from_file(audio_path)audio_converted_path = base + ".converted.wav"sound.export(audio_converted_path, format="wav")audio_path = audio_converted_pathexcept Exception as e:return f"Error converting audio: {str(e)}"# Transcribetry:result = pipe(audio_path, chunk_length_s=30, generate_kwargs={"task": "transcribe", "language": "sv"})return result["text"]except Exception as e:return f"Transcription failed: {str(e)}"# Build Gradio interfacegr.Interface(fn=transcribe,inputs=gr.Audio(type="filepath", label="Upload Swedish Audio"),outputs=gr.Textbox(label="Transcribed Text"),title="KB-Whisper Transcriber (Swedish, Free CPU)",description="Upload .m4a, .mp3, or .wav files. Transcribes Swedish speech using KBLab's Whisper Large model.",).launch()123456789101112131415161718192021from pydub import AudioSegmentimport mimetypesdef transcribe(audio_path):try:# Detect file type using MIME or extensionmime_type, _ = mimetypes.guess_type(audio_path)ext = os.path.splitext(audio_path)[1].lower()if mime_type == "audio/mp4" or ext == ".m4a":print("Converting .m4a to .wav...")sound = AudioSegment.from_file(audio_path, format="m4a")converted_path = audio_path.replace(".m4a", ".converted.wav")sound.export(converted_path, format="wav")audio_path = converted_pathresult = pipe(audio_path, chunk_length_s=30, generate_kwargs={"task": "transcribe", "language": "sv"})return result["text"]except Exception as e:return f"Error during transcription: {str(e)}"
app.py+14-48