├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── apispec.yaml ├── app.json ├── app.py ├── deploy.sh ├── requirements.txt └── tempdoc.pdf /.gitignore: -------------------------------------------------------------------------------- 1 | key.json 2 | launch.json 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | pip-wheel-metadata/ 26 | share/python-wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | .python-version 88 | 89 | # pipenv 90 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 91 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 92 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 93 | # install all needed dependencies. 94 | #Pipfile.lock 95 | 96 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 97 | __pypackages__/ 98 | 99 | # Celery stuff 100 | celerybeat-schedule 101 | celerybeat.pid 102 | 103 | # SageMath parsed files 104 | *.sage.py 105 | 106 | # Environments 107 | .env 108 | .venv 109 | env/ 110 | venv/ 111 | ENV/ 112 | env.bak/ 113 | venv.bak/ 114 | 115 | # Spyder project settings 116 | .spyderproject 117 | .spyproject 118 | 119 | # Rope project settings 120 | .ropeproject 121 | 122 | # mkdocs documentation 123 | /site 124 | 125 | # mypy 126 | .mypy_cache/ 127 | .dmypy.json 128 | dmypy.json 129 | 130 | # Pyre type checker 131 | .pyre/ 132 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:latest 2 | 3 | # Create app directory 4 | WORKDIR /app 5 | 6 | # Install app dependencies 7 | COPY requirements.txt ./ 8 | 9 | RUN pip install -r requirements.txt 10 | # Bundle app source 11 | COPY . /app 12 | # COPY . . 13 | 14 | EXPOSE 8080 15 | CMD [ "python", "app.py" ] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AppSheet Document AI Adapter 2 | 3 | This service provides a REST API for AppSheet to integrate GCP Document AI services into AppSheet no-code apps. It uses MongoDB to store the document AI results, and then sync to AppSheet through the API hosted in this service. 4 | 5 | AppSheet connects to this service using the API data provider (Apigee provider), which can then synchronize document forms to the API and get the form processing results back to display to the user. 6 | 7 | ## Deployment 8 | 9 | [![Run on Google Cloud](https://deploy.cloud.run/button.svg)](https://deploy.cloud.run) 10 | 11 | You can run this service on any container platform, for example Google Cloud Run (see button above) or Google Kubernetes Engine. 12 | 13 | Set these environment variables when deploying. 14 | 15 | | Env name | Env description | 16 | | -------------------------------- | --------------------------------------------------------- | 17 | | GCP_DOCAI_REGION | The Document AI region (eu or us) | 18 | | GCP_DOCAI_PROCESSOR_ID | The Document AI processor ID (from the GCP console) | 19 | | API_KEY | A secret that AppSheet can use to call this API | 20 | 21 | ## Configuration in AppSheet 22 | 23 | After deploying the service, add a new **Apigee** data source to your AppSheet account pointing to the deployed service URL + "/spec". 24 | -------------------------------------------------------------------------------- /apispec.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.3 2 | info: 3 | description: API for managing Formfield resources. 4 | version: 0.0.1 5 | title: Formfields API 6 | servers: 7 | - url: SERVER_URL 8 | security: [] 9 | paths: 10 | /formfields: 11 | get: 12 | summary: List 'Formfield' objects. 13 | description: Retrieve a page of 'Formfield' objects from the server. Follows 14 | the standards for parameters from the [List AIP]( https://aip.dev/132). 15 | parameters: 16 | - name: pageSize 17 | in: query 18 | description: Max size of returned list. 19 | schema: 20 | type: integer 21 | default: "25" 22 | - name: pageToken 23 | in: query 24 | description: A page token recieved from the previous list call. Provide this 25 | to retrieve the next page. 26 | schema: 27 | type: string 28 | - name: orderBy 29 | in: query 30 | description: The ordering of the returned list. See the [List Ordering API]( 31 | https://aip.dev/132) for details on the formatting of this field. 32 | schema: 33 | type: string 34 | default: displayName 35 | - name: filter 36 | in: query 37 | description: Filter that will be used to select Formfield objects to return. 38 | See the [Filtering AIP](https://aip.dev/160) for usage and details on the 39 | filtering grammar. 40 | schema: 41 | type: string 42 | responses: 43 | "200": 44 | description: Successful response 45 | content: 46 | application/json: 47 | schema: 48 | type: object 49 | properties: 50 | formfields: 51 | type: array 52 | items: 53 | $ref: '#/components/schemas/ListOfFormfields' 54 | post: 55 | summary: Creates a new 'Formfield' object. 56 | description: Creates a new 'Formfield' object. 57 | requestBody: 58 | description: The Formfield object to create. 59 | required: false 60 | content: 61 | application/json: 62 | schema: 63 | $ref: '#/components/schemas/Formfield' 64 | responses: 65 | "201": 66 | description: Successful response 67 | content: 68 | application/json: 69 | schema: 70 | $ref: '#/components/schemas/Formfield' 71 | /formfields/{formfield}: 72 | get: 73 | summary: Retrieve Formfield object. 74 | description: Retrieve a single Formfield object. 75 | parameters: 76 | - name: formfield 77 | in: path 78 | required: true 79 | description: Unique identifier of the desired Formfield object. 80 | schema: 81 | type: string 82 | responses: 83 | "200": 84 | description: Successful response 85 | content: 86 | application/json: 87 | schema: 88 | $ref: '#/components/schemas/Formfield' 89 | "404": 90 | description: Formfield was not found. 91 | put: 92 | summary: Update Formfield object. 93 | description: Update a single Formfield object. 94 | parameters: 95 | - name: formfield 96 | in: path 97 | required: true 98 | description: Unique identifier of the desired Formfield object. 99 | schema: 100 | type: string 101 | requestBody: 102 | description: The Formfield object to update. 103 | required: false 104 | content: 105 | application/json: 106 | schema: 107 | $ref: '#/components/schemas/Formfield' 108 | responses: 109 | "200": 110 | description: Successful response 111 | content: 112 | application/json: 113 | schema: 114 | $ref: '#/components/schemas/Formfield' 115 | "404": 116 | description: Formfield was not found. 117 | delete: 118 | summary: Delete Formfield object. 119 | description: Delete a single Formfield object. 120 | parameters: 121 | - name: formfield 122 | in: path 123 | required: true 124 | description: Unique identifier of the desired Formfield object. 125 | schema: 126 | type: string 127 | responses: 128 | "200": 129 | description: Successful response 130 | "404": 131 | description: Formfield was not found. 132 | components: 133 | securitySchemes: {} 134 | schemas: 135 | Formfield: 136 | title: Formfield 137 | type: object 138 | properties: 139 | _id: 140 | description: The _id of the Formfield 141 | type: string 142 | example: 61423ce41b520b8e9296fca3 143 | documentId: 144 | description: The documentId of the Formfield 145 | type: string 146 | example: jdkjrk3 147 | documentPath: 148 | description: The documentPath of the Formfield 149 | type: string 150 | example: /path/to/doc 151 | formFields: 152 | description: The formFields of the Formfield 153 | type: string 154 | example: "\nEnglish\n=☑ \nFrançais\n=\nEsperanto\n=\nHouse nr: =88\n\nPostcode:\n=12345\n\nDeutsch 155 | =☐ \nLatin\n=☐ \nGender:\n=Man\n\nCity: =Hobiton\n\nGiven Name:\n=Bilbo\n\nFamily 156 | Name:\n=Baggins\n\nAddress 1:\n=Bag End\n\nHeight (cm):\n=65\n\nCountry:\n=The 157 | Shire\n\nFavourite colour:\n=Red\n\nDriving License:\n=" 158 | formId: 159 | description: The formId of the Formfield 160 | type: string 161 | example: test123 162 | ListOfFormfields: 163 | title: List of Formfield objects 164 | type: array 165 | items: 166 | $ref: '#/components/schemas/Formfield' 167 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "document-ai-adapter", 3 | "env": { 4 | "GCP_DOCAI_REGION": { 5 | "value": "eu", 6 | "description": "Region (eu or us) where the Document AI form processor is deployed." 7 | }, 8 | "GCP_DOCAI_PROCESSOR_ID": { 9 | "description": "The Document AI form processor ID from the deployment (visible in the overview information for the processor)." 10 | }, 11 | "API_KEY": { 12 | "generator": "secret", 13 | "description": "A secret that to be used to access the API." 14 | } 15 | }, 16 | "options": { 17 | "allow-unauthenticated": true 18 | }, 19 | "hooks": { 20 | "postbuild": { 21 | "commands": [ 22 | "gcloud config set project $GOOGLE_CLOUD_PROJECT", 23 | "gcloud services enable appengine.googleapis.com", 24 | "gcloud services enable firebase.googleapis.com", 25 | "gcloud services enable drive.googleapis.com", 26 | "gcloud app create --region=europe-west", 27 | "gcloud firestore databases create --region=europe-west", 28 | "PROJECTNUMBER=$(gcloud projects list --filter=\"$(gcloud config get-value project)\" --format=\"value(PROJECT_NUMBER)\") && gcloud projects add-iam-policy-binding $GOOGLE_CLOUD_PROJECT --member=\"serviceAccount:$PROJECTNUMBER-compute@developer.gserviceaccount.com\" --role='roles/documentai.apiUser'", 29 | "echo $API_KEY" 30 | ] 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import pprint 2 | from proto import fields 3 | import web 4 | import json 5 | import logging 6 | import urllib 7 | import requests 8 | import io 9 | import os 10 | from googleapiclient.http import MediaIoBaseDownload 11 | from google.cloud import documentai_v1 as documentai 12 | import os.path 13 | from googleapiclient.discovery import build 14 | from google.oauth2 import service_account 15 | from google.auth.transport.requests import Request 16 | from google.oauth2.credentials import Credentials 17 | 18 | import google.auth 19 | 20 | SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] 21 | location = os.getenv('GCP_DOCAI_REGION') 22 | processor_id = os.getenv('GCP_DOCAI_PROCESSOR_ID') 23 | 24 | urls = ( 25 | '/formfields(.*)', 'formfields', 26 | '/(.*)', 'openapispec' 27 | ) 28 | app = web.application(urls, globals()) 29 | 30 | class formfields: 31 | 32 | result = { 33 | "formfields": [ 34 | { 35 | "formId": "bec38fd6", 36 | "documentId": "bec38fd6", 37 | "documentPath": "Document AI Forms_Files_/e111806a.Attachment.162159.pdf", 38 | "formFields": "\nEnglish=☑ \nFrançais=\nEsperanto=\nHouse nr=1\nPostcode=11111\nDeutsch=☐ \nLatin=☐ \nGender=Man\nCity=Hobbiton\nCountry=Britain\nGiven Name=Bilbo\nHeight (cm)=100\nAddress 1=Bag End\nAddress 2=Under Hill\nFamily Name=Baggins\nFavourite colour=Red\nDriving License=", 39 | "formThumbnail": "https://storage.googleapis.com/bruno-hosting/appsheet/form_thumb.png", 40 | "totalFields": 17, 41 | "filledFields": 14 42 | } 43 | ] 44 | } 45 | 46 | # Returns all of the formfields 47 | def GET(self, name): 48 | 49 | pprint.pprint(web.ctx.home + web.ctx.fullpath) 50 | 51 | pprint.pprint(self.result) 52 | 53 | web.header('Content-Type', 'application/json') 54 | return json.dumps(self.result) 55 | 56 | # Posts a new form to be processed 57 | def POST(self, name): 58 | 59 | data = json.loads(web.data()) 60 | 61 | logging.info(json.dumps(data)) 62 | 63 | docId, documentPath = "", "" 64 | if "documentId" in data: 65 | docId = data["documentId"] 66 | if "documentPath" in data: 67 | documentPath = data["documentPath"] 68 | 69 | newRecord = { 70 | "formId": data["formId"], 71 | "documentId": docId, 72 | "documentPath": documentPath 73 | } 74 | 75 | fieldsInfo = { 76 | "formFields": "", 77 | "formThumbnail": "" 78 | } 79 | 80 | if documentPath: 81 | fieldsInfo = callDocAI(documentPath) 82 | 83 | for key in fieldsInfo: 84 | newRecord[key] = fieldsInfo[key] 85 | 86 | self.result["formfields"].append(newRecord) 87 | 88 | pprint.pprint(newRecord) 89 | 90 | web.header('Content-Type', 'application/json') 91 | return json.dumps(newRecord) 92 | 93 | # Returns the OpenAPI spec, filled in with the current server 94 | class openapispec: 95 | 96 | #Returns the OpenAPI spec, filled in with the current server 97 | def GET(self, name): 98 | f = open("apispec.yaml", "r") 99 | spec = f.read() 100 | spec = spec.replace("SERVER_URL", web.ctx.home.replace("http://", "https://")) 101 | web.header('Content-Type', 'text/plain;charset=UTF-8') 102 | return spec 103 | 104 | # Leftover for testing.. not used. 105 | def quickstart(project_id: str, location: str, processor_id: str, file_path: str): 106 | 107 | # You must set the api_endpoint if you use a location other than 'us', e.g.: 108 | opts = {} 109 | if location == "eu": 110 | opts = {"api_endpoint": "eu-documentai.googleapis.com"} 111 | 112 | client = documentai.DocumentProcessorServiceClient(client_options=opts) 113 | 114 | # The full resource name of the processor, e.g.: 115 | # projects/project-id/locations/location/processor/processor-id 116 | # You must create new processors in the Cloud Console first 117 | name = f"projects/{project_id}/locations/{location}/processors/{processor_id}" 118 | 119 | # Read the file into memory 120 | with open(file_path, "rb") as image: 121 | image_content = image.read() 122 | 123 | document = {"content": image_content, "mime_type": "application/pdf"} 124 | 125 | # Configure the process request 126 | request = {"name": name, "raw_document": document} 127 | 128 | result = client.process_document(request=request) 129 | document = result.document 130 | 131 | document_pages = document.pages 132 | # For a full list of Document object attributes, please reference this page: https://googleapis.dev/python/documentai/latest/_modules/google/cloud/documentai_v1beta3/types/document.html#Document 133 | 134 | # Read the text recognition output from the processor 135 | print("The document contains the following paragraphs:") 136 | for page in document_pages: 137 | paragraphs = page.paragraphs 138 | formFields = page.form_fields 139 | 140 | for form_field in page.form_fields: 141 | print( 142 | "Field Name: {}\tConfidence: {}".format( 143 | _get_text(form_field.field_name, document), form_field.field_name.confidence 144 | ) 145 | ) 146 | print( 147 | "Field Value: {}\tConfidence: {}".format( 148 | _get_text(form_field.field_value, document), form_field.field_value.confidence 149 | ) 150 | ) 151 | # for block in page.lines: 152 | # print(str(block)) 153 | # for field in formFields: 154 | # print(str(field)) 155 | 156 | # for paragraph in paragraphs: 157 | # #print(paragraph) 158 | # paragraph_text = get_text(paragraph.layout, document) 159 | # print(f"Paragraph text: {paragraph_text}") 160 | 161 | # Helper function to get text from form fields 162 | def _get_text(el, document): 163 | """Doc AI identifies form fields by their offsets 164 | in document text. This function converts offsets 165 | to text snippets. 166 | """ 167 | response = "" 168 | # If a text segment spans several lines, it will 169 | # be stored in different text segments. 170 | for segment in el.text_anchor.text_segments: 171 | start_index = segment.start_index 172 | end_index = segment.end_index 173 | response += document.text[start_index:end_index] 174 | return response 175 | 176 | # Helper function to get text from form fields 177 | def get_text(doc_element: dict, document: dict): 178 | """ 179 | Document AI identifies form fields by their offsets 180 | in document text. This function converts offsets 181 | to text snippets. 182 | """ 183 | response = "" 184 | # If a text segment spans several lines, it will 185 | # be stored in different text segments. 186 | for segment in doc_element.text_anchor.text_segments: 187 | start_index = ( 188 | int(segment.start_index) 189 | if segment in doc_element.text_anchor.text_segments 190 | else 0 191 | ) 192 | end_index = int(segment.end_index) 193 | response += document.text[start_index:end_index] 194 | return response 195 | 196 | # Method to call the Document AI API and get the form processing results 197 | def callDocAI(documentPath: str): 198 | 199 | output = { 200 | "formFields": "", 201 | "formThumbnail": "", 202 | "totalFields": 0, 203 | "filledFields": 0 204 | } 205 | 206 | creds, project_id = google.auth.default(scopes=SCOPES) 207 | #creds = service_account.Credentials.default(scopes=SCOPES) 208 | 209 | service = build('drive', 'v3', credentials=creds) 210 | page_token = None 211 | 212 | response = service.files().list(q="name='" + documentPath.split("/")[-1] + "'", 213 | spaces='drive', 214 | fields='nextPageToken, files(id, name, thumbnailLink)', 215 | pageToken=page_token).execute() 216 | 217 | for file in response.get('files', []): 218 | # Process change 219 | print("Found file: " + file.get('name') + " and id: " + file.get('id')) 220 | request = service.files().get_media(fileId=file.get('id')) 221 | # fh = io.BytesIO() 222 | fh = io.FileIO('tempdoc.pdf', 'wb') 223 | downloader = MediaIoBaseDownload(fh, request) 224 | done = False 225 | while done is False: 226 | status, done = downloader.next_chunk() 227 | print("Download " + str(int(status.progress() * 100))) 228 | 229 | output["formThumbnail"] = file["thumbnailLink"] 230 | break 231 | 232 | opts = {"api_endpoint": "eu-documentai.googleapis.com"} 233 | 234 | client = documentai.DocumentProcessorServiceClient(client_options=opts) 235 | name = f"projects/{project_id}/locations/{location}/processors/{processor_id}" 236 | 237 | with open("tempdoc.pdf", "rb") as image: 238 | image_content = image.read() 239 | 240 | mime = "application/pdf" 241 | if documentPath.endswith(".png"): 242 | mime = "image/png" 243 | 244 | document = {"content": image_content, "mime_type": mime} 245 | 246 | # Configure the process request 247 | request = {"name": name, "raw_document": document} 248 | 249 | result = client.process_document(request=request) 250 | document = result.document 251 | 252 | document_pages = document.pages 253 | 254 | formFields = "" 255 | for page in document_pages: 256 | for form_field in page.form_fields: 257 | fieldLabel = _get_text(form_field.field_name, document).replace("\n", "").replace(":", "").strip() 258 | fieldValue = _get_text(form_field.field_value, document).replace("\n", "") 259 | formFields += "\n" + fieldLabel + "=" + fieldValue 260 | 261 | output["totalFields"] = output["totalFields"] + 1 262 | if fieldValue != "": 263 | output["filledFields"] = output["filledFields"] + 1 264 | 265 | output["formFields"] = formFields 266 | return output 267 | 268 | # formFields = callDocAI("Customer_Files_/9a62a9a8.Document.184617.pdf") 269 | # print(formFields) 270 | 271 | if __name__ == "__main__": 272 | app.run() 273 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | export servicename=document-ai-adapter 2 | export PROJECT_ID=$(gcloud config get-value project) 3 | export REGION=europe-west1 4 | export ENV=GCP_DOCAI_REGION=eu,GCP_DOCAI_PROCESSOR_ID=eade9760f6f088f 5 | 6 | # docker build -t local/$servicename . 7 | # docker tag local/$servicename eu.gcr.io/$PROJECT_ID/$servicename 8 | # docker push eu.gcr.io/$PROJECT_ID/$servicename 9 | 10 | gcloud builds submit --tag "eu.gcr.io/$PROJECT_ID/$servicename" 11 | 12 | gcloud run deploy $servicename --image eu.gcr.io/$PROJECT_ID/$servicename --platform managed --project $PROJECT_ID --region $REGION --update-env-vars $ENV --allow-unauthenticated 13 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | web.py 2 | google-cloud-documentai 3 | google-api-python-client 4 | google-auth-httplib2 5 | google-auth-oauthlib 6 | google-auth -------------------------------------------------------------------------------- /tempdoc.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyayers/appsheet-documentai-adapter/b86b19ddc33b3dcc6b2406e5952da302b6e223f9/tempdoc.pdf --------------------------------------------------------------------------------