storing.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. from google.cloud import storage, bigquery, datastore
  2. from google.oauth2 import service_account
  3. from utils.bq_fcn import bqCreateDataset, bqCreateTable, exportItems2BQ
  4. from utils.ner_fcn import loadModel, addTask, extractMedEntities
  5. import en_core_sci_lg
  6. import logging
  7. import time
  8. import os
  9. import pandas as pd
  10. project_id = os.getenv('PROJECT_ID')
  11. bucket_name = os.getenv('BUCKET_NAME')
  12. location = os.getenv('LOCATION')
  13. key_path = os.getenv('SA_KEY_PATH')
  14. dataset_name = os.getenv('BQ_DATASET_NAME')
  15. table_name = os.getenv('BQ_TABLE_NAME')
  16. credentials = service_account.Credentials.from_service_account_file(key_path)
  17. storage_client = storage.Client(credentials=credentials)
  18. datastore_client = datastore.Client(credentials=credentials)
  19. gcs_source_prefix = 'raw_txt'
  20. lst_blobs = storage_client.list_blobs(bucket_or_name=bucket_name,
  21. prefix=gcs_source_prefix)
  22. start_time = time.time()
  23. try:
  24. dataset_id = bqCreateDataset(dataset_name)
  25. logging.info("The following dataset {} was successfully created/retrieved.".format(dataset_name))
  26. except Exception as e:
  27. logging.error("An error occurred.", e)
  28. try:
  29. table_id = bqCreateTable(dataset_id, table_name)
  30. logging.info("The following table {} was successfully created/retrieved.".format(table_name))
  31. except Exception as e:
  32. logging.error("An error occurred.", e)
  33. for blob in lst_blobs:
  34. doc_title = blob.name.split('/')[-1].split('.txt')[0]
  35. # download as string
  36. it_raw_blob = storage_client.get_bucket(bucket_name).get_blob('raw_txt/{}.txt'.format(doc_title))
  37. # set the GCS path
  38. path_blob_eng_raw = 'eng_txt/{}/{}_raw_txt_{}_en_translations.txt'.format(doc_title,
  39. bucket_name,
  40. doc_title)
  41. eng_raw_blob = storage_client.get_bucket(bucket_name).get_blob(path_blob_eng_raw)
  42. # Upload blob of interest
  43. curated_eng_blob = storage_client.get_bucket(bucket_name) \
  44. .get_blob('curated_eng_txt/{}.txt'.format(doc_title))
  45. # populate to BQ dataset
  46. exportItems2BQ(dataset_id, table_id, doc_title, it_raw_blob, eng_raw_blob, curated_eng_blob)
  47. total_time = time.time() - start_time
  48. logging.info('The export to BigQuery was completed successfully and took {} minutes.'.format(round(total_time / 60, 1)))
  49. curated_gcs_source_prefix = 'curated_eng_txt'
  50. lst_curated_blobs = storage_client.list_blobs(bucket_or_name=bucket_name,
  51. prefix=curated_gcs_source_prefix)
  52. nlp = loadModel(model=en_core_sci_lg)
  53. start_time = time.time()
  54. for blob in lst_curated_blobs:
  55. doc_title = blob.name.split('/')[-1].split('.txt')[0]
  56. # download as string
  57. eng_string = blob.download_as_string().decode('utf-8')
  58. # convert to vector
  59. doc = nlp(eng_string)
  60. # Extract medical entities
  61. UMLS_tuis_entity = extractMedEntities(doc)
  62. # Generate dataframes
  63. entities = list(UMLS_tuis_entity.keys())
  64. TUIs = list(UMLS_tuis_entity.values())
  65. df_entities = pd.DataFrame(data={'entity': entities, 'TUIs': TUIs})
  66. df_reference_TUIs = pd.read_csv('~/data/UMLS_tuis.csv')
  67. df_annotated_text_entities = pd.merge(df_entities, df_reference_TUIs, how='inner', on=['TUIs'])
  68. # Upload entities to datastore
  69. entities_dict = {}
  70. for idx in range(df_annotated_text_entities.shape[0]):
  71. category = df_annotated_text_entities.iloc[idx].values[2]
  72. med_entity = df_annotated_text_entities.iloc[idx].values[0]
  73. # Append to list of entities if the key,value pair already exist
  74. try:
  75. entities_dict[category].append(med_entity)
  76. except:
  77. entities_dict[category] = []
  78. entities_dict[category].append(med_entity)
  79. # API call
  80. key = addTask(datastore_client, doc_title, entities_dict)
  81. logging.info('The upload of {} entities is done.'.format(doc_title))
  82. total_time = time.time() - start_time
  83. logging.info(
  84. "The export to Datastore was completed successfully and took {} minutes.".format(round(total_time / 60, 1)))