【发布时间】:2022-09-23 17:48:05
【问题描述】:
当我单击html 代码中的预测按钮时,我想使用Flask 应用程序发送图像。
代码应该得到提示并运行 ML 模型并根据输入提示生成图像。我可以生成图片,但不知何故我无法将其发送到 html 或 html 不显示图像。
任何人都可以检查我的flask 和html 代码问题出在哪里?我的flask 图像发送方法错误或html 部分错误?如何在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>
-
请您打印 img_data=encoded_img_data.decode(\'utf-8\') 并显示它的输出,好吗?只是为了确保它是如何解码的。
标签: html python-3.x flask