I wanted to integrate my frontend code with my python backend functionality
This is my frontend code with html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Subtitle AI</title>
...
</head>
<body>
<div class="upload">
<h3>Step 1: upload a .wav file</h3>
<input id="wavFile" type="file" name="myFile" accept=".wav" />
<button id="submit-button">Submit</button>
</div>
<h3>Step 2: Wait for model to generate closed captioning</h3>
<p id="result"></p>
<script>
$("#submit-button").click(function(event) {
let parameter1 = {
return1: $("#wavFile").val(),
};
$.post(
"http://127.0.0.1:5000/predict",
JSON.stringify(parameter1),
function(transcription) {
$("#result").text(transcription.result);
console.log(transcription);
}
);
});
</script>
</body>
</html>
And this is my pytohn backend code functionality + attempted integration. I tried to integrate it with Flask, not sure what went wrong, but when I clicked the button, the return value from my python backend function is not displaying.
...
from flask import Flask
from flask import jsonify
app = Flask(__name__)
#app.route('/predict', methods=['POST'])
...
# define the prediction function which takes in the file path to a wav file and outputs the predicted words
def predict (model, device, path):
...
# decode the IDs to text
transcription = processor.decode(predicted_ids[0])
return jsonify(transcription)
Related
I would like to use flask to check when a button is pressed in an HTML coded website, the website will be up and running and the py app needs to be running too and wait for the button click, then on the button click, it will get the input content and print it. How do I do this?
this is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
</head>
<body>
<input type="hallo">
<button>Hallo</button>
</body>
</html>
I have searched for a while but nothing I tried worked, please help.
some code snippets would be great, thanks.
Use a simple form that is submitted with a post request.
The value from the input field is queried using the name attribute.
The button of type submit submits the form.
from flask import (
Flask,
render_template,
request
)
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
print(request.form.get('hallo'))
return render_template('index.html')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
</head>
<body>
<form method="post">
<input type="text" name="hallo" />
<button type="submit">Hallo</button>
</form>
</body>
</html>
I'm building a website in flask and python and I want to store the user's input in a variable, then output it onto the website screen.
This is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
<div><h1>Home Page</h1>
<p>Hello, {{ name }}</p>
</div>
<form>
<label for="fname">Enter Sq. ft.</label><br>
<input type="text" id="estimate" name="estimate" value="Ex. 1000"><br>
<input type="submit" value="Calculate Estimate">
</form>
Click me
</body>
</html>
and this is my python/flask code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/my-link/')
def my_link():
temp = 0
for i in range(10):
temp = i
return str(temp)
if __name__ == '__main__':
app.run(debug=True, port=8000)
When I run this, this is what I see:
When I type in 54 and hit "Calculate Estimate", I don't understand why I get http://127.0.0.1:8000/?estimate=54 in my search bar, I don't understand why it's going there. How would I be able to get that 54 and just print it on the website screen?
While I would recommend using POST if you're submitting sensitive data, GET suffices in your case.
To solve your issue, we have to first specify an action endpoint (by default, it's /, which loads too much responsibility onto one endpoint).
<form action="/calculate-estimate">
<label for="fname">Enter Sq. ft.</label><br>
<input type="text" id="estimate" name="estimate" value="Ex. 1000"><br>
<input type="submit" value="Calculate Estimate">
</form>
Second, we need to create a FLASK endpoint to handle the form data.
#app.route("/calculate-estimate", methods=["GET"])
def calculate_estimate():
estimate = request.args.get("estimate")
## Use your data however you desire.
This should be enough to solve your issue.
so I have tried to fix this internal server error for a few days now for a personal project and when I debug just says "NameError: name 'pred' is not defined". I have looked at other posts and such, but I haven't had any luck so far. Here is the code I have written:
!pip install flask-ngrok
from flask import Flask, render_template, request
from flask_ngrok import run_with_ngrok
import pickle
app = Flask(__name__, template_folder="templates")
run_with_ngrok(app)
def cloud_prediction(time):
model = pickle.load(open('model.pkl', 'rb'))
return float(model.forecast(time)[0][time-1])
#app.route("/", methods= ["GET", "POST"])
def final():
if request.method =="POST":
time = int(request.form["time"])
global pred
pred = cloud_prediction(time)
mypred= pred
print(mypred)
return render_template("index.html", name= mypred)
if __name__=="__main__":
app.run()
My index.html file is saved in a folder named templates, and it looks like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WeatherNexus Inc.</title>
<meta name="description" content="A fortune teller for cloud activity.">
<meta name="author" content="Jesus_Lopez">
<meta property="og:title" content="WeatherNexus Inc.">
<meta property="og:type" content="website">
<meta property="og:description" content="A fortune teller for cloud activity.">
</head>
<body>
<body bgcolor='black' text='white'>
<h1>WeatherNexus Inc.<h1>
<p>
<font size=15 class="text-center">
Please input the time when you want to predict the cloud coverage. Timesteps are in 5 min increments. Ex: 6 = 30min
</p>
<form action="/" method="POST">
<input type="number" name="time" placeholder="Input Time here">
<input type="submit">
<p>Here is your residual output: </p>{{name}}
</form>
</body>
</html>
The thing is, if I take "name = mypred" out of the render_template command, then the variable gets defined and prints in the notebook, but I'd like to print the result in the webpage not just in my notebook.
Thanks for any help or suggestions.
#app.route("/", methods= ['GET'])
def home():
return render_template('index.html')
This was needed before my final definition.
I have an html page, custom.html, and a python script, test.py (both screenshotted below). The html page only has a button that should trigger the python script to print a line (in my next python script I'd like it to do more but this is my starting point).
Under Chrome's developer tools, once I click the button, I receive a GET 404 error, initiated by Jquery. Any advice on successfully activating the python script from my html button is greatly appreciated.
My test.py script is simply
print("Successful line print")
Here is my custom.html document
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="../static/css/style2.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<pre>
</pre>
<body>
<div>
<div>
<button style="text-align: center; margin-bottom: 150px" class="search-btn" type="button" value=" Run Script " onclick="goPython()">Trigger Python
<script>
function goPython() {
$.ajax({
url: "../folder/test.py",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
</button>
</div>
</div>
</body>
</html>
EDIT: I am adding the code to my main.py script required for Google App Engine to handle URL calls and importing Flask.
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route("/")
def index():
return render_template('index.html')
#app.route("/learn.html")
def learn():
return render_template('learn.html')
#app.route("/custom.html")
def custom():
return render_template('custom.html')
if __name__ == "__main__":
app.run()
EDIT 2, after attempting #Dustin Ingram's answer:
Here is the new code to my custom.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="../static/css/style2.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div>
<div>
<button style="text-align: center; margin-bottom: 150px" class="search-btn" type="button" value=" Run Script " onclick="goPython()">Click Here
<script>
function goPython() {
$.ajax({
url: "/trigger-python",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
</button>
</div>
</div>
</body>
</html>
And I made a simple test.py just to test the ability for the html button click to activate the python script
from flask import Flask
app = Flask(__name__)
#app.route("/trigger-python")
def print_something():
print("Successful line print")
return 'OK'
print_something()
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
After fixing the URL called in AJAX, I'm still getting the same 404 error when clicking the button. Below is an updated Chrome Developer Tool screenshot.
You can't call a Python script via an AJAX request like that. You'll need to call a URL that corresponds to an endpoint of a Python web application.
So, for example, on the frontend:
$.ajax({
url: "/do-something",
context: document.body
})
and then on the backend there is a corresponding route:
#app.route("/do-something")
def do_something():
print("Successful line print")
return 'OK'
See https://cloud.google.com/appengine/docs/standard/python3/quickstart for details on getting started with Python web applications on App Engine.
EDIT: Here's exactly what I've tested and confirmed works:
app.yaml:
runtime: python37
requirements.txt:
Flask==1.1.2
main.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/custom.html')
def custom():
return render_template('custom.html')
#app.route("/trigger-python")
def print_something():
print("Successful line print")
return 'OK'
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
templates/custom.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="../static/css/style2.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div>
<div>
<button style="text-align: center; margin-bottom: 150px" class="search-btn" type="button" value=" Run Script " onclick="goPython()">Click Here
<script>
function goPython() {
$.ajax({
url: "/trigger-python",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
</button>
</div>
</div>
</body>
</html>
You can see it working here: https://stackoverflow-61195723.uc.r.appspot.com/custom.html
from flask import Flask,render_template,url_for
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/okay")
def okay():
return render_template("okay.html")
if __name__ == '__main__':
app.run(debug=True)
this is index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>index</h1>
<h2 onclick="{{ url_for('okay') }}">click me</h2>
<h2>click me</h2>
</body>
</html>
click me
this is not working
also
form action url_for is not working
change route and send message using socketio but socketio is working
how to solve this issue?
When used on a HTML element, onclick normally results to a call to a script function like this onclick=myFunction().
<body>
<h1>index</h1>
<h2 id="foo" onclick="myFunction();">click me</h2>
<h2>click me</h2>
</body>
You'll need to add some Javascript code for onclick=myFunction(); to work.
function myFunction() {
$.ajax({
url: '/okay',
data: JSON.stringify(data),
method: 'POST',
contentType: 'application/json',
success: function(data) {
$('#foo').replaceWith(data);
}
});
};