extraction.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from google.cloud import storage, vision
  2. from google.oauth2 import service_account
  3. from utils.preprocessing_fcn import async_detect_document, read_json_result, upload_blob
  4. import logging
  5. logging.getLogger().setLevel(logging.INFO)
  6. import time
  7. import os
  8. project_id = os.getenv('PROJECT_ID')
  9. bucket_name = os.getenv('BUCKET_NAME')
  10. location = os.getenv('LOCATION')
  11. key_path = os.getenv('SA_KEY_PATH')
  12. credentials = service_account.Credentials.from_service_account_file(key_path)
  13. storage_client = storage.Client(credentials=credentials)
  14. vision_client = vision.ImageAnnotatorClient(credentials=credentials)
  15. lst_pdf_blobs = storage_client.list_blobs(bucket_or_name=bucket_name,
  16. prefix='pdf')
  17. lst_json_blobs = storage_client.list_blobs(bucket_or_name=bucket_name,
  18. prefix='json')
  19. start_time = time.time()
  20. for blob in lst_pdf_blobs:
  21. doc_title = blob.name.split('/')[-1].split('.pdf')[0]
  22. # Generate all paths
  23. gcs_source_path = 'gs://' + bucket_name + '/' + blob.name
  24. json_gcs_dest_path = 'gs://' + bucket_name + '/json/' + doc_title
  25. # OCR pdf documents
  26. async_detect_document(vision_client,
  27. gcs_source_path,
  28. json_gcs_dest_path)
  29. total_time = time.time() - start_time
  30. logging.info("Vision API successfully completed OCR of all {} documents on {} minutes".format(round(total_time / 60,1)))
  31. # Extracting the text now
  32. start_time = time.time()
  33. for blob in lst_json_blobs:
  34. doc_title = blob.name.split('/')[-1].split('-')[0]
  35. # Define GCS paths
  36. #json_gcs_dest_path = 'gs://' + bucket_name + '/{}'.format(blob.name)
  37. txt_gcs_dest_path = 'gs://' + bucket_name + '/raw_txt/' + doc_title + '.txt'
  38. # Parse json
  39. all_text = read_json_result(bucket_name=bucket_name, doc_title=doc_title)
  40. # Upload raw text to GCS
  41. upload_blob(all_text, txt_gcs_dest_path)
  42. total_time = time.time() - start_time
  43. logging.info(
  44. 'Successful parsing of all {} documents resulting from Vision API on {} minutes'.format(round(total_time / 60, 1)))