Запрос FastAPI POST к конечной точке /submit_response возвращает ошибку 404 Not FoundPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Запрос FastAPI POST к конечной точке /submit_response возвращает ошибку 404 Not Found

Сообщение Anonymous »

Вопрос:
Я разрабатываю приложение с использованием FastAPI и сталкиваюсь с ошибкой 404 Not Found при попытке отправить его. ответ на конечную точку /submit_response. Ниже приведены соответствующие части моего кода:
main.py:

Код: Выделить всё

from fastapi import FastAPI, HTTPException, Request, File, UploadFile, Form
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from typing import Optional
import uuid
from fastapi.middleware.cors import CORSMiddleware

# Import necessary functions from your utils file
from utils import *

app = FastAPI()

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

class ResponseModel(BaseModel):
question_id: str
response: str

@app.post("/submit_response")
async def submit_response(
session_id: str = Form(...),
audio: UploadFile = File(...)
):
session = get_session(session_id)

# Read the audio file
audio_content = await audio.read()

# Transcribe the audio
response = transcribe_audio(audio_content)

# Update the current scenario conversation with the candidate's response
session.current_scenario_conversation[-1] = (
session.current_scenario_conversation[-1][0],
session.current_scenario_conversation[-1][1],
response
)
save_conversation_to_file(session.interview_filename, session.current_scenario_conversation[-1])

# Retrieve the current trait and perform satisfaction check
trait = TRAITS[session.current_trait_index]
status, feedback = satisfaction_check(
session.agents["satisfaction_check"],
session.current_scenario_conversation[-1][1],
response,
trait['trait_name']
)

if status == "satisfied":
# If satisfied, score the scenario and move to the next trait/scenario
score = score_scenario(session.agents["scoring"], session.current_scenario_conversation, trait)
save_conversation_to_file(session.interview_filename, ("Score", score))
next_scenario = move_to_next_scenario(session)
return {
"message": "Moving to next scenario",
"question": next_scenario["question"] if "question" in next_scenario else None,
"score": score
}
elif status == "insufficient":
# If the response is insufficient, generate a follow-up question
if len(session.current_scenario_conversation) >= 2:
next_scenario = move_to_next_scenario(session)
return {
"message": "Moving to next scenario due to insufficient response",
"question": next_scenario["question"] if "question"  in next_scenario else None
}
else:
follow_up_question = generate_follow_up(
session.agents["follow_up"],
session.candidate_name,
session.current_scenario_conversation,
len(session.current_scenario_conversation),
insufficient=True
)
session.current_scenario_conversation.append(("Follow-Up", len(session.current_scenario_conversation), follow_up_question, ""))
save_conversation_to_file(session.interview_filename, session.current_scenario_conversation[-1])
return {
"message": "Follow-up question for insufficient response",
"question": follow_up_question
}
else:  # unsatisfied
# Generate a follow-up question for unsatisfactory response
follow_up_question = generate_follow_up(
session.agents["follow_up"],
session.candidate_name,
session.current_scenario_conversation,
len(session.current_scenario_conversation),
insufficient=False
)
session.current_scenario_conversation.append(("Follow-Up", len(session.current_scenario_conversation), follow_up_question, ""))
save_conversation_to_file(session.interview_filename, session.current_scenario_conversation[-1])

if len(session.current_scenario_conversation) >= 3:
next_scenario = move_to_next_scenario(session)
return {
"message": "Moving to next scenario after follow-up",
"question": next_scenario["question"] if "question" in next_scenario else None
}

return {
"message": "Follow-up question for unsatisfactory response",
"question": follow_up_question
}

@app.get("/")
async def read_root():
return {"message": "Hello, World!"}
utils.py:

Код: Выделить всё

def transcribe_audio(audio_content):
client = speech_v1.SpeechClient.from_service_account_json(credentials_file)

audio = types.RecognitionAudio(content=audio_content)
config = types.RecognitionConfig(
encoding=types.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code='en-US'
)

response = client.recognize(config=config, audio=audio)

transcript = ""
for result in response.results:
transcript += result.alternatives[0].transcript

return transcript
index.js:

Код: Выделить всё

const submitResponse = async (audioBlob) => {
const formData = new FormData();
formData.append('audio', audioBlob, 'response.wav');
formData.append('session_id', sessionId);

try {
const response = await fetch('http://localhost:8000/submit_response', {
method: 'POST',
body: formData,
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();
logConversation('Candidate', 'Audio Response');

if (data.message === 'Interview completed') {
alert('Interview completed. Thank you for your participation!');
resetInterview();
} else {
displayQuestion(data.question);
if (data.score) {
setScenarioScore(data.score);
logConversation('System', `Scenario score: ${data.score}`);
}
if (data.message) {
logConversation('System', data.message);
}
}
} catch (error) {
console.error('Error:', error);
alert('An error occurred while submitting your response.  Please try again.');
}
};
Когда я пытаюсь отправить POST-запрос на http://localhost:8000/submit_response, в журналах появляется следующая ошибка:

Код: Выделить всё

INFO:main:Request: POST http://localhost:8000/submit_response
INFO:__main__:Response status: 404
INFO: 127.0.0.1:52983 - "POST /submit_response HTTP/1.1" 404 Not Found
Я подтвердил, что сервер FastAPI работает и конечная точка / работает нормально. Что может быть причиной ошибки 404 Not Found для конечной точки /submit_response?

Подробнее здесь: https://stackoverflow.com/questions/787 ... ound-error
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Заголовок: Конечная точка Spring Boot API возвращает 404 Not Found для запроса на регистрацию (без баз данных)
    Anonymous » » в форуме JAVA
    0 Ответы
    23 Просмотры
    Последнее сообщение Anonymous
  • Как устранить ошибку «HTTP Error 404.3 — Not Found»?
    Anonymous » » в форуме C#
    0 Ответы
    65 Просмотры
    Последнее сообщение Anonymous
  • Развернутые функции Azure возвращают ошибку 404 Not Found.
    Anonymous » » в форуме C#
    0 Ответы
    20 Просмотры
    Последнее сообщение Anonymous
  • Почему я получаю ошибку 404 Not Found в Thymeleaf при использовании SpringBoot
    Anonymous » » в форуме JAVA
    0 Ответы
    21 Просмотры
    Последнее сообщение Anonymous
  • Почему я получаю ошибку 404 Not Found в Thymeleaf при использовании SpringBoot
    Anonymous » » в форуме JAVA
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»