การรู้จำอักขระด้วยภาพ (OCR) ด้วย Document AI (Python)

1. ภาพรวม

Document AI คืออะไร

Document AI เป็นโซลูชันการทำความเข้าใจเอกสารซึ่งนำข้อมูลที่ไม่มีโครงสร้าง (เช่น เอกสาร อีเมล ใบแจ้งหนี้ แบบฟอร์ม ฯลฯ) มาใช้ และทำให้ข้อมูลนั้นเข้าใจ วิเคราะห์ และใช้งานได้ง่ายขึ้น โดย API นี้ให้โครงสร้างผ่านการจัดประเภทเนื้อหา การแยกเอนทิตี การค้นหาขั้นสูง และอีกมากมาย

ในห้องทดลองนี้ คุณจะได้เรียนรู้วิธีการรู้จักอักขระด้วยภาพโดยใช้ Document AI API กับ Python

เราจะใช้ไฟล์ PDF ของนวนิยายคลาสสิกเรื่อง "วินนี่เดอะพูห์" โดย A.A. Milne ซึ่งเพิ่งเป็นส่วนหนึ่งของสาธารณสมบัติในสหรัฐอเมริกา ไฟล์นี้ได้รับการสแกนและแปลงเป็นข้อมูลดิจิทัลโดย Google Books

สิ่งที่คุณจะได้เรียนรู้

  • วิธีเปิดใช้ Document AI API
  • วิธีตรวจสอบสิทธิ์คำขอ API
  • วิธีติดตั้งไลบรารีของไคลเอ็นต์สำหรับ Python
  • วิธีใช้ API การประมวลผลแบบกลุ่มทางออนไลน์และแบบกลุ่ม
  • วิธีแยกวิเคราะห์ข้อความจากไฟล์ PDF

สิ่งที่คุณต้องมี

  • โปรเจ็กต์ Google Cloud
  • เบราว์เซอร์ เช่น Chrome หรือ Firefox
  • ความคุ้นเคยกับการใช้ Python (3.9+)

แบบสำรวจ

คุณจะใช้บทแนะนำนี้อย่างไร

อ่านเท่านั้น อ่านและทำแบบฝึกหัด

คุณจะให้คะแนนประสบการณ์การใช้งาน Python อย่างไร

มือใหม่ ระดับกลาง ผู้ชำนาญ

คุณจะให้คะแนนความพึงพอใจในการใช้บริการ Google Cloud อย่างไร

มือใหม่ ระดับกลาง ผู้ชำนาญ

2. การตั้งค่าและข้อกำหนด

การตั้งค่าสภาพแวดล้อมตามเวลาที่สะดวก

  1. ลงชื่อเข้าใช้ Cloud Console และสร้างโปรเจ็กต์ใหม่หรือใช้โปรเจ็กต์ที่มีอยู่ซ้ำ (หากยังไม่มีบัญชี Gmail หรือ Google Workspace คุณต้องสร้างบัญชี)

เลือกโปรเจ็กต์

โปรเจ็กต์ใหม่

รับรหัสโปรเจ็กต์

จดจำรหัสโปรเจ็กต์ ซึ่งเป็นชื่อที่ไม่ซ้ำกันในโปรเจ็กต์ Google Cloud ทั้งหมด (ระบบได้ใช้รหัสโปรเจ็กต์ด้านบนแล้วและจะใช้รหัสไม่ได้ ขออภัย) คุณต้องระบุรหัสนี้ในภายหลังเป็น PROJECT_ID

  1. ถัดไป คุณต้องเปิดใช้การเรียกเก็บเงินใน Cloud Console เพื่อใช้ทรัพยากร Google Cloud

ตรวจสอบว่าคุณได้ทำตามวิธีการใน "การล้างข้อมูล" ส่วนนี้จะแนะนำวิธีปิดทรัพยากรเพื่อไม่ให้มีการเรียกเก็บเงินนอกเหนือจากบทแนะนำนี้ ผู้ใช้ใหม่ของ Google Cloud จะมีสิทธิ์เข้าร่วมโปรแกรมทดลองใช้ฟรี$300 USD

เริ่มต้น Cloud Shell

แม้ว่าคุณจะใช้งาน Google Cloud จากระยะไกลได้จากแล็ปท็อป แต่ Codelab นี้ใช้ Google Cloud Shell ซึ่งเป็นสภาพแวดล้อมแบบบรรทัดคำสั่งที่ทำงานในระบบคลาวด์

เปิดใช้งาน Cloud Shell

  1. คลิกเปิดใช้งาน Cloud Shell เปิดใช้งาน Cloud Shell จาก Cloud Console

เปิดใช้งาน Cloud Shell

