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)