storing.py 4.4 KB

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