डॉक्यूमेंट एआई (Python) की मदद से ऑप्टिकल कैरेक्टर रिकग्निशन (ओसीआर) की सुविधा

1. खास जानकारी

डॉक्यूमेंट एआई (AI) क्या है?

दस्तावेज़ एआई, दस्तावेज़ों को समझने का एक ऐसा तरीका है जो बिना स्ट्रक्चर वाला डेटा इकट्ठा करता है. जैसे, दस्तावेज़, ईमेल, इनवॉइस, फ़ॉर्म वगैरह. इससे डेटा को समझना, उसका विश्लेषण करना, और उसका इस्तेमाल करना आसान हो जाता है. यह एपीआई, कॉन्टेंट क्लासिफ़िकेशन, इकाई एक्सट्रैक्शन, बेहतर खोज वगैरह के ज़रिए स्ट्रक्चर उपलब्ध कराता है.

इस लैब में, आपको Python के साथ Document AI API का इस्तेमाल करके ऑप्टिकल कैरेक्टर रिकग्निशन की सुविधा इस्तेमाल करने का तरीका बताया जाएगा.

हम क्लासिक नॉवेल "विनी द पूह" की PDF फ़ाइल का इस्तेमाल करेंगे ए॰ए॰ की ओर से मिल्ने, जो हाल ही में अमेरिका में सार्वजनिक डोमेन का हिस्सा बन गया है. इस फ़ाइल को Google Books ने स्कैन और डिजिटल कॉपी किया है.

आपको इनके बारे में जानकारी मिलेगी

  • Document AI API को चालू करने का तरीका
  • एपीआई अनुरोधों की पुष्टि करने का तरीका
  • Python के लिए क्लाइंट लाइब्रेरी इंस्टॉल करने का तरीका
  • ऑनलाइन और बैच प्रोसेसिंग एपीआई इस्तेमाल करने का तरीका
  • PDF फ़ाइल से टेक्स्ट पार्स करने का तरीका

आपको इन चीज़ों की ज़रूरत होगी

  • Google Cloud प्रोजेक्ट
  • ब्राउज़र, जैसे कि Chrome या Firefox
  • Python (3.9+) का इस्तेमाल करना

सर्वे

इस ट्यूटोरियल का इस्तेमाल कैसे किया जाएगा?

इसे सिर्फ़ पढ़ें इसे पढ़ें और कसरतों को पूरा करें

Python के साथ अपने अनुभव को आप कितनी रेटिंग देंगे?

शुरुआती इंटरमीडिएट कुशल

Google Cloud की सेवाएं इस्तेमाल करने का आपका अनुभव कैसा रहा?

शुरुआती इंटरमीडिएट कुशल

2. सेटअप और ज़रूरी शर्तें

अपने हिसाब से एनवायरमेंट सेटअप करना

  1. Cloud Console में साइन इन करें और नया प्रोजेक्ट बनाएं या किसी मौजूदा प्रोजेक्ट का फिर से इस्तेमाल करें. (अगर आपके पास पहले से Gmail या Google Workspace खाता नहीं है, तो आपको एक खाता बनाना होगा.)

प्रोजेक्ट का चयन करें

नया प्रोजेक्ट

प्रोजेक्ट आईडी पाएं

प्रोजेक्ट आईडी याद रखें. यह Google Cloud के सभी प्रोजेक्ट के लिए एक खास नाम होता है. (माफ़ करें, ऊपर दिया गया प्रोजेक्ट आईडी पहले ही ले लिया गया है और यह आपके लिए काम नहीं करेगा!). आपको यह आईडी बाद में, PROJECT_ID के तौर पर देना होगा.

  1. इसके बाद, आपको Google Cloud के संसाधनों का इस्तेमाल करने के लिए, Cloud Console में बिलिंग की सुविधा चालू करनी होगी.

"साफ़ करना" सेक्शन में दिए गए निर्देशों का पालन करना न भूलें सेक्शन में जाएं. इस सेक्शन में, संसाधनों को बंद करने का तरीका बताया गया है. इससे इस ट्यूटोरियल के अलावा बिलिंग की सुविधा नहीं मिलेगी. Google Cloud के नए उपयोगकर्ता, 300USD डॉलर के मुफ़्त में आज़माने वाले प्रोग्राम में हिस्सा ले सकते हैं.

Cloud Shell शुरू करना

Google Cloud को अपने लैपटॉप से, कहीं से भी इस्तेमाल किया जा सकता है. हालांकि, यह कोडलैब Google Cloud Shell का इस्तेमाल करता है. यह क्लाउड में चलने वाला कमांड लाइन एनवायरमेंट है.

