阅读973 返回首页    go 阿里云 go 技术社区[云栖]


用Google API 提取名片信息

介绍

我们每个人或多或少都会使用到名片。但是如果名片数量一大,管理它们就显得非常麻烦。因此我产生用这篇文章的案例来管理他们。

这里,我先用手机对每张名片拍照,并按以下流程进行处理:

38e6c9eb36604a8b974cb8cce546a2e4e2979f78

把获得的名片图像交给我们的应用程序,抽取人名,公司名称,地址等信息。这里我使用了Google Vision API 和 自然语言(Natural Language )API,因为这两个API简单易用,并且性能也很不错。

我使用Python来编写我的这个应用程序,来调用 Google Vision API 和 Natural Language API。

创建步骤

第 0 步: 准备

第 1 步: 用Google Vision API识别文本

第 2 步: 用Natural Language API抽取人名,公司名称及地址信息

第 3 步: 整合第1和第2步

第0步 准备

在开始应用程序编写之前,我们要安装必要的类库,下载配置以及设置API的键值。从这个链接你能设置 Google API key 。

安装类库

执行一下命令行来安装类库。

$ pip install requests
$ pip install pyyaml

下载资源库

这里我已经事先准备好了资源库。也可以从下面的链接下载。

设置API Key

把Google API key 写进配置文件 (plugins/config/google.yaml).
首先,打开 google.yaml 把你的API key替换掉 xxx。

token: xxx

第1步 用Google Vision API识别文本

Vision API 简介

依靠强大的机器学习模型,谷歌 Vision API 能让你编写自己的图像识别应用程序。Vision API 有以下的功能:

  • 图像分类 (例如 “快艇” “狮子” “埃菲尔铁塔” 等等)
  • 脸部识别
  • 文本识别
  • 标志识别
  • 地标识别
  • 安全搜索识别

Vision API 每月有1000个免费请求。

编写脚本

这里我们编写Python脚本来使用 Vision API。把以下代码保存为plugins/apis/vision.py。 这里我们要使用UTF-8编码。

# -*- coding: utf-8 -*-
import base64
import requests


def detect_text(image_file, access_token=None):

    with open(image_file, 'rb') as image:
        base64_image = base64.b64encode(image.read()).decode()

    url = 'https://vision.googleapis.com/v1/images:annotate?key={}'.format(access_token)
    header = {'Content-Type': 'application/json'}
    body = {
        'requests': [{
            'image': {
                'content': base64_image,
            },
            'features': [{
                'type': 'TEXT_DETECTION',
                'maxResults': 1,
            }]

        }]
    }
    response = requests.post(url, headers=header, json=body).json()
    text = response['responses'][0]['textAnnotations'][0]['description'] if len(response['responses'][0]) > 0 else ''
    return text

输入图像文件路径和API key到detect_text 函数, 我们就能得到图像文件中的文本信息

运行脚本

首先,把脚本文件移入 plugins/tests 文件夹。其中已经有一个test_vision.py 文件。在test_vision.py中, 编写调用detect_text 函数的测试用例。如果运行正常,我们就能获取图像中的文本信息了。

用下面 example_en.png这张名片作为输入,运行脚本。

a05bb95b1700b76f30c8e7b775657dc7af0fcf43

$ python test_vision.py data/example_en.png

输出结果

John Smith.
Capsule Corporation
217-767-8187
1332 Spring Street Elwin Illinois

第 2 步用Natural Language API抽取人名,公司名称及地址信息

Natural Language API简介

Natural Language API 提供了强大的机器学习模型,以REST API 的形式识别文本结构和其中的含义。Natural Language API 有一下功能:

  • 实体识别 (如,个人姓名,机构名称,事件信息等)
  • 语意分析 (产品评论中的情感,客户意见等)
  • 语法分析

Vision API 每月有5000个免费请求。

运行脚本

同样我们编写Python脚本来调用Natural Language API. 保存脚本为plugins/apis/language.py。注意使用UTF-8编码。

# -*- coding: utf-8 -*-
import requests


def extract_entities(text, access_token=None):

    url = 'https://language.googleapis.com/v1beta1/documents:analyzeEntities?key={}'.format(access_token)
    header = {'Content-Type': 'application/json'}
    body = {
        "document": {
            "type": "PLAIN_TEXT",
            "language": "EN",
            "content": text
        },
        "encodingType": "UTF8"
    }
    response = requests.post(url, headers=header, json=body).json()
    return response


def extract_required_entities(text, access_token=None):
    entities = extract_entities(text, access_token)
    required_entities = {'ORGANIZATION': '', 'PERSON': '', 'LOCATION': ''}
    for entity in entities['entities']:
        t = entity['type']
        if t in required_entities:
            required_entities[t] += entity['name']

    return required_entities

把文本数据和API key 以参数形式传入 extract_entities 函数, 不同的实体信息就能被提取出来。而我们只需要 公司名称个人姓名, 地点信息 。extract_required_entities 函数就是用来筛选出这些需要的内容。

运行脚本

st, move to the plugins/tests folder. Can you see that there is test_language.py in the folder? In test_language.py, it is specified to call extract_required_entities function. In other words, if it works correctly, it will return the company name, person’s name and address in the text.

I will do it. Give example_en.txt in the data folder and run it. In example_en.txt contains the character recognition result as above image.

$ python test_language.py data/example.txt

输出结果

{'LOCATION': 'Spring Street Elwin Illinois', 'PERSON': 'John Smith', 'ORGANIZATION': 'Capsule Corporation'}

Step 3 整合第1和第2步I

最后,我们再编写另一个脚本整合 Vision API 和 Natural Language API。

编写脚本

编写脚本整合 Vision API 和 Natural Language API. 保存为 plugins/apis/integration.py。这里我们要使用UTF-8编码。

# -*- coding: utf-8 -*-
from .language import extract_required_entities
from .vision import detect_text


def extract_entities_from_img(img_path, access_token):

    text = detect_text(img_path, access_token)
    entities = extract_required_entities(text, access_token)

    return entities

By giving the image file path and API key to extract_entities_from_img function, it recognizes and returns the company name and person’s name in the image file. Let’s run it for checking.

运行脚本

Let’s run the script.
First, move to the plugins/tests folder. Can you see that there is test_integration.py in it? In test_integration.py, it is specified to call extract_entities_from_img function. In other words, if it operates correctly, it will return the company name etc. in the image.

I will do it. Give example_en.png in the data folder and run it.

$ python test_integration.py data/example_en.png

输出结果

{'LOCATION': 'Spring Street Elwin Illinois', 'PERSON': 'John Smith', 'ORGANIZATION': 'Capsule Corporation'}

结论

以上我们用 Google Vision API 和 Natural Language API编写了一个简单的提取名片信息的应用程序。然而,这只是个简单的原型,之后我还会对它进行改进,让它更加完善。


以上为译文

文章原标题《Extracting Information from Business Card with Google API》,作者:HIRONSAN

文章为简译,更为详细的内容,请查看原文


最后更新:2017-04-12 14:30:20

  上一篇:go 绝密隐私,竟然有这样的高效的办公软件
  下一篇:go 杞︽带APP鍙戠幇瀹夊叏闅愭偅锛岀爷绌朵汉锻樻ā鎷熼粦瀹㈠叆渚?鍗氩-浜戞尔绀惧尯-阒块噷浜?