Spaces:
Build error

irfan989's picture
Update app.py
ae466fc verified
Raw History Blame Contribute Delete
3.28 kB
import datetime
import subprocess
import wave
import contextlib
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from transformers import pipeline
import gradio as gr
import whisper
from pyannote.audio import Audio
from pyannote.audio.pipelines.speaker_verification import PretrainedSpeakerEmbedding
from pyannote.core import Segment
# Define the parameters
num_speakers = 4
language = 'English'
model_size = 'base'
model_name = model_size
# Check language and model size for model name
if language == 'English' and model_size != 'large':
model_name += '.en'
# Load the whisper model
model = whisper.load_model(model_name)
# Initialize the speaker embedding model
embedding_model = PretrainedSpeakerEmbedding("speechbrain/spkrec-ecapa-voxceleb")
def summarize(text):
# Use T5 model for text summarization
pipe = pipeline("summarization", model="t5-small")
pipe_out = pipe(text)
return pipe_out[0]['summary_text']
def transcribe_audio(path):
# Transcribe audio using whisper model
result = model.transcribe(path)
segments = result["segments"]
# Check if input file is in WAV format
if path[-3:] != 'wav':
subprocess.call(['ffmpeg', '-i', path, 'audio.wav', '-y'])
path = 'audio.wav'
# Get duration of audio file
with contextlib.closing(wave.open(path, 'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
# Initialize Audio object
audio = Audio()
def segment_embedding(segment):
# Extract speaker embedding from segment
start = segment["start"]
end = min(duration, segment["end"])
clip = Segment(start, end)
waveform, sample_rate = audio.crop(path, clip)
return embedding_model(waveform[None])
# Calculate embeddings for speaker diarization
embeddings = np.zeros(shape=(len(segments), 192))
for i, segment in enumerate(segments):
embeddings[i] = segment_embedding(segment)
embeddings = np.nan_to_num(embeddings)
# Perform speaker diarization using Agglomerative Clustering
clustering = AgglomerativeClustering(num_speakers).fit(embeddings)
labels = clustering.labels_
for i in range(len(segments)):
segments[i]["speaker"] = 'SPEAKER ' + str(labels[i] + 1)
def time(secs):
return datetime.timedelta(seconds=round(secs))
# Write transcribed text with speaker labels to file
f = open("transcript.txt", "w")
for (i, segment) in enumerate(segments):
if i == 0 or segments[i - 1]["speaker"] != segment["speaker"]:
f.write("\n" + segment["speaker"] + ' ' + str(time(segment["start"])) + '\n')
f.write(segment["text"][1:] + ' ')
f.close()
# Summarize transcribed text
text = result["text"]
summary = summarize(text)
return text, summary
# Define Gradio interface
iface = gr.Interface(
fn=transcribe_audio,
inputs=[
gr.inputs.Audio(source="upload", type="file")
],
outputs=[
"text",
"text"
],
title="Audio Transcription & Summarization",
description="Upload an audio file for transcription and receive a summarized text output."
)
# Launch Gradio interface
iface.launch(inline=True, debug=True)