Cloud Shell चालू करें

  1. Cloud Console में, Cloud Shell चालू करें Cloud Shell चालू करें पर क्लिक करें

Cloud Shell चालू करें

अगर आपने पहले कभी Cloud Shell का इस्तेमाल शुरू नहीं किया है, तो आपको एक इंटरमीडिएट स्क्रीन (पेज के फ़ोल्ड के नीचे) दिखेगी, जो यह बताती है कि यह क्या है. अगर ऐसा है, तो जारी रखें पर क्लिक करें (यह आपको फिर कभी नहीं दिखेगा). एक बार इस्तेमाल होने वाली स्क्रीन कुछ इस तरह दिखती है:

क्लाउड शेल के बारे में जानकारी

प्रावधान करने और Cloud Shell से कनेक्ट होने में कुछ ही समय लगेगा. Cloud Shell अभी तक किसी भी व्यक्ति ने चेक इन नहीं किया है

Cloud Shell से आपको क्लाउड में होस्ट की जाने वाली वर्चुअल मशीन का टर्मिनल ऐक्सेस मिलता है. वर्चुअल मशीन में वे सभी डेवलपमेंट टूल होते हैं जिनकी आपको ज़रूरत होती है. यह पांच जीबी की स्थायी होम डायरेक्ट्री उपलब्ध कराता है और Google Cloud में चलता है. यह नेटवर्क की परफ़ॉर्मेंस और पुष्टि करने की प्रोसेस को बेहतर बनाता है. अगर सभी नहीं, तो इस कोडलैब में आपका बहुत सारा काम किसी ब्राउज़र से किया जा सकता है.

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 चालू करता है

दस्तावेज़ एआई (AI) का इस्तेमाल शुरू करने से पहले, आपको एपीआई चालू करना होगा. ऐसा करने के लिए, gcloud कमांड लाइन इंटरफ़ेस या Cloud Console का इस्तेमाल किया जा सकता है.

gcloud सीएलआई का इस्तेमाल करें

  1. अगर Cloud Shell का इस्तेमाल नहीं किया जा रहा है, तो अपने कंप्यूटर पर gcloud सीएलआई इंस्टॉल करें में दिया गया तरीका अपनाएं.
  2. इन gcloud निर्देशों का इस्तेमाल करके, एपीआई चालू किए जा सकते हैं.
gcloud services enable documentai.googleapis.com storage.googleapis.com

आपको कुछ ऐसा दिखेगा:

Operation "operations/..." finished successfully.

Cloud Console का इस्तेमाल करना

अपने ब्राउज़र में Cloud Console खोलें.

  1. कंसोल में सबसे ऊपर मौजूद खोज बार का इस्तेमाल करके, "Document AI API" खोजें. इसके बाद, Google Cloud प्रोजेक्ट में एपीआई का इस्तेमाल करने के लिए, चालू करें पर क्लिक करें

खोज API

  1. Google Cloud Storage API के लिए पिछला चरण दोहराएं.

अब दस्तावेज़ एआई (AI) का इस्तेमाल किया जा सकता है!

4. प्रोसेसर बनाना और उसकी जांच करना

आपको सबसे पहले दस्तावेज़ ओसीआर प्रोसेसर का इंस्टेंस बनाना होगा, जो एक्सट्रैक्ट करेगा. इस प्रक्रिया को Cloud Console या प्रोसेसर मैनेजमेंट एपीआई का इस्तेमाल करके पूरा किया जा सकता है.

Cloud Console

  1. कंसोल में, दस्तावेज़ एआई प्लैटफ़ॉर्म की खास जानकारी पर जाएंडॉक्यूमेंट एआई (AI) की खास जानकारी देने वाला कंसोल
  2. प्रोसेसर एक्सप्लोर करें पर क्लिक करें और दस्तावेज़ ओसीआर चुनेंप्रोसेसर
  3. इसे codelab-ocr नाम दें (या कुछ और जो आपको याद रहेगा) और सूची में अपना सबसे नज़दीकी इलाका चुनें.
  4. अपना प्रोसेसर बनाने के लिए, बनाएं पर क्लिक करें
  5. अपना प्रोसेसर आईडी कॉपी करें. आपको बाद में अपने कोड में इसका इस्तेमाल करना होगा. प्रोसेसर आईडी अभी तक किसी भी व्यक्ति ने चेक इन नहीं किया है

दस्तावेज़ अपलोड करके, कंसोल में अपने प्रोसेसर की जांच की जा सकती है. टेस्ट दस्तावेज़ अपलोड करें पर क्लिक करें और पार्स करने के लिए कोई दस्तावेज़ चुनें.

