Spaces:
Sleeping

File size: 11,467 Bytes
7f186c5
 
 
 
 
 
 
 
 
 
 
 
 
976ffc5
b3b6af6
 
7f186c5
 
 
 
 
 
 
 
 
976ffc5
7f186c5
 
976ffc5
7f186c5
 
 
 
 
 
67aa9ab
 
 
 
5383670
 
 
 
 
 
 
 
 
 
 
 
67aa9ab
 
7f186c5
976ffc5
7f186c5
 
 
976ffc5
7f186c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
976ffc5
 
 
 
 
 
 
 
 
 
 
 
 
 
b2de802
976ffc5
 
 
 
 
 
 
 
67aa9ab
b2de802
976ffc5
b2de802
 
 
 
 
976ffc5
b2de802
 
976ffc5
 
 
 
 
 
 
 
 
 
 
 
 
 
7f186c5
b2de802
976ffc5
 
7f186c5
976ffc5
 
b2de802
976ffc5
 
 
b2de802
976ffc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b56da9
976ffc5
 
 
 
 
 
 
 
 
 
 
 
e45e60a
 
 
 
976ffc5
 
 
 
 
 
 
 
5666ed1
976ffc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f186c5
 
976ffc5
 
7f186c5
 
 
976ffc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f186c5
 
 
 
 
976ffc5
7f186c5
 
 
 
9589e86
976ffc5
 
9589e86
 
976ffc5
 
 
 
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
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import os
import io
import tempfile
import time
from typing import Any, Dict, Optional
import requests
from pydantic import BaseModel
from pydub import AudioSegment
import whisper
from pyannote.audio import Pipeline
import openai
import logging
from datetime import datetime
import boto3
from fastapi import FastAPI, HTTPException, BackgroundTasks, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

app = FastAPI()

# Environment variables
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
HUGGINGFACE_ACCESS_TOKEN = os.getenv('HUGGINGFACE_TOKEN')
DEFAULT_ENV = os.getenv('DEFAULT_ENVIRONMENT', 'dev')  # Default to dev environment

if not HUGGINGFACE_ACCESS_TOKEN:
    raise EnvironmentError("Hugging Face access token not found.")

progress_store = {}

AUTH_TOKEN = os.getenv("API_AUTH_TOKEN")
if not AUTH_TOKEN:
    raise EnvironmentError("API_AUTH_TOKEN is not set")

