File size: 11,687 Bytes
1cea235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# -*- coding: utf-8 -*-
"""using_dataset_hugginface.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1soGxkZu4antYbYG23GioJ6zoSt_GhSNT
"""

"""**Hugginface loggin for push on Hub**"""
###
#
#  Used bibliografy:
#    https://huggingface.co/learn/nlp-course/chapter5/5
#
###

import os
import time
import math
from huggingface_hub import login
from datasets import load_dataset, concatenate_datasets
from functools import reduce
from pathlib import Path
import pandas as pd
import pathlib
import xml.etree.ElementTree as ET

# Load model directly
from transformers import AutoTokenizer, AutoModelForCausalLM

typeMedicalDictionary = {
 'Nucleotide_Sequence':'Secuencia de Nucleotidos', 
 'Gene_or_Genome': 'Gen o Genoma', 
  'Professional_Society': 'Sociedad Profesional',
  'Molecular_Biology_Research_Technique':'Técnica de Investigación de Biología Molecular',
  'Occupation_or_Discipline':'Ocupacion o Disciplina',
  'Natural_Phenomenon_or_Process':'Proceso o Fenómeno Natural',
  'Bird':'Pájaro', 'Drug_Delivery_Device':'Dispositivo de entrega de medicamentos', 
   'Animal':'Animal', 'Temporal_Concept':'Concepto Temporal', 'Physiologic_Function':'Función Psicológica',
  'Regulation_or_Law':'Ley o Regulacion', 'Mental_or_Behavioral_Dysfunction':'Disfunción mental o de comportamiento', 
   'Event':'Evento', 'Antibiotic':'Antibiótico', 'Family_Group':'Grupo Familiar', 'Chemical':'Quimico',
   'Educational_Activity':'Actividad Educacional', 'Organism_Attribute':'Atributo organismo', 'Functional_Concept':'Concepto Funcional', 
   'Age_Group':'Grupo Etareo', 'Organic_Compound':'Compuesto orgánico', 'Human':'Humano', 'Health_Care_Activity':'Actividad de cuidado de salud', 
   'Mental_Process':'Proceso mental', 'Hormone':'Hormona', 'Experimental_Model_of_Disease':'Modelo experimental de una enfermedad',
    'Fully_Formed_Anatomical_Structure':'Estructura anatómica completamente formada', 'Classification':'Clasificación', 'Food':'Comida', 'Amino_Acid_Peptide_or_Protein':'Aminoácido péptido o proteína', 
    'Injury_or_Poisoning':'Lesión o envenenamiento', 'Substance':'Sustancia', 'Organization':'Organizacion', 'Intellectual_Product':'Producto Intelectual', 'Behavior':'Comportamiento',
    'Body_Part_Organ_or_Organ_Component':'Parte del cuerpo órgano o componente del órgano', 'Cell_or_Molecular_Dysfunction':'Disfunción celular o molecular', 'Fish':'Pescado', 'Vertebrate':'Vertebrado', 
    'Congenital_Abnormality':'Anormalidad congénita', 'Governmental_or_Regulatory_Activity':'Actividad gubernamental o regulatoria',
    'Daily_or_Recreational_Activity':'Actividad diaria o recreacional', 'Hazardous_or_Poisonous_Substance':'Sustancia peligrosa o venenosa', 'Group_Attribute':'Atributo grupo', 'Immunologic_Factor':'Factor inmunológico', 'Laboratory_or_Test_Result':'Resultado de la prueba o laboratorio',
    'Neoplastic_Process':'Proceso neoplásico', 'Phenomenon_or_Process':'Fenómeno o proceso', 'Cell_Component':'Componente celular', 'Health_Care_Related_Organization':'Organización relacionada con el cuidado dela_salud', 'Anatomical_Structure': 'Estructura anatómica', 'Chemical_Viewed_Structurally':'Química vista estructuralmente',
    'Population_Group':'Grupo poblacional', 'Biologic_Function':'Función biológica', 'Biologically_Active_Substance':'Sustancia activa biologicamente', 'Clinical_Attribute':'Atributo clínico', 'Laboratory_Procedure':'Procedimiento de laboratorio', 'Fungus':'Hongo', 'Body_Space_or_Junction':'Espacio del cuerpo o unión', 'Finding':'Hallazgo', 'Spatial_Concept':'Concepto espacial', 
    'Quantitative_Concept':'Concepto cuantitativo', 'Archaeon':'Arqueón', 'Biomedical_Occupation_or_Discipline':'Ocupación o disciplina biomédica', 'Therapeutic_or_Preventive_Procedure':'Procedimiento terapéutico o preventivo', 'Organ_or_Tissue_Function': 'Función de órgano o tejido', 'Cell':'Célula', 'Organic_Chemical':'Orgánico químico', 
    'Human-caused_Phenomenon_or_Process':'Fenómeno o proceso causado por el humano', 'Body_System':'Sistema corporal', 'Sign_or_Symptom':'Signo o síntoma', 'Plant':'Planta', 'Virus':'Virus', 'Activity':'Actividad', 'Organism_Function':'Organismo Función', 'Molecular_Sequence':'Secuencia molecular', 'Steroid':'Esteroide', 'Reptile':'Reptil', 
    'Molecular_Function':'Función molecular', 'Professional_or_Occupational_Group':'Grupo profesional o ocupacional', 'Embryonic_Structure':'Estructura embrionaria', 'Organism':'Organismo', 'Anatomical_Abnormality':'Anormalidad anatómica', 'Patient_or_Disabled_Group':'Grupo de paciente o discapacitado', 'Qualitative_Concept':'Concepto cualitativo', 
    'Bacterium':'Bacteria', 'Idea_or_Concept':'Idea o concepto', 'Enzyme':'Enzima', 'Research_Device':'Dispositivo de investigación', 'Geographic_Area':'Área geográfica', 'Entity':'Entidad', 'Body_Location_or_Region':'Ubicación del cuerpo o región', 'Social_Behavior':'Comportamiento social', 'Self-help_or_Relief_Organization':'Organización de ayuda o alivio', 
    'Inorganic_Chemical':'Químico inorgánico', 'Body_Substance':'Sustancia corporal', 'Conceptual_Entity':'Entidad conceptual', 'Physical_Object':'Objeto físico', 
    'Mammal':'Mamífero', 'Manufactured_Object':'Objeto fabricado', 'Eukaryote':'Eucariota', 'Pathologic_Function':'Función patológica', 'Machine_Activity':'Actividad mecánica', 'Occupational_Activity':'Actividad ocupacional', 'Vitamin':'Vitamina', 'Research_Activity':'Actividad de investigación',
    'Biomedical_or_Dental_Material':'Material biomédico o dental', 'Environmental_Effect_of_Humans':'Efecto ambiental de los humanos', 'Amino_Acid_Sequence':'Secuencia de aminoácidos', 'Clinical_Drug':'Fármaco clinico', 'Receptor':'Receptor', 'Diagnostic_Procedure':'Procedimiento diagnóstico',
    'Pharmacologic_Substance':'Sustancia farmacológica', 'Medical_Device':'Dispositivo médico', 'Cell_Function':'Función celular', 'Nucleic_Acid_Nucleoside_or_Nucleotide':'Nucleósido o nucleósido de ácido nucleico', 'Language':'Idioma', 'Chemical_Viewed_Functionally':'Químico visto funcionalmente', 
    'Group':'Grupo', 'Tissue':'Tejido', 'Element_Ion_or_Isotope':'Elemento ion o isótopo', 'Individual_Behavior':'Comportamiento individual', 'Indicator_Reagent_or_Diagnostic_Aid':'Indicador reactivo o ayuda de diagnóstico', 'Genetic_Function':'Función genética', 'Acquired_Abnormality': 'Anormalidad adquirida', 'Disease_or_Syndrome':'Enfermedad o síndrome'
}


