inoid commited on
Commit
a7a8642
1 Parent(s): 6f4a453

Upload using_dataset_hugginface.py

Browse files
Files changed (1) hide show
  1. meddocan/using_dataset_hugginface.py +182 -0
meddocan/using_dataset_hugginface.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """using_dataset_hugginface.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1soGxkZu4antYbYG23GioJ6zoSt_GhSNT
8
+ """
9
+
10
+ """**Hugginface loggin for push on Hub**"""
11
+ ###
12
+ #
13
+ # Used bibliografy:
14
+ # https://huggingface.co/learn/nlp-course/chapter5/5
15
+ #
16
+ ###
17
+
18
+ import os
19
+ import time
20
+ import math
21
+ from huggingface_hub import login
22
+ from datasets import load_dataset, concatenate_datasets
23
+ from functools import reduce
24
+ from pathlib import Path
25
+ import pandas as pd
26
+ import mysql.connector
27
+
28
+ # Load model directly
29
+ from transformers import AutoTokenizer, AutoModelForCausalLM
30
+
31
+ HF_TOKEN = ''
32
+ DATASET_TO_LOAD = 'bigbio/meddocan'
33
+ DATASET_TO_UPDATE = 'somosnlp/spanish_medica_llm'
34
+
35
+ #Loggin to Huggin Face
36
+ login(token = HF_TOKEN)
37
+
38
+ dataset_CODING = load_dataset(DATASET_TO_LOAD)
39
+ dataset_CODING
40
+ royalListOfCode = {}
41
+ issues_path = 'dataset'
42
+ tokenizer = AutoTokenizer.from_pretrained("DeepESP/gpt2-spanish-medium")
43
+ DATASET_SOURCE_ID = '6'
44
+ #Read current path
45
+ path = Path(__file__).parent.absolute()
46
+
47
+ '''
48
+ Bibliografy:
49
+ https://www.w3schools.com/python/python_mysql_getstarted.asp
50
+ https://www.w3schools.com/python/python_mysql_select.as
51
+
52
+ '''
53
+ mydb = mysql.connector.connect(
54
+ host="localhost",
55
+ user="root",
56
+ password="",
57
+ database="icd10_dx_hackatonnlp"
58
+ )
59
+
60
+
61
+
62
+ def getCodeDescription(labels_of_type):
63
+ """
64
+ Search description associated with some code
65
+ in royalListOfCode
66
+
67
+ """
68
+ icd10CodeDict = {}
69
+ mycursor = mydb.cursor()
70
+ codeIcd10 = ''
71
+
72
+ for iValue in labels_of_type:
73
+ codeIcd10 = iValue
74
+
75
+ if codeIcd10.find('.') == -1:
76
+ codeIcd10 += '.0'
77
+
78
+ mycursor.execute(f"SELECT dx_code, long_desc FROM `icd10_dx_order_code` WHERE dx_code = '{codeIcd10}' LIMIT 1;")
79
+
80
+ myresult = mycursor.fetchall()
81
+
82
+ for x in myresult:
83
+ code, description = x
84
+ icd10CodeDict[code] = description
85
+
86
+ return icd10CodeDict
87
+
88
+
89
+ # raw_text: Texto asociado al documento, pregunta, caso clínico u otro tipo de información.
90
+
91
+ # topic: (puede ser healthcare_treatment, healthcare_diagnosis, tema, respuesta a pregunta, o estar vacío p.ej en el texto abierto)
92
+
93
+ # speciality: (especialidad médica a la que se relaciona el raw_text p.ej: cardiología, cirugía, otros)
94
+
95
+ # raw_text_type: (puede ser caso clínico, open_text, question)
96
+
97
+ # topic_type: (puede ser medical_topic, medical_diagnostic,answer,natural_medicine_topic, other, o vacio)
98
+
99
+ # source: Identificador de la fuente asociada al documento que aparece en el README y descripción del dataset.
100
+
101
+ # 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.).
102
+ cantemistDstDict = {
103
+ 'raw_text': '',
104
+ 'topic': '',
105
+ 'speciallity': '',
106
+ 'raw_text_type': 'clinic_case',
107
+ 'topic_type': '',
108
+ 'source': DATASET_SOURCE_ID,
109
+ 'country': 'es',
110
+ 'document_id': ''
111
+ }
112
+
113
+ totalOfTokens = 0
114
+ corpusToLoad = []
115
+ countCopySeveralDocument = 0
116
+ counteOriginalDocument = 0
117
+
118
+ for iDataset in dataset_CODING:
119
+ if iDataset == 'train':
120
+ for item in dataset_CODING[iDataset]:
121
+ #print ("Element in dataset")
122
+ idFile = str(item['document_id'])
123
+ text = item['text']
124
+
125
+ #Find topic or diagnosti clasification about the text
126
+
127
+ counteOriginalDocument += 1
128
+ newCorpusRow = cantemistDstDict.copy()
129
+
130
+ #print('Current text has ', currentSizeOfTokens)
131
+ #print('Total of tokens is ', totalOfTokens)
132
+
133
+ listOfTokens = tokenizer.tokenize(text)
134
+ currentSizeOfTokens = len(listOfTokens)
135
+ totalOfTokens += currentSizeOfTokens
136
+
137
+ newCorpusRow['raw_text'] = text
138
+ newCorpusRow['document_id'] = idFile
139
+ corpusToLoad.append(newCorpusRow)
140
+
141
+ df = pd.DataFrame.from_records(corpusToLoad)
142
+
143
+ if os.path.exists(f"{str(path)}/{issues_path}/spanish_medical_llms.jsonl"):
144
+ os.remove(f"{str(path)}/{issues_path}/spanish_medical_llms.jsonl")
145
+
146
+
147
+ df.to_json(f"{str(path)}/{issues_path}/spanish_medical_llms.jsonl", orient="records", lines=True)
148
+ print(
149
+ f"Downloaded all the issues for {DATASET_TO_LOAD}! Dataset stored at {issues_path}/spanish_medical_llms.jsonl"
150
+ )
151
+
152
+ print(' On dataset there are as document ', counteOriginalDocument)
153
+ print(' On dataset there are as copy document ', countCopySeveralDocument)
154
+ print(' On dataset there are as size of Tokens ', totalOfTokens)
155
+ file = Path(f"{str(path)}/{issues_path}/spanish_medical_llms.jsonl") # or Path('./doc.txt')
156
+ size = file.stat().st_size
157
+ print ('File size on Kilobytes (kB)', size >> 10) # 5242880 kilobytes (kB)
158
+ print ('File size on Megabytes (MB)', size >> 20 ) # 5120 megabytes (MB)
159
+ print ('File size on Gigabytes (GB)', size >> 30 ) # 5 gigabytes (GB)
160
+
161
+ #Once the issues are downloaded we can load them locally using our
162
+ ##Update local dataset with cloud dataset
163
+ local_spanish_dataset = load_dataset("json", data_files=f"{str(path)}/{issues_path}/spanish_medical_llms.jsonl", split="train")
164
+
165
+
166
+ try:
167
+ spanish_dataset = load_dataset(DATASET_TO_UPDATE, split="train")
168
+ spanish_dataset = concatenate_datasets([spanish_dataset, local_spanish_dataset])
169
+ except Exception:
170
+ print ('<=== Error ===>')
171
+ spanish_dataset = local_spanish_dataset
172
+
173
+ spanish_dataset.push_to_hub(DATASET_TO_UPDATE)
174
+
175
+ print(spanish_dataset)
176
+ # Augmenting the dataset
177
+
178
+ #Importan if exist element on DATASET_TO_UPDATE we must to update element
179
+ # in list, and review if the are repeted elements
180
+
181
+ #spanish_dataset.push_to_hub(DATASET_TO_UPDATE)
182
+