閱讀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鍙戠幇瀹夊叏闅愭偅锛岀爺絀朵漢鍛樻ā鎷熼粦瀹㈠靉渚?鍗氬-浜戞爾紺懼尯-闃塊噷浜?