0

I am making a fake tweet prediction app in which i want to connect my front end with my back end using fast api but I am getting an error 405 i am new to java script as a student and this is my first front end app so please guide me through it this is the back end

class model_input(BaseModel):
    tweet : str

@app.post("/predict")
def predict(input_parameter: model_input):
    input_data = input_parameter.json()
    dict_parameter = json.loads(input_data)
    tweet = dict_parameter["tweet"]

    encoded_input = tokenizer.encode_plus(tweet, add_special_tokens=True, return_attention_mask=True)
    input_ids, attention_mask = encoded_input["input_ids"], encoded_input["attention_mask"]
    input_tensor: Tensor = torch.tensor([input_ids])
    attention_tensor = torch.tensor([attention_mask])
    model.eval()

    with torch.no_grad():
        outputs = model(input_tensor, attention_mask=attention_tensor)
        logits = outputs[0]
        predictions = torch.softmax(logits, dim=1)
    y
    predicted_class = torch.argmax(predictions).item()
    predicted_probability = predictions[0][predicted_class].item()

    if predicted_class == 1:
        response_text = 0
    else:
        response_text = 1
    response_data = {"prediction": response_text, "probability": predicted_probability}
    print(response_data)

    return response_data

and this is the front end

<!DOCTYPE html>
<html>
<head>
  <title>Text Classification</title>
</head>
<body>
  <h1>Text Classification</h1>
  <form>
    <label for="input-text">Enter text to classify:</label>
    <br>
    <textarea id="input-text" rows="4" cols="50"></textarea>
    <br>
    <button id="submit-button">Classify</button>
  </form>
  <div id="results"></div>
  <script>
    const inputText = document.getElementById('input-text');
    const submitButton = document.getElementById('submit-button');

    // Add an event listener to the submit button
    submitButton.addEventListener('click', function (event) {
      event.preventDefault();
      // Get the input text
      const text = inputText.value;
      // Send the text to the BERT-based model for classification
      classifyText(text);
    });

    function classifyText(text) {
      // Send a request to the server with the input text
      fetch('http://127.0.0.1:8000/predict', {
        method: 'POST',
        body: JSON.stringify({ tweet: text }),
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => response.json())
      .then(data => {
        // Get the results element
        const results = document.getElementById('results');
        // Clear any previous results
        results.innerHTML = '';
        // Display the results on the web page
        if (data.prediction === 1) {
          results.innerHTML = 'The text is Real';
        } 
        else if (data.prediction === 0) {
          results.innerHTML = 'The text is Fake';
        } 
        else {
          results.innerHTML = 'Error: Could not classify the text';
        }
      })
      .catch(error => {
        console.error(error);
        results.innerHTML = 'Error: ' + error;
      });
    }
  </script>
</body>
</html>

i tried to convert it to get method

  • Are your frontend and API running from the same origin? Are you seeing a CORS issue in the browser console? – Dennis Kats Jan 20 '23 at 09:01
  • yes my frontend and API are running on same origin. I tried a CORS extension doesn't work too. – Aditya Raj Jan 20 '23 at 10:28
  • Does this answer your question? [Can't access or print any request data with FastAPI](https://stackoverflow.com/questions/71563503/cant-access-or-print-any-request-data-with-fastapi) – Chris Jan 20 '23 at 12:00
  • Please take a look at [this answer](https://stackoverflow.com/a/73761724/17865804) and [this answer](https://stackoverflow.com/a/71741617/17865804) on how to submit JSON data to FastAPI backend using JavaScript Fetch API in the frontend. – Chris Jan 20 '23 at 12:04

0 Answers0