HF_TOKEN = ''
DATASET_TO_LOAD = 'bigbio/distemist'
DATASET_TO_UPDATE = 'somosnlp/spanish_medica_llm'
DATASET_SOURCE_ID = '13'
BASE_DIR = "SPACC"  + os.sep + "SPACCC"  + os.sep + "SPACCC"  + os.sep + "corpus"
FILE_PATH = "MedLexSp_v2" + os.sep + "MedLexSp_v2" + os.sep  + "MedLexSp_v2.xml"

#Loggin to Huggin Face
login(token = HF_TOKEN)

dataset_CODING = load_dataset(DATASET_TO_LOAD)
royalListOfCode = {}
issues_path = 'dataset'
tokenizer = AutoTokenizer.from_pretrained("DeepESP/gpt2-spanish-medium")

#Read current path
path = Path(__file__).parent.absolute()
MAIN_FILE_ADRESS = str(path) + os.sep + BASE_DIR
#print ( os.listdir(str(path) + os.sep + BASE_DIR))

#     # raw_text: Texto asociado al documento, pregunta, caso clínico u otro tipo de información.

#     # topic: (puede ser healthcare_treatment, healthcare_diagnosis, tema, respuesta a pregunta, o estar vacío p.ej en el texto abierto)

#     # speciality: (especialidad médica a la que se relaciona el raw_text p.ej: cardiología, cirugía, otros)

