问题
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