SMC / barr2 /using_dataset_hugginface.py
inoid's picture
Upload 2 files
219ab4d verified
# -*- 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
# Load model directly
from transformers import AutoTokenizer, AutoModelForCausalLM
HF_TOKEN = ''
DATASET_TO_LOAD = 'bigbio/distemist'
DATASET_TO_UPDATE = 'somosnlp/spanish_medica_llm'
DATASET_SOURCE_ID = '11'
BASE_DIR = "BARR2" + os.sep + "txt"
#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))
files = [ str(path) + os.sep + BASE_DIR + os.sep + f for f in os.listdir(MAIN_FILE_ADRESS) if os.path.isfile(str(path) + os.sep + BASE_DIR + os.sep + f) and pathlib.Path(MAIN_FILE_ADRESS + os.sep + f).suffix == ".txt" ]
#print (files)
for iFile in files:
with open( iFile,encoding='utf8') as file:
linesInFile = file.readlines()
text = reduce(lambda a, b: a + " "+ b, linesInFile, "")
#print (dataset_CODING)
# with open( str(path) + os.sep + 'ICD-O-3_valid-codes.txt',encoding='utf8') as file:
# """
# # Build a dictionary with ICD-O-3 associated with
# # healtcare problems
# """
# linesInFile = file.readlines()
# for iLine in linesInFile:
# listOfData = iLine.split('\t')
# code = listOfData[0]
# description = reduce(lambda a, b: a + " "+ b, listOfData[1:2], "")
# royalListOfCode[code.strip()] = description.strip()
# def getCodeDescription(labels_of_type, royalListOfCode):
# """
# Search description associated with some code
# in royalListOfCode
# """
# classification = []
# for iValue in labels_of_type:
# if iValue in royalListOfCode.keys():
# classification.append(royalListOfCode[iValue])
# return classification
# # 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': 'clinic_case',
'topic_type': '',
'source': DATASET_SOURCE_ID,
'country': 'es',
'document_id': ''
}
totalOfTokens = 0
corpusToLoad = []
countCopySeveralDocument = 0
counteOriginalDocument = 0
#print (dataset_CODING['train'][5]['entities'])
for iFile in files:
with open( iFile,encoding='utf8') as file:
linesInFile = file.readlines()
text = reduce(lambda a, b: a + " "+ b, linesInFile, "")
#print ("Element in dataset")
#Find topic or diagnosti clasification about the text
counteOriginalDocument += 1
listOfTokens = tokenizer.tokenize(text)
currentSizeOfTokens = len(listOfTokens)
totalOfTokens += currentSizeOfTokens
newCorpusRow = cantemistDstDict.copy()
newCorpusRow['raw_text'] = text
newCorpusRow['document_id'] = str(counteOriginalDocument)
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)
# 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