openai_client = openai.Client(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None

# Initialize models at server startup
logger.info("Loading diarization pipeline...")
pipeline = Pipeline.from_pretrained(
    "pyannote/speaker-diarization-3.1",
    use_auth_token=HUGGINGFACE_ACCESS_TOKEN
)

logger.info("Loading Whisper model...")
whisper_model = whisper.load_model("turbo")

security = HTTPBearer()

class DiarizeRequest(BaseModel):
    audio_source: str  # Key/path in the S3 bucket
    speakers_quantity: Optional[int] = 2
    speech_to_text_source: Optional[str] = 'internal'
    webhook_url: Optional[str] = None
    env: Optional[str] = None  # Environment parameter (dev/prod)

class ProgressStatus:
    def __init__(self):
        self.status = "initiated"
        self.progress = 0
        self.current_step = ""
        self.start_time = datetime.now()
        self.end_time = None
        self.result = None
    
    def to_dict(self):
        return {
            "status": self.status,
            "progress": self.progress,
            "current_step": self.current_step,
            "start_time": self.start_time.isoformat(),
            "end_time": self.end_time.isoformat() if self.end_time else None,
            "elapsed_time": str(datetime.now() - self.start_time) if not self.end_time else str(self.end_time - self.start_time),
            "result": self.result
        }

def create_progress_tracker(job_id: str) -> str:
    """Create a new progress tracker"""
    progress_store[job_id] = ProgressStatus()
    return job_id

def update_progress(job_id: str, progress: float, step: str, status: str = "processing", result: Any = None):
    """Update progress for a job"""
    if job_id in progress_store:
        progress_store[job_id].progress = progress
        progress_store[job_id].current_step = step
        progress_store[job_id].status = status
        if result:
            progress_store[job_id].result = result
        if status == "completed":
            progress_store[job_id].end_time = datetime.now()

def send_webhook(webhook_url: str, data: Dict[str, Any]):
    """Send results to webhook URL"""
    try:
        response = requests.post(
            webhook_url,
            json=data,
            headers={'Content-Type': 'application/json',
                     'Authorization': f'Bearer {HUGGINGFACE_ACCESS_TOKEN}'}
        )
        response.raise_for_status()
        logger.info(f"Webhook sent successfully to {webhook_url}")
    except Exception as e:
        logger.error(f"Failed to send webhook: {e}")

def get_s3_client(env: str):
    """
    Create an S3 client with environment-specific credentials
    """
    env = env.upper()
    
    aws_access_key_id = os.getenv(f"AWS_ACCESS_KEY_ID_{env}")
    aws_secret_access_key = os.getenv(f"AWS_SECRET_ACCESS_KEY_{env}")
    aws_region = os.getenv(f"AWS_REGION_{env}")
    
    if not aws_access_key_id or not aws_secret_access_key:
        raise ValueError(f"AWS credentials for environment '{env}' not found")
    
    return boto3.client(
        's3',
        aws_access_key_id=aws_access_key_id,
        aws_secret_access_key=aws_secret_access_key,
        region_name=aws_region
    )

def get_bucket_name(env: str) -> str:
    """Get the appropriate bucket name based on environment"""
    return os.getenv(f"AWS_BUCKET_{env.upper()}")

def download_from_s3(file_key: str, env: str) -> bytes:
    """Download file from AWS S3 using environment-specific credentials"""
    env = env or DEFAULT_ENV
    bucket_name = get_bucket_name(env)
    
    if not bucket_name:
        raise ValueError(f"Bucket name for environment '{env}' not found")
    
    logger.info(f"Downloading file {file_key} from {bucket_name} bucket (env: {env})")
    
    try:
        s3_client = get_s3_client(env)
        response = s3_client.get_object(Bucket=bucket_name, Key=file_key)
        return response['Body'].read()
    except Exception as e:
        logger.error(f"Error downloading file from S3: {e}")
        raise ValueError(f"Failed to download file from S3: {e}")

def authenticate_bearer_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    if credentials.credentials != AUTH_TOKEN:
        raise HTTPException(status_code=401, detail="Not authenticated")
    
def process_diarization(
    job_id: str,
    speakers_quantity: int,
    audio_source: str,
    speech_to_text_source: str,
    env: Optional[str] = None,
    webhook_url: Optional[str] = None
) -> Dict[str, Any]:
    """Process diarization with progress tracking"""
    metrics = {
        'total_execution_time_sec': 0.0,
        'audio_conversion_time_sec': 0.0,
        'diarization_time_sec': 0.0,
        'transcription_time_sec': 0.0
    }

    total_start_time = time.perf_counter()
    env = env or DEFAULT_ENV

    try:
        # Download audio from S3
        update_progress(job_id, 5, f"Downloading audio file from S3 ({env} environment)")
        audio_file = download_from_s3(audio_source, env)
        
        with tempfile.TemporaryDirectory() as temp_dir:
            # Convert audio
            update_progress(job_id, 15, "Converting audio format")
            audio_conversion_start = time.perf_counter()
            temp_audio_file = os.path.join(temp_dir, 'temp_audio.wav')
            
            audio_segment = AudioSegment.from_file(io.BytesIO(audio_file))
            audio_segment.export(temp_audio_file, format='wav')
            
            metrics['audio_conversion_time_sec'] = time.perf_counter() - audio_conversion_start

            # Rest of the function remains the same
            update_progress(job_id, 25, "Loading diarization model")
            
            update_progress(job_id, 40, "Performing speaker diarization")
            diarization_start = time.perf_counter()
            diarization = pipeline(temp_audio_file, num_speakers=speakers_quantity)
            metrics['diarization_time_sec'] = time.perf_counter() - diarization_start

            update_progress(job_id, 60, "Initializing transcription")
            transcription_start = time.perf_counter()
            dialogue = []

            if speech_to_text_source == 'openai_api' and not openai_client:
                raise ValueError("OpenAI API key not configured")

            segments = list(diarization.itertracks(yield_label=True))
            total_segments = len(segments)
            
            for idx, (turn, _, speaker) in enumerate(segments, 1):
                progress_percent = 60 + (idx / total_segments * 35)
                update_progress(
                    job_id, 
                    progress_percent, 
                    f"Transcribing segment {idx}/{total_segments}"
                )

                if (turn.end - turn.start) < 0.1:
                    dialogue.append(f"Speaker {speaker} [{turn.start:.2f}s - {turn.end:.2f}s]: [Too short to transcribe]")
                    continue
                
                segment = audio_segment[int(turn.start * 1000):int(turn.end * 1000)]
                
                with tempfile.NamedTemporaryFile(suffix=".wav", dir=temp_dir, delete=True) as segment_file:
                    segment.export(segment_file.name, format="wav")
                    
                    try:
                        if speech_to_text_source == 'internal':
                            result = whisper_model.transcribe(segment_file.name)
                            transcription = result['text'].strip()
                        else:  # openai_api
                            with open(segment_file.name, "rb") as audio:
                                response = openai_client.audio.transcriptions.create(
                                    model="whisper-1",
                                    file=audio,
                                    response_format='text'
                                )
                            transcription = response
                    except Exception as e:
                        transcription = f"[Transcription failed: {e}]"

                dialogue.append(f"Speaker {speaker} [{turn.start:.2f}s - {turn.end:.2f}s]: {transcription}")

            metrics['transcription_time_sec'] = time.perf_counter() - transcription_start
            metrics['total_execution_time_sec'] = time.perf_counter() - total_start_time

            result = {
                'job_id': job_id,
                'transcribed_text': '\n'.join(dialogue),
                'speaker_labels': sorted([f"Speaker {label}" for label in diarization.labels()]),
                'metrics': metrics
            }

            update_progress(job_id, 100, "Completing process", "completed", result)

            if webhook_url:
                send_webhook(webhook_url, result)

            return result

    except Exception as e:
        error_msg = f"Error in diarization process: {str(e)}"
        update_progress(job_id, 100, error_msg, "failed")
        logger.error(error_msg)
        raise

@app.post("/diarize")
async def diarize_endpoint(diarize_request: DiarizeRequest, background_tasks: BackgroundTasks, credentials: HTTPAuthorizationCredentials = Depends(authenticate_bearer_token)):
    """FastAPI endpoint for diarization"""
    try:
        job_id = f"job_{int(time.time())}"
        create_progress_tracker(job_id)
        
        background_tasks.add_task(
            process_diarization, 
            job_id, 
            diarize_request.speakers_quantity, 
            diarize_request.audio_source, 
            diarize_request.speech_to_text_source,
            diarize_request.env,
            diarize_request.webhook_url
        )
        
        return {
            "status": "Processing started",
            "job_id": job_id,
            "message": "Check progress at /progress/{job_id}"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/progress/{job_id}")
async def get_progress(job_id: str):
    """Get progress for a specific job"""
    if job_id not in progress_store:
        raise HTTPException(status_code=404, detail="Job not found")
    return progress_store[job_id].to_dict()

@app.get("/progress")
async def get_all_progress():
    """Get progress for all jobs"""
    return {job_id: progress.to_dict() for job_id, progress in progress_store.items()}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)