Spaces:
Build error

File size: 3,282 Bytes
ae466fc
 
 
 
 
 
 
7051c4b
 
ae466fc
 
 
7051c4b
ae466fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7051c4b
 
ae466fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7051c4b
ae466fc
 
 
 
 
 
 
7051c4b
ae466fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7051c4b
ae466fc
7051c4b
ae466fc
7051c4b
 
ae466fc
 
 
 
 
 
7051c4b
ae466fc
7051c4b
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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)