Update app.py
Browse files
app.py
CHANGED
@@ -10,142 +10,166 @@ import io
|
|
10 |
|
11 |
@st.cache_resource
|
12 |
def load_models():
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
def process_audio(audio_file, max_duration=600):
|
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 |
def format_speaker_segments(diarization_result):
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
|
|
|
|
|
|
|
|
|
|
95 |
|
96 |
def format_timestamp(seconds):
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
|
101 |
def main():
|
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 |
if __name__ == "__main__":
|
151 |
-
|
|
|
10 |
|
11 |
@st.cache_resource
|
12 |
def load_models():
|
13 |
+
try:
|
14 |
+
# Back to original model name
|
15 |
+
diarization = Pipeline.from_pretrained(
|
16 |
+
"pyannote/speaker-diarization", # Original model name
|
17 |
+
use_auth_token=st.secrets["hf_token"]
|
18 |
+
)
|
19 |
+
|
20 |
+
transcriber = whisper.load_model("base")
|
21 |
+
|
22 |
+
summarizer = tf_pipeline(
|
23 |
+
"summarization",
|
24 |
+
model="facebook/bart-large-cnn",
|
25 |
+
device=0 if torch.cuda.is_available() else -1
|
26 |
+
)
|
27 |
+
|
28 |
+
# Validate models loaded correctly
|
29 |
+
if not diarization or not transcriber or not summarizer:
|
30 |
+
raise ValueError("One or more models failed to load")
|
31 |
+
|
32 |
+
return diarization, transcriber, summarizer
|
33 |
+
except Exception as e:
|
34 |
+
st.error(f"Error loading models: {str(e)}")
|
35 |
+
st.error("Debug info: Check if HF token is valid and has necessary permissions")
|
36 |
+
return None, None, None
|
37 |
|
38 |
def process_audio(audio_file, max_duration=600):
|
39 |
+
try:
|
40 |
+
audio_bytes = io.BytesIO(audio_file.getvalue())
|
41 |
+
|
42 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
|
43 |
+
try:
|
44 |
+
if audio_file.name.lower().endswith('.mp3'):
|
45 |
+
audio = AudioSegment.from_mp3(audio_bytes)
|
46 |
+
else:
|
47 |
+
audio = AudioSegment.from_wav(audio_bytes)
|
48 |
+
|
49 |
+
# Standardize format
|
50 |
+
audio = audio.set_frame_rate(16000)
|
51 |
+
audio = audio.set_channels(1)
|
52 |
+
audio = audio.set_sample_width(2)
|
53 |
+
|
54 |
+
audio.export(
|
55 |
+
tmp.name,
|
56 |
+
format="wav",
|
57 |
+
parameters=["-ac", "1", "-ar", "16000"]
|
58 |
+
)
|
59 |
+
tmp_path = tmp.name
|
60 |
+
|
61 |
+
except Exception as e:
|
62 |
+
st.error(f"Error converting audio: {str(e)}")
|
63 |
+
return None
|
64 |
|
65 |
+
diarization, transcriber, summarizer = load_models()
|
66 |
+
if not all([diarization, transcriber, summarizer]):
|
67 |
+
return "Model loading failed"
|
68 |
|
69 |
+
with st.spinner("Identifying speakers..."):
|
70 |
+
diarization_result = diarization(tmp_path)
|
71 |
+
|
72 |
+
with st.spinner("Transcribing audio..."):
|
73 |
+
transcription = transcriber.transcribe(tmp_path)
|
74 |
+
|
75 |
+
with st.spinner("Generating summary..."):
|
76 |
+
summary = summarizer(transcription["text"], max_length=130, min_length=30)
|
77 |
|
78 |
+
os.unlink(tmp_path)
|
79 |
+
|
80 |
+
return {
|
81 |
+
"diarization": diarization_result,
|
82 |
+
"transcription": transcription,
|
83 |
+
"summary": summary[0]["summary_text"]
|
84 |
+
}
|
85 |
+
|
86 |
+
except Exception as e:
|
87 |
+
st.error(f"Error processing audio: {str(e)}")
|
88 |
+
return None
|
89 |
|
90 |
def format_speaker_segments(diarization_result):
|
91 |
+
if diarization_result is None:
|
92 |
+
return []
|
93 |
+
|
94 |
+
formatted_segments = []
|
95 |
+
try:
|
96 |
+
for turn, _, speaker in diarization_result.itertracks(yield_label=True):
|
97 |
+
formatted_segments.append({
|
98 |
+
'speaker': str(speaker), # Ensure string
|
99 |
+
'start': float(turn.start) if turn.start is not None else 0.0,
|
100 |
+
'end': float(turn.end) if turn.end is not None else 0.0
|
101 |
+
})
|
102 |
+
except Exception as e:
|
103 |
+
st.error(f"Error formatting segments: {str(e)}")
|
104 |
+
return []
|
105 |
+
|
106 |
+
return formatted_segments
|
107 |
|
108 |
def format_timestamp(seconds):
|
109 |
+
minutes = int(seconds // 60)
|
110 |
+
seconds = seconds % 60
|
111 |
+
return f"{minutes:02d}:{seconds:05.2f}"
|
112 |
|
113 |
def main():
|
114 |
+
st.title("Multi-Speaker Audio Analyzer")
|
115 |
+
st.write("Upload an audio file (MP3/WAV) up to 5 minutes long for best performance")
|
116 |
|
117 |
+
uploaded_file = st.file_uploader("Choose a file", type=["mp3", "wav"])
|
118 |
|
119 |
+
if uploaded_file:
|
120 |
+
file_size = len(uploaded_file.getvalue()) / (1024 * 1024)
|
121 |
+
st.write(f"File size: {file_size:.2f} MB")
|
122 |
+
|
123 |
+
st.audio(uploaded_file, format='audio/wav')
|
124 |
+
|
125 |
+
if st.button("Analyze Audio"):
|
126 |
+
if file_size > 200:
|
127 |
+
st.error("File size exceeds 200MB limit")
|
128 |
+
else:
|
129 |
+
results = process_audio(uploaded_file)
|
130 |
+
|
131 |
+
if results:
|
132 |
+
tab1, tab2, tab3 = st.tabs(["Speakers", "Transcription", "Summary"])
|
133 |
+
|
134 |
+
with tab1:
|
135 |
+
st.write("Speaker Timeline:")
|
136 |
+
segments = format_speaker_segments(results["diarization"])
|
137 |
+
|
138 |
+
if segments: # Only proceed if we have segments
|
139 |
+
for segment in segments:
|
140 |
+
col1, col2 = st.columns([2,8])
|
141 |
+
|
142 |
+
with col1:
|
143 |
+
try:
|
144 |
+
speaker_num = int(segment['speaker'].split('_')[1])
|
145 |
+
colors = ['🔵', '🔴'] # Two colors for alternating speakers
|
146 |
+
speaker_color = colors[speaker_num % len(colors)]
|
147 |
+
st.write(f"{speaker_color} {segment['speaker']}")
|
148 |
+
except (IndexError, ValueError) as e:
|
149 |
+
st.write(f"⚪ {segment['speaker']}")
|
150 |
+
|
151 |
+
with col2:
|
152 |
+
start_time = format_timestamp(segment['start'])
|
153 |
+
end_time = format_timestamp(segment['end'])
|
154 |
+
st.write(f"{start_time} → {end_time}")
|
155 |
+
|
156 |
+
st.markdown("---")
|
157 |
+
else:
|
158 |
+
st.warning("No speaker segments detected")
|
159 |
+
|
160 |
+
with tab2:
|
161 |
+
st.write("Transcription:")
|
162 |
+
if "text" in results["transcription"]:
|
163 |
+
st.write(results["transcription"]["text"])
|
164 |
+
else:
|
165 |
+
st.warning("No transcription available")
|
166 |
+
|
167 |
+
with tab3:
|
168 |
+
st.write("Summary:")
|
169 |
+
if results["summary"]:
|
170 |
+
st.write(results["summary"])
|
171 |
+
else:
|
172 |
+
st.warning("No summary available")
|
173 |
|
174 |
if __name__ == "__main__":
|
175 |
+
main()
|