หากคุณไม่เคยเริ่มต้นใช้งาน Cloud Shell มาก่อน คุณจะเห็นหน้าจอตรงกลาง (ครึ่งหน้าล่าง) ซึ่งอธิบายว่านี่คืออะไร หากเป็นเช่นนั้น ให้คลิกดำเนินการต่อ (คุณจะไม่เห็นการดำเนินการนี้อีก) หน้าจอแบบครั้งเดียวมีลักษณะดังนี้

ข้อมูลเบื้องต้นเกี่ยวกับ Cloud Shell

การจัดสรรและเชื่อมต่อกับ Cloud Shell ใช้เวลาเพียงไม่กี่นาที Cloud Shell

Cloud Shell ให้คุณเข้าถึงเทอร์มินัลไปยังเครื่องเสมือนที่โฮสต์ในระบบคลาวด์ได้ เครื่องเสมือนจะมีเครื่องมือการพัฒนาทั้งหมดที่ต้องใช้ โดยมีไดเรกทอรีหลักขนาด 5 GB ที่ทำงานอย่างต่อเนื่องใน Google Cloud ซึ่งจะช่วยเพิ่มประสิทธิภาพของเครือข่ายและการตรวจสอบสิทธิ์ได้อย่างมาก งานใน Codelab นี้ส่วนใหญ่หรือทั้งหมดก็ทำได้ด้วยเบราว์เซอร์

เมื่อเชื่อมต่อกับ Cloud Shell แล้ว คุณควรเห็นว่าตนเองผ่านการตรวจสอบสิทธิ์แล้วและโปรเจ็กต์ได้รับการตั้งค่าเป็นรหัสโปรเจ็กต์แล้ว

  1. เรียกใช้คำสั่งต่อไปนี้ใน Cloud Shell เพื่อยืนยันว่าคุณได้รับการตรวจสอบสิทธิ์แล้ว
gcloud auth list

เอาต์พุตจากคำสั่ง

 Credentialed Accounts
ACTIVE  ACCOUNT
*      <my_account>@<my_domain.com>

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
gcloud config list project

เอาต์พุตจากคำสั่ง

[core]
project = <PROJECT_ID>

หากไม่ใช่ ให้ตั้งคำสั่งด้วยคำสั่งนี้

gcloud config set project <PROJECT_ID>

เอาต์พุตจากคำสั่ง

Updated property [core/project].

3. เปิดใช้ Document AI API

ก่อนที่จะเริ่มใช้ Document AI คุณต้องเปิดใช้ API ซึ่งทำได้โดยใช้อินเทอร์เฟซบรรทัดคำสั่ง gcloud หรือ Cloud Console

ใช้ gcloud CLI

  1. หากไม่ได้ใช้ Cloud Shell ให้ทำตามขั้นตอนในหัวข้อติดตั้ง gcloud CLI ในเครื่องของคุณ
  2. คุณเปิดใช้ API ได้โดยใช้คำสั่ง gcloud ต่อไปนี้
gcloud services enable documentai.googleapis.com storage.googleapis.com

คุณควรจะเห็นบางสิ่งเช่นนี้:

Operation "operations/..." finished successfully.

ใช้ Cloud Console

เปิด Cloud Console ในเบราว์เซอร์

  1. ใช้แถบค้นหาที่ด้านบนของคอนโซลเพื่อค้นหา "Document AI API" แล้วคลิกเปิดใช้เพื่อใช้ API ในโปรเจ็กต์ Google Cloud

API การค้นหา

  1. ทำซ้ำขั้นตอนก่อนหน้ากับ Google Cloud Storage API

คุณใช้ Document AI ได้แล้ว

4. สร้างและทดสอบโปรเซสเซอร์

คุณต้องสร้างอินสแตนซ์ของตัวประมวลผล OCR เอกสารที่จะทำการแตกข้อมูลก่อน ซึ่งสามารถดำเนินการได้โดยใช้ Cloud Console หรือ Processor Management API

Cloud Console

  1. ในคอนโซล ให้ไปที่ภาพรวมของ Document AI Platformคอนโซลภาพรวมของ AI ของเอกสาร
  2. คลิกสำรวจผู้ประมวลผลข้อมูล แล้วเลือก OCR เอกสารโปรเซสเซอร์
  3. ตั้งชื่อว่า codelab-ocr (หรือชื่ออื่นที่คุณจำได้) แล้วเลือกภูมิภาคที่ใกล้เคียงที่สุดในรายการ
  4. คลิกสร้างเพื่อสร้างโปรเซสเซอร์
  5. คัดลอกรหัสโปรเซสเซอร์ คุณต้องใช้สิ่งนี้ในรหัสในภายหลัง รหัสผู้ประมวลผลข้อมูล

คุณสามารถทดสอบโปรเซสเซอร์ในคอนโซลได้โดยอัปโหลดเอกสาร คลิกอัปโหลดเอกสารทดสอบ แล้วเลือกเอกสารที่จะแยกวิเคราะห์

