Send Image from Flask to HTML is not successful - html

I would like to send image with Flask app when I click to predict button in my html code.
Code is supposed to get prompt and run ML model and generate image based on input prompt. I can generate the picture but somehow I can not send it to html or html doesn't show the image.
Anyone can check my flask and html code where the problem is ? My flask image send method is wrong or html part is wrong ? How to show the image in html ?
import os
import io
import base64
from PIL import Image
import torch
from torch import autocast
from diffusers import StableDiffusionPipeline, LMSDiscreteScheduler
import transformers
from flask import Flask, render_template, request
app = Flask(__name__)
lms = LMSDiscreteScheduler(
beta_start=0.00085,
beta_end=0.012,
beta_schedule="scaled_linear"
)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
pipe = StableDiffusionPipeline.from_pretrained(
"CompVis/stable-diffusion-v1-4",
scheduler=lms,
use_auth_token=True,
cache_dir=os.getenv("cache_dir", "./models")
).to("cuda")
#app.route('/', methods=['GET'])
def page_template():
return render_template('index.html')
#app.route('/', methods=['POST'])
def predict():
prompt_text = request.form['word']
with autocast("cuda"):
image = pipe(prompt_text)["sample"][0]
data = io.BytesIO()
image.save(data, "JPEG")
encoded_img_data = base64.b64encode(data.getvalue())
return render_template("index.html", img_data=encoded_img_data.decode('utf-8'))
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html>
<head>
<title>Tutorial</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<h1 class="text-center">Stable Diffusion</h1>
<form class="p-3 text-center" action='/', method="post" enctype="multipart/form-data" >
<label for="promptfield" class="form-label">StableDiffusionPrompt</label>
<input type="text" class="form-control" id="promptfield" name="word" placeholder="Please enter your prompt" />
<input class="form-control" type="file" name="imagefile" >
<input class="btn btn-primary mt-3" type="submit" value="Predict Image" >
</form>
{% if prediction %}
<img id="picture" src="data:image/jpeg;base64,{{ img_data }}">
<p> img id="picture" src="data:image/jpeg;base64,{{ img_data }}"</p>
{% endif %}
</body>
</html>

here is the output of encoded_img_data.decode('utf-8').

Related

Why can't my flask app.py render_template a html file on chrome extension popup?

I have the following app.py code
from flask import Flask, render_template, request, jsonify
import numpy as np
from joblib import load
import pandas as pd
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
#app.route('/predict', methods=['POST'])
def predict():
t = request.form['reviewfield']
text = [t]
pipeline = load("ModelSVMNew.joblib")
pred = pipeline.predict(text)
return render_template('after.html', data=pred)
if __name__ == "__main__":
app.run(port=3000, debug=True)
and i want a form to submit the text from chrome extension to predict function and render the html in place of the popup.html (as in manifest.json). now this works with a normal web page on local host but gives an error that the file is not accessible when doing the same on chrome extension.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fake Review Detection</title>
</head>
<body>
<center>
<h1>Fake Review Detection</h1>
<form action="{{url_for('predict')}}" method="post">
<b> Enter Review: <input type="text" name="reviewfield" /></b> <br />
<br />
<input type="submit" value="Predict" />
</form>
</center>
</body>
</html>

Have CSS connected in HTML in a Flask project

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<div class = "tela">
<h1>Login</h1>
<form action="/" method = "post">
<input class = "inf" type="text" placeholder="Email">
<br><br>
<input class = "inf" type="password" placeholder="Senha">
<br><br>
<button class = "main-btt">Log in</button>
</form>
<form action="/criarconta" method="post">
<button class = "criar">Criar conta</button>
</form>
</div>
</body>
</html>
from flask import Flask, request, render_template, redirect
app = Flask("__name__")
#app.route("/")
def index():
return render_template("login.html")
#app.route("/criarconta", methods=["POST"])
def create():
return render_template("criarconta.html")
I'm working on a Login page, with flask, html and css, but always that I run flask the link that shows up is a html page without css, even when I link css in the html file. I want to resolve tis, and finds out how to open the page and the css is there. OBS: When I open the file alone, without flask, it works.
I tried using href="styles.css" but it didn't work so I changed for url_for, but its still not working.
I think the problem is in the html but I putted the python if you need.

werkzeug.routing.BuildError: with flask app image gallery

