利用flask写的接口(base64, 二进制, 上传视频流)+异步+gunicorn部署Flask服务+多gpu卡部署

一.flask写的接口

1.1 manage.py启动服务(发送图片base64版)

这里要注意的是用docker的话,记得端口映射

#coding:utf-8
import base64
import io
import logging
import picklefrom flask import Flask, jsonify, request
from PIL import Image
from sklearn import metricslogging.basicConfig(format="%(asctime)s %(levelname)s: %(message)s",level=logging.INFO,datefmt="%Y-%m-%d %H:%M:%S",
)app = Flask(__name__)@app.route("/evaluate", methods=["POST"])
def evaluate():"""评价指标"""logging.info("Call evaluate")truth = request.json["truth"]predcition = request.json["prediction"]accuracy = metrics.accuracy_score(truth, predcition)f1 = metrics.f1_score(truth, predcition, average="macro")precision = metrics.precision_score(truth, predcition, average="macro")recall = metrics.recall_score(truth, predcition, average="macro")return jsonify({"accuracy": accuracy, "precision": precision, "recall": recall, "f1": f1})@app.route("/ocr", methods=["POST"])
def ocr():"""图像分析 OCR"""logging.info("OCR")base64str = request.json["img"]# print('base64str:',base64str)img = Image.open(io.BytesIO(base64.b64decode(base64str)))print('img:',img.size)# text = pytesseract.image_to_string(Image.open(io.BytesIO(img)), lang="chi_sim")return jsonify({"text": 'Success'})if __name__ == "__main__":app.run(host="0.0.0.0", port=6006)

1.2.test_route  测试路由文件(发送图片base64版)

#coding:utf-8
from io import BytesIO
from PIL import Image
import base64
import json
import re
import requestsdef image_to_base64(img_path):with open(img_path, "rb") as f:  # 转为二进制格式data_base64 = base64.b64encode(f.read()).decode()  # 使用base64进行加密return data_base64def base64_to_image(base64_str):base64_data = re.sub('^data:image/.+;base64,', '', base64_str)byte_data = base64.b64decode(base64_data)image_data = BytesIO(byte_data)img = Image.open(image_data)return imgdef json_send(dataPModel,url):headers = {"Content-type": "application/json", "Accept": "text/plain", "charset": "UTF-8"}response = requests.post(url=url, headers=headers, data=json.dumps(dataPModel))# print('response:',response)return json.loads(response.text)if __name__ == "__main__":url = 'http://192.168.102.193:1112/ocr'img = Image.open('haha.png').convert('RGB')print('img.size:', img.size)img_base64 = image_to_base64('haha.png')dataPModel = {}dataPModel['img'] = img_base64# dataPModel['uid'] = "0x031"print('dataPModel:', dataPModel)result = json_send(dataPModel, url)print(result['text'])

服务器返回结果:

本地返回结果:

2.1.manage.py启动服务(发送图片二进制版)

#coding:utf-8
"""
fzh created on 2020/06/28
"""
import logging
logging.basicConfig(format="%(asctime)s %(levelname)s: %(message)s",level=logging.INFO,datefmt="%Y-%m-%d %H:%M:%S",
)
import os
import base64
import io
from PIL import Image
import os
from flask import Flask, jsonify, request
import cv2
import glob
import numpy as np
import json
import datetime
import time
import re
import randomapp = Flask(__name__)@app.route("/express_reco", methods=["POST"])
def express_reco():logging.info('====快递单接收图片成功====')st1_time = time.time()algirm_info = {}path = './algrim_img'os.makedirs(path, exist_ok=True)#二进制图片方式name_ = random.randint(0, 1000)data_binary = request.files['encode_data']img_path = os.path.join(path, str(name_)+'.jpg')data_binary.save(img_path)#data_binary.filenameimg = cv2.imread(img_path)if __name__ == "__main__":app.run(host="0.0.0.0", port=6006)#注意部署要改为6006

2.2.test_route  测试路由文件(发送图片二进制版)

#coding:utf-8
import json
import os
import requests
import base64def json_send(url,dataPModel):# header = {"Content-type": "application/json", "Accept": "text/plain", "charset": "UTF-8"}header = {'Content-Type': 'application/json'}# response = requests.post(url=url, headers=header, data=json.dumps(dataPModel))response = requests.post(url=url, files=dataPModel)# print('response:', response)return json.loads(response.text)def send_express_reco():url = 'http://192.168.102.191:3112/express_reco'dataPModel = {}import cv2img_path = './快递单原始数据'imgs_list_path = [os.path.join(img_path, i) for i in os.listdir(img_path)]for i, img_list_path in enumerate(imgs_list_path[:10]):print('==img_list_path:', img_list_path)dataPModel['encode_data'] = open(img_list_path, 'rb')result = json_send(url, dataPModel)print('result:', result)print('==imgs_list_path[0]:',imgs_list_path[0])for i in range(10):dataPModel['encode_data'] = open(imgs_list_path[0], 'rb')result = json_send(url, dataPModel)print('result:', result)