คุณสามารถดาวน์โหลดไฟล์ PDF ด้านล่าง ซึ่งมี 3 หน้าแรกของนิยายของเรา

หน้าชื่อ

เอาต์พุตควรมีลักษณะดังนี้ หนังสือที่แยกวิเคราะห์

ไลบรารีของไคลเอ็นต์ Python

ทำตาม Codelab นี้เพื่อดูวิธีจัดการตัวประมวลผล Document AI ด้วยไลบรารีของไคลเอ็นต์ Python ดังนี้

การจัดการตัวประมวลผล Document AI ด้วย Python - Codelab

5. ตรวจสอบสิทธิ์คำขอ API

หากต้องการส่งคำขอไปยัง Document AI API คุณต้องใช้บัญชีบริการ บัญชีบริการเป็นของโปรเจ็กต์และไลบรารีของไคลเอ็นต์ Python จะใช้บัญชีนี้เพื่อสร้างคำขอ API บัญชีบริการจะแสดงด้วยอีเมลเช่นเดียวกับบัญชีผู้ใช้อื่นๆ ในส่วนนี้ คุณจะใช้ Cloud SDK เพื่อสร้างบัญชีบริการ จากนั้นจึงสร้างข้อมูลเข้าสู่ระบบที่ต้องใช้เพื่อตรวจสอบสิทธิ์ว่าเป็นบัญชีบริการ

ก่อนอื่น ให้เปิด Cloud Shell แล้วตั้งค่าตัวแปรสภาพแวดล้อมด้วย PROJECT_ID ซึ่งคุณจะใช้ทั่วทั้ง Codelab นี้

export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value core/project)

ถัดไป ให้สร้างบัญชีบริการใหม่เพื่อเข้าถึง Document AI API โดยใช้สิ่งต่อไปนี้

gcloud iam service-accounts create my-docai-sa \
  --display-name "my-docai-service-account"

จากนั้นให้ให้สิทธิ์แก่บัญชีบริการในการเข้าถึง Document AI และ Cloud Storage ในโปรเจ็กต์ของคุณ

gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
    --member="serviceAccount:my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
    --role="roles/documentai.admin"

gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
    --member="serviceAccount:my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
    --role="roles/storage.admin"

gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
    --member="serviceAccount:my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
    --role="roles/serviceusage.serviceUsageConsumer"

จากนั้น สร้างข้อมูลเข้าสู่ระบบที่โค้ด Python ใช้เพื่อเข้าสู่ระบบเป็นบัญชีบริการใหม่ สร้างข้อมูลเข้าสู่ระบบเหล่านี้และบันทึกเป็นไฟล์ JSON ~/key.json โดยใช้คำสั่งต่อไปนี้

gcloud iam service-accounts keys create ~/key.json \
  --iam-account  my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com

สุดท้าย ตั้งค่าตัวแปรสภาพแวดล้อม GOOGLE_APPLICATION_CREDENTIALS ซึ่งไลบรารีใช้ในการค้นหาข้อมูลเข้าสู่ระบบของคุณ หากต้องการอ่านเพิ่มเติมเกี่ยวกับการตรวจสอบสิทธิ์รูปแบบนี้ โปรดดูที่คำแนะนำ ควรตั้งค่าตัวแปรสภาพแวดล้อมเป็นเส้นทางแบบเต็มของไฟล์ JSON ของข้อมูลเข้าสู่ระบบที่คุณสร้างขึ้น โดยใช้สิ่งต่อไปนี้

export GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"

6. ติดตั้งไลบรารีของไคลเอ็นต์

ติดตั้งไลบรารีของไคลเอ็นต์ Python สำหรับ Document AI, Cloud Storage และ Document AI Toolbox:

pip3 install --upgrade google-cloud-documentai
pip3 install --upgrade google-cloud-storage
pip3 install --upgrade google-cloud-documentai-toolbox

คุณควรจะเห็นบางสิ่งเช่นนี้:

...
Installing collected packages: google-cloud-documentai
Successfully installed google-cloud-documentai-2.15.0
.
.
Installing collected packages: google-cloud-storage
Successfully installed google-cloud-storage-2.9.0
.
.
Installing collected packages: google-cloud-documentai-toolbox
Successfully installed google-cloud-documentai-toolbox-0.6.0a0

ตอนนี้คุณพร้อมที่จะใช้ Document AI API แล้ว

7. ดาวน์โหลด PDF ตัวอย่าง

เรามีเอกสารตัวอย่างที่มี 3 หน้าแรกของนวนิยาย

คุณดาวน์โหลดไฟล์ PDF ได้โดยใช้ลิงก์ต่อไปนี้ จากนั้นอัปโหลดไปยังอินสแตนซ์ Cloud Shell

