I am new to Python development.
I am trying to integrate ChatterBot in a webpage on my local host.
So to do this my first challenge is to establish a talk between a web page and Python script and I have achieved this.
The issue I am facing is - when I train ChatterBot using a list it shows verbose but I don't want those verbose on the webpage since they are of no use for the end user, so for this I tried logging.basicConfig with diifferent-2 logging levels but I am not able to hide logs.
Here is my webpage (index.html) :
<!DOCTYPE html>
<html>
<body>
<h2>Text Input</h2>
<form action = "chatbot.py" method = "POST" >
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<button type = "submit" >Submit</button>
</form>
<p>Note that the form itself is not visible.</p>
<p>Also note that the default width of a text input field is 20 characters.</p>
</body>
</html>
Here is chatbot.py
#!C:\Users\Shishupal\AppData\Local\Programs\Python\Python36-32\python.exe
# This program prints Hello, world!
from chatterbot import ChatBot
import logging
print("Content-Type: text/html")
print()
import cgi
print('Hello, world!')
logging.basicConfig(logging.INFO)
# Create a new chat bot named Charlie
chatbot = ChatBot(
'Charlie',
trainer='chatterbot.trainers.ListTrainer'
)
chatbot.train([
"Hi, can I help you?",
"Sure, I'd like to book a flight to Iceland.",
"Your flight has been booked."
])
# Get a response to the input text 'How are you?'
response = chatbot.get_response('I would like to book a flight.')
print(response)
Verbose that comes when I don't put or when I put logging.basicConfig(logging.INFO) in chatbot.py, so I want to hide these logs since they are of no use for end user.
Is there any Python expert over the Globe who can help me in sorting this out :)
You can hide the verbose output by changing the logging level.
Take a look at this line in your code:
logging.basicConfig(logging.INFO)
Right now, the logging level is INFO which prints everything.
You can choose a less verbose logging level such as WARNING, ERROR, or CRITICAL.
You can also remove the logging configuration line entirely to disable the verbose logging.
Related
This form shuld show the output on current page
<div class="form">
<form action="QA.py" method="POST" onsubmit="return false; >
<label for="form-search"></label>
<input type="text" id="form-search" placeholder="Search code ">
<!-- BUTTONS -->
<input type="submit" value="code Search" id="code_search" onclick = "processQuery()">
</form>
<p>Answer: </p>
<p id = 'output'></p>
</div>
Insted it just opens this code given billow
def main():
print("Hello,")
IN = input("query ")
QT = f"Q: {IN} ? A:"
response = openai.Completion.create(
model="text-davinci-003",
prompt=QT,
temperature=0,
max_tokens=64,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
stop=["\n\n"]
)
user will input query in form-search on Html page
after clicking submit query shuld go to QA.py Python code
in python code input quary shud be submited to "IN"
after python Proveieds "A:" output shuld seen in 'output
Insted it just opens QA.py
You are missing a quotation mark on the form OnSubmit. The resulting javascript error allows the form to submit to the specified action which is your python file.
The Python file will only execute if run on a webserver that is properly configured. It may be that your web server is not configured for Python, or that you are running the html as a local file (ie from disk, not via a web server), and thus your Python file gets served as a file rather than executed.
It would appear you are trying to run a submit through javascript on a button. In which case the form action isn't required. Instead your processQuery() function which you haven't shared needs to specify which file to exectue.
I am trying to create a webapp and am fairly new to it. I have a python script(file.py) that transforms data selected by a user. It handles all the inputs and outputs.
I am using flask(main.py) for the server part of it and html. I want to place a button in my html code so it will start the execution of the file.py. Can anyone assist me with an example setup for the connections between the 3?
I've looked at other examples but I'm unable to recreate it as they're doing different things. Also, file.py is fairly large so I want to avoid putting it into a function.
Edit: not looking for a flask tutorial. I've tried 3things:
A shell pops up for half a second but the disappears. Then I'm redirected to a page which just has the text in my return statement
in my html file
<form action="/pic" method="POST">
<input type="submit" value="GET THE SCRIPT">
</form>
in my main.py flask file
#app.route('/pic', methods=['GET', 'POST'])
def pic():
os.system("python file.py") #file.py is the script I'm trying to start
return "done"
Doesn't do anything at all.
in html file:
<input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
function goPython(){
$.ajax({
url: "/scripts/file.py",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
I get a GET "/scripts/file.py HTTP/1.1" 404 message. I have my scripts folder in the same directory as my templates folder. Also tried placing the scripts folder inside the templates folder.
in html
<form action="/run" method = "POST">
<input type="button" id='script' name="submit" value="Run Scripttttttt">
</form>
in flask main.py
#app.route('/run',methods=['GET', 'POST'])
def index():
def inner():
proc = subprocess.Popen(
['python file.py'],
shell=True,
stdout=subprocess.PIPE
)
for line in iter(proc.stdout.readline,''):
time.sleep(1)
yield line.rstrip() + '<br/>\n'
return Flask.Response(inner(), mimetype='text/html')
Using an HTML Anchor tag (i.e ) is the easiest way. Here is an example:
This is a link
But since you've chosen button, JavaScript will come in handy. Here's an example(inline):
<button onclick="window.location.href='your_flask_route';">
This is a link
</button>
and then in your flask main.py file you should have this:
#app.route('/your_flask_route')
def your_flask_route():
'''some lines of code'''
You can set up a Flask endpoint that your button can send a request to. Then let the endpoint's function call your python script.
Have a look at this discussion about Flask - Calling python function on button OnClick event and this discussion about How can I make one python file run another? to get you started.
I built an alexa skill using Python with Flask_ask, which goes to my DB and retrieves information that I need and spells it out.
I am now trying to create a web UI which would have an option of asking the required question by typing it in or speaking directly to alexa. The web UI works easily as it redirects to the page I want as below :
#app.route('/getdog')
def getdog():
return render_template('mypage.html')
Ideally I would configure an intent which would trigger the change in webpage e.g.
#ask.intent('myintent')
def changepage():
getdog()
Any ideas how to handle this?
You can use use a simple HTML form with a text input box:<form method="POST" action="/changepage/">
Enter Your Query: <input type="text" name="intent_string" />
<input type="submit" value="Ask Alexa"/>
</form>
Your changepage url should call a method which handles calling other intents based on whatever string has been passes in the POST request.
If you not able to exactly match the required intent to call you can add a full text search and match with that
I am trying to design and implement a basic calculator in HTML and Python(using CGI). Below given is a static HTML web page and it is being redirected to a python script (calci.py) where, I am able to calculate the sum but unable to append the resultant to the 'output' textbox.
calculator.html
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form action="python_scripts/calci.py" method="post">
Input 1 : <input type="text" name="input1"/><br>
Input 2 : <input type="text" name="input2"/><br>
<input type="submit" value="+" title="add" /><br>
output : <input type="text" name="output"/><br>
</form>
</body>
</html>
calci.py
import cgi
form = cgi.FieldStorage()
input1 = form.getvalue('input1')
input2 = form.getvalue('input2')
output = str(int(input1)+int(input2))
#how to return the response to the html
#and append it to the textbox
Thanks
This is not the way Web applications work - not hat simply, at least.
If you want to rely only on the browser, and plain HTML for your application, each request has to send the whole html page as a string. You have to use Python's string formatting capabilities to put the resulting number in the correct place in the HTML form.
This way of working is typical of "Web 1.0" applications (as opposed to the "Web 2.0" term used about ten years ago).
Modern web applications use logic that runs on the client side, in Javascript code, to make an HTTP request to retrieve only the needed data - and them, this client-side logic would place your result in the proper place in the page, without reloading the page. This is what isgenerally known as "ajax". It is not that complex, but the html + javascript side of the application become much more complex.
I think one should really understand the "Web 1.0" way before doing it the "Ajax way". in your case, let's suppose your HTML containing the calculator form is in a file called "calc.html". Inside it, where the result should lie, put a markup that can be understood by Python's built-in native string formatting methods, like {result} -
<html>
<body>
...
calculator body
...
Answer: <input type="text" readonly="true" value={result} />
</body>
</html>
And rewrite your code like:
import cgi
form = cgi.FieldStorage()
input1 = form.getvalue('input1')
input2 = form.getvalue('input2')
result = int(input1)+int(input2)
html = open("calc.html".read())
header = "Content-Type: text/html; charset=UTF-8\n\n"
output = header + html.format(result=result)
print (output)
The CGI way is outdated, but is nice for learning: it relies on your whole program being run, and whatever it prints to the standard output to be redirected to the HTTP request as a response. That includes the HTTP Headers, which are included, in a minimal form, above.
(I will leave the complete implementation of a way for the raw '{result}' string not to show up in the inital calculator form as an exercise from where you are 0- the path is to get the initial calculator html template through a CGI script as well, instead of statically, (maybe the same) as well - and just populate "result" with "0" or an empty string)
you can transfer response with the help of java script.
use under print("window.location=url")
i want to go from one page to another in my website using a button.
my code for this is like the following:
self.response.out.write('''<form
action="/sign" method=post> <br><input type=submit value="go to lesson 2 ">
</form>
''') % self.redirect("/lesson1")
now i am in lesson one page and i want using this button to go to lesson1 page but i keep getting this error:
PyDev breakpoint
inconsistent dedent at line 53, column 2
Bad Indentation (7 spaces)
does any one know how to fix this?
thanks
Amal
Aside from bad indentation and an errant attempt at using %, self.redirect(...) is done for effect, not to get a string you can use to embed elsewhere. What you've got it more properly divided into a get handler (to emit the form) and a post handler to do the redirect.
An alternative is to do the redirect in the browser, using JavaScript.
I got the correct answer using html.
I have two pages inside my website in google app engine and they are:
lesson1.py
lesson2.py
to go from lesson one to lesson using a button i put this code inside lesson1.py:
self.response.out.write('''<form action="/lesson2" method="get">
<input type="submit" value="go to lesson2" />
</form> ''')
application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
application = webapp.WSGIApplication([('/lesson1', MainHandler)],debug = True)
then in lesson2.py where i want to go i put this code:
application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
application = webapp.WSGIApplication([('/lesson2', MainHandler)],debug = True)
an important issue is the app.yaml file mine looks like this:
application: Sign-language version: 1
runtime: python
api_version: 1
handlers:
- url: /lesson2
script: lesson2.py
- url: /.*
script: lesson1.py
Use Preferences->Pydev->Editor and uncheck replace tabs with spaces. Tabs can be 4 spaces despite popular opinion that it should be changed to 8 spaces.