3.1 flask上传视频流

(1)代码结构:

其中index.html用来渲染页面,app.py用来起服务

(2)index.html代码:

<!doctype html>
<html lang="en">
<head><!-- Required meta tags --><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><!-- Bootstrap CSS --><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"><title>Live Streaming Demonstration</title>
</head>
<body>
<div class="container"><div class="row"><div class="col-lg-8  offset-lg-2"><h3 class="mt-5">视频显示</h3><img src="{{ url_for('video_feed') }}" width="100%"></div></div>
</div>
</body>
</html>

(3)app.py代码:

#coding:utf-8
from flask import Flask, render_template, Response
import cv2app = Flask(__name__)
camera = cv2.VideoCapture(0)  # use 0 for web camera
# Use Ip Camera/CCTV/RTSP Link
# cv2.VideoCapture('rtsp://username:password@camera_ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp')
### Example RTSP Link
# cv2.VideoCapture('rtsp://mamun:123456@101.134.16.117:554/user=mamun_password=123456_channel=0_stream=0.sdp') ```
def gen_frames():  # generate frame by frame from camerawhile True:# Capture frame-by-framesuccess, frame = camera.read()  # read the camera frame# print('===frame.shape', frame.shape)if not success:breakelse:ret, buffer = cv2.imencode('.jpg', frame)frame = buffer.tobytes()yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')  # concat frame one by one and show result@app.route('/video_feed')
def video_feed():#Video streaming route. Put this in the src attribute of an img tagreturn Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')@app.route('/video', methods=["get"])
def index():"""Video streaming home page."""return render_template('index.html')if __name__ == '__main__':# app.run(debug=True, port=6006)app.run(host="0.0.0.0", port=6006)

python app.py启动服务即可

3.2查看视频流

二.开异步:

https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(1)executor.submit(second_send_houduan,json_info)

注意传递参数要放在外面

#coding:utf-8
from threading import Thread
import os
import base64
import io
import logging
import pickle
from whole_image_detect_first_plate import main_plate
from whole_image_detect_second_recognize import main_recoginze
from third_title_word_recognize import main_title_word_recoginze
from flask import Flask, jsonify, request
from PIL import Image
from config import model_title_detect, model_word_detect,crnn_model
# from sklearn import metrics
import requests
import json
import time
from time import sleep
from sql_tools import *
import asyncio
from multiprocessing import Process, Poolfrom concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(1)logging.basicConfig(format="%(asctime)s %(levelname)s: %(message)s",level=logging.INFO,datefmt="%Y-%m-%d %H:%M:%S",
)app = Flask(__name__)def json_send_head(dataPModel,url):# headers = {"Content-type": "application/json", "Accept": "text/plain", "charset": "UTF-8"}response = requests.post(url=url, data=dataPModel)# print('response:',response)return json.loads(response.text)#第二次算法返回的结果
def second_send_houduan(json_info):print('entrance second houduan!!!')# 发给后端url = 'http://tc.aa.zhangzb.site:9091/api/page/plateGetJson'dataPmodel = {}if len(json_info):info = main_recoginze(json_info, model_title_detect, model_word_detect, crnn_model)dataPmodel['json'] = json.dumps(info)text = json_send_head(url, dataPmodel)print('text:', text)else:dataPmodel = {}info = {'NO': 'NO JSON INFO!!'}dataPmodel['json'] = json.dumps(info)json_send_head(url, dataPmodel)#第二次对接,后端发给我版面框划分好后传的json信息
@app.route("/second_recognize", methods=["POST"])
def second_recognize():logging.info("second_recognize")str_info = request.json["json"]json_info = json.loads(str_info)# json_info = str_info #自己调试用print('json_info:', json_info)executor.submit(second_send_houduan,json_info)# print('len(json_info):', len(json_info))data = {}if len(json_info):data['msg'] = ''data['code'] = '200'else:data['msg'] = '接收的json有问题'data['code'] = '201'return jsonify(data)if __name__ == "__main__":app.run(host="0.0.0.0", port=6006)

三.gunicorn部署Flask服务

pip install gunicorn