คุณยังดาวน์โหลดจากที่เก็บข้อมูล Google Cloud Storage สาธารณะของเราได้โดยใช้ gsutil

gsutil cp gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh_3_Pages.pdf .

8. ส่งคำขอดำเนินการออนไลน์

ในขั้นตอนนี้ คุณจะประมวลผล 3 หน้าแรกของนิยายโดยใช้ API การประมวลผลออนไลน์ (ซิงโครนัส) วิธีนี้เหมาะที่สุดสำหรับเอกสารขนาดเล็กที่เก็บไว้ในเครื่อง ดูรายการตัวประมวลผลแบบเต็มเพื่อดูหน้าสูงสุดและขนาดไฟล์ของโปรเซสเซอร์แต่ละประเภท

ใช้ Cloud Shell Editor หรือเครื่องมือแก้ไขข้อความในเครื่องของคุณเพื่อสร้างไฟล์ชื่อ online_processing.py และใช้โค้ดด้านล่าง

แทนที่ YOUR_PROJECT_ID, YOUR_PROJECT_LOCATION, YOUR_PROCESSOR_ID และ FILE_PATH ด้วยค่าที่เหมาะสมสำหรับสภาพแวดล้อมของคุณ

online_processing.py

from google.api_core.client_options import ClientOptions
from google.cloud import documentai


PROJECT_ID = "YOUR_PROJECT_ID"
LOCATION = "YOUR_PROJECT_LOCATION"  # Format is 'us' or 'eu'
PROCESSOR_ID = "YOUR_PROCESSOR_ID"  # Create processor in Cloud Console

# The local file in your current working directory
FILE_PATH = "Winnie_the_Pooh_3_Pages.pdf"
# Refer to https://cloud.google.com/document-ai/docs/file-types
# for supported file types
MIME_TYPE = "application/pdf"

# Instantiates a client
docai_client = documentai.DocumentProcessorServiceClient(
    client_options=ClientOptions(api_endpoint=f"{LOCATION}-documentai.googleapis.com")
)

# The full resource name of the processor, e.g.:
# projects/project-id/locations/location/processor/processor-id
# You must create new processors in the Cloud Console first
RESOURCE_NAME = docai_client.processor_path(PROJECT_ID, LOCATION, PROCESSOR_ID)

# Read the file into memory
with open(FILE_PATH, "rb") as image:
    image_content = image.read()

# Load Binary Data into Document AI RawDocument Object
raw_document = documentai.RawDocument(content=image_content, mime_type=MIME_TYPE)

# Configure the process request
request = documentai.ProcessRequest(name=RESOURCE_NAME, raw_document=raw_document)

# Use the Document AI client to process the sample form
result = docai_client.process_document(request=request)

document_object = result.document
print("Document processing complete.")
print(f"Text: {document_object.text}")

เรียกใช้โค้ด ซึ่งจะดึงข้อความออกมาและสั่งพิมพ์ไปยังคอนโซล

คุณควรเห็นผลลัพธ์ต่อไปนี้หากใช้เอกสารตัวอย่างของเรา:

Document processing complete.
Text: CHAPTER I
IN WHICH We Are Introduced to
Winnie-the-Pooh and Some
Bees, and the Stories Begin
Here is Edward Bear, coming
downstairs now, bump, bump, bump, on the back
of his head, behind Christopher Robin. It is, as far
as he knows, the only way of coming downstairs,
but sometimes he feels that there really is another
way, if only he could stop bumping for a moment
and think of it. And then he feels that perhaps there
isn't. Anyhow, here he is at the bottom, and ready
to be introduced to you. Winnie-the-Pooh.
When I first heard his name, I said, just as you
are going to say, "But I thought he was a boy?"
"So did I," said Christopher Robin.
"Then you can't call him Winnie?"
"I don't."
"But you said "

...

Digitized by
Google

9. ส่งคำขอประมวลผลเป็นกลุ่ม

ทีนี้สมมติว่าคุณต้องการอ่านข้อความจากนิยายทั้งเรื่อง

  • การประมวลผลออนไลน์มีการจำกัดจำนวนหน้าและขนาดไฟล์ที่จะส่ง และอนุญาตให้อัปโหลดไฟล์เอกสารได้เพียง 1 ไฟล์ต่อการเรียก API 1 ครั้ง
  • การประมวลผลแบบกลุ่มทำให้สามารถประมวลผลไฟล์ขนาดใหญ่/หลายไฟล์ในแบบที่ไม่พร้อมกัน

ในขั้นตอนนี้ เราจะประมวลผล "วินนี่เดอะพูห์" ทั้งหมด ใหม่ที่มี Document AI Batch Processing API และเอาต์พุตข้อความไปยังที่เก็บข้อมูล Google Cloud Storage