#     # raw_text_type: (puede ser caso clínico, open_text, question)

#     # topic_type: (puede ser medical_topic, medical_diagnostic,answer,natural_medicine_topic, other, o vacio)

#     # source: Identificador de la fuente asociada al documento que aparece en el README y descripción del dataset.

#     # country: Identificador del país de procedencia de la fuente (p.ej.; ch, es) usando el estándar ISO 3166-1 alfa-2 (Códigos de país de dos letras.).
cantemistDstDict = {
  'raw_text': '',
  'topic': '',
  'speciallity': '',
  'raw_text_type': 'question',
  'topic_type': 'answer',
  'source': DATASET_SOURCE_ID,
  'country': 'es',
  'document_id': ''
}

totalOfTokens = 0
corpusToLoad = []
countCopySeveralDocument = 0
counteOriginalDocument = 0
setOfTopic = set()

#print (dataset_CODING['train'][5]['entities'])

path = Path(__file__).parent.absolute()
tree = ET.parse(str(path) + os.sep + FILE_PATH)
root = tree.getroot()
sets = []
counterSeveralType = 0
counterDocument = 0
for group in root.findall("{http://www.lexicalmarkupframework.org/}Lexicon"):
    for igroup in group.findall("{http://www.lexicalmarkupframework.org/}LexicalEntry"):
        for item in igroup.findall("{http://www.lexicalmarkupframework.org/}Lemma"):
            text = str(item.attrib['writtenForm']).capitalize()   
            #print (str(item.attrib['writtenForm']).capitalize())
            counteOriginalDocument += 1

            listOfTokens = tokenizer.tokenize(text)
            currentSizeOfTokens = len(listOfTokens)
            totalOfTokens += currentSizeOfTokens
            newCorpusRow = cantemistDstDict.copy()

            
            newCorpusRow['raw_text'] = text
            newCorpusRow['document_id'] = str(counteOriginalDocument)
           

            counterType = 0
        for doc in igroup.findall("{http://www.lexicalmarkupframework.org/}SemanticType"):
            if counterType > 0:
                newCorpusRow = cantemistDstDict.copy()
                newCorpusRow['raw_text'] = text
                newCorpusRow['document_id'] = str(counteOriginalDocument)
            
            topic = doc.attrib['val']
           
            newCorpusRow['topic'] = typeMedicalDictionary[topic]  

            setOfTopic.add(topic)

            counterSeveralType += 1
            counterType += 1
            corpusToLoad.append(newCorpusRow)        

df = pd.DataFrame.from_records(corpusToLoad)

if os.path.exists(f"{str(path)}/{issues_path}/spanish_medical_llms.jsonl"):
  os.remove(f"{str(path)}/{issues_path}/spanish_medical_llms.jsonl")

df.to_json(f"{str(path)}/{issues_path}/spanish_medical_llms.jsonl", orient="records", lines=True)
print(
        f"Downloaded all the issues for {DATASET_TO_LOAD}! Dataset stored at {issues_path}/spanish_medical_llms.jsonl"
)

print(' On dataset there are as document ', counteOriginalDocument)
print(' On dataset there are as copy document ', countCopySeveralDocument)
print(' On dataset there are as size of Tokens ', totalOfTokens)
file = Path(f"{str(path)}/{issues_path}/spanish_medical_llms.jsonl")  # or Path('./doc.txt')
size = file.stat().st_size
print ('File size on Kilobytes (kB)', size >> 10)  # 5242880 kilobytes (kB)
print ('File size on Megabytes  (MB)', size >> 20 ) # 5120 megabytes (MB)
print ('File size on Gigabytes (GB)', size >> 30 ) # 5 gigabytes (GB)

#Once the issues are downloaded we can load them locally using our 
local_spanish_dataset = load_dataset("json", data_files=f"{str(path)}/{issues_path}/spanish_medical_llms.jsonl", split="train")


##Update local dataset with cloud dataset
try:  
  spanish_dataset = load_dataset(DATASET_TO_UPDATE, split="train")
  print("=== Before ====")
  print(spanish_dataset)
  spanish_dataset = concatenate_datasets([spanish_dataset, local_spanish_dataset])
except Exception:
  spanish_dataset = local_spanish_dataset

spanish_dataset.push_to_hub(DATASET_TO_UPDATE)

print("=== After ====")
print(spanish_dataset)

#print('List of Term Topic')
#print(setOfTopic)

# Augmenting the dataset

#Importan if exist element on DATASET_TO_UPDATE we must to update element 
# in list, and review if the are repeted elements