当飞桨PaddleHub遇到微信小程序,AI也能指物作诗
喜欢就关注我们吧!
方仲永
唐伯虎
项目组成
PaddleHub Serving服务,由于需要进行推理,需要内存较大或能力突出的显卡支持。 后台服务,使用flask提供后台进行数据输入预处理,以及serving处理后的资源调度等。 微信小程序,负责微信模块展示 。
详细代码解析
hub serving start --config config.json
(base) root@iZ2ze74yt1daioe0s04o9kZ
:~/paddlehubweixinbox# cat config.json {
"modules_info"
: {
"stylepro_artistic"
: {
"init_args"
: {
"version"
:
"1.0.0" },
"predict_args"
: {
"use_gpu"
:
false }
},
"reading_pictures_writing_poems"
: {
"init_args"
: {
"version"
:
"1.0.0" },
"predict_args"
: {
"use_gpu"
:
false }
}
},
"port"
:
8866,
"use_multiprocess"
:
false,
"workers"
:
1}
Web后台的作用一是提供看图写诗图片上传、处理,生成的诗返回;二是提供风格画图片上传、风格选择、处理,生成风格画文件路径返回。
看图写诗
# author: Livingbody
# date: 2020.05.06
from
flask
import Flask, render_template, request, jsonify, Response
from
werkzeug.utils
import secure_filename
import
os
import
requests
import
paddlehub
as hub
import
cv2
import
time
from
flask
import Blueprint, render_template
import
requests
import
json
import
cv2
import
base64
from
flask
import json
index_reading_pictures = Blueprint(
"reading_pictures", __name__)
# 设置允许的文件格式
ALLOWED_EXTENSIONS = set([
'png',
'jpg',
'bmp',
'jpeg'])
# 当前文件所在路径
basepath = os.path.dirname(__file__)
defcv2_to_base64(image):
data = cv2.imencode(
'.jpg', image)[
1]
return
base64.b64encode(data.tostring()).decode(
'utf8')
defallowed_file(filename):
filename = filename.lower()
return'.'in
filename
and filename.rsplit(
'.',
1)[
1]
in ALLOWED_EXTENSIONS
# 上传并写诗
@index_reading_pictures.route('/reading_pictures', methods=['POST', 'GET']) # 添加路由
defupload():
print(request)
if
request.method ==
'POST':
try
:
f = request.files[
'file']
print(f.filename)
ifnot
(f
and allowed_file(f.filename)):
# return jsonify({"error": 1001, "msg": "请检查上传的图片类型,仅限于png、jpg、bmp"})
return
render_template(
'404.html')
sourcefile = os.path.join(
'static/images/source', secure_filename(f.filename))
print(
'sourcefile: %s' % sourcefile)
upload_path = os.path.join(basepath, sourcefile)
# 注意:没有的文件夹一定要先创建,不然会提示没有该路径 f.save(upload_path)
print(upload_path)
print(
'upload_path: %s' % upload_path)
results = reading_pictures(sourcefile)
headers = {
"Content-type":
"application/json",
"charset":
"gbk"}
# results: [{'Poetrys': '山隈山坳山,海滨岭颠海。中有无底渊,千古不可改。'}]
# return Response(json.dumps(results), content_type='application/json')
return
jsonify(results)
except
Exception:
return
render_template(
'404.html')
return
render_template(
'poem.html')
# 读取图片
defreading_pictures(upload_path):
print(
'upload_path: %s' % upload_path)
# 指定图片分割方法为deeplabv3p_xception65_humanseg并发送post请求
data = {
'images': [cv2_to_base64(cv2.imread(upload_path))]}
headers = {
"Content-type":
"application/json"}
url =
"http://localhost:8861/predict/reading_pictures_writing_poems" r = requests.post(url=url, headers=headers, data=json.dumps(data))
print(
'request: %s' % r)
t = time.time()
results = r.json()[
"results"]
number = results[
0][
'Poetrys'].count(
"。") -
1 results[
0][
'Poetrys'] = results[
0][
'Poetrys'].replace(
"。",
"。\n", number)
print(
'results: %s' % results)
return
results
风格画
# author: Livingbody
# date: 2020.05.06
from
flask
import Flask, render_template, request, jsonify, Response
from
werkzeug.utils
import secure_filename
import
os
import
requests
import
paddlehub
as hub
import
cv2
import
time
import
numpy
as np
from
flask
import Blueprint, render_template
import
requests
import
json
import
cv2
import
base64
from
flask
import json
index_stylepro_artistic = Blueprint(
"stylepro_artistic", __name__)
# 设置允许的文件格式
ALLOWED_EXTENSIONS = set([
'png',
'jpg',
'bmp',
'jpeg'])
# 当前文件所在路径
basepath = os.path.dirname(__file__)
defcv2_to_base64(image):
data = cv2.imencode(
'.jpg', image)[
1]
return
base64.b64encode(data.tostring()).decode(
'utf8')
defbase64_to_cv2(b64str):
data = base64.b64decode(b64str.encode(
'utf8'))
data = np.fromstring(data, np.uint8)
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
return
data
defallowed_file(filename):
filename = filename.lower()
return'.'in
filename
and filename.rsplit(
'.',
1)[
1]
in ALLOWED_EXTENSIONS
@index_stylepro_artistic.route('/stylepro_artistic', methods=['POST', 'GET']) # 添加路由
defupload():
print(request)
if
request.method ==
'POST':
try
:
f = request.files[
'file']
print(f.filename)
print(request.form.get(
'mystyle'))
mystyle = request.form.get(
'mystyle')
ifnot
(f
and allowed_file(f.filename)):
# return jsonify({"error": 1001, "msg": "请检查上传的图片类型,仅限于png、jpg、bmp"})
return
render_template(
'404.html')
sourcefile = os.path.join(
'static/images/source', secure_filename(f.filename))
print(
'sourcefile: %s' % sourcefile)
upload_path = os.path.join(basepath, sourcefile)
# 注意:没有的文件夹一定要先创建,不然会提示没有该路径 f.save(upload_path)
results = change_pictures(sourcefile, mystyle)
headers = {
"Content-type":
"application/json",
"charset":
"gbk"}
return
jsonify(results)
except
Exception:
return
render_template(
'404.html')
return
render_template(
'style.html')
defchange_pictures(upload_path, style):
style =
'static/images/style/' + str(style) +
'.jpg' data = {
'images': [
{
'content'
: cv2_to_base64(cv2.imread(upload_path)),
'styles'
: [cv2_to_base64(cv2.imread(style))],
# 'use_gpu': False,
# 'visualization': True,
# 'output_dir': 'static/images/stylepro_artistic'
}
]}
headers = {
"Content-type":
"application/json"}
url =
"http://localhost/predict/stylepro_artistic" r = requests.post(url=url, headers=headers, data=json.dumps(data))
print(
'*' *
50)
print(
'stylepro_artistic OK...........')
t = time.time()
filename = str(t) +
'.jpg' mypath = os.path.join(basepath,
'static/images/stylepro_artistic', filename)
cv2.imwrite(mypath, base64_to_cv2(r.json()[
"results"][
0][
'data']))
filepath = {
'save_path': os.path.join(
'static/images/stylepro_artistic', filename)}
print(
'filepath: %s' % filepath)
return
filepath
申请小程序账号 本地开发小程序 上传小程序,并申请审核 审核通过,申请上线
(base) root@iZ2ze74yt1daioe0s04o9kZ:~/paddlehubweixinbox
# cat app.pyfrom
flask
import Flask, render_template
from
flask_bootstrap
import Bootstrap
# from datetime import timedelta
app = Flask(__name__)
from
reading_pictures
import *
app.register_blueprint(index_reading_pictures)
from
stylepro_artistic
import *
app.register_blueprint(index_stylepro_artistic)
Bootstrap(app)
@app.route('/', methods=['POST', 'GET'])
defindex():
return
render_template(
'index.html')
@app.route('/error', methods=['POST', 'GET'])
deferror():
return
render_template(
'404.html')
if
__name__ ==
'__main__':
app.config[
'JSON_AS_ASCII'] =
False app.run(host=
'0.0.0.0', port=
8080, debug=
True,
ssl_context=(
"4543112_www.livingbody.xyz.pem",
"4543112_www.livingbody.xyz.key"))
# If a persistence installation is required, you need to use the persistence path as the following:
!mkdir /home/aistudio/external-libraries
!pip
install beautifulsoup4 -t /home/aistudio/
external-libraries
# 同时添加如下代码, 这样每次环境(kernel)启动的时候只要运行下方代码即可:
# Also add the following code, so that every time the environment (kernel) starts, just run the following code:
importsys
sys.path.append(
'/home/aistudio/external-libraries')
如果您想详细了解更多飞桨的相关内容,请参阅以下文档。
https://gitee.com/paddlepaddle/PaddleHub
往期精彩回顾 ▼
关键词
图片
os.path
os.path.join
项目
微信
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。