I am following this video to create an image gallery using flask and python https://www.youtube.com/watch?v=yO_XNCsBIsg&t=636s
I these github files for (coppied the #app.route('/gallery')) app.py and gallery.html and ran the exact code but I am getting an error:
werkzeug.routing.BuildError: Could not build url for endpoint 'send_image' with values ['filename']. Did you mean 'index' instead?
Here is my exact code
main.py
#!/usr/bin/env python
from flask import Flask, request, send_from_directory, flash, redirect, render_template, request, url_for,jsonify
#https://stackoverflow.com/questions/32019733/getting-value-from-select-tag-using-flask
# reference to code is from https://pythonprogramming.net/jquery-flask-tutorial/
# and from https://www.blog.pythonlibrary.org/2017/12/13/flask-101-how-to-add-a-search-form/
app = Flask(__name__)
# this runs in the background for registering the compnay link that was put in
#app.route('/background_process')
def background_process():
lang = request.args.get('proglang', 0, type=str)
#just checking what was typed, this will be put into a python code eventrually
return jsonify(result=lang)
#app.route('/')
def index():
return render_template('interactive.html', data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}])
filename = request.args.get('proglang')
#app.route("/black" , methods=['GET', 'POST'])
def black():
select = request.form.get('comp_select')
if select=="blue":
return(str("hi")) # just to see what select is
else:
return(str("bye"))
import os
#app.route('/gallery')
def get_gallery():
image_names = os.listdir('./images')
print(image_names)
return render_template("gallery.html", image_names=image_names)
if __name__=='__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
gallery.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Thumbnail Gallery</h1>
</div>
{{image_names}}
<hr>
{% for image_name in image_names %}
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<img class="img-responsive" src=" {{url_for('send_image', filename=image_name)}}">
</div>
{% endfor %}
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous"></script>
</body>
</html>
I'm leaving out my other html files because they aren't needed for my testing of the gallery route.
You are missing the "send_image" route in your Python code:
#app.route('/upload/<filename>')
def send_image(filename):
return send_from_directory("images", filename)

GET data from HTML and process in python using Flask and POST back in same HTML

hi i am trying to implement a chat type module. My front end in a HTML page from which i GET a data. The obtained data is passed to python flask. And finally the processed data must be posted back to the same HTML page.
I am able to GET the data. But unable to post it back to the same HTML page.
the following is the HTML code
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function ajaxcall(){
var p_name = $('#p_name').val();
var p_email = $('#p_email').val();
$.post("http://127.0.0.1:5000/getdata?chatbox="+p_name);
}
</script>
</head>
<form action="" method="POST" name='chat'>
<div>
{{text_typed}}
</div>
Enter Chat: <textarea id="p_name" name="chatbox" rows="4" cols="50"></textarea>
<input type="button" onclick="ajaxcall()" value="submit me!" />
<label name='get_test' id='get_test'></label>
</form>
</html>
the value entered in the text area must be posted in {{text_typed}}. i am unable to get this
this is my python flask coding [i am performing this in a local environment]
from flask import Flask, jsonify, request, render_template, flash, url_for, redirect #import objects from the Flask model
app = Flask(__name__) #define app using Flask
#app.route('/')
def hello():
print("hello")
return "Welcome to mychat.in"
#app.route('/chat', methods=['GET', 'POST'])
def chat():
return render_template("getpost.html")
#app.route('/getdata', methods=['GET', 'POST'])
def getdata():
print('hi')
text_typed = request.args.get('chatbox')
print(text_typed)
return render_template("getpost.html", text_typed = text_typed)# this is the line i am trying to post back in html
if __name__ == '__main__':
app.run()
Thanks in advance.
Update your JS code:
$.post("http://127.0.0.1:5000/getdata?chatbox="+p_name);
According to the jQuery documentation you should put it as
$.post("http://127.0.0.1:5000/getdata?chatbox="+p_name, null, function(data) {
Put your code to insert returned _data_ into the form here.
});

Django form not being submitted

I have a Django model/view/form that is rendering correctly in the template, but it is not submitting the data that is input to the database. Any help with this would be greatly appreciated!
#models.py
from django.db import models
from django.forms import ModelForm
class UserRegistration(models.Model):
user_first = models.CharField(max_length=50)
user_last = models.CharField(max_length=50)
user_email = models.EmailField()
#user_fantasyhost = models.CharField(max_length=50)
def __unicode__(self):
return u'%s %s %s' % (self.user_first, self.user_last, self.user_email)
class RegForm(ModelForm):
class Meta:
model = UserRegistration
#views.py
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from acme.dc_django.models import UserRegistration
from acme.dc_django.models import RegForm
def regPage(request, id=None):
form = RegForm(request.POST or None,
instance=id and UserRegistration.objects.get(id=id))
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/league_setup/')
user_info = UserRegistration.objects.all()
context = {
'form':form,
'user_info' :user_info,
}
return render(request, 'regpage.html', context)
#repage.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML lang="en">
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="/league/">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Create Account"
</form><br /><br />
</body>
</HTML>
Thank you for your help,
dp
I tried your code. Your problem is that the action attribute of your html form tag is set to "/league/".
Unless reqPage url is actually "/league/", it won't work. When i changed action="/league/" to action="" as such:
<HTML lang="en">
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Create Account" />
</form><br /><br />
</body>
</HTML>
The form did work:
In [3]: UserRegistration.objects.all()
Out[3]: [<UserRegistration: aoeu oeu oeu#aeou.com>]