Мой проект Django запускается в Docker, и для обработки очередей я использую Celery. Когда пользователь отправляет аудиофайл, система запускает асинхронную задачу (которая расшифровывает аудио), постоянно проверяет ее ход и обновляет пользовательский интерфейс после завершения расшифровки с помощью кнопки загрузки. Однако я получаю сообщение об ошибке после завершения транскрипции, но до появления кнопки загрузки. Ошибка указывает на то, что не удается найти представление, предоставляющее пользователю завершенную расшифровку. Вот мой код.
views.py:
def initiate_transcription(request, session_id):
file_name = request.session.get('uploaded_file_name')
file_path = request.session.get('uploaded_file_path')
if request.method == 'GET':
if not file_name or not file_path:
return redirect(reverse('transcribeSubmit'))
if request.method == 'POST':
try:
if not file_name or not file_path:
return redirect(reverse('transcribeSubmit'))
audio_language = request.POST.get('audio_language')
output_file_type = request.POST.get('output_file_type')
if file_name and file_path:
print(str("VIEW: "+session_id))
task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id)
return JsonResponse({'status': 'success', 'task_id': task.id})
except Exception as e:
return JsonResponse({'status': 'error', 'error': 'No file uploaded'})
return render(request, 'transcribe/transcribe-complete-en.html')
def check_task_status(request, session_id, task_id):
task_result = AsyncResult(task_id)
if task_result.ready():
transcribed_doc = TranscribedDocument.objects.get(id=session_id)
return JsonResponse({
'status': 'completed',
'output_file_url': transcribed_doc.output_file.url
})
else:
return JsonResponse({'status': 'pending'})
JS:
form.addEventListener('submit', function(event) {
event.preventDefault();
const transcribeField = document.querySelector('.transcribe-output-lang-select')
const errorDiv = document.querySelector('.error-transcribe-div');
transcribeField.style.opacity = '0';
setTimeout(function() {
transcribeField.style.display = 'none';
transcribingFileField.style.display = 'block';
errorDiv.style.opacity = '0';
errorDiv.style.display = 'none';
}, 300);
setTimeout(function() {
transcribingFileField.style.opacity = '1'
}, 500);
const formData = new FormData(form);
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status == 200) {
const response = JSON.parse(xhr.responseText);
if (response.status === 'success') {
pollTaskStatus(response.task_id);
} else {
showError('An error occurred while initiating the transcription.');
}
} else {
showError('An error occurred while uploading the file.');
}
};
xhr.onerror = function() {
showError('An error occurred while uploading the file.');
};
xhr.open('POST', form.action, true);
xhr.send(formData);
});
function pollTaskStatus(taskId) {
const pollInterval = setInterval(() => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status == 200) {
const response = JSON.parse(xhr.responseText);
if (response.status === 'completed') {
clearInterval(pollInterval);
showCompletedUI(response.output_file_url);
}
}
};
xhr.open('GET', `/check_task_status/${taskId}/`, true);
xhr.send();
}, 5000); // Poll every 5 seconds
}
function showCompletedUI(outputFileUrl) {
const transcribingText = document.querySelector('.transcribing-text');
transcribingText.textContent = 'Transcript Completed';
const downloadBtn = document.querySelector('.download-btn');
downloadBtn.addEventListener('click', function() {
window.location.href = outputFileUrl;
this.innerHTML = 'Transcript downloaded!';
setTimeout(() => {
this.innerHTML = 'Click to download';
}, 3000);
});
}
function showError(message) {
const errorDiv = document.querySelector('.error-transcribe-div');
errorDiv.textContent = message;
errorDiv.style.opacity = '1';
errorDiv.style.display = 'block';
const transcribingFileField = document.querySelector('.transcribing-file-field');
transcribingFileField.style.opacity = '0';
transcribingFileField.style.display = 'none';
}
function showTranscriptionComplete(fileUrl) {
// Update UI to show transcription is complete
console.log('success')
const transcribingText = document.querySelector('.transcribing-text');
transcribingText.textContent = 'Transcript Completed';
const orderComplete = document.querySelector('.order-complete-data');
orderComplete.style.opacity = '0';
transcriptComplete = document.querySelector('.transcript-complete');
const transcriptSVG = document.querySelector('.transcript-svg');
setTimeout(function() {
orderComplete.style.display = 'none';
transcriptComplete.style.opacity = '1';
transcriptComplete.style.display = 'block';
transcribeLoader.style.opacity = '0';
transcribeLoader.style.display = 'none';
transcriptSVG.style.opacity = '1';
transcriptSVG.style.display = 'block';
}, 300);
let blob = new Blob([xhr.response], {type: xhr.getResponseHeader('Content-Type')});
let fileName = xhr.getResponseHeader('Content-Disposition').split('filename=')[1];
console.log(fileName);
// Set up download button
const downloadBtn = document.querySelector('.download-btn');
downloadBtn.addEventListener('click', function() {
download(blob, fileName);
this.innerHTML = 'Transcript downloaded!';
setTimeout(() => {
this.innerHTML = 'Click to download';
}, 3000);
}
)};
urls.py:
urlpatterns = [
path("", views.transcribeSubmit, name="transcribeSubmit"),
path("init-transcription//", views.initiate_transcription, name="initiate_transcription"),
path("check_task_status//", views.check_task_status, name="check_task_status"),
]
Вот журнал ошибок:
web-1 | Not Found: /check_task_status/02760416-c2fb-4526-b0d0-d5cdafabf8cf/
Подробнее здесь: https://stackoverflow.com/questions/786 ... rl-pattern