extraction.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. import time
  6. import os
  7. project_id = os.getenv('PROJECT_ID')
  8. bucket_name = os.getenv('BUCKET_NAME')
  9. location = os.getenv('LOCATION')
  10. key_path = os.getenv('SA_KEY_PATH')
  11. credentials = service_account.Credentials.from_service_account_file(key_path)
  12. storage_client = storage.Client(credentials=credentials)
  13. vision_client = vision.ImageAnnotatorClient(credentials=credentials)
  14. lst_pdf_blobs = storage_client.list_blobs(bucket_or_name=bucket_name,
  15. prefix='pdf')
  16. lst_json_blobs = storage_client.list_blobs(bucket_or_name=bucket_name,
  17. prefix='json')
  18. start_time = time.time()
  19. nbr_documents = len(lst_pdf_blobs)
  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/' + blob.name
  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(nbr_documents,
  31. round(total_time / 60,
  32. 1)))
  33. start_time = time.time()
  34. for blob in lst_json_blobs:
  35. doc_title = blob.name.split('/')[-1].split('-')[0]
  36. # Define GCS paths
  37. json_gcs_dest_path = 'gs://' + bucket_name + '/{}'.format(blob.name)
  38. txt_gcs_dest_path = 'gs://' + bucket_name + '/raw_txt/' + doc_title + '.txt'
  39. # Parse json
  40. all_text = read_json_result(json_gcs_dest_path, doc_title)
  41. # Upload raw text to GCS
  42. upload_blob(all_text, txt_gcs_dest_path)
  43. total_time = time.time() - start_time
  44. logging.info(
  45. 'Successful parsing of all {} documents resulting from Vision API on {} minutes'.format(round(total_time / 60, 1)))