การประมวลผลแบบกลุ่มจะใช้การดำเนินการที่ใช้เวลานานในการจัดการคำขอในลักษณะที่ไม่พร้อมกัน เราจึงต้องสร้างคำขอและดึงผลลัพธ์ในลักษณะที่ต่างจากการประมวลผลออนไลน์ แต่เอาต์พุตจะอยู่ในรูปแบบออบเจ็กต์ Document เดียวกันไม่ว่าจะใช้การประมวลผลแบบออนไลน์หรือแบบกลุ่มก็ตาม

ขั้นตอนนี้จะแสดงวิธีส่งเอกสารที่เฉพาะเจาะจงเพื่อให้ Document AI ประมวลผล ขั้นตอนต่อไปจะแสดงวิธีประมวลผลไดเรกทอรีทั้งหมดของเอกสาร

อัปโหลด PDF ไปยัง Cloud Storage

ปัจจุบันเมธอด batch_process_documents() ยอมรับไฟล์จาก Google Cloud Storage ดูข้อมูลเพิ่มเติมเกี่ยวกับโครงสร้างออบเจ็กต์ได้ที่ documentai_v1.types.BatchProcessRequest

สำหรับตัวอย่างนี้ คุณจะอ่านไฟล์ได้โดยตรงจากที่เก็บข้อมูลตัวอย่างของเรา

คุณยังคัดลอกไฟล์ไปยังที่เก็บข้อมูลของคุณเองโดยใช้ gsutil... ได้ด้วย

gsutil cp gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh.pdf gs://YOUR_BUCKET_NAME/

...หรือคุณสามารถดาวน์โหลดไฟล์ตัวอย่างของนวนิยายจากลิงก์ด้านล่าง แล้วอัปโหลดไปยังที่เก็บข้อมูลของคุณเอง

นอกจากนี้ คุณจะต้องใช้ที่เก็บข้อมูล GCS เพื่อจัดเก็บเอาต์พุตของ API ด้วย

คุณสามารถติดตามเอกสารประกอบของ Cloud Storage เพื่อดูวิธีสร้างที่เก็บข้อมูลของพื้นที่เก็บข้อมูล

การใช้เมธอด batch_process_documents()

สร้างไฟล์ชื่อ batch_processing.py และใช้รหัสด้านล่าง

แทนที่ YOUR_PROJECT_ID, YOUR_PROCESSOR_LOCATION, YOUR_PROCESSOR_ID, YOUR_INPUT_URI และ YOUR_OUTPUT_URI ด้วยค่าที่เหมาะสมสำหรับสภาพแวดล้อมของคุณ

ตรวจสอบว่า YOUR_INPUT_URI ชี้ไปที่ไฟล์ PDF โดยตรง เช่น gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh.pdf

batch_processing.py

"""
Makes a Batch Processing Request to Document AI
"""

import re

from google.api_core.client_options import ClientOptions
from google.api_core.exceptions import InternalServerError
from google.api_core.exceptions import RetryError
from google.cloud import documentai
from google.cloud import storage

# TODO(developer): Fill these variables before running the sample.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"
processor_id = "YOUR_PROCESSOR_ID"  # Create processor before running sample
gcs_output_uri = "YOUR_OUTPUT_URI"  # Must end with a trailing slash `/`. Format: gs://bucket/directory/subdirectory/
processor_version_id = (
    "YOUR_PROCESSOR_VERSION_ID"  # Optional. Example: pretrained-ocr-v1.0-2020-09-23
)

# TODO(developer): If `gcs_input_uri` is a single file, `mime_type` must be specified.
gcs_input_uri = "YOUR_INPUT_URI"  # Format: `gs://bucket/directory/file.pdf` or `gs://bucket/directory/`
input_mime_type = "application/pdf"
field_mask = "text,entities,pages.pageNumber"  # Optional. The fields to return in the Document object.


