forked from GoogleCloudPlatform/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_function.py
More file actions
67 lines (57 loc) · 2.46 KB
/
document_function.py
File metadata and controls
67 lines (57 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# [START bigquery_remote_function_document]
import urllib.request
import flask
import functions_framework
from google.api_core.client_options import ClientOptions
from google.cloud import documentai
_PROJECT_ID = "YOUR_PROJECT_ID"
_LOCATION = "us" # Change to "eu"
_PROCESSOR_ID = "YOUR_PROCESSOR_ID"
@functions_framework.http
def document_ocr(request: flask.Request) -> flask.Response:
"""BigQuery remote function to process document using Document AI OCR.
For complete Document AI use cases:
https://cloud.google.com/document-ai/docs/samples/documentai-process-ocr-document
Args:
request: HTTP request from BigQuery
https://cloud.google.com/bigquery/docs/reference/standard-sql/remote-functions#input_format
Returns:
HTTP response to BigQuery
https://cloud.google.com/bigquery/docs/reference/standard-sql/remote-functions#output_format
"""
try:
client = documentai.DocumentProcessorServiceClient(
client_options=ClientOptions(
api_endpoint=f"{_LOCATION}-documentai.googleapis.com"
)
)
processor_name = client.processor_path(_PROJECT_ID, _LOCATION, _PROCESSOR_ID)
calls = request.get_json()["calls"]
replies = []
for call in calls:
content = urllib.request.urlopen(call[0]).read()
content_type = call[1]
results = client.process_document(
{
"name": processor_name,
"raw_document": {"content": content, "mime_type": content_type},
}
)
replies.append({"text": results.document.text})
return flask.make_response(flask.jsonify({"replies": replies}))
except Exception as e: # Check error message if GoogleAPIException
return flask.make_response(flask.jsonify({"errorMessage": str(e)}), 400)
# [END bigquery_remote_function_document]