提交 c093331e 编写于 作者: G grasswolfs

test=develop, test=documents_fix

上级 c4f19c8e
<p align="center">
<img src="./docs/imgs/paddlehub_logo.jpg" align="middle"
</p>
[![Build Status](https://travis-ci.org/PaddlePaddle/PaddleHub.svg?branch=release/v1.8)](https://travis-ci.org/PaddlePaddle/PaddleHub)
[![License](https://img.shields.io/badge/license-Apache%202-red.svg)](LICENSE)
[![Version](https://img.shields.io/github/release/PaddlePaddle/PaddleHub.svg)](https://github.com/PaddlePaddle/PaddleHub/releases)
![python version](https://img.shields.io/badge/python-3.6+-orange.svg)
![support os](https://img.shields.io/badge/os-linux%2C%20win%2C%20mac-yellow.svg)
## 简介
PaddleHub是飞桨生态的预训练模型应用工具,开发者可以便捷地使用高质量的预训练模型结合Fine-tune API快速完成模型迁移到部署的全流程工作。PaddleHub提供的预训练模型涵盖了图像分类、目标检测、词法分析、语义模型、情感分析、视频分类、图像生成、图像分割、文本审核、关键点检测等主流模型。更多详情可查看官网:https://www.paddlepaddle.org.cn/hub
- PaddleHub旨在为开发者提供丰富的、高质量的、直接可用的预训练模型,**【无需深度学习背景、无需数据与训练过程】,**也可快速使用AI模型。
- 涵盖CV、NLP、Audio、Video主流四大品类,支持**一键预测****一键服务化部署****快速迁移学习**
- 全部模型开源下载,**离线可运行**
## 近期更新
- **2020.11.20**,发布2.0版本,全面迁移动态图编程模式,服务化部署Serving能力升级;新增手部关键点检测1个、图像动漫化类12个、图片编辑类3个,语音合成类3个,句法分析1个,预训练模型总量到达 **【182】** 个。
- **2020.10.09**,新增OCR多语言系列模型4个,图像编辑模型4个,预训练模型总量到达 **【162】** 个。
- **2020.09.27**,新增文本生成模型6个,图像分割模型1个,预训练模型总量到达 **【154】** 个。
- **2020.08.13**,发布v1.8.1,新增人像分割模型Humanseg,支持EMNLP2019-Sentence-BERT作为文本匹配任务网络,预训练模型总量到达 **【147】** 个。
- **2020.07.29**,发布v1.8.0,新增AI对联和AI写诗、jieba切词,文本数据LDA、语义相似度计算,新增目标检测,短视频分类模型,超轻量中英文OCR,新增行人检测、车辆检测、动物识别等工业级模型,支持VisualDL可视化训练,预训练模型总量到达 **【135】** 个。
- [More]()
## 特性
- **模型即软件**:通过Python API或命令行实现模型调用,可快速体验或集成飞桨特色预训练模型。[-> 效果展示](#模型即软件)
- **易用的迁移学习**:通过Fine-tune API,只需少量代码即可完成预训练模型的Fine-tuning。[-> 效果展示](#易用的迁移学习)
- **一键模型转服务**:简单一行命令即可搭建属于自己的深度学习模型API服务完成部署。[-> 效果展示](#一键模型转服务)
- **【丰富的预训练模型】**:涵盖CV、NLP、Audio、Video主流四大品类的 180+ 预训练模型,全部开源下载,离线可运行。
- **【一键模型快速预测】**:通过一行命令行或者极简的Python API实现模型调用,可快速体验模型效果。
- **【一键模型转服务化】**:一行命令,搭建深度学习模型API服务化部署能力。
- **【十行代码迁移学习】**:十行代码完成图片分类、文本分类的迁移学习任务
- **【PIP安装便捷】**:支持PIP快速安装使用
- **【跨平台兼容性】**:可运行于Linux、Windows、MacOS等多种操作系统
## 精品模型效果展示
- [图像分类]()
- [目标检测]()
- [关键点检测]()
- [图像分割]()
- [图像生成]()
- [文本识别]()
- [词法分析]()
- [句法分析]()
- [文本审核]()
- [文本生成]()
- [语音合成]()
- [视频分类]()
<a name="欢迎加入PaddleOCR技术交流群"></a>
## 欢迎加入PaddleHub技术交流群
- 微信扫描二维码加入官方交流群,获得更高效的问题答疑,与各行各业开发者充分交流,期待您的加入。
<div align="center">
<img src="./docs/imgs/joinus.PNG" width = "200" height = "200" />
</div>
如扫码失败,请添加微信15711058002,并备注“Hub”,运营同学会邀请您入群。
## 文档教程 [[readthedocs]](https://paddlehub.readthedocs.io/zh_CN/develop/index.html)
- [概述](./docs/overview.md)
- [PIP安装](./docs/installation.md)
- [快速体验](./docs/quickstart.md)
- [丰富的预训练模型](./docs/pretrained_models.md)
- [飞桨优势特色模型](./docs/pretrained_models.md)
- [计算机视觉](./docs/pretrained_models.md)
- [图像分类](./docs/pretrained_models.md)
- [目标检测](./docs/pretrained_models.md)
- [图像分割](./docs/pretrained_models.md)
- [关键点检测](./docs/pretrained_models.md)
- [图像生成](./docs/pretrained_models.md)
- [自然语言处理](./docs/pretrained_models.md)
- [中文词法分析与词向量](./docs/pretrained_models.md)
- [情感分析](./docs/pretrained_models.md)
- [文本相似度计算](./docs/pretrained_models.md)
- [文本生成](./docs/pretrained_models.md)
- [语义表示](./docs/pretrained_models.md)
- [视频](./docs/pretrained_models.md)
- 使用教程
- [命令行工具](./docs/tutorial/cmdintro.md)
- [自定义数据](./docs/tutorial/how_to_load_data.md)
- [服务化部署](./docs/tutorial/serving.md)
- 进阶指南
- [文本Embedding服务](./docs/tutorial/bert_service.md)
- [语义相似度计算](./docs/tutorial/sentence_sim.md)
- API
- [hub.datasets](./docs/reference/datasets.md)
- [hub.finetune](./docs/reference/finetune.md)
- [hub.Module](./docs/reference/module.md)
- [hub.vision.transforms](./docs/reference/vision.md)
- [FAQ](./docs/faq.md)
- 快速开始
- [命令行调用](./docs/quick_experience/cmd_quick_run.md)
- [Python API调用](./docs/quick_experience/python_use_hub.md)
- [在线运行体验demo【Official】](https://github.com/PaddlePaddle/PaddleHub/tree/release/v1.8/demo)
- [生态趣味项目demo【ThirdPary】](./docs/quick_experience/more_demos.md)
- 丰富的预训练模型 182 个
- [精品特色模型](./docs/pretrained_models.md)
- 计算机视觉 126 个
- [图像分类 64 个](./modules/image/classification)
- [目标检测 13 个](./modules/image/object_detection)
- [人脸检测 7 个](./modules/image/face_detection)
- [关键点检测 3 个](./modules/image/keypoint_detection)
- [图像分割 7 个](./modules/image/semantic_segmentation)
- [文本识别 8 个](./modules/image/text_recognition)
- [图像生成 17 个](./modules/image/gan)
- [图像编辑 7 个](./modules/image/style_transfer)
- 自然语言处理 48 个
- [词法分析 2 个](./modules/text/lexical_analysis)
- [句法分析 1 个](./modules/text/syntactic_analysis)
- [情感分析 7 个](./modules/text/semantic_model)
- [文本审核 3 个](./modules/text/text_review)
- [文本生成 9 个](./modules/text/text_generation)
- [语义模型 26 个](./modules/text/semantic_model)
- 语音 3 个
- [语音合成 3 个](./modules/audio)
- 视频5个
- [视频分类 5 个](./modules/video)
- 部署
- [一行代码服务化部署](./docs/tutorial/serving.md)
- C++ Inference 部署(建议加群沟通)
- 移动端 Lite 部署(建议加群沟通)
- 进阶文档
- [命令行工具详解](./docs/tutorial/cmdintro.md)
- [自定义数据迁移学习](./docs/tutorial/how_to_load_data.md)
- [模型转module](./docs/tutorial/contri_pretrained_model.md)
- [文本Embedding任务](./docs/tutorial/bert_service.md)
- 社区交流
- [加入技术交流群](#欢迎加入PaddleHub技术交流群)
- [贡献预训练模型](./docs/contribution/contri_pretrained_model.md)
- [贡献代码](./docs/contribution/contri_pr.md)
- [FAQ](./docs/faq.md)
- [更新历史](./docs/release.md)
- [许可证书](#许可证书)
- [致谢](#致谢)
## 效果展示
<a name="模型即软件"></a>
### 1、模型即软件
PaddleHub采用模型即软件的设计理念,所有的预训练模型与Python软件包类似,具备版本的概念,通过`hub install/uninstall` 可以便捷完成模型的升级和卸载。还可以通过Python的API或命令行实现快速预测的软件集成,更方便地应用和集成深度学习模型。
安装PaddleHub后,执行命令[hub run](./docs/tutorial/cmdintro.md),即可快速体验无需代码、一键预测的功能:
* 使用[文字识别](https://www.paddlepaddle.org.cn/hublist?filter=en_category&value=TextRecognition)轻量级中文OCR模型chinese_ocr_db_crnn_mobile即可一键快速识别图片中的文字。
```shell
$ wget https://paddlehub.bj.bcebos.com/model/image/ocr/test_ocr.jpg
$ hub run chinese_ocr_db_crnn_mobile --input_path test_ocr.jpg --visualization=True
```
预测结果图片保存在当前运行路径下ocr_result文件夹中,如下图所示。
<p align="center">
<img src="./docs/imgs/ocr_res.jpg" width='70%' align="middle"
</p>
* 使用[目标检测](https://www.paddlepaddle.org.cn/hublist?filter=en_category&value=ObjectDetection)模型pyramidbox_lite_mobile_mask对图片进行口罩检测
```shell
$ wget https://paddlehub.bj.bcebos.com/resources/test_mask_detection.jpg
$ hub run pyramidbox_lite_mobile_mask --input_path test_mask_detection.jpg
```
<p align="center">
<img src="./docs/imgs/test_mask_detection_result.jpg" align="middle"
</p>
* 使用[词法分析](https://www.paddlepaddle.org.cn/hublist?filter=en_category&value=LexicalAnalysis)模型LAC进行分词
```shell
$ hub run lac --input_text "现在,慕尼黑再保险公司不仅是此类行动的倡议者,更是将其大量气候数据整合进保险产品中,并与公众共享大量天气信息,参与到新能源领域的保障中。"
[{
'word': ['现在', ',', '慕尼黑再保险公司', '不仅', '是', '此类', '行动', '的', '倡议者', ',', '更是', '将', '其', '大量', '气候', '数据', '整合', '进', '保险', '产品', '中', ',', '并', '与', '公众', '共享', '大量', '天气', '信息', ',', '参与', '到', '新能源', '领域', '的', '保障', '中', '。'],
'tag': ['TIME', 'w', 'ORG', 'c', 'v', 'r', 'n', 'u', 'n', 'w', 'd', 'p', 'r', 'a', 'n', 'n', 'v', 'v', 'n', 'n', 'f', 'w', 'c', 'p', 'n', 'v', 'a', 'n', 'n', 'w', 'v', 'v', 'n', 'n', 'u', 'vn', 'f', 'w']
}]
```
PaddleHub还提供图像分类、语义模型、视频分类、图像生成、图像分割、文本审核、关键点检测等主流模型,更多模型介绍,请前往[预训练模型介绍](./docs/pretrained_models.md)或者PaddleHub官网[https://www.paddlepaddle.org.cn/hub](https://www.paddlepaddle.org.cn/hub) 查看
<a name="易用的迁移学习"></a>
### 2、易用的迁移学习
通过Fine-tune API,只需要少量代码即可完成深度学习模型在计算机视觉场景下的迁移学习。
* [Demo示例](./demo)提供丰富的Fine-tune API的使用代码,包括[图像分类](./demo/image_classification)[图像着色](./demo/colorization)[风格迁移](./demo/style_transfer)、等场景的模型迁移示例。
<p align="center">
<img src="./docs/imgs/paddlehub_finetune.gif" align="middle"
</p>
<p align='center'>
十行代码完成图像风格迁移
</p>
* 如需在线快速体验,请点击[PaddleHub教程合集](https://aistudio.baidu.com/aistudio/projectdetail/231146),可使用AI Studio平台提供的GPU算力进行快速尝试。
<a name="一键模型转服务"></a>
### 3、一键模型转服务
PaddleHub提供便捷的模型转服务的能力,只需简单一行命令即可完成模型的HTTP服务部署。通过以下命令即可快速启动LAC词法分析服务:
```shell
$ hub serving start --modules lac
```
更多关于模型服务化使用说明参见[PaddleHub模型一键服务化部署](./docs/tutorial/serving.md)
## FAQ
**Q:** 利用PaddleHub Fine-tune如何适配自定义数据集?
**A:** 参考[PaddleHub使用自定义数据集完成Fine-tune](./docs/tutorial/how_to_load_data.md)
**Q:** 使用PaddleHub时,无法下载预置数据集、Module的等现象。
**A:** 下载数据集、module等,PaddleHub要求机器可以访问外网。可以使用server_check()可以检查本地与远端PaddleHub-Server的连接状态,使用方法如下:
```python
import paddlehub
paddlehub.server_check()
# 如果可以连接远端PaddleHub-Server,则显示Request Hub-Server successfully。
# 如果无法连接远端PaddleHub-Server,则显示Request Hub-Server unsuccessfully。
```
**[More](./docs/faq.md)**
当您安装或者使用遇到问题时,如果在FAQ中没有找到解决方案,欢迎您将问题以[Github Issues](https://github.com/PaddlePaddle/PaddleHub/issues)的形式提交给我们,我们会第一时间进行跟进。
<a name="欢迎加入PaddleHub技术交流群"></a>
## 微信扫描二维码,欢迎加入PaddleHub技术交流群
<div align="center">
<img src="./docs/imgs/joinus.JPEG" width = "200" height = "200" />
</div>
如扫码失败,请添加微信15711058002,并备注“Hub”,运营同学会邀请您入群。
<a name="许可证书"></a>
## 许可证书
......
# 如何编写一个PaddleHub Module
## 模型基本信息
我们准备编写一个PaddleHub Module,Module的基本信息如下:
```yaml
name="openpose_body_estimation",
type="CV/image_editing",
author="paddlepaddle",
author_email="",
summary="Openpose_body_estimation is a body pose estimation model based on Realtime Multi-Person 2D Pose \
Estimation using Part Affinity Fields.",
version="1.0.0"
```
Module存在一个接口predict,用于接收传入图片,并得到最终输出的结果,支持python接口调用和命令行调用。
```python
import paddlehub as hub
model = hub.Module(name="openpose_body_estimation")
result = model.predict("demo.jpg")
```
```cmd
hub run openpose_body_estimation --input_path demo.jpg
```
## Module创建
### step 1. 创建必要的目录与文件
创建一个openpose_body_estimation的目录,并在openpose_body_estimation目录下分别创建module.py, processor.py。其中
|文件名|用途|
|-|-|
|module.py|主模块,提供Module的实现代码|
|processor.py|辅助模块,提供词表加载的方法|
```cmd
➜ tree openpose_body_estimation
openpose_body_estimation/
├── module.py
└── processor.py
```
### step 2. 实现辅助模块processor
在processor.py中实现一些在module.py里面需要调用到的类和函数。例如在processor.py 中实现ResizeScaling类:
```python
class ResizeScaling:
"""Resize images by scaling method.
Args:
target(int): Target image size.
interpolation(Callable): Interpolation method.
"""
def __init__(self, target: int = 368, interpolation: Callable = cv2.INTER_CUBIC):
self.target = target
self.interpolation = interpolation
def __call__(self, img, scale_search):
scale = scale_search * self.target / img.shape[0]
resize_img = cv2.resize(img, (0, 0), fx=scale, fy=scale, interpolation=self.interpolation)
return resize_img
```
### step 3. 编写Module处理代码
module.py文件为Module的入口代码所在,我们需要在其中实现预测逻辑。
#### step 3_1. 引入必要的头文件
```python
import os
import time
import copy
import base64
import argparse
from typing import Union
from collections import OrderedDict
import cv2
import paddle
import paddle.nn as nn
import numpy as np
from paddlehub.module.module import moduleinfo, runnable, serving
import paddlehub.vision.transforms as T
import openpose_body_estimation.processor as P
```
**NOTE:** `paddlehub.vision.transforms`有常见的图像处理方法,可以方便调用。
#### step 3_2. 定义BodyPoseModel类
module.py中需要有一个继承了nn.Layer,该类负责实现预测逻辑,并使用moduleinfo填写基本信息。当使用hub.Module(name="openpose_body_estimation")加载Module时,PaddleHub会自动创建openpose_body_estimation的对象并返回。
```python
@moduleinfo(
name="openpose_body_estimation",
type="CV/image_editing",
author="paddlepaddle",
author_email="",
summary="Openpose_body_estimation is a body pose estimation model based on Realtime Multi-Person 2D Pose \
Estimation using Part Affinity Fields.",
version="1.0.0")
class BodyPoseModel(nn.Layer):
...
```
#### step 3_3. 执行必要的初始化及模型搭建
模型的初始化主要完成几个功能:待使用的类的声明,模型使用的类的声明及参数加载。
```python
def __init__(self, load_checkpoint: str = None):
super(BodyPoseModel, self).__init__()
#将会使用到的类的声明
self.resize_func = P.ResizeScaling()
self.norm_func = T.Normalize(std=[1, 1, 1])
#模型声明
self.input_nc = 4
self.output_nc = 2
model1 = (
Conv2D(self.input_nc, 64, 3, 1, 1),
nn.ReLU(),
Conv2D(64, 64, 3, 1, 1),
nn.ReLU(),
nn.BatchNorm(64),
)
self.model1 = nn.Sequential(*model1)
#参数加载
if load_checkpoint is not None:
self.model_dict = paddle.load(load_checkpoint)
self.set_dict(self.model_dict)
print("load custom checkpoint success")
else:
checkpoint = os.path.join(self.directory, 'model.pdparams')
self.model_dict = paddle.load(checkpoint)
self.set_dict(self.model_dict)
print("load pretrained checkpoint success")
```
模型的搭建主要在`forward`里面实现:
```python
def forward(self, input: paddle.Tensor) -> paddle.Tensor:
result = self.model1(input)
return result
```
#### step 3_4. 完善预测逻辑
```python
def predict(self, img:Union(np.ndarray,str), visualization: bool = True):
self.eval()
self.visualization = visualization
if isinstance(img, str):
orgImg = cv2.imread(img)
else:
orgImg = img
data = self.resize_func(self.norm_func(orgImg))
output = self.forward(paddle.to_tensor(data.astype('float32')))
output = paddle.clip(output[0].transpose((1, 2, 0)), 0, 255).numpy()
output = output.astype(np.uint8)
if self.visualization:
style_name = "body_" + str(time.time()) + ".png"
if not os.path.exists(save_path):
os.mkdir(save_path)
path = os.path.join(save_path, style_name)
cv2.imwrite(path, output)
return output
```
#### step 3_5. 支持命令行调用
如果希望Module可以支持命令行调用,则需要提供一个经过runnable修饰的接口,接口负责解析传入数据并进行预测,将结果返回。
```python
@runnable
def run_cmd(self, argvs):
"""
Run as a command.
"""
self.parser = argparse.ArgumentParser(
description="Run the {} module.".format(self.name),
prog='hub run {}'.format(self.name),
usage='%(prog)s',
add_help=True)
self.arg_input_group = self.parser.add_argument_group(
title="Input options", description="Input data. Required")
self.arg_config_group = self.parser.add_argument_group(
title="Config options",
description=
"Run configuration for controlling module behavior, not required.")
self.add_module_config_arg()
self.add_module_input_arg()
args = self.parser.parse_args(argvs)
results = self.predict(
img=args.input_path,
save_path=args.output_dir,
visualization=args.visualization)
return results
def add_module_config_arg(self):
"""
Add the command config options.
"""
self.arg_config_group.add_argument(
'--output_dir',
type=str,
default='openpose_body',
help="The directory to save output images.")
self.arg_config_group.add_argument(
'--save_dir',
type=str,
default='openpose_model',
help="The directory to save model.")
self.arg_config_group.add_argument(
'--visualization',
type=bool,
default=True,
help="whether to save output as images.")
def add_module_input_arg(self):
"""
Add the command input options.
"""
self.arg_input_group.add_argument(
'--input_path', type=str, help="path to image.")
```
#### step 3_6. 支持serving调用
如果希望Module可以支持PaddleHub Serving部署预测服务,则需要提供一个经过serving修饰的接口,接口负责解析传入数据并进行预测,将结果返回。
如果不需要提供PaddleHub Serving部署预测服务,则可以不需要加上serving修饰。
```python
@serving
def serving_method(self, images, **kwargs):
"""
Run as a service.
"""
images_decode = [base64_to_cv2(image) for image in images]
results = self.predict(img=images_decode[0], **kwargs)
final={}
final['data'] = P.cv2_to_base64(results)
return final
```
## 测试步骤
完成Module编写后,我们可以通过以下方式测试该Module
### 调用方法1
将Module安装到本机中,再通过Hub.Module(name=...)加载
```shell
hub install openpose_body_estimation
```
```python
import paddlehub as hub
if __name__ == "__main__":
model = hub.Module(name='openpose_hands_estimation')
result = model.predict("demo.jpg")
```
### 调用方法2
将Module安装到本机中,再通过hub run运行
```shell
hub install openpose_body_estimation
hub run openpose_body_estimation --input_path demo.jpg
```
### 测试serving方法
运行启动命令:
```shell
$ hub serving start -m openpose_body_estimation
```
发送预测请求,获取预测结果.
```python
import requests
import json
import cv2
import base64
import numpy as np
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
def base64_to_cv2(b64str):
data = base64.b64decode(b64str.encode('utf8'))
data = np.fromstring(data, np.uint8)
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
return data
# 发送HTTP请求
org_im = cv2.imread('/PATH/TO/IMAGE')
data = {'images':[cv2_to_base64(org_im)]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/openpose_body_estimation"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
canvas = base64_to_cv2(r.json()["results"]['data'])
cv2.imwrite('keypoint_body.png', canvas)
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册