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. 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(storage_client=storage_client, bucket_name=bucket_name, doc_title=doc_title)
  40. # Upload raw text to GCS
  41. upload_blob(storage_client=storage_client, bucket_name=bucket_name,
  42. txt_content=all_text, destination_blob_name=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)))