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
Related
I've been using Python and Selenium to try to automate an export process in Qualtrics. I have the web driver navigate to the login page, input my login credentials, and then navigate to the Data and Analytics page of the relevant survey. However, once I navigate to the Data and Analysis page, I'm having trouble selecting the element for the dropdown icon under the action header, which I need to click in order to export the responses.
I've tried to use this code (omitting the part where I login):
from selenium import webdriver
survey_url= {The Survey Url}
browser= webdriver.Chrome()
browser.get(survey_url)
browser.find_element_by_xpath("//div[#id='itemContext']").click()
However, I keep getting this error: NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[#id='itemContext']"}
I've tried using both the absolute (/html/body/div[6]) and the relative (//*[#id="itemContext"]) xpath given to me by inspect element, but neither worked.
This is the HTML that I see for the element:
<div id="itemContext" ng-click="removeSelf()" qmenu items="recordActions" on-select="selectRecordAction()(value,rowId, recordIndex)" class="response-context ng-scope ng-isolate-scope" style="left:1315px;top:357px">
<span ng-transclude></span></div>
Here is the HTML for the webpage:
<html ng-app="responses-client">
<head>
<meta charset="utf-8">
<title>Data | Qualtrics Experience Management</title>
<script>
(function (window) {
'use strict';
/*
* This function is used to attempt to get the initial definition before
* angular is loaded. If this fails for some reason the definition will
* still be loaded, but not via this function. See fast-definition-service.
*/
function rejectError(data, status, statusText) {
data = data || {};
window.fastDefinitionState = 'ERROR';
window.fastDefinitionError = {
status: status || 500,
statusText: statusText || 'Internal Server Error',
data: data,
config: {
method: 'GET',
url: url
}
};
}
function handleResponse() {
var status = request.status;
var data;
try {
data = JSON.parse(request.responseText);
} catch (e) {
data = request.responseText;
}
function handleSuccess() {
window.returnedDefinition = { data };
window.fastDefinitionState = 'SUCCESS';
}
if (status >= 200 && status < 400) {
return handleSuccess();
} else {
return rejectError(data, status, request.statusText);
}
}
function attemptRequest() {
request.open('GET', url, true);
request.onload = handleResponse; // Recieved response from server
request.onerror = rejectError; // Connection to server error
request.send();
window.fastDefinitionState = 'PENDING';
}
var surveyIdRegex = /surveys\/(SV_[a-zA-Z0-9]{15})/;
var canonicalId = (surveyIdRegex.exec(window.location.hash) || [])[1];
var fieldsetIdRegex = /fieldsets\/([\w-]+)/;
var fieldsetId = (fieldsetIdRegex.exec(window.location.hash) || [])[1];
var conjointIdRegex = /surveys\/SV_[a-zA-Z0-9]{15}\?conjointProjectId=(.+)/;
var conjointId = (conjointIdRegex.exec(window.location.hash) || [])[1];
var idpProjectRegex = /fieldsets\/[\w-]+\?(?:projectId|idpProjectId)=(IDP_.+|PROJ_.+)/;
var idpProjectId = (idpProjectRegex.exec(window.location.hash) || [])[1];
var resourceIdRegex = /surveys\/SV_[a-zA-Z0-9]{15}\?resourceId=(.+)/;
var resourceId = (resourceIdRegex.exec(window.location.hash) || [])[1];
var projectIdRegex = /surveys\/SV_[a-zA-Z0-9]{15}\?projectId=(.+)/;
var projectId = (projectIdRegex.exec(window.location.hash) || [])[1];
var url;
if (canonicalId) {
url = '/responses/surveys/' + canonicalId;
} else if (fieldsetId) {
url = '/responses/fieldsets/' + fieldsetId;
} else {
return rejectError(new Error('Missing surveyId for fast definition'));
}
if (conjointId) {
url += '?optProjectId=' + conjointId;
} else if (idpProjectId) {
url += '?idpProjectId=' + idpProjectId;
} else if (resourceId) {
url += '?resourceId=' + resourceId;
} else if (projectId) {
url += '?projectId=' + projectId;
}
window.fastDefinitionUrl = url;
var request = new XMLHttpRequest();
return attemptRequest();
})(window);
</script>
<link rel="icon" href="/brand-management/favicon">
<link rel="apple-touch-icon-precomposed" href="/brand-management/apple-touch-icon">
<link href="/responses/static/vendor/vendor.min.a113b2563.css" rel="stylesheet" type="text/css">
<link href="/responses/static/css/responsesclient.min.a49de54f5.css" rel="stylesheet" type="text/css">
</head>
<body ng-click="checkMenu()" ng-controller="MainController" keep-alive style="margin:0px;">
<div class="dp-container">
<div ng-view></div>
<div q-footer user-id="userId" language="userLanguage"></div>
</div>
</body>
<script src="/responses/static/vendor/vendor.min.a4f381856.js"></script>
<script src="/responses/static/js/responsesclient.min.ad8d40058.js"></script>
<script src="/wrapper/static/client.js"></script>
<script type="text/javascript" src="/project-workflow/static/bundle.js"></script>
<script type="text/javascript" src="https://static-assets.qualtrics.com/static/expert-review-ui/prod/response-iq.js"></script>
<script>
window.Qualtrics = {"User":{"brandId":"mindshare";
function hackAFixForProjectFramework() {
var surveyIdRegex = /surveys\/(SV_[a-zA-Z0-9]{15})/;
var fieldsetIdRegex = /fieldsets\/([\w-]+)/;
var canonicalId = (surveyIdRegex.exec(window.location.hash) || [])[1];
var fieldsetId = (fieldsetIdRegex.exec(window.location.hash) || [])[1];
window.Qualtrics.surveyId = canonicalId || fieldsetId;
}
// Hack a fix for updating to jquery 3.5 breaking project framework as they assumed it was ready sooner with jquery 3.5. Couldn't discover why, but it's somewhere in their code base.
hackAFixForProjectFramework();
var user = _.get(window, 'Qualtrics.User', {}),
requiredUserKeys = [
'userId',
'brandId',
'brandName',
'brandType',
'language',
'email',
'userName',
'firstName',
'lastName',
'accountType',
'accountCreationDate'
];
angular.module('responses-client').config([
'rsw.userServiceProvider',
function(userServiceProvider) {
try {
userServiceProvider.setUser(_.pick(user, requiredUserKeys));
} catch (e) {
console.log(e);
}
}
]);
</script>
</html>
I suspect the problem may be that the website is using a lot of javascript to dynamically change the responses. Above the HTML element I showed above, there are a bunch of "<'script type...'>" and src programs that I don't really understand, though I can guess from the names that they are handling the display of responses. Thinking it might be a loading problem, I've also tried making the program wait before searching for the element, but that didn't work either.
Cheers!
I have a function that loads user information including followers and following,
From that function, I go to the 2nd function that loads a button
on clicking the button it goes to the 3rd function that changes the value in the backend.
After updating the value, how can I change the innerHTML of the divs in my first function that loads the user info?
The goal is to show the new value without refreshing the page.
The function that loads the user info.
function load_user_info(user_clicked_on){
document.querySelector('#page-view').style.display = 'none';
document.querySelector('#posts-view').style.display = 'none';
document.querySelector('#show-posts').style.display = 'none';
document.querySelector('#load-profile').style.display = 'block';
fetch(`/profile/${user_clicked_on}`)
.then(response => response.json())
.then(profile => {
const profile_element = document.createElement('div');
const followers = document.createElement('div');
const following = document.createElement('div');
followers.innerHTML = 'Followers: ' + profile.followers;
following.innerHTML = 'Following: ' + profile.following;
profile_element.appendChild(followers);
profile_element.appendChild(following);
profile_element.classList.add('profile_element');
insert_follow_btn(user_clicked_on) // insert follow or unfollow button.
document.querySelector('#user-profile').appendChild(profile_element);
});
document.querySelector('#user-profile').innerHTML = `<h3>${user_clicked_on.charAt(0).toUpperCase() + user_clicked_on.slice(1)} Profile</h3>`;
}
the function that inserts a button and then when clicking on the button it goes to the 3rd function that updates the value in the backend.
function insert_follow_btn(user_clicked_on){
// For any other user who is signed in show the follow button
current_logged_in_user = document.querySelector('#user_detail').value;
if(user_clicked_on != current_logged_in_user){
const profile_buttons = document.createElement('div');
const follow_button = document.createElement('button');
fetch(`/following/${user_clicked_on}`)
.then(response => response.json())
.then(data => {
result = data.result
if(result == true){
follow_button.innerHTML += 'UnFollow'
profile_buttons.appendChild(follow_button);
follow_button.addEventListener("click", () => {
if(follow_button.innerHTML === 'Follow'){
follow_button.innerHTML = 'UnFollow'
}else{
follow_button.innerHTML = 'Follow'
}
unfollow_user(user_clicked_on)
});
}else{
follow_button.innerHTML += 'Follow'
profile_buttons.appendChild(follow_button);
follow_button.addEventListener("click", () => {
if(follow_button.innerHTML === 'Follow'){
follow_button.innerHTML = 'UnFollow'
}else{
follow_button.innerHTML = 'Follow'
}
follow_user(user_clicked_on)
});
}
})
profile_buttons.classList.add('profile_buttons');
document.querySelector('#user-profile').appendChild(profile_buttons);
console.log('Current profile:'+user_clicked_on+' Current logged in user: '+ current_logged_in_user);
}else{
return ``;
}
}
the function that updates on the backend
function follow_user(user_clicked_on){
fetch(`/follow/${user_clicked_on}`, {
method: 'PUT',
body: JSON.stringify({
user_clicked_on: user_clicked_on
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result.followers)
// How to update my followers.innerHTML in load_user_info function?
})
}
When you create the followers div inside load_user_info give it an id, like "followersdiv":
const followers = document.createElement('div');
followers.setAttribute("id", "followersdiv");
Then, inside the last function, follow_user, you can:
console.log(result.followers);
document.querySelector('#followersdiv').innerHTML='Followers: ' + result.followers;
Or
document.getElementById('followersdiv').innerHTML='Followers: ' + result.followers;
everyone. Hope everyone is safe. I have a question.
I'm building this email-like application with javascript as a project for CS50 Web.
Everything is working smoothly, but I have this "archive" button that should update the database, return to the "inbox" page and show the emails that are unarchived, and hide it otherwise.
However, after I click this archive button, it updates the database, returns to the inbox but it doesn't update the page. Once I refresh, it works.
I have a feeling this error has something to do with the fetch methods.
Can someone help me?
Any advice on how to improve my code would be highly appreciated as well.
function load_mailbox(mailbox) {
// Show the mailbox and hide other views
document.querySelector('#emails-view').style.display = 'flex';
document.querySelector('#compose-view').style.display = 'none';
document.querySelector('#emails-page').style.display = 'none';
document.querySelector('#emails-page').innerHTML = '';
// Show the mailbox name
document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;
// Fetch all emails
fetch('/emails/' + mailbox)
.then(response => response.json())
.then(emails => {
// Loop through all emails
emails.forEach(email => {
// Create elements and set the html content
const sender = document.createElement('p');
sender.innerHTML = `<strong>From:</strong> ${email.sender}`;
const subject = document.createElement('p');
subject.innerHTML = `<strong>Subject:</strong> ${email.subject}`;
const timestamp = document.createElement('p');
timestamp.innerHTML = email.timestamp;
const body = document.createElement('p');
body.innerHTML = email.body;
const recipient = document.createElement('p');
recipient.innerHTML = `<strong>To:</strong> ${email.recipients}`;
// Create archive button
const archive = document.createElement('button');
archive.className = "btn btn-light"
// Check if email is arquived or not, set the inner html for the button and change status if clicked.
if (email.archived === true) {
archive.innerHTML = "Unarchive"
archive.addEventListener('click', function () {
fetch('/emails/' + email.id, {
method: 'PUT',
body: JSON.stringify(
{ archived: false })
})
load_mailbox('inbox')
});
}
else {
archive.innerHTML = "Archive"
archive.addEventListener('click', function () {
fetch('/emails/' + email.id, {
method: 'PUT',
body: JSON.stringify(
{ archived: true })
})
load_mailbox('inbox')
});
}
// Create main div to hold all elements in the DOM
const element = document.createElement('div');
element.className = "div_email_view";
// Append elements fetch function returned.
element.appendChild(sender);
element.appendChild(subject);
element.appendChild(timestamp);
// Redirect to email page if div is clicked
element.addEventListener('click', function () {
// Hide other divs and show email page one.
document.querySelector('#emails-view').style.display = 'none';
document.querySelector('#compose-view').style.display = 'none';
document.querySelector('#emails-page').style.display = 'flex';
// Create reply button
const reply = document.createElement('button');
reply.innerHTML = "Reply Email"
reply.className = "btn btn-light"
// If reply is clicked, redirect to form in order to compose another email
reply.addEventListener('click', function () {
compose_email();
// Hide other divs
document.querySelector('#emails-page').style.display = 'none';
// Pre-fill form inputs with original email content
document.querySelector('#compose-recipients').value = `${email.sender}`;
if (email.subject.includes("Re:")) {
document.querySelector('#compose-subject').value = `${email.subject}`;
}
else {
document.querySelector('#compose-subject').value = `Re: ${email.subject}`;
}
document.querySelector('#compose-body').placeholder = `On ${email.timestamp}, ${email.sender} wrote: ${email.body}`;
})
// Fetch email that was clicked and and display its content
fetch('/emails/' + email.id)
.then(response => response.json())
.then(() => {
// Append all info related to that email
email_page = document.querySelector("#emails-page")
email_page.appendChild(sender);
email_page.appendChild(recipient);
email_page.appendChild(subject);
email_page.appendChild(body);
email_page.appendChild(timestamp);
// Get user email who's logged in
let user = localStorage.getItem('user')
// Append archive and reply buttons
if (user !== email.sender) {
email_page.appendChild(archive);
}
email_page.appendChild(reply);
// Set the "read" property to true if user has clicked on it to open.
if (email.read === false) {
fetch('/emails/' + email.id, {
method: 'PUT',
body: JSON.stringify({
read: true
})
})
}
})
});
// Append elements to inbox page
document.querySelector('#emails-view').append(element);
if (email.read === false) {
element.style.background = "#FAFAFA";
}
else {
element.style.background = "#E6E6E6";
}
});
});
}
This is supposed to handle the form validation for a simple contact form with name, email address, website url, and 10 line comment section for project description, then hand the information as a JSON object to a php file to send to a designated email address.
When I had action="emailprocessor.php in the HTML code, the form validation went through the PHP file and not JS, and it sent properly to the designated email address.
Without the action in the html, it's supposed to flow through the JS and then to the PHP. It's not doing that.
Here is my code:
(function () {
"use strict";
const contactForm = document.getElementById('contactform');
contactForm.addEventListener('submit', validateForm);
//Messages to be put in the message element when there is an error or success...
// The last element in this array loads the preloader css.
const feedBackMessage = [
'<div class="error"><h3>Ooops!</h3><p>The name field is reqired, that\'s how I know who you are. Please fix that and try again!</p></div>',
'<div class="error"><h3>Ooops!</h3><p>You forgot to give me a valid email address. Please fix that and try again!</p></div>',
'<div class="error"><h3>Ooops!</h3><p>You forgot to enter your website. Please fix that and try again!</p></div>',
'<div class="error"><h3>Ooops!</h3><p>Please enter your project description or comment.</p></div>',
'<div class="success"><h3>Thank you!</h3><p>Your information has been sent, and we will be in touch.</p></div>',
'<div class="preloader"><div class="loading-dot"></div></div>'
];
// The actual form validation function. Added url regex.
function validateForm(event) {
event.preventDefault();
const nameField = document.getElementById('name');
const emailField = document.getElementById('email');
const siteField = document.getElementById('website');
const commentField = document.getElementById('comment');
const reName = /^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/;
const reEmail = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;
const reUrl = /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/;
let errors = 0;
if (!reName.test(nameField.value)) {
displayMessage(nameField, feedBackMessage[0]);
errors++;
}
else if (!reEmail.test(emailField.value)) {
displayMessage(emailField, feedBackMessage[1]);
errors++;
}
else if (!reUrl.test(siteField.value)) {
displayMessage(siteField, feedBackMessage[2]);
errors++;
}
else if (commentField.value == "") {
displayMessage(commentField, feedBackMessage[3]);
errors++;
}
else if (errors === 0) {
sendData();
}
}
// This displays error / success messages
function displayMessage(field, message) {
document.getElementById('message').className = "show-message";
document.getElementById('message').innerHTML = message;
setTimeout(function () {
document.getElementById('message').classList.add("fadeOutElement");
setTimeout(function () {
if (field != 'success') {
document.getElementById('message').className = "hide-message";
document.getElementById(field.id).focus();
}
else {
document.getElementById('message').setAttribute("class", "hide-message");
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('website').value = '';
document.getElementById('comment').value = '';
}
}, 2000);
}, 2000);
//puts messages in the DOM??
}
function sendData() {
document.getElementById('message').className = "show-message";
document.getElementById('message').innerHTML = feedBackMessage[5];
setTimeout(async () => {
const formdata = new FormData(contactForm);
const fetchPromise = await fetch('emailprocessor.php', { method: 'POST', body: formdata });
const data = await fetchPromise.json();
console.log(data.result);
if (data.result == "success") {
displayMessage('success', feedBackMessage[4]);
}
}, 2000);
}
//actually sends the data asynchronously or so it claims
});
I have used Jsoup library to fetch the metadata from url.
Document doc = Jsoup.connect("http://www.google.com").get();
String keywords = doc.select("meta[name=keywords]").first().attr("content");
System.out.println("Meta keyword : " + keywords);
String description = doc.select("meta[name=description]").get(0).attr("content");
Elements images = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
String src = images.get(0).attr("src");
System.out.println("Meta description : " + description);
System.out.println("Meta image URl : " + src);
But I want to do it in client side using javascript
You can't do it client only because of the cross-origin issue. You need a server side script to get the content of the page.
OR You can use YQL. In this way, the YQL will used as proxy.
https://policies.yahoo.com/us/en/yahoo/terms/product-atos/yql/index.htm
Or you can use https://cors-anywhere.herokuapp.com. In this way, cors-anywhere will used as proxy:
For example:
$('button').click(function() {
$.ajax({
url: 'https://cors-anywhere.herokuapp.com/' + $('input').val()
}).then(function(data) {
var html = $(data);
$('#kw').html(getMetaContent(html, 'description') || 'no keywords found');
$('#des').html(getMetaContent(html, 'keywords') || 'no description found');
$('#img').html(html.find('img').attr('src') || 'no image found');
});
});
function getMetaContent(html, name) {
return html.filter(
(index, tag) => tag && tag.name && tag.name == name).attr('content');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Type URL here" value="http://www.html5rocks.com/en/tutorials/cors/" />
<button>Get Meta Data</button>
<pre>
<div>Meta Keyword: <div id="kw"></div></div>
<div>Description: <div id="des"></div></div>
<div>image: <div id="img"></div></div>
</pre>
Pure Javascript function
From node.js backend (Next.js) I use that:
export const fetchMetadata = async (url) => {
const html = await (await fetch(url, {
timeout: 5000,
headers: {
'User-Agent': 'request'
}
})).text()
var metadata = {};
html.replace(/<meta.+(property|name)="(.*?)".+content="(.*?)".*\/>/igm, (m,p0, p1, p2)=>{ metadata[p1] = decode(p2) } );
return metadata
}
export const decode = (str) => str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
})
You could use it on the client with https://cors-anywhere.herokuapp.com/corsdemo
You can use open-graph-scraper for this, for more info see this answer.