gunicorn命令启动

gunicorn -w 4 -b ip:port xxx:app启动一个Flask应用

例如:gunicorn -w 4 -b 0.0.0.0:6006 manage:app

  • -w 4是指预定义的工作进程数为4,
  • -b 127.0.0.1:4000指绑定地址和端口
  • manage是flask的启动python文件,app则是flask应用程序实例 
# run.py
from flask import Flask
app = Flask(__name__)

进行配置config.py

# gunicorn config
workers = 6  # must be 1, because of gpu
# threads = 4
bind = "0.0.0.0:6006"
worker_class = "gevent"
worker_connections = 1500
timeout = 60
loglevel = "debug"
accesslog = "-"
errorlog = "-"
daemon = False
pidfile = "master_pid"

启动的时候:gunicorn  -c ./config.py manage:app

退出gunicorn,通过下面命令查看

pstree -ap|grep gunicorn

在kill即可。

四.多GPU卡部署

 

 

 

参考:https://blog.miguelgrinberg.com/post/video-streaming-with-flask

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/493243.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2018中国自动驾驶市场专题分析

来源&#xff1a;智车科技未来智能实验室是人工智能学家与科学院相关机构联合成立的人工智能&#xff0c;互联网和脑科学交叉研究机构。未来智能实验室的主要工作包括&#xff1a;建立AI智能系统智商评测体系&#xff0c;开展世界人工智能智商评测&#xff1b;开展互联网&#…

python写日志

需要再加入按照日期生成日志 #coding:utf-8 import logging import logging.handlers class Logger:logFile def __init__(self, logFile):self.logFile logFileself.logger logging.getLogger(mylogger)self.logger.setLevel(logging.INFO)rf_handler logging.handlers.…

MIT科学家Dimitri P. Bertsekas最新2019出版《强化学习与最优控制》(附书稿PDF讲义)...

来源&#xff1a;专知摘要&#xff1a;MIT科学家Dimitri P. Bertsekas今日发布了一份2019即将出版的《强化学习与最优控制》书稿及讲义&#xff0c;该专著目的在于探索这人工智能与最优控制的共同边界&#xff0c;形成一个可以在任一领域具有背景的人员都可以访问的桥梁。REINF…

yolov3 anchors用kmeans聚类出先验框+anchor宽高比分析

一&#xff0e;yolov v3聚类出框 # -*- coding: utf-8 -*- import numpy as np import random import argparse import os# # 参数名称 # parser argparse.ArgumentParser(description使用该脚本生成YOLO-V3的anchor boxes\n) # parser.add_argument(--input_annotation_txt…

Geoff Hinton:全新的想法将比微小的改进更有影响力

来源&#xff1a;AI科技评论摘要&#xff1a;日前&#xff0c;WIRED 对 Hinton 进行了一次专访&#xff0c;在访谈中&#xff0c;WIRED 针对人工智能带来的道德挑战和面临的挑战等问题进行了提问&#xff0c;以下为谈话内容。“作为一名谷歌高管&#xff0c;我认为在公开场合抱…

修改TOMCAT服务器图标为应用LOGO

在tomcat下部署应用程序&#xff0c;运行后&#xff0c;发现在地址栏中会显示tomcat的小猫咪图标。有时候&#xff0c;我们自己不想显示这个图标&#xff0c;想换成自己定义的的图标&#xff0c;那么按如下方法操作即可&#xff1a; 参考网上的解决方案&#xff1a;1、将$TOMCA…

python连接mysql的一些基础知识+安装Navicat可视化数据库+flask_sqlalchemy写数据库

一&#xff0e;mysql基础知识 &#xff11;&#xff0e;connect连接数据库 import pymysqldef get_conn():conn pymysql.connect(hostxxx.xxx.xxx.xxx, port3306, userroot, passwd, dbnewspaper_rest) # db:表示数据库名称return conn &#xff12;&#xff0e;创建表 im…

工业互联网平台创新发展白皮书(2018)

来源&#xff1a;走向智能论坛摘要&#xff1a;近日&#xff0c;在“2018年产业互联网与数据经济大会——首届工业互联网平台创新发展暨两化融合推进会”上&#xff0c;国家工业信息安全发展研究中心尹丽波主任发布并解读了《工业互联网平台创新发展白皮书&#xff08;2018&…

迭代器模式和组合模式混用

迭代器模式和组合模式混用 前言 园子里说设计模式的文章算得上是海量了&#xff0c;所以本篇文章所用到的迭代器设计模式和组合模式不提供原理解析&#xff0c;有兴趣的朋友可以到一些前辈的设计模式文章上学学&#xff0c;很多很有意思的。在Head First 设计模式这本书中&…

