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

1. ภาพรวม

Document AI คืออะไร

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

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

เราจะใช้ไฟล์ PDF ของนวนิยายคลาสสิกเรื่อง "Winnie the Pooh" โดย 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 เพื่อใช้ทรัพยากร Google Cloud

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

เริ่ม Cloud Shell

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

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

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

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

หากคุณไม่เคยเริ่มใช้ 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

คุณต้องเปิดใช้ API ก่อนจึงจะเริ่มใช้ Document AI ได้ คุณสามารถดำเนินการนี้ได้โดยใช้อินเทอร์เฟซบรรทัดคำสั่ง 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

Search API

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

ตอนนี้คุณใช้ Document AI ได้แล้ว

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

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

Cloud Console

  1. ในคอนโซล ให้ไปที่ภาพรวมแพลตฟอร์ม Document AIคอนโซลภาพรวมของ Document AI
  2. คลิกสำรวจโปรเซสเซอร์ แล้วเลือก Document 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 /_p/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
  • การประมวลผลแบบกลุ่มช่วยให้ประมวลผลไฟล์ขนาดใหญ่/หลายไฟล์ได้ด้วยวิธีแบบอะซิงโครนัส

ในขั้นตอนนี้ เราจะประมวลผลนวนิยายเรื่อง "Winnie the Pooh" ทั้งเรื่องด้วย 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:
            # /_p/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,
    )

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

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

อย่างไรก็ตาม เมื่อใช้ Batch Processing 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
/_p/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

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

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

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

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 เพื่อดึงข้อความจากนิยายโดยใช้การประมวลผลออนไลน์ การประมวลผลแบบกลุ่ม และ Document AI Toolbox เรียบร้อยแล้ว

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

ล้างข้อมูล

วิธีหลีกเลี่ยงการเรียกเก็บเงินจากบัญชี Google Cloud สำหรับทรัพยากรที่ใช้ในบทแนะนำนี้มีดังนี้

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

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

เรียนรู้เกี่ยวกับ Document AI ต่อด้วย Codelab ที่ติดตามผลเหล่านี้

แหล่งข้อมูล

ใบอนุญาต

งานนี้ได้รับอนุญาตภายใต้สัญญาอนุญาตครีเอทีฟคอมมอนส์สำหรับยอมรับสิทธิของผู้สร้าง (Creative Commons Attribution License) 2.0 แบบทั่วไป