आप नीचे दी गई PDF फ़ाइल डाउनलोड कर सकते हैं. इसमें हमारे नॉवल के पहले तीन पेज शामिल हैं.

टाइटल पेज

आपका आउटपुट ऐसा दिखना चाहिए: पार्स की गई किताब

Python क्लाइंट लाइब्रेरी

Python क्लाइंट लाइब्रेरी की मदद से, दस्तावेज़ एआई प्रोसेसर को मैनेज करने का तरीका जानने के लिए, इस कोडलैब का इस्तेमाल करें:

Python - कोडलैब (कोड बनाना सीखना) की मदद से दस्तावेज़ के एआई प्रोसेसर मैनेज करना

5. एपीआई अनुरोधों की पुष्टि करें

Document AI API को अनुरोध करने के लिए, आपको किसी सेवा खाते का इस्तेमाल करना होगा. सेवा खाता आपके प्रोजेक्ट से जुड़ा होता है. Python क्लाइंट लाइब्रेरी, इसका इस्तेमाल एपीआई अनुरोध करने के लिए करती है. किसी भी दूसरे उपयोगकर्ता खाते की तरह, सेवा खाते को ईमेल पते के तौर पर दिखाया जाता है. इस सेक्शन में, आपको सेवा खाता बनाने के लिए Cloud SDK टूल का इस्तेमाल करना होगा. इसके बाद, ऐसे क्रेडेंशियल बनाने होंगे जिनकी पुष्टि सेवा खाते के तौर पर करनी हो.

सबसे पहले, Cloud Shell खोलें और अपने PROJECT_ID की मदद से, एक एनवायरमेंट वैरिएबल सेट करें. आपको इस वैरिएबल का इस्तेमाल, पूरे कोडलैब के दौरान करना है:

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"

इसके बाद, अपने सेवा खाते को अपने प्रोजेक्ट में दस्तावेज़ एआई और 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. क्लाइंट लाइब्रेरी इंस्टॉल करना

Document AI, Cloud Storage, और Document AI टूलबॉक्स के लिए Python क्लाइंट लाइब्रेरी इंस्टॉल करें:

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 डाउनलोड करें

हमारे पास एक नमूना दस्तावेज़ है, जिसमें इस उपन्यास के पहले तीन पेज शामिल हैं.

नीचे दिए गए लिंक का इस्तेमाल करके, PDF डाउनलोड की जा सकती है. इसके बाद, इसे Cloud Shell इंस्टेंस में अपलोड करें.

इसे gsutil का इस्तेमाल करके, हमारे सार्वजनिक Google Cloud Storage बकेट से भी डाउनलोड किया जा सकता है.

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

8. ऑनलाइन प्रोसेसिंग का अनुरोध करें

इस चरण में, ऑनलाइन प्रोसेसिंग (सिंक्रोनस) एपीआई का इस्तेमाल करके, नॉवल के पहले तीन पेजों को प्रोसेस किया जाएगा. डिवाइस पर सेव किए गए छोटे दस्तावेज़ों के लिए, यह तरीका सबसे अच्छा है. हर तरह के प्रोसेसर के लिए, ज़्यादा से ज़्यादा पेजों और फ़ाइल साइज़ के बारे में जानने के लिए, प्रोसेसर की पूरी सूची देखें.

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. बैच प्रोसेसिंग का अनुरोध करें

अब मान लीजिए कि आप पूरे उपन्यास के टेक्स्ट को पढ़ना चाहते हैं.

  • ऑनलाइन प्रोसेसिंग में, भेजे जा सकने वाले पेजों की संख्या और फ़ाइल के साइज़ की एक सीमा तय होती है. साथ ही, हर एपीआई कॉल में सिर्फ़ एक दस्तावेज़ फ़ाइल जोड़ी जा सकती है.
  • बैच प्रोसेसिंग की मदद से, एसिंक्रोनस तरीके से बड़ी या एक से ज़्यादा फ़ाइलों को प्रोसेस किया जा सकता है.

इस चरण में, हम पूरी "विनी द पूह" को प्रोसेस करेंगे दस्तावेज़ एआई बैच प्रोसेसिंग एपीआई के साथ नए वर्शन के साथ काम करता है और टेक्स्ट को Google Cloud Storage बकेट में डिलीवर करता है.

