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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import requests
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import torch
|
| 6 |
+
from huggingface_hub import login
|
| 7 |
+
from pyannote.audio import Pipeline
|
| 8 |
+
from transformers import pipeline
|
| 9 |
+
from pydub import AudioSegment
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
HUGGINGFACE_HUB_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
|
| 14 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 15 |
+
|
| 16 |
+
if not HUGGINGFACE_HUB_TOKEN:
|
| 17 |
+
raise EnvironmentError("HUGGINGFACE_HUB_TOKEN not found in environment variables.")
|
| 18 |
+
|
| 19 |
+
# Authenticate with Hugging Face
|
| 20 |
+
login(token=HUGGINGFACE_HUB_TOKEN)
|
| 21 |
+
|
| 22 |
+
# === Initialize Pipelines ===
|
| 23 |
+
print("Initializing speaker diarization pipeline...")
|
| 24 |
+
diarization_pipeline = Pipeline.from_pretrained(
|
| 25 |
+
"pyannote/speaker-diarization-3.1",
|
| 26 |
+
use_auth_token=HUGGINGFACE_HUB_TOKEN
|
| 27 |
+
)
|
| 28 |
+
print("Diarization pipeline loaded successfully.")
|
| 29 |
+
|
| 30 |
+
print("Initializing transcription pipeline (Whisper)...")
|
| 31 |
+
transcription_pipeline = pipeline(
|
| 32 |
+
"automatic-speech-recognition",
|
| 33 |
+
model="openai/whisper-large-v3",
|
| 34 |
+
device=0 if torch.cuda.is_available() else -1
|
| 35 |
+
)
|
| 36 |
+
print("Transcription pipeline loaded successfully.")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def extract_audio_segment(audio_path, start_time, end_time):
|
| 40 |
+
"""
|
| 41 |
+
Extracts a segment from the audio file.
|
| 42 |
+
|
| 43 |
+
Parameters:
|
| 44 |
+
- audio_path: Path to the audio file.
|
| 45 |
+
- start_time: Start time in seconds.
|
| 46 |
+
- end_time: End time in seconds.
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
- BytesIO object containing the audio segment in WAV format.
|
| 50 |
+
"""
|
| 51 |
+
audio = AudioSegment.from_file(audio_path)
|
| 52 |
+
segment = audio[start_time * 1000 : end_time * 1000]
|
| 53 |
+
buffer = BytesIO()
|
| 54 |
+
segment.export(buffer, format="wav")
|
| 55 |
+
buffer.seek(0)
|
| 56 |
+
return buffer
|
| 57 |
+
|
| 58 |
+
def transcribe_segment(audio_segment, method='gradio'):
|
| 59 |
+
"""
|
| 60 |
+
Transcribes an audio segment using the specified method.
|
| 61 |
+
|
| 62 |
+
Parameters:
|
| 63 |
+
- audio_segment: BytesIO object containing the audio segment.
|
| 64 |
+
- method: 'gradio' or 'openai'
|
| 65 |
+
|
| 66 |
+
Returns:
|
| 67 |
+
- Transcribed text as a string.
|
| 68 |
+
"""
|
| 69 |
+
if method == 'gradio':
|
| 70 |
+
result = transcription_pipeline(audio_segment, return_timestamps=False)
|
| 71 |
+
return result.get("text", "No transcription available.")
|
| 72 |
+
elif method == 'openai':
|
| 73 |
+
headers = {
|
| 74 |
+
"Authorization": f"Bearer {OPENAI_API_KEY}"
|
| 75 |
+
}
|
| 76 |
+
files = {
|
| 77 |
+
"file": ("segment.wav", audio_segment, "audio/wav")
|
| 78 |
+
}
|
| 79 |
+
data = {
|
| 80 |
+
"model": "whisper-1"
|
| 81 |
+
}
|
| 82 |
+
response = requests.post(
|
| 83 |
+
"https://api.openai.com/v1/audio/transcriptions",
|
| 84 |
+
headers=headers,
|
| 85 |
+
files=files,
|
| 86 |
+
data=data
|
| 87 |
+
)
|
| 88 |
+
if response.status_code == 200:
|
| 89 |
+
return response.json().get("text", "No transcription available.")
|
| 90 |
+
else:
|
| 91 |
+
return f"Transcription failed: {response.text}"
|
| 92 |
+
else:
|
| 93 |
+
return "Invalid transcription method."
|
| 94 |
+
|
| 95 |
+
def process_audio(audio_file, resourceId, webhookUrl, transcription_method='gradio'):
|
| 96 |
+
"""
|
| 97 |
+
Processes the audio file by performing speaker diarization and transcription.
|
| 98 |
+
Sends the results to the specified webhook URL along with the resourceId.
|
| 99 |
+
|
| 100 |
+
Parameters:
|
| 101 |
+
- audio_file: Uploaded audio file.
|
| 102 |
+
- resourceId: Identifier for the resource.
|
| 103 |
+
- webhookUrl: URL to send the processed results.
|
| 104 |
+
- transcription_method: Method to use for transcription ('gradio' or 'openai')
|
| 105 |
+
|
| 106 |
+
Returns:
|
| 107 |
+
- Confirmation message indicating the status of the operation.
|
| 108 |
+
"""
|
| 109 |
+
start_time_total = time.time()
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
audio_path = "temp_audio"
|
| 113 |
+
with open(audio_path, "wb") as f:
|
| 114 |
+
f.write(audio_file.read())
|
| 115 |
+
|
| 116 |
+
diarization_start = time.time()
|
| 117 |
+
diarization_result = diarization_pipeline(audio_path)
|
| 118 |
+
diarization_time = time.time() - diarization_start
|
| 119 |
+
|
| 120 |
+
speaker_segments = []
|
| 121 |
+
for turn, _, speaker in diarization_result.itertracks(yield_label=True):
|
| 122 |
+
speaker_segments.append({
|
| 123 |
+
"speaker": speaker,
|
| 124 |
+
"start": turn.start,
|
| 125 |
+
"end": turn.end
|
| 126 |
+
})
|
| 127 |
+
|
| 128 |
+
transcription_start = time.time()
|
| 129 |
+
transcribed_text = ""
|
| 130 |
+
for segment in speaker_segments:
|
| 131 |
+
segment_audio = extract_audio_segment(
|
| 132 |
+
audio_path, segment["start"], segment["end"]
|
| 133 |
+
)
|
| 134 |
+
transcription = transcribe_segment(segment_audio, method=transcription_method)
|
| 135 |
+
transcribed_text += f"Speaker {segment['speaker']} [{segment['start']:.2f}s - {segment['end']:.2f}s]: {transcription}\n"
|
| 136 |
+
transcription_time = time.time() - transcription_start
|
| 137 |
+
|
| 138 |
+
total_execution_time = time.time() - start_time_total
|
| 139 |
+
|
| 140 |
+
metrics = {
|
| 141 |
+
"total_execution_time_sec": total_execution_time,
|
| 142 |
+
"audio_conversion_time_sec": 0.1,
|
| 143 |
+
"diarization_time_sec": diarization_time,
|
| 144 |
+
"transcription_time_sec": transcription_time
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
result_payload = {
|
| 148 |
+
"resourceId": resourceId,
|
| 149 |
+
"transcribed_text": transcribed_text.strip(),
|
| 150 |
+
"speaker_labels": list({f"Speaker {seg['speaker']}" for seg in speaker_segments}),
|
| 151 |
+
"metrics": metrics
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
headers = {"Content-Type": "application/json"}
|
| 155 |
+
response = requests.post(webhookUrl, json=result_payload, headers=headers)
|
| 156 |
+
response.raise_for_status()
|
| 157 |
+
|
| 158 |
+
return transcribed_text.strip()
|
| 159 |
+
|
| 160 |
+
except requests.exceptions.RequestException as req_err:
|
| 161 |
+
error_message = f"Failed to send data to webhook: {req_err}"
|
| 162 |
+
print(error_message)
|
| 163 |
+
return error_message
|
| 164 |
+
except Exception as e:
|
| 165 |
+
error_message = f"An error occurred during processing: {e}"
|
| 166 |
+
print(error_message)
|
| 167 |
+
return error_message
|
| 168 |
+
finally:
|
| 169 |
+
if os.path.exists(audio_path):
|
| 170 |
+
os.remove(audio_path)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
interface = gr.Interface(
|
| 174 |
+
fn=process_audio,
|
| 175 |
+
inputs=[
|
| 176 |
+
gr.Audio(type="file", label="Upload Audio File"),
|
| 177 |
+
gr.Textbox(label="Resource ID", placeholder="Enter Resource ID"),
|
| 178 |
+
gr.Textbox(label="Webhook URL", placeholder="https://your-webhook-url.com/endpoint"),
|
| 179 |
+
gr.Radio(
|
| 180 |
+
choices=["gradio", "openai"],
|
| 181 |
+
value="gradio",
|
| 182 |
+
label="Transcription Method",
|
| 183 |
+
info="Choose the method for transcription: 'gradio' uses the local Whisper model, 'openai' uses OpenAI's Whisper API."
|
| 184 |
+
)
|
| 185 |
+
],
|
| 186 |
+
outputs="text",
|
| 187 |
+
title="Unified Diarization and Transcription Service",
|
| 188 |
+
description=(
|
| 189 |
+
"Upload an audio file, provide a resource ID and a webhook URL. "
|
| 190 |
+
"Choose the transcription method, and the service will perform speaker diarization and transcription, then send the results to the specified webhook."
|
| 191 |
+
),
|
| 192 |
+
examples=[
|
| 193 |
+
[
|
| 194 |
+
"path/to/audio1.wav",
|
| 195 |
+
"resource_123",
|
| 196 |
+
"https://webhook.site/your-webhook-url",
|
| 197 |
+
"gradio"
|
| 198 |
+
],
|
| 199 |
+
[
|
| 200 |
+
"path/to/audio2.mp3",
|
| 201 |
+
"resource_456",
|
| 202 |
+
"https://webhook.site/your-webhook-url",
|
| 203 |
+
"openai"
|
| 204 |
+
]
|
| 205 |
+
],
|
| 206 |
+
allow_flagging="never"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if __name__ == "__main__":
|
| 211 |
+
interface.launch(share=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
requests
|
| 3 |
+
huggingface_hub
|
| 4 |
+
pyannote.audio
|
| 5 |
+
transformers
|
| 6 |
+
pydub
|
| 7 |
+
torch
|