Spaces:
Sleeping
Sleeping
added download file from s3 by sdk
Browse files
app.py
CHANGED
|
@@ -13,6 +13,8 @@ import logging
|
|
| 13 |
from datetime import datetime
|
| 14 |
from fastapi import FastAPI, HTTPException, BackgroundTasks, Depends
|
| 15 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
|
|
|
|
|
| 16 |
|
| 17 |
logging.basicConfig(
|
| 18 |
level=logging.INFO,
|
|
@@ -40,6 +42,7 @@ security = HTTPBearer()
|
|
| 40 |
|
| 41 |
class DiarizeRequest(BaseModel):
|
| 42 |
audio_source: str
|
|
|
|
| 43 |
speakers_quantity: Optional[int] = 2
|
| 44 |
speech_to_text_source: Optional[str] = 'internal'
|
| 45 |
webhook_url: Optional[str] = None
|
|
@@ -80,172 +83,68 @@ def update_progress(job_id: str, progress: float, step: str, status: str = "proc
|
|
| 80 |
if status == "completed":
|
| 81 |
progress_store[job_id].end_time = datetime.now()
|
| 82 |
|
| 83 |
-
def
|
| 84 |
-
"""
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
json=data,
|
| 89 |
-
headers={'Content-Type': 'application/json',
|
| 90 |
-
'Authorization': f'Bearer {HUGGINGFACE_ACCESS_TOKEN}'}
|
| 91 |
-
)
|
| 92 |
-
response.raise_for_status()
|
| 93 |
-
logger.info(f"Webhook sent successfully to {webhook_url}")
|
| 94 |
-
except Exception as e:
|
| 95 |
-
logger.error(f"Failed to send webhook: {e}")
|
| 96 |
-
|
| 97 |
-
def download_from_url(url: str) -> bytes:
|
| 98 |
-
"""Download file from URL with error handling"""
|
| 99 |
-
try:
|
| 100 |
-
response = requests.get(url)
|
| 101 |
-
response.raise_for_status()
|
| 102 |
-
return response.content
|
| 103 |
-
except requests.exceptions.RequestException as e:
|
| 104 |
-
logger.error(f"Error downloading file from URL: {e}")
|
| 105 |
-
raise ValueError(f"Failed to download file from URL: {e}")
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
def authenticate_bearer_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 109 |
-
if credentials.credentials != AUTH_TOKEN:
|
| 110 |
-
raise HTTPException(status_code=401, detail="Not authenticated")
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
'transcription_time_sec': 0.0
|
| 125 |
-
}
|
| 126 |
-
|
| 127 |
-
total_start_time = time.perf_counter()
|
| 128 |
-
|
| 129 |
try:
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
audio_file = download_from_url(audio_source)
|
| 133 |
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
metrics['audio_conversion_time_sec'] = time.perf_counter() - audio_conversion_start
|
| 144 |
-
|
| 145 |
-
update_progress(job_id, 25, "Loading diarization model")
|
| 146 |
-
pipeline = Pipeline.from_pretrained(
|
| 147 |
-
"pyannote/speaker-diarization-3.1",
|
| 148 |
-
use_auth_token=HUGGINGFACE_ACCESS_TOKEN
|
| 149 |
-
)
|
| 150 |
-
|
| 151 |
-
update_progress(job_id, 40, "Performing speaker diarization")
|
| 152 |
-
diarization_start = time.perf_counter()
|
| 153 |
-
diarization = pipeline(temp_audio_file, num_speakers=speakers_quantity)
|
| 154 |
-
metrics['diarization_time_sec'] = time.perf_counter() - diarization_start
|
| 155 |
-
|
| 156 |
-
update_progress(job_id, 60, "Initializing transcription")
|
| 157 |
-
transcription_start = time.perf_counter()
|
| 158 |
-
dialogue = []
|
| 159 |
-
|
| 160 |
-
if speech_to_text_source == 'internal':
|
| 161 |
-
model = whisper.load_model("turbo")
|
| 162 |
-
elif speech_to_text_source == 'openai_api' and not openai_client:
|
| 163 |
-
raise ValueError("OpenAI API key not configured")
|
| 164 |
-
|
| 165 |
-
segments = list(diarization.itertracks(yield_label=True))
|
| 166 |
-
total_segments = len(segments)
|
| 167 |
-
|
| 168 |
-
for idx, (turn, _, speaker) in enumerate(segments, 1):
|
| 169 |
-
progress_percent = 60 + (idx / total_segments * 35)
|
| 170 |
-
update_progress(
|
| 171 |
-
job_id,
|
| 172 |
-
progress_percent,
|
| 173 |
-
f"Transcribing segment {idx}/{total_segments}"
|
| 174 |
-
)
|
| 175 |
-
|
| 176 |
-
segment = audio_segment[int(turn.start * 1000):int(turn.end * 1000)]
|
| 177 |
-
|
| 178 |
-
with tempfile.NamedTemporaryFile(suffix=".wav", dir=temp_dir, delete=True) as segment_file:
|
| 179 |
-
segment.export(segment_file.name, format="wav")
|
| 180 |
-
|
| 181 |
-
try:
|
| 182 |
-
if speech_to_text_source == 'internal':
|
| 183 |
-
result = model.transcribe(segment_file.name)
|
| 184 |
-
transcription = result['text'].strip()
|
| 185 |
-
else: # openai_api
|
| 186 |
-
with open(segment_file.name, "rb") as audio:
|
| 187 |
-
response = openai_client.audio.transcriptions.create(
|
| 188 |
-
model="whisper-1",
|
| 189 |
-
file=audio,
|
| 190 |
-
response_format='text'
|
| 191 |
-
)
|
| 192 |
-
transcription = response
|
| 193 |
-
except Exception as e:
|
| 194 |
-
transcription = f"[Transcription failed: {e}]"
|
| 195 |
-
|
| 196 |
-
dialogue.append(f"Speaker {speaker} [{turn.start:.2f}s - {turn.end:.2f}s]: {transcription}")
|
| 197 |
-
|
| 198 |
-
metrics['transcription_time_sec'] = time.perf_counter() - transcription_start
|
| 199 |
-
metrics['total_execution_time_sec'] = time.perf_counter() - total_start_time
|
| 200 |
-
|
| 201 |
-
result = {
|
| 202 |
-
'job_id': job_id,
|
| 203 |
-
'transcribed_text': '\n'.join(dialogue),
|
| 204 |
-
'speaker_labels': sorted([f"Speaker {label}" for label in diarization.labels()]),
|
| 205 |
-
'metrics': metrics
|
| 206 |
-
}
|
| 207 |
-
|
| 208 |
-
update_progress(job_id, 100, "Completing process", "completed", result)
|
| 209 |
-
|
| 210 |
-
if webhook_url:
|
| 211 |
-
send_webhook(webhook_url, result)
|
| 212 |
-
|
| 213 |
-
return result
|
| 214 |
-
|
| 215 |
except Exception as e:
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
@app.post("/diarize")
|
| 222 |
-
async def diarize_endpoint(diarize_request: DiarizeRequest, background_tasks: BackgroundTasks,
|
| 223 |
-
"""FastAPI endpoint for diarization"""
|
| 224 |
try:
|
| 225 |
job_id = f"job_{int(time.time())}"
|
| 226 |
create_progress_tracker(job_id)
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
return {
|
| 231 |
-
"status": "Processing started",
|
| 232 |
-
"job_id": job_id,
|
| 233 |
-
"message": "Check progress at /progress/{job_id}"
|
| 234 |
-
}
|
| 235 |
except Exception as e:
|
| 236 |
raise HTTPException(status_code=500, detail=str(e))
|
| 237 |
|
| 238 |
@app.get("/progress/{job_id}")
|
| 239 |
async def get_progress(job_id: str):
|
| 240 |
-
"""Get progress for a specific job"""
|
| 241 |
if job_id not in progress_store:
|
| 242 |
raise HTTPException(status_code=404, detail="Job not found")
|
| 243 |
return progress_store[job_id].to_dict()
|
| 244 |
|
| 245 |
-
@app.get("/progress")
|
| 246 |
-
async def get_progress():
|
| 247 |
-
return {job_id: progress.to_dict() for job_id, progress in progress_store.items()}
|
| 248 |
-
|
| 249 |
-
|
| 250 |
import uvicorn
|
| 251 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 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,
|
|
|
|
| 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
|
|
|
|
| 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
|
| 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 |
import uvicorn
|
| 150 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|