我正在进行一个任务,需要从一张图片中提取日期。这些日期是通过Google Cloud Platform Vision API提取的。我怎样才能使用Flask创建一个可以接受图片并返回日期的API?格式看起来应该像下面这样:
请求:POST /extract_date
负载:{“base_64_image_content”: }
响应:如果日期存在:{“date”: “YYYY-MM-DD”} 如果日期不存在:{“date”: null}
你能帮我吗?
回答:
Flask 是Python中最受欢迎的Web框架之一。它相对容易学习,而其扩展 Flask-RESTful 能让你快速构建REST API。
最小示例:
from flask import Flaskfrom flask_restful import Resource, Apiapp = 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()
使用 curl
测试:
curl http://localhost:5000/ -d "data=base_64_image_content" -X PUT
根据评论中的讨论,以下是如何使用 GCP Functions 构建OCR REST API 的方法:
import reimport jsonfrom google.protobuf.json_format import MessageToJsonfrom google.cloud import visionfrom flask import Responsedef detect_text(request): """响应任何HTTP请求。 Args: request (flask.Request): HTTP请求对象。 Returns: 响应文本或任何可以转换为 使用 `make_response <http://flask.pocoo.org/docs/0.12/api/#flask.Flask.make_response>` 生成的 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
以下是用于发送请求的代码片段:
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