How to make a REST API for OCR

坚强是说给别人听的谎言 提交于 2019-12-13 09:04:23

问题


I am doing a task in which I have an image and have to extract dates from it. The dates are extracted with Google Cloud Platform Vision API. How can I make API with flask that accepts image and returns date? The format would look something like below:

Request:POST /extract_date

Payload: {“base_64_image_content”: }

Response: If date is present: {“date”: “YYYY-MM-DD”} If date is not present: {“date”: null}

Can you please help me?


回答1:


Flask is among the most popular web frameworks for Python. It's relatively easy to learn, while its extension Flask-RESTful enables you to quickly build REST API.

Minimal example:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class MyApi(Resource):
    def get(self, date):
        return {'date': 'if present'}

api.add_resource(MyApi, '/')

if __name__ == '__main__':
    app.run()

Test with curl:

curl http://localhost:5000/ -d "data=base_64_image_content" -X PUT

Following discussion in comments, here's how one can build OCR REST API with GCP Functions:

import re
import json
from google.protobuf.json_format import MessageToJson
from google.cloud import vision
from flask import Response


def detect_text(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/0.12/api/#flask.Flask.make_response>`.
    """
    client = vision.ImageAnnotatorClient()
    image = vision.types.Image(content=request.data)
    response = client.text_detection(image=image)
    serialized = MessageToJson(response)
    annotations = json.loads(serialized)

    full_text = annotations['textAnnotations'][0]['description']
    annotations = json.dumps(annotations)

    r = Response(response=annotations, status=200, mimetype="application/json")
    return r

Here's piece of code you can use to make the request:

def post_image(path, URL):
    headers = {'content-type': 'image/jpeg'}
    img = open(path, 'rb').read()
    response = requests.post(URL, data=img, headers=headers)
    return response


来源:https://stackoverflow.com/questions/58999196/how-to-make-a-rest-api-for-ocr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!