बैच प्रोसेसिंग, अनुरोधों को एसिंक्रोनस तरीके से मैनेज करने के लिए, लंबे समय तक चल रही कार्रवाइयों का इस्तेमाल करती है. इसलिए, हमें अनुरोध करना होता है और आउटपुट को ऑनलाइन प्रोसेसिंग के मुकाबले, अलग तरीके से हासिल करना होता है. हालांकि, ऑनलाइन या बैच प्रोसेसिंग का इस्तेमाल करने पर, आउटपुट उसी 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 बकेट की ज़रूरत होगी.

स्टोरेज बकेट बनाने का तरीका जानने के लिए, 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,
    )

कोड चलाएं. आपको पूरा नॉवल टेक्स्ट निकाला हुआ दिखेगा और अपने कंसोल में प्रिंट होगा.

इस प्रोसेस को पूरा होने में कुछ समय लग सकता है, क्योंकि यह फ़ाइल, पिछले उदाहरण से काफ़ी बड़ी है. (अरे, परेशान न हों...)

हालांकि, बैच प्रोसेसिंग एपीआई से आपको एक ऑपरेशन आईडी मिलेगा. इसका इस्तेमाल टास्क पूरा होने के बाद, 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() तरीका, खास दस्तावेज़ों की सूची या डायरेक्ट्री पाथ के इनपुट के साथ काम करता है.

इस चरण में दस्तावेज़ फ़ाइलों की पूरी डायरेक्ट्री प्रोसेस करने का तरीका बताया जाएगा. ज़्यादातर कोड पिछले चरण की तरह ही काम करते हैं. अंतर सिर्फ़ BatchProcessRequest के साथ भेजे गए GCS यूआरआई का है.

हमारे नमूना बकेट में एक निर्देशिका है जिसमें अलग-अलग फ़ाइलों में उपन्यास के एकाधिक पृष्ठ हैं.

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

आपके पास फ़ाइलों को सीधे पढ़ने या उन्हें अपने Cloud Storage बकेट में कॉपी करने का विकल्प होता है.

Cloud Storage में मौजूद डायरेक्ट्री से YOUR_INPUT_URI को बदलकर, पिछले चरण से कोड को फिर से चलाएं.

कोड चलाने के बाद, आपको 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. दस्तावेज़ एआई टूलबॉक्स की मदद से, बैच प्रोसेसिंग रिस्पॉन्स को मैनेज करना

Cloud Storage के साथ इंटिग्रेशन की वजह से, बैच प्रोसेसिंग को पूरा करने के लिए कुछ कार्रवाइयां करनी पड़ती हैं. Document आउटपुट "शर्डेड" भी हो सकता है इनपुट दस्तावेज़ के साइज़ के आधार पर कई .json फ़ाइलों में फ़ॉर्मैट किया जा सकता है.

डॉक्यूमेंट एआई टूलबॉक्स Python SDK टूल को, दस्तावेज़ एआई (AI) की मदद से पोस्ट-प्रोसेसिंग और दूसरे सामान्य कामों को आसान बनाने के लिए बनाया गया था. यह लाइब्रेरी, दस्तावेज़ एआई (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. बधाई हो

आपने ऑनलाइन प्रोसेसिंग, बैच प्रोसेसिंग, और डॉक्यूमेंट एआई टूलबॉक्स का इस्तेमाल करके, नॉवल से टेक्स्ट निकालने के लिए, दस्तावेज़ एआई (AI) का सही तरीके से इस्तेमाल किया है.

हमारा सुझाव है कि आप अन्य दस्तावेज़ों के साथ एक्सपेरिमेंट करें. साथ ही, इस प्लैटफ़ॉर्म पर उपलब्ध अन्य प्रोसेसर को एक्सप्लोर करें.

स्टोरेज खाली करें

इस ट्यूटोरियल में इस्तेमाल किए गए संसाधनों के लिए, आपके Google Cloud खाते पर लगने वाले शुल्क से बचने के लिए:

  • Cloud Console में, संसाधन मैनेज करें पेज पर जाएं.
  • प्रोजेक्ट की सूची में, अपना प्रोजेक्ट चुनें. इसके बाद, 'मिटाएं' पर क्लिक करें.
  • डायलॉग बॉक्स में, प्रोजेक्ट आईडी टाइप करें. इसके बाद, प्रोजेक्ट मिटाने के लिए 'शट डाउन करें' पर क्लिक करें.

ज़्यादा जानें

इन फ़ॉलो-अप कोडलैब की मदद से, दस्तावेज़ एआई (AI) के बारे में ज़्यादा जानें.

संसाधन

लाइसेंस

इस काम को क्रिएटिव कॉमंस एट्रिब्यूशन 2.0 जेनरिक लाइसेंस के तहत लाइसेंस मिला है.