Покрой эту задачу try exceptions и выдай сообщение в sentry с помощью их sdk.
@shared_task
def process_file(file_id, user_id, language_code):
file_instance = get_object_or_404(File, id=file_id)
user = User.objects.get(id=user_id)
audio_file_path = convert_to_audio(file_instance.file.path)
code
Assistant
sentry_sdk.set_user({ # setting user for the sentry context
"id": user.id,
"email": user.email
})
if audio_file_path is None:
return
config = aai.TranscriptionConfig(
speaker_labels=True,
language_code=language_code,
)
transcriber = aai.Transcriber()
try:
audio_url = transcriber.upload_file(audio_file_path)
transcript = transcriber.transcribe(audio_url, config=config)
speakers = {}
for utterance in transcript.utterances:
if utterance.speaker not in speakers:
speakers[utterance.speaker] = create_or_get_speaker(
utterance.speaker, file_instance
)
transcription_text = transcript.text
process_transcription(transcript, file_instance, speakers)
action_type_id = TranscriptionActionType.objects.get_or_create(
name_en="Summary",
defaults={
"system_content": "You are a text summarization assistant that provides very concise summaries. "
"The summary must be under 180 characters.",
"user_content": "Provide a summary of the text '${text}' in ${language}. "
"You are a text summarization assistant that provides concise summaries. "
"Ensure the summary is under 180 characters and is written in the requested language.",
},
)[0].id
transcription_action_id = prompt.delay(
transcription_text, action_type_id, file_id, language_code
).get(disable_sync_subtasks=False)
s3_client.upload_file(audio_file_path, file_instance.s3_key)
file_instance.is_transcribed = True
file_instance.summary = TranscriptionAction.objects.get(
id=transcription_action_id
).content
file_instance.save()
FailedTranscriptionTask.objects.filter(file_id=file_id).delete()
subject = "Транскрибация файла готова!"
to_email = user.email
link_to_transcription = f"{APP_URL}/transcription/{file_id}/"
send_transcription_email.delay(
to_email,
re.match(r"^.{0,100}", transcription_text).group(0) + "...",
link_to_transcription,
file_instance.true_file_name,
subject,
)
except Exception as e:
error_message = f"An error occurred inside transcription: {e}"
print(error_message)
sentry_sdk.capture_message(f"Transcription has been failed: {e}", level="error")
failed_task, created = FailedTranscriptionTask.objects.get_or_create(
file=file_instance,
defaults={
'user': user,
'language_code': language_code,
'error_message': str(e),
'retry_count': 0,
}
)
if not created:
failed_task.error_message = str(e)
failed_task.retry_count += 1
failed_task.last_attempted_at = timezone.now()
failed_task.save()
return "error"
finally:
sentry_sdk.set_user(None)
cleanup_files([audio_file_path, file_instance.file.path])
Конечно! Вот обновлённая версия вашей функции process_file, где я добавил блоки try-except для обработки исключений и отправки сообщений в Sentry с помощью их SDK:
python
@shared_task
def process_file(file_id, user_id, language_code):
try:
file_instance = get_object_or_404(File, id=file_id)
user = User.objects.get(id=user_id)
audio_file_path = convert_to_audio(file_instance.file.path)
sentry_sdk.set_user({ # Установка пользователя для контекста Sentry
"id": user.id,
"email": user.email
})
if audio_file_path is None:
return
config = aai.TranscriptionConfig(
speaker_labels=True,
language_code=language_code,
)
transcriber = aai.Transcriber()
try:
audio_url = transcriber.upload_file(audio_file_path)
transcript = transcriber.transcribe(audio_url, config=config)
speakers = {}
for utterance in transcript.utterances:
if utterance.speaker not in speakers:
speakers[utterance.speaker] = create_or_get_speaker(
utterance.speaker, file_instance
)
transcription_text = transcript.text
process_transcription(transcript, file_instance, speakers)
action_type, _ = TranscriptionActionType.objects.get_or_create(
name_en="Summary",
defaults={
"system_content": (
"You are a text summarization assistant that provides very concise summaries. "
"The summary must be under 180 characters."
),
"user_content": (
"Provide a summary of the text '${text}' in ${language}. "
"You are a text summarization assistant that provides concise summaries. "
"Ensure the summary is under 180 characters and is written in the requested language."
),
},
)
transcription_action_id = prompt.delay(
transcription_text, action_type.id, file_id, language_code
).get(disable_sync_subtasks=False)
s3_client.upload_file(audio_file_path, file_instance.s3_key)
file_instance.is_transcribed = True
file_instance.summary = TranscriptionAction.objects.get(
id=transcription_action_id
).content
file_instance.save()
FailedTranscriptionTask.objects.filter(file_id=file_id).delete()
subject = "Транскрибация файла готова!"
to_email = user.email
link_to_transcription = f"{APP_URL}/transcription/{file_id}/"
preview_text = re.match(r"^.{0,100}", transcription_text).group(0) + "..."
send_transcription_email.delay(
to_email,
preview_text,
link_to_transcription,
file_instance.true_file_name,
subject,
)
except Exception as e:
error_message = f"An error occurred during transcription: {e}"
print(error_message)
sentry_sdk.capture_exception(e) # Отправка исключения в Sentry
failed_task, created = FailedTranscriptionTask.objects.get_or_create(
file=file_instance,
defaults={
'user': user,
'language_code': language_code,
'error_message': str(e),
'retry_count': 0,
}
)
if not created:
failed_task.error_message = str(e)
failed_task.retry_count += 1
failed_task.last_attempted_at = timezone.now()
failed_task.save()
return "error"
except Exception as e:
error_message = f"An unexpected error occurred: {e}"
print(error_message)
sentry_sdk.capture_exception(e) # Отправка неожиданного исключения в Sentry
return "error"
finally:
sentry_sdk.set_user(None)
cleanup_files([audio_file_path, file_instance.file.path])
Пояснения к изменениям:
Верхний блок try-except: Обернул всю функцию process_file в дополнительный блок try-except для отлова любых неожиданых исключений и отправки их в Sentry.
Использование sentry_sdk.capture_exception(e): Вместо sentry_sdk.capture_message лучше использовать capture_exception, чтобы отправить полную информацию об исключении, включая стек вызовов.
Очистка контекста пользователя в Sentry: В блоке finally добавил sentry_sdk.set_user(None), чтобы сбросить информацию о пользователе после обработки задачи.
Обработка исключений в функции prompt:
Также рекомендую добавить блоки try-except в функцию prompt, чтобы обеспечить обработку возможных ошибок:
Инициализация Sentry: Убедитесь, что Sentry правильно инициализирован в настройках вашего проекта Django, включая корректный DSN и другие необходимые параметры.
Логгирование исключений: Использование sentry_sdk.capture_exception(e) позволит вам получить более детальную информацию об ошибках, включая стек вызовов, что облегчит их отладку.
Обработка ошибок в асинхронных задачах: Всегда важно обрабатывать исключения в задачах Celery, чтобы они не приводили к неожиданным сбоям и позволяли системе корректно реагировать на ошибки.
Дополнительная информация:
Очистка временных файлов: Важно, чтобы временные файлы, такие как сконвертированные аудио, всегда удалялись после обработки, даже если произошла ошибка. Поэтому размещение cleanup_files в блоке finally гарантирует, что очистка произойдёт в любом случае.
Надеюсь, это поможет улучшить ваш код и обеспечить корректную обработку исключений с отправкой сообщений в Sentry!