Spaces:
Sleeping

mindSoftPro commited on
Commit
976ffc5
·
verified ·
1 Parent(s): 9589e86

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -41
app.py CHANGED
@@ -11,10 +11,9 @@ from pyannote.audio import Pipeline
11
  import openai
12
  import logging
13
  from datetime import datetime
 
14
  from fastapi import FastAPI, HTTPException, BackgroundTasks, Depends
15
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
16
- import boto3
17
- from botocore.exceptions import BotoCoreError, NoCredentialsError
18
 
19
  logging.basicConfig(
20
  level=logging.INFO,
@@ -24,8 +23,10 @@ logger = logging.getLogger(__name__)
24
 
25
  app = FastAPI()
26
 
 
27
  OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
28
  HUGGINGFACE_ACCESS_TOKEN = os.getenv('HUGGINGFACE_TOKEN')
 
29
 
30
  if not HUGGINGFACE_ACCESS_TOKEN:
31
  raise EnvironmentError("Hugging Face access token not found.")
@@ -41,11 +42,11 @@ if not AUTH_TOKEN:
41
  security = HTTPBearer()
42
 
43
  class DiarizeRequest(BaseModel):
44
- audio_source: str
45
- env: str
46
  speakers_quantity: Optional[int] = 2
47
  speech_to_text_source: Optional[str] = 'internal'
48
  webhook_url: Optional[str] = None
 
49
 
50
  class ProgressStatus:
51
  def __init__(self):
@@ -83,72 +84,216 @@ def update_progress(job_id: str, progress: float, step: str, status: str = "proc
83
  if status == "completed":
84
  progress_store[job_id].end_time = datetime.now()
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  def get_s3_client(env: str):
87
- """Отримання S3 клієнта з відповідними обліковими даними залежно від оточення"""
88
- aws_access_key_id = os.getenv(f"AWS_ACCESS_KEY_ID_{env.upper()}")
89
- aws_secret_access_key = os.getenv(f"AWS_SECRET_ACCESS_KEY_{env.upper()}")
90
- aws_region = os.getenv(f"AWS_REGION_{env.upper()}")
 
 
 
 
91
 
92
  if not aws_access_key_id or not aws_secret_access_key:
93
- raise EnvironmentError(f"S3 credentials for {env} not found.")
94
 
95
  return boto3.client(
96
  's3',
97
  aws_access_key_id=aws_access_key_id,
98
  aws_secret_access_key=aws_secret_access_key,
99
- region_name=aws_region if aws_region else None
100
  )
101
 
102
- def download_from_s3(audio_source: str, env: str) -> bytes:
103
- """Завантаження файлу з S3 за ключем"""
 
 
 
 
 
 
 
 
 
 
 
 
104
  try:
105
  s3_client = get_s3_client(env)
106
- bucket_name = os.getenv(f"S3_BUCKET_{env.upper()}")
107
-
108
- if not bucket_name:
109
- raise ValueError(f"S3 bucket for {env} is not set.")
110
-
111
- obj = s3_client.get_object(Bucket=bucket_name, Key=audio_source)
112
- return obj['Body'].read()
113
- except NoCredentialsError:
114
- raise ValueError("S3 credentials are incorrect or missing.")
115
- except BotoCoreError as e:
116
- raise ValueError(f"Error accessing S3: {e}")
117
  except Exception as e:
118
- raise ValueError(f"Unexpected error downloading from S3: {e}")
 
119
 
120
- def process_diarization(job_id: str, speakers_quantity: int, audio_source: str, speech_to_text_source: str, env: str, webhook_url: Optional[str] = None):
121
- """Оновлений процес обробки аудіо"""
122
- update_progress(job_id, 5, "Downloading audio file")
123
- audio_file = download_from_s3(audio_source, env)
124
 
125
- with tempfile.TemporaryDirectory() as temp_dir:
126
- temp_audio_file = os.path.join(temp_dir, 'temp_audio.wav')
127
- audio_segment = AudioSegment.from_file(io.BytesIO(audio_file))
128
- audio_segment.export(temp_audio_file, format='wav')
129
-
130
- update_progress(job_id, 100, "Completing process", "completed")
131
- return {"job_id": job_id, "status": "completed"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
  @app.post("/diarize")
134
- async def diarize_endpoint(diarize_request: DiarizeRequest, background_tasks: BackgroundTasks, credentials: HTTPAuthorizationCredentials = Depends(security)):
 
135
  try:
136
  job_id = f"job_{int(time.time())}"
137
  create_progress_tracker(job_id)
138
- 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)
139
- return {"status": "Processing started", "job_id": job_id, "message": "Check progress at /progress/{job_id}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  except Exception as e:
141
  raise HTTPException(status_code=500, detail=str(e))
142
 
143
  @app.get("/progress/{job_id}")
144
  async def get_progress(job_id: str):
 
145
  if job_id not in progress_store:
146
  raise HTTPException(status_code=404, detail="Job not found")
147
  return progress_store[job_id].to_dict()
148
 
149
  @app.get("/progress")
150
- async def get_progress():
 
151
  return {job_id: progress.to_dict() for job_id, progress in progress_store.items()}
152
 
153
- import uvicorn
154
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
11
  import openai
12
  import logging
13
  from datetime import datetime
14
+ import boto3
15
  from fastapi import FastAPI, HTTPException, BackgroundTasks, Depends
16
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
 
 
17
 
18
  logging.basicConfig(
19
  level=logging.INFO,
 
23
 
24
  app = FastAPI()
25
 
26
+ # Environment variables
27
  OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
28
  HUGGINGFACE_ACCESS_TOKEN = os.getenv('HUGGINGFACE_TOKEN')
29
+ DEFAULT_ENV = os.getenv('DEFAULT_ENVIRONMENT', 'dev') # Default to dev environment
30
 
31
  if not HUGGINGFACE_ACCESS_TOKEN:
32
  raise EnvironmentError("Hugging Face access token not found.")
 
42
  security = HTTPBearer()
43
 
44
  class DiarizeRequest(BaseModel):
45
+ audio_source: str # Key/path in the S3 bucket
 
46
  speakers_quantity: Optional[int] = 2
47
  speech_to_text_source: Optional[str] = 'internal'
48
  webhook_url: Optional[str] = None
49
+ env: Optional[str] = None # Environment parameter (dev/prod)
50
 
51
  class ProgressStatus:
52
  def __init__(self):
 
84
  if status == "completed":
85
  progress_store[job_id].end_time = datetime.now()
86
 
87
+ def send_webhook(webhook_url: str, data: Dict[str, Any]):
88
+ """Send results to webhook URL"""
89
+ try:
90
+ response = requests.post(
91
+ webhook_url,
92
+ json=data,
93
+ headers={'Content-Type': 'application/json',
94
+ 'Authorization': f'Bearer {HUGGINGFACE_ACCESS_TOKEN}'}
95
+ )
96
+ response.raise_for_status()
97
+ logger.info(f"Webhook sent successfully to {webhook_url}")
98
+ except Exception as e:
99
+ logger.error(f"Failed to send webhook: {e}")
100
+
101
  def get_s3_client(env: str):
102
+ """
103
+ Create an S3 client with environment-specific credentials
104
+ """
105
+ env = env.upper()
106
+
107
+ aws_access_key_id = os.getenv(f"AWS_ACCESS_KEY_ID_{env}")
108
+ aws_secret_access_key = os.getenv(f"AWS_SECRET_ACCESS_KEY_{env}")
109
+ aws_region = os.getenv(f"AWS_REGION_{env}")
110
 
111
  if not aws_access_key_id or not aws_secret_access_key:
112
+ raise ValueError(f"AWS credentials for environment '{env}' not found")
113
 
114
  return boto3.client(
115
  's3',
116
  aws_access_key_id=aws_access_key_id,
117
  aws_secret_access_key=aws_secret_access_key,
118
+ region_name=aws_region
119
  )
120
 
121
+ def get_bucket_name(env: str) -> str:
122
+ """Get the appropriate bucket name based on environment"""
123
+ return os.getenv(f"AWS_BUCKET_{env.upper()}")
124
+
125
+ def download_from_s3(file_key: str, env: str) -> bytes:
126
+ """Download file from AWS S3 using environment-specific credentials"""
127
+ env = env or DEFAULT_ENV
128
+ bucket_name = get_bucket_name(env)
129
+
130
+ if not bucket_name:
131
+ raise ValueError(f"Bucket name for environment '{env}' not found")
132
+
133
+ logger.info(f"Downloading file {file_key} from {bucket_name} bucket (env: {env})")
134
+
135
  try:
136
  s3_client = get_s3_client(env)
137
+ response = s3_client.get_object(Bucket=bucket_name, Key=file_key)
138
+ return response['Body'].read()
 
 
 
 
 
 
 
 
 
139
  except Exception as e:
140
+ logger.error(f"Error downloading file from S3: {e}")
141
+ raise ValueError(f"Failed to download file from S3: {e}")
142
 
143
+ def authenticate_bearer_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
144
+ if credentials.credentials != AUTH_TOKEN:
145
+ raise HTTPException(status_code=401, detail="Not authenticated")
 
146
 
147
+ def process_diarization(
148
+ job_id: str,
149
+ speakers_quantity: int,
150
+ audio_source: str,
151
+ speech_to_text_source: str,
152
+ env: Optional[str] = None,
153
+ webhook_url: Optional[str] = None
154
+ ) -> Dict[str, Any]:
155
+ """Process diarization with progress tracking"""
156
+ metrics = {
157
+ 'total_execution_time_sec': 0.0,
158
+ 'audio_conversion_time_sec': 0.0,
159
+ 'diarization_time_sec': 0.0,
160
+ 'transcription_time_sec': 0.0
161
+ }
162
+
163
+ total_start_time = time.perf_counter()
164
+ env = env or DEFAULT_ENV
165
+
166
+ try:
167
+ # Download audio from S3
168
+ update_progress(job_id, 5, f"Downloading audio file from S3 ({env} environment)")
169
+ audio_file = download_from_s3(audio_source, env)
170
+
171
+ with tempfile.TemporaryDirectory() as temp_dir:
172
+ # Convert audio
173
+ update_progress(job_id, 15, "Converting audio format")
174
+ audio_conversion_start = time.perf_counter()
175
+ temp_audio_file = os.path.join(temp_dir, 'temp_audio.wav')
176
+
177
+ audio_segment = AudioSegment.from_file(io.BytesIO(audio_file))
178
+ audio_segment.export(temp_audio_file, format='wav')
179
+
180
+ metrics['audio_conversion_time_sec'] = time.perf_counter() - audio_conversion_start
181
+
182
+ # Rest of the function remains the same
183
+ update_progress(job_id, 25, "Loading diarization model")
184
+ pipeline = Pipeline.from_pretrained(
185
+ "pyannote/speaker-diarization-3.1",
186
+ use_auth_token=HUGGINGFACE_ACCESS_TOKEN
187
+ )
188
+
189
+ update_progress(job_id, 40, "Performing speaker diarization")
190
+ diarization_start = time.perf_counter()
191
+ diarization = pipeline(temp_audio_file, num_speakers=speakers_quantity)
192
+ metrics['diarization_time_sec'] = time.perf_counter() - diarization_start
193
+
194
+ update_progress(job_id, 60, "Initializing transcription")
195
+ transcription_start = time.perf_counter()
196
+ dialogue = []
197
+
198
+ if speech_to_text_source == 'internal':
199
+ model = whisper.load_model("turbo")
200
+ elif speech_to_text_source == 'openai_api' and not openai_client:
201
+ raise ValueError("OpenAI API key not configured")
202
+
203
+ segments = list(diarization.itertracks(yield_label=True))
204
+ total_segments = len(segments)
205
+
206
+ for idx, (turn, _, speaker) in enumerate(segments, 1):
207
+ progress_percent = 60 + (idx / total_segments * 35)
208
+ update_progress(
209
+ job_id,
210
+ progress_percent,
211
+ f"Transcribing segment {idx}/{total_segments}"
212
+ )
213
+
214
+ segment = audio_segment[int(turn.start * 1000):int(turn.end * 1000)]
215
+
216
+ with tempfile.NamedTemporaryFile(suffix=".wav", dir=temp_dir, delete=True) as segment_file:
217
+ segment.export(segment_file.name, format="wav")
218
+
219
+ try:
220
+ if speech_to_text_source == 'internal':
221
+ result = model.transcribe(segment_file.name)
222
+ transcription = result['text'].strip()
223
+ else: # openai_api
224
+ with open(segment_file.name, "rb") as audio:
225
+ response = openai_client.audio.transcriptions.create(
226
+ model="whisper-1",
227
+ file=audio,
228
+ response_format='text'
229
+ )
230
+ transcription = response
231
+ except Exception as e:
232
+ transcription = f"[Transcription failed: {e}]"
233
+
234
+ dialogue.append(f"Speaker {speaker} [{turn.start:.2f}s - {turn.end:.2f}s]: {transcription}")
235
+
236
+ metrics['transcription_time_sec'] = time.perf_counter() - transcription_start
237
+ metrics['total_execution_time_sec'] = time.perf_counter() - total_start_time
238
+
239
+ result = {
240
+ 'job_id': job_id,
241
+ 'transcribed_text': '\n'.join(dialogue),
242
+ 'speaker_labels': sorted([f"Speaker {label}" for label in diarization.labels()]),
243
+ 'metrics': metrics
244
+ }
245
+
246
+ update_progress(job_id, 100, "Completing process", "completed", result)
247
+
248
+ if webhook_url:
249
+ send_webhook(webhook_url, result)
250
+
251
+ return result
252
+
253
+ except Exception as e:
254
+ error_msg = f"Error in diarization process: {str(e)}"
255
+ update_progress(job_id, 100, error_msg, "failed")
256
+ logger.error(error_msg)
257
+ raise
258
 
259
  @app.post("/diarize")
260
+ async def diarize_endpoint(diarize_request: DiarizeRequest, background_tasks: BackgroundTasks, credentials: HTTPAuthorizationCredentials = Depends(authenticate_bearer_token)):
261
+ """FastAPI endpoint for diarization"""
262
  try:
263
  job_id = f"job_{int(time.time())}"
264
  create_progress_tracker(job_id)
265
+
266
+ background_tasks.add_task(
267
+ process_diarization,
268
+ job_id,
269
+ diarize_request.speakers_quantity,
270
+ diarize_request.audio_source,
271
+ diarize_request.speech_to_text_source,
272
+ diarize_request.env,
273
+ diarize_request.webhook_url
274
+ )
275
+
276
+ return {
277
+ "status": "Processing started",
278
+ "job_id": job_id,
279
+ "message": "Check progress at /progress/{job_id}"
280
+ }
281
  except Exception as e:
282
  raise HTTPException(status_code=500, detail=str(e))
283
 
284
  @app.get("/progress/{job_id}")
285
  async def get_progress(job_id: str):
286
+ """Get progress for a specific job"""
287
  if job_id not in progress_store:
288
  raise HTTPException(status_code=404, detail="Job not found")
289
  return progress_store[job_id].to_dict()
290
 
291
  @app.get("/progress")
292
+ async def get_all_progress():
293
+ """Get progress for all jobs"""
294
  return {job_id: progress.to_dict() for job_id, progress in progress_store.items()}
295
 
296
+
297
+ if __name__ == "__main__":
298
+ import uvicorn
299
+ uvicorn.run(app, host="0.0.0.0", port=7860)