def batch_process_documents(
    project_id: str,
    location: str,
    processor_id: str,
    gcs_input_uri: str,
    gcs_output_uri: str,
    processor_version_id: str = None,
    input_mime_type: str = None,
    field_mask: str = None,
    timeout: int = 400,
):
    # You must set the api_endpoint if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")

    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    if not gcs_input_uri.endswith("/") and "." in gcs_input_uri:
        # Specify specific GCS URIs to process individual documents
        gcs_document = documentai.GcsDocument(
            gcs_uri=gcs_input_uri, mime_type=input_mime_type
        )
        # Load GCS Input URI into a List of document files
        gcs_documents = documentai.GcsDocuments(documents=[gcs_document])
        input_config = documentai.BatchDocumentsInputConfig(gcs_documents=gcs_documents)
    else:
        # Specify a GCS URI Prefix to process an entire directory
        gcs_prefix = documentai.GcsPrefix(gcs_uri_prefix=gcs_input_uri)
        input_config = documentai.BatchDocumentsInputConfig(gcs_prefix=gcs_prefix)

    # Cloud Storage URI for the Output Directory
    gcs_output_config = documentai.DocumentOutputConfig.GcsOutputConfig(
        gcs_uri=gcs_output_uri, field_mask=field_mask
    )

    # Where to write results
    output_config = documentai.DocumentOutputConfig(gcs_output_config=gcs_output_config)

    if processor_version_id:
        # The full resource name of the processor version, e.g.:
        # projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}
        name = client.processor_version_path(
            project_id, location, processor_id, processor_version_id
        )
    else:
        # The full resource name of the processor, e.g.:
        # projects/{project_id}/locations/{location}/processors/{processor_id}
        name = client.processor_path(project_id, location, processor_id)

    request = documentai.BatchProcessRequest(
        name=name,
        input_documents=input_config,
        document_output_config=output_config,
    )

    # BatchProcess returns a Long Running Operation (LRO)
    operation = client.batch_process_documents(request)

    # Continually polls the operation until it is complete.
    # This could take some time for larger files
    # Format: projects/{project_id}/locations/{location}/operations/{operation_id}
    try:
        print(f"Waiting for operation {operation.operation.name} to complete...")
        operation.result(timeout=timeout)
    # Catch exception when operation doesn"t finish before timeout
    except (RetryError, InternalServerError) as e:
        print(e.message)

    # NOTE: Can also use callbacks for asynchronous processing
    #
    # def my_callback(future):
    #   result = future.result()
    #
    # operation.add_done_callback(my_callback)

    # Once the operation is complete,
    # get output document information from operation metadata
    metadata = documentai.BatchProcessMetadata(operation.metadata)

    if metadata.state != documentai.BatchProcessMetadata.State.SUCCEEDED:
        raise ValueError(f"Batch Process Failed: {metadata.state_message}")

    storage_client = storage.Client()

    print("Output files:")
    # One process per Input Document
    for process in list(metadata.individual_process_statuses):
        # output_gcs_destination format: gs://BUCKET/PREFIX/OPERATION_NUMBER/INPUT_FILE_NUMBER/
        # The Cloud Storage API requires the bucket name and URI prefix separately
        matches = re.match(r"gs://(.*?)/(.*)", process.output_gcs_destination)
        if not matches:
            print(
                "Could not parse output GCS destination:",
                process.output_gcs_destination,
            )
            continue

        output_bucket, output_prefix = matches.groups()

        # Get List of Document Objects from the Output Bucket
        output_blobs = storage_client.list_blobs(output_bucket, prefix=output_prefix)

        # Document AI may output multiple JSON files per source file
        for blob in output_blobs:
            # Document AI should only output JSON files to GCS
            if blob.content_type != "application/json":
                print(
                    f"Skipping non-supported file: {blob.name} - Mimetype: {blob.content_type}"
                )
                continue

            # Download JSON File as bytes object and convert to Document Object
            print(f"Fetching {blob.name}")
            document = documentai.Document.from_json(
                blob.download_as_bytes(), ignore_unknown_fields=True
            )

            # For a full list of Document object attributes, please reference this page:
            # https://cloud.google.com/python/docs/reference/documentai/latest/google.cloud.documentai_v1.types.Document

            # Read the text recognition output from the processor
            print("The document contains the following text:")
            print(document.text)


if __name__ == "__main__":
    batch_process_documents(
        project_id=project_id,
        location=location,
        processor_id=processor_id,
        gcs_input_uri=gcs_input_uri,
        gcs_output_uri=gcs_output_uri,
        input_mime_type=input_mime_type,
        field_mask=field_mask,
    )

เรียกใช้โค้ดดังกล่าว คุณควรเห็นข้อความใหม่ฉบับเต็มที่แยกออกมาแล้วพิมพ์ไว้ในคอนโซล

การดำเนินการนี้อาจใช้เวลาสักครู่เนื่องจากไฟล์มีขนาดใหญ่กว่าตัวอย่างก่อนหน้านี้มาก (อ๊ะ รบกวน...)

แต่เมื่อใช้ API การประมวลผลแบบกลุ่ม คุณจะได้รับรหัสการดำเนินการซึ่งจะใช้เพื่อรับเอาต์พุตจาก GCS ได้เมื่องานเสร็จสมบูรณ์แล้ว

เอาต์พุตควรมีลักษณะดังนี้

Waiting for operation projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_NUMBER to complete...
Document processing complete.
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-0.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-1.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-10.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-11.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-12.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-13.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-14.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-15.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-16.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-17.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-18.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-2.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-3.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-4.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-5.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-6.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-7.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-8.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-9.json

This is a reproduction of a library book that was digitized
by Google as part of an ongoing effort to preserve the
information in books and make it universally accessible.
TM
Google books
https://books.google.com

.....

He nodded and went
out ... and in a moment
I heard Winnie-the-Pooh
-bump, bump, bump-go-ing up the stairs behind
him.
Digitized by
Google

