Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,218 +10,135 @@ from pathlib import Path
|
|
| 10 |
from tempfile import NamedTemporaryFile
|
| 11 |
from datetime import timedelta
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
logging.basicConfig(level=logging.INFO
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
-
#
|
| 18 |
MODEL_ID = "KBLab/kb-whisper-large"
|
| 19 |
CHUNK_DURATION_MS = 10000
|
| 20 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 21 |
TORCH_DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
|
| 22 |
SUPPORTED_FORMATS = {".wav", ".mp3", ".m4a"}
|
| 23 |
|
| 24 |
-
#
|
| 25 |
def check_ffmpeg():
|
| 26 |
try:
|
| 27 |
subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
|
| 28 |
-
logger.info("ffmpeg is installed and accessible.")
|
| 29 |
return True
|
| 30 |
-
except
|
| 31 |
-
logger.error("ffmpeg is not installed or not found in PATH.")
|
| 32 |
return False
|
| 33 |
|
| 34 |
-
#
|
| 35 |
def initialize_pipeline():
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
# Convert audio if needed
|
| 57 |
def convert_to_wav(audio_path: str) -> str:
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
audio = AudioSegment.from_file(audio_path)
|
| 67 |
-
wav_path = str(Path(audio_path).with_suffix(".converted.wav"))
|
| 68 |
-
audio.export(wav_path, format="wav")
|
| 69 |
-
logger.info(f"Conversion successful: {wav_path}")
|
| 70 |
-
return wav_path
|
| 71 |
-
return audio_path
|
| 72 |
-
except CouldntDecodeError:
|
| 73 |
-
logger.error(f"Failed to decode .m4a file: {audio_path}")
|
| 74 |
-
raise ValueError("The .m4a file is corrupted or not supported. Ensure it's a valid iPhone recording and ffmpeg is installed.")
|
| 75 |
-
except OSError as e:
|
| 76 |
-
logger.error(f"OS error during audio conversion: {str(e)}")
|
| 77 |
-
raise ValueError("Failed to process the .m4a file due to a system error. Check file permissions or disk space.")
|
| 78 |
-
except Exception as e:
|
| 79 |
-
logger.error(f"Unexpected error during .m4a conversion: {str(e)}")
|
| 80 |
-
raise ValueError(f"An unexpected error occurred while converting the .m4a file: {str(e)}")
|
| 81 |
-
|
| 82 |
-
# Split audio into chunks
|
| 83 |
-
def split_audio(audio_path: str) -> list:
|
| 84 |
-
try:
|
| 85 |
audio = AudioSegment.from_file(audio_path)
|
| 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 |
-
final_transcript = f"Warning: {failed_chunks}/{total_chunks} chunks failed to transcribe.\n{final_transcript}"
|
| 168 |
-
|
| 169 |
-
download_content = "\n".join(timestamped_transcript) if include_timestamps else final_transcript
|
| 170 |
-
download_path = None
|
| 171 |
-
try:
|
| 172 |
-
with NamedTemporaryFile(suffix=".txt", delete=False, mode='w', encoding='utf-8') as temp_file:
|
| 173 |
-
temp_file.write(download_content)
|
| 174 |
-
download_path = temp_file.name
|
| 175 |
-
except OSError as e:
|
| 176 |
-
logger.error(f"Failed to create downloadable transcript: {str(e)}")
|
| 177 |
-
final_transcript = f"{final_transcript}\nNote: Could not generate downloadable transcript due to a file error."
|
| 178 |
-
|
| 179 |
-
return final_transcript, download_path
|
| 180 |
-
|
| 181 |
-
except ValueError as e:
|
| 182 |
-
logger.error(f"Value error during transcription: {str(e)}")
|
| 183 |
-
return str(e), None
|
| 184 |
-
except Exception as e:
|
| 185 |
-
logger.error(f"Unexpected error during transcription: {str(e)}")
|
| 186 |
-
return f"An unexpected error occurred while processing the .m4a file: {str(e)}. Please ensure the file is a valid iPhone recording and try again.", None
|
| 187 |
-
|
| 188 |
-
# Initialize pipeline globally
|
| 189 |
-
try:
|
| 190 |
-
PIPELINE = initialize_pipeline()
|
| 191 |
-
except RuntimeError as e:
|
| 192 |
-
logger.critical(f"Pipeline initialization failed: {str(e)}")
|
| 193 |
-
raise
|
| 194 |
-
|
| 195 |
-
# Gradio Interface with Blocks
|
| 196 |
-
def create_interface():
|
| 197 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 198 |
-
gr.Markdown("# Swedish Whisper Transcriber")
|
| 199 |
-
gr.Markdown("Upload an .m4a file from your iPhone for real-time Swedish speech transcription.")
|
| 200 |
-
|
| 201 |
-
with gr.Row():
|
| 202 |
-
with gr.Column():
|
| 203 |
-
audio_input = gr.Audio(type="filepath", label="Upload .m4a Audio")
|
| 204 |
-
timestamp_toggle = gr.Checkbox(label="Include Timestamps in Download", value=False)
|
| 205 |
-
transcribe_btn = gr.Button("Transcribe")
|
| 206 |
-
|
| 207 |
-
with gr.Column():
|
| 208 |
-
transcript_output = gr.Textbox(label="Live Transcription", lines=10)
|
| 209 |
-
download_output = gr.File(label="Download Transcript")
|
| 210 |
-
|
| 211 |
-
transcribe_btn.click(
|
| 212 |
-
fn=transcribe,
|
| 213 |
-
inputs=[audio_input, timestamp_toggle],
|
| 214 |
-
outputs=[transcript_output, download_output]
|
| 215 |
-
)
|
| 216 |
-
|
| 217 |
-
return demo
|
| 218 |
-
|
| 219 |
-
if __name__ == "__main__":
|
| 220 |
-
try:
|
| 221 |
-
if not check_ffmpeg():
|
| 222 |
-
print("Error: ffmpeg is required to process .m4a files. Please install ffmpeg and ensure it's in your PATH.")
|
| 223 |
-
exit(1)
|
| 224 |
-
create_interface().launch()
|
| 225 |
-
except Exception as e:
|
| 226 |
-
logger.critical(f"Failed to launch Gradio interface: {str(e)}")
|
| 227 |
-
print(f"Error: Could not start the application. Please check the logs for details.")
|
|
|
|
| 10 |
from tempfile import NamedTemporaryFile
|
| 11 |
from datetime import timedelta
|
| 12 |
|
| 13 |
+
# ---------------- LOGGING ----------------
|
| 14 |
+
logging.basicConfig(level=logging.INFO)
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
+
# ---------------- CONFIG ----------------
|
| 18 |
MODEL_ID = "KBLab/kb-whisper-large"
|
| 19 |
CHUNK_DURATION_MS = 10000
|
| 20 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 21 |
TORCH_DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
|
| 22 |
SUPPORTED_FORMATS = {".wav", ".mp3", ".m4a"}
|
| 23 |
|
| 24 |
+
# ---------------- FFMPEG CHECK ----------------
|
| 25 |
def check_ffmpeg():
|
| 26 |
try:
|
| 27 |
subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
|
|
|
|
| 28 |
return True
|
| 29 |
+
except Exception:
|
|
|
|
| 30 |
return False
|
| 31 |
|
| 32 |
+
# ---------------- LOAD MODEL ----------------
|
| 33 |
def initialize_pipeline():
|
| 34 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
| 35 |
+
MODEL_ID,
|
| 36 |
+
torch_dtype=TORCH_DTYPE,
|
| 37 |
+
low_cpu_mem_usage=True
|
| 38 |
+
).to(DEVICE)
|
| 39 |
+
|
| 40 |
+
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
| 41 |
+
|
| 42 |
+
return pipeline(
|
| 43 |
+
"automatic-speech-recognition",
|
| 44 |
+
model=model,
|
| 45 |
+
tokenizer=processor.tokenizer,
|
| 46 |
+
feature_extractor=processor.feature_extractor,
|
| 47 |
+
device=DEVICE,
|
| 48 |
+
torch_dtype=TORCH_DTYPE
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
PIPELINE = initialize_pipeline()
|
| 52 |
+
|
| 53 |
+
# ---------------- AUDIO UTILS ----------------
|
|
|
|
| 54 |
def convert_to_wav(audio_path: str) -> str:
|
| 55 |
+
if not check_ffmpeg():
|
| 56 |
+
raise RuntimeError("ffmpeg not available")
|
| 57 |
+
|
| 58 |
+
ext = Path(audio_path).suffix.lower()
|
| 59 |
+
if ext not in SUPPORTED_FORMATS:
|
| 60 |
+
raise ValueError("Unsupported audio format")
|
| 61 |
+
|
| 62 |
+
if ext != ".wav":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
audio = AudioSegment.from_file(audio_path)
|
| 64 |
+
wav_path = str(Path(audio_path).with_suffix(".wav"))
|
| 65 |
+
audio.export(wav_path, format="wav")
|
| 66 |
+
return wav_path
|
| 67 |
+
|
| 68 |
+
return audio_path
|
| 69 |
+
|
| 70 |
+
def split_audio(audio_path: str):
|
| 71 |
+
audio = AudioSegment.from_file(audio_path)
|
| 72 |
+
return [audio[i:i + CHUNK_DURATION_MS] for i in range(0, len(audio), CHUNK_DURATION_MS)]
|
| 73 |
+
|
| 74 |
+
def get_chunk_time(index: int) -> str:
|
| 75 |
+
return str(timedelta(milliseconds=index * CHUNK_DURATION_MS))
|
| 76 |
+
|
| 77 |
+
# ---------------- TRANSCRIBE ----------------
|
| 78 |
+
def transcribe(audio_path: str, include_timestamps: bool, progress=gr.Progress()):
|
| 79 |
+
if not audio_path or not os.path.exists(audio_path):
|
| 80 |
+
yield "Please upload an audio file.", None
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
wav_path = convert_to_wav(audio_path)
|
| 84 |
+
chunks = split_audio(wav_path)
|
| 85 |
+
|
| 86 |
+
transcript = []
|
| 87 |
+
timestamped = []
|
| 88 |
+
|
| 89 |
+
for i, chunk in enumerate(chunks):
|
| 90 |
+
with NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
|
| 91 |
+
chunk.export(tmp.name, format="wav")
|
| 92 |
+
|
| 93 |
+
result = PIPELINE(
|
| 94 |
+
tmp.name,
|
| 95 |
+
generate_kwargs={"task": "transcribe", "language": "sv"}
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
os.remove(tmp.name)
|
| 99 |
+
|
| 100 |
+
text = result["text"].strip()
|
| 101 |
+
if text:
|
| 102 |
+
transcript.append(text)
|
| 103 |
+
if include_timestamps:
|
| 104 |
+
ts = get_chunk_time(i)
|
| 105 |
+
timestamped.append(f"[{ts}] {text}")
|
| 106 |
+
|
| 107 |
+
progress((i + 1) / len(chunks))
|
| 108 |
+
yield " ".join(transcript), None
|
| 109 |
+
|
| 110 |
+
content = "\n".join(timestamped) if include_timestamps else " ".join(transcript)
|
| 111 |
+
|
| 112 |
+
with NamedTemporaryFile(
|
| 113 |
+
suffix=".txt",
|
| 114 |
+
delete=False,
|
| 115 |
+
mode="w",
|
| 116 |
+
encoding="utf-8"
|
| 117 |
+
) as f:
|
| 118 |
+
f.write(content)
|
| 119 |
+
download_path = f.name
|
| 120 |
+
|
| 121 |
+
yield " ".join(transcript), download_path
|
| 122 |
+
|
| 123 |
+
# ---------------- UI ----------------
|
| 124 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 125 |
+
gr.Markdown("# Swedish Whisper Transcriber")
|
| 126 |
+
gr.Markdown("Upload an .m4a file and download the transcript with timestamps.")
|
| 127 |
+
|
| 128 |
+
with gr.Row():
|
| 129 |
+
with gr.Column():
|
| 130 |
+
audio_input = gr.Audio(type="filepath", label="Upload Audio (.m4a)")
|
| 131 |
+
timestamp_toggle = gr.Checkbox(label="Include timestamps in download")
|
| 132 |
+
transcribe_btn = gr.Button("Transcribe")
|
| 133 |
+
|
| 134 |
+
with gr.Column():
|
| 135 |
+
transcript_output = gr.Textbox(label="Live Transcription", lines=12)
|
| 136 |
+
download_output = gr.File(label="Download Transcript")
|
| 137 |
+
|
| 138 |
+
transcribe_btn.click(
|
| 139 |
+
fn=transcribe,
|
| 140 |
+
inputs=[audio_input, timestamp_toggle],
|
| 141 |
+
outputs=[transcript_output, download_output]
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|