python实现可扩容队列

#coding:utf-8 """ fzh created on 2019/10/15 构建一个队列 """ import datetimeclass LoopQueue(object):def __init__(self, n10):self.arr [None] * (n1) # 由于特意浪费了一个空间&#xff0c;所以arr的实际大小应该是用户传入的容量1sel…

5G 产业链重要投资节点

来源&#xff1a;兴业证券 ▌5G:大通信容量及超低延时&#xff0c;未来多项应用的基础5G:高工作频率以及频谱带宽带来高通信容量5G(5thgeneration)是指第五代移动电话通信标准。3GPP(第三代合作伙伴计划&#xff0c;电信标准化机构)将5G标准分为了NSA(非独立组网)和SA(独立组网…

Kneser猜想与相关推广

本文本来是想放在Borsuk-Ulam定理的应用这篇文章当中。但是这个文章实在是太长&#xff0c;导致有喧宾夺主之嫌&#xff0c;从而独立出为一篇文章&#xff0c;仅供参考。$\newcommand{\di}{\mathrm{dist}}$ &#xff08;图1&#xff1a;Kneser叙述他的猜想原文手稿&#xff09;…

python .py文件变为.so文件进行加密

&#xff11;.mytest.py 需要加密的内容 #coding:utf-8 import datetimeclass Today():def get_time(self):print(datetime.datetime.now())def say(self):print("hello word!")today Today() today.say() today.get_time() 2.执行setup.py 也就是加密脚本 from…

从技术上解读大数据的应用现状和开源未来

来源&#xff1a;网络大数据作者 | 韩锐、 Lizy Kurian John、詹剑锋摘要&#xff1a;近年来&#xff0c;随着大数据系统的快速发展&#xff0c;各式各样的开源基准测试集被开发出来&#xff0c;以评测和分析大数据系统并促进其技术改进。然而&#xff0c;迄今为止&#xff0c;…

十八岁华裔天才携手「量子计算先驱」再次颠覆量子计算

来源&#xff1a;机器之心编译参与&#xff1a;刘晓坤、李泽南摘要&#xff1a;量子计算再一次「被打败了」。今年 8 月&#xff0c;刚刚年满 18 岁的 Ewin Tang 证明了经典算法能以和量子计算机相近的速度解决推荐问题&#xff0c;这位天才少女&#xff08;更正&#xff1a;不…

resnet系列+mobilenet v2+pytorch代码实现

一.resnet系列backbone import torch.nn as nn import math import torch.utils.model_zoo as model_zooBatchNorm2d nn.BatchNorm2d__all__ [ResNet, resnet18, resnet34, resnet50, resnet101, deformable_resnet18, deformable_resnet50,resnet152]model_urls {resnet18:…

广度优先搜索(BFS)与深度优先搜索(DFS)

一.广度优先搜索&#xff08;BFS&#xff09; 1.二叉树代码 # 实现一个二叉树 class TreeNode:def __init__(self, x):self.val xself.left Noneself.right Noneself.nexts []root_node TreeNode(1) node_2 TreeNode(2) node_3 TreeNode(3) node_4 TreeNode(4) node_…

骁龙855在AI性能上真的秒杀麒麟980?噱头而已

来源&#xff1a;网易智能摘要&#xff1a;前段时间的高通发布会上&#xff0c;有关骁龙855 AI性能达到友商竞品两倍的言论可谓是赚足了眼球。高通指出&#xff0c;骁龙855针对CPU、GPU、DSP都进行了AI计算优化&#xff0c;结合第四代AI引擎可以实现每秒超过7万亿次运算&#x…

MySQL主从复制(Master-Slave)与读写分离(MySQL-Proxy)实践 转载

http://heylinux.com/archives/1004.html MySQL主从复制&#xff08;Master-Slave&#xff09;与读写分离&#xff08;MySQL-Proxy&#xff09;实践 Mysql作为目前世界上使用最广泛的免费数据库&#xff0c;相信所有从事系统运维的工程师都一定接触过。但在实际的生产环境中&am…

深度解析AIoT背后的发展逻辑

来源&#xff1a;iotworld摘要&#xff1a;AI与IoT融合领域近年来一片火热&#xff0c;不论是资本市场&#xff0c;还是大众创业&#xff0c;无不对其表现出极大的热情。AIoT领域中人机交互的市场机会自2017年开始&#xff0c;“AIoT”一词便开始频频刷屏&#xff0c;成为物联网…