10. ส่งคำขอประมวลผลเป็นกลุ่มสำหรับไดเรกทอรี

บางครั้งคุณอาจต้องการประมวลผลไดเรกทอรีทั้งหมดของเอกสาร โดยไม่แสดงรายการเอกสารแต่ละรายการ เมธอด batch_process_documents() รองรับการป้อนข้อมูลรายการเอกสารที่ระบุหรือเส้นทางไดเรกทอรี

ขั้นตอนนี้จะแสดงวิธีประมวลผลไดเรกทอรีแบบเต็มของไฟล์เอกสาร โค้ดส่วนใหญ่ทำงานเหมือนกับขั้นตอนก่อนหน้า ความแตกต่างเดียวคือ URI ของ GCS ที่ส่งด้วย BatchProcessRequest

เรามีไดเรกทอรีในที่เก็บข้อมูลตัวอย่างของเราที่มีหน้านิยายหลายหน้าอยู่ในไฟล์แยกต่างหาก

  • gs://cloud-samples-data/documentai/codelabs/ocr/multi-document/

คุณสามารถอ่านไฟล์โดยตรงหรือคัดลอกไฟล์ลงในที่เก็บข้อมูล Cloud Storage ของคุณเองก็ได้

เรียกใช้โค้ดจากขั้นตอนก่อนหน้าอีกครั้ง โดยแทนที่ YOUR_INPUT_URI ด้วยไดเรกทอรีใน Cloud Storage

เรียกใช้โค้ด และคุณควรเห็นข้อความที่ดึงมาจากไฟล์เอกสารทั้งหมดในไดเรกทอรี Cloud Storage

เอาต์พุตควรมีลักษณะดังนี้

Waiting for operation projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_NUMBER to complete...
Document processing complete.
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh_Page_0-0.json
Fetching docai-output/OPERATION_NUMBER/1/Winnie_the_Pooh_Page_1-0.json
Fetching docai-output/OPERATION_NUMBER/2/Winnie_the_Pooh_Page_10-0.json
Fetching docai-output/OPERATION_NUMBER/3/Winnie_the_Pooh_Page_12-0.json
Fetching docai-output/OPERATION_NUMBER/4/Winnie_the_Pooh_Page_16-0.json
Fetching docai-output/OPERATION_NUMBER/5/Winnie_the_Pooh_Page_7-0.json

Introduction
(I₂
F YOU happen to have read another
book about Christopher Robin, you may remember
th
CHAPTER I
IN WHICH We Are Introduced to
Winnie-the-Pooh and Some
Bees, and the Stories Begin
HERE is
10
WINNIE-THE-POOH
"I wonder if you've got such a thing as a balloon
about you?"
"A balloon?"
"Yes, 
12
WINNIE-THE-POOH
and you took your gun with you, just in case, as
you always did, and Winnie-the-P
16
WINNIE-THE-POOH
this song, and one bee sat down on the nose of the
cloud for a moment, and then g
WE ARE INTRODUCED
7
"Oh, help!" said Pooh, as he dropped ten feet on
the branch below him.
"If only 

11. จัดการคำตอบการประมวลผลแบบกลุ่มด้วย Document AI Toolbox

การประมวลผลแบบกลุ่มมี 2-3 ขั้นตอนที่ต้องดำเนินการเนื่องจากการผสานรวมกับพื้นที่เก็บข้อมูลระบบคลาวด์ เอาต์พุต Document อาจเป็น "ชาร์ด" ได้ด้วย ลงในไฟล์ .json หลายไฟล์ โดยขึ้นอยู่กับขนาดของเอกสารอินพุต

Python SDK สร้าง Document AI Toolbox เพื่อทำให้กระบวนการหลังการประมวลผลและงานทั่วไปอื่นๆ ง่ายขึ้นด้วย Document AI ไลบรารีนี้มีไว้เพื่อเป็นส่วนเสริมของไลบรารีของไคลเอ็นต์ Document AI ไม่ใช่การทดแทน ไปที่เอกสารอ้างอิงเพื่อดูข้อกำหนดทั้งหมด

ขั้นตอนนี้จะแสดงวิธีสร้างคำขอการประมวลผลแบบกลุ่มและดึงผลลัพธ์โดยใช้กล่องเครื่องมือ Document AI

batch_processing_toolbox.py

"""
Makes a Batch Processing Request to Document AI using Document AI Toolbox
"""

from google.api_core.client_options import ClientOptions
from google.cloud import documentai
from google.cloud import documentai_toolbox

# TODO(developer): Fill these variables before running the sample.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"
processor_id = "YOUR_PROCESSOR_ID"  # Create processor before running sample
gcs_output_uri = "YOUR_OUTPUT_URI"  # Must end with a trailing slash `/`. Format: gs://bucket/directory/subdirectory/
processor_version_id = (
    "YOUR_PROCESSOR_VERSION_ID"  # Optional. Example: pretrained-ocr-v1.0-2020-09-23
)

# TODO(developer): If `gcs_input_uri` is a single file, `mime_type` must be specified.
gcs_input_uri = "YOUR_INPUT_URI"  # Format: `gs://bucket/directory/file.pdf`` or `gs://bucket/directory/``
input_mime_type = "application/pdf"
field_mask = "text,entities,pages.pageNumber"  # Optional. The fields to return in the Document object.


def batch_process_toolbox(
    project_id: str,
    location: str,
    processor_id: str,
    gcs_input_uri: str,
    gcs_output_uri: str,
    processor_version_id: str = None,
    input_mime_type: str = None,
    field_mask: str = None,
):
    # You must set the api_endpoint if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")

    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    if not gcs_input_uri.endswith("/") and "." in gcs_input_uri:
        # Specify specific GCS URIs to process individual documents
        gcs_document = documentai.GcsDocument(
            gcs_uri=gcs_input_uri, mime_type=input_mime_type
        )
        # Load GCS Input URI into a List of document files
        gcs_documents = documentai.GcsDocuments(documents=[gcs_document])
        input_config = documentai.BatchDocumentsInputConfig(gcs_documents=gcs_documents)
    else:
        # Specify a GCS URI Prefix to process an entire directory
        gcs_prefix = documentai.GcsPrefix(gcs_uri_prefix=gcs_input_uri)
        input_config = documentai.BatchDocumentsInputConfig(gcs_prefix=gcs_prefix)

    # Cloud Storage URI for the Output Directory
    gcs_output_config = documentai.DocumentOutputConfig.GcsOutputConfig(
        gcs_uri=gcs_output_uri, field_mask=field_mask
    )

    # Where to write results
    output_config = documentai.DocumentOutputConfig(gcs_output_config=gcs_output_config)

    if processor_version_id:
        # The full resource name of the processor version, e.g.:
        # projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}
        name = client.processor_version_path(
            project_id, location, processor_id, processor_version_id
        )
    else:
        # The full resource name of the processor, e.g.:
        # projects/{project_id}/locations/{location}/processors/{processor_id}
        name = client.processor_path(project_id, location, processor_id)

    request = documentai.BatchProcessRequest(
        name=name,
        input_documents=input_config,
        document_output_config=output_config,
    )

    # BatchProcess returns a Long Running Operation (LRO)
    operation = client.batch_process_documents(request)

    # Operation Name Format: projects/{project_id}/locations/{location}/operations/{operation_id}
    documents = documentai_toolbox.document.Document.from_batch_process_operation(
        location=location, operation_name=operation.operation.name
    )

    for document in documents:
        # Read the text recognition output from the processor
        print("The document contains the following text:")
        # Truncated at 100 characters for brevity
        print(document.text[:100])


if __name__ == "__main__":
    batch_process_toolbox(
        project_id=project_id,
        location=location,
        processor_id=processor_id,
        gcs_input_uri=gcs_input_uri,
        gcs_output_uri=gcs_output_uri,
        input_mime_type=input_mime_type,
        field_mask=field_mask,
    )

12. ขอแสดงความยินดี

คุณได้ใช้ Document AI เพื่อดึงข้อความจากนวนิยายโดยใช้การประมวลผลออนไลน์ การประมวลผลเป็นกลุ่ม และกล่องเครื่องมือ AI เอกสารเรียบร้อยแล้ว

เราขอแนะนำให้คุณทดสอบเอกสารอื่นๆ และสำรวจผู้ประมวลผลข้อมูลรายอื่นๆ ที่มีในแพลตฟอร์ม

ล้างข้อมูล

โปรดทำดังนี้เพื่อเลี่ยงไม่ให้เกิดการเรียกเก็บเงินกับบัญชี Google Cloud สำหรับทรัพยากรที่ใช้ในบทแนะนำนี้

  • ใน Cloud Console ให้ไปที่หน้าจัดการทรัพยากร
  • ในรายการโปรเจ็กต์ ให้เลือกโปรเจ็กต์ของคุณ แล้วคลิกลบ
  • ในกล่องโต้ตอบ ให้พิมพ์รหัสโปรเจ็กต์แล้วคลิกปิดเครื่องเพื่อลบโปรเจ็กต์

ดูข้อมูลเพิ่มเติม

ศึกษาเพิ่มเติมเกี่ยวกับ Document AI ต่อไปด้วย Codelab ติดตามผลเหล่านี้

แหล่งข้อมูล

ใบอนุญาต

ผลงานนี้ได้รับอนุญาตภายใต้ใบอนุญาตทั่วไปครีเอทีฟคอมมอนส์แบบระบุแหล่งที่มา 2.0