# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Medical Dialog dataset in english and chinese""" import copy import json import os import re import datasets _CITATION = """\ @article{chen2020meddiag, title={MedDialog: a large-scale medical dialogue dataset}, author={Chen, Shu and Ju, Zeqian and Dong, Xiangyu and Fang, Hongchao and Wang, Sicheng and Yang, Yue and Zeng, Jiaqi and Zhang, Ruisi and Zhang, Ruoyu and Zhou, Meng and Zhu, Penghui and Xie, Pengtao}, journal={arXiv preprint arXiv:2004.03329}, year={2020} } """ _DESCRIPTION = """\ The MedDialog dataset (English) contains conversations (in English) between doctors and patients.\ It has 0.26 million dialogues. The data is continuously growing and more dialogues will be added. \ The raw dialogues are from healthcaremagic.com and icliniq.com.\ All copyrights of the data belong to healthcaremagic.com and icliniq.com. """ _HOMEPAGE = "https://github.com/UCSD-AI4H/Medical-Dialogue-System" _LICENSE = "Unknown" # URLS of processed data _URLS = { "en": "data/Medical-Dialogue-Dataset-English.zip", "zh": "data/Medical-Dialogue-Dataset-Chinese.zip", "processed.en": "data/processed-english.zip", "processed.zh": "data/processed-chinese.zip", } _FILENAMES = { "processed.en": { "train": "english-train.json", "validation": "english-dev.json", "test": "english-test.json", }, "processed.zh": { "train": "train_data.json", "validation": "validate_data.json", "test": "test_data.json", }, } class MedicalDialog(datasets.GeneratorBasedBuilder): VERSION = datasets.Version("2.0.0") BUILDER_CONFIGS = [ datasets.BuilderConfig( name="en", description="The raw dataset of medical dialogs in English.", version=VERSION ), datasets.BuilderConfig( name="zh", description="The raw dataset of medical dialogs in Chinese.", version=VERSION ), datasets.BuilderConfig( name="processed.en", description="The processed dataset of medical dialogs in English.", version=VERSION ), datasets.BuilderConfig( name="processed.zh", description="The processed dataset of medical dialogs in Chinese.", version=VERSION ), ] def _info(self): if self.config.name == "zh": features = datasets.Features( { "file_name": datasets.Value("string"), "dialogue_id": datasets.Value("int32"), "dialogue_url": datasets.Value("string"), "dialogue_turns": datasets.Sequence( { "speaker": datasets.ClassLabel(names=["病人", "医生"]), "utterance": datasets.Value("string"), } ), } ) elif self.config.name == "en": features = datasets.Features( { "file_name": datasets.Value("string"), "dialogue_id": datasets.Value("int32"), "dialogue_url": datasets.Value("string"), "dialogue_turns": datasets.Sequence( { "speaker": datasets.ClassLabel(names=["Patient", "Doctor"]), "utterance": datasets.Value("string"), } ), } ) elif self.config.name == "processed.en": features = datasets.Features( { "description": datasets.Value("string"), "utterances": datasets.Sequence(datasets.Value("string")), } ) elif self.config.name == "processed.zh": features = datasets.Features( { "utterances": datasets.Sequence(datasets.Value("string")), } ) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" *processed, lang = self.config.name.split(".") if processed: # data_dir = dl_manager.download(_URLS[lang]) data_dir = dl_manager.download_and_extract(_URLS[self.config.name]) splits = [datasets.Split.TRAIN, datasets.Split.VALIDATION, datasets.Split.TEST] return [datasets.SplitGenerator(name=split, gen_kwargs={"filepaths": os.path.join(data_dir, _FILENAMES[self.config.name][split])}) for split in splits] else: archive = dl_manager.download(_URLS[self.config.name]) return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepaths": dl_manager.iter_archive(archive)})] def _generate_examples(self, filepaths): """Yields examples. Iterates over each file and give the creates the corresponding features. NOTE: - The code makes some assumption on the structure of the raw .txt file. - There are some checks to separate different id's. Hopefully, should not cause further issues later when more txt files are added. """ *processed, data_lang = self.config.name.split(".") if processed: with open(filepaths, encoding="utf-8") as f: if self.config.name == "processed.en": data = json.load(f) for idx, item in enumerate(data): yield idx, item elif self.config.name == "processed.zh": idx = 0 array = "" for line in f: if line[0] not in ["[", "]"]: if line != " ],\n": array += line else: array += "]" item = json.loads(array) yield idx, {"utterances": item} idx += 1 array = "" else: id_ = -1 for filepath, f_in in filepaths: # with open(filepath, encoding="utf-8") as f_in: # Parameters to just "sectionize" the raw data last_part = "" last_dialog = {} last_list = [] last_user = "" check_list = [] # These flags are present to have a single function address both chinese and english data # English data is a little hahazard (i.e. the sentences spans multiple different lines), # Chinese is compact with one line for doctor and patient. conv_flag = False des_flag = False while True: line = f_in.readline().decode("utf-8") if not line: break # Extracting the dialog id if line[:2] == "id": # Hardcode alert! # Handling ID references that may come in the description # These were observed in the Chinese dataset and were not # followed by numbers try: dialogue_id = int(re.findall(r"\d+", line)[0]) except IndexError: continue # Extracting the url if line[:4] == "http": # Hardcode alert! dialogue_url = line.rstrip() # Extracting the patient info from description. if line[:11] == "Description": # Hardcode alert! last_part = "description" last_dialog = {} last_list = [] last_user = "" last_conv = {"speaker": "", "utterance": ""} while True: line = f_in.readline().decode("utf-8") if (not line) or (line in ["\n", "\n\r"]): break else: if data_lang == "zh": # Condition in chinese if line[:5] == "病情描述:": # Hardcode alert! last_user = "病人" sen = f_in.readline().decode("utf-8").rstrip() des_flag = True if data_lang == "en": last_user = "Patient" sen = line.rstrip() des_flag = True if des_flag: if sen == "": continue if sen in check_list: last_conv["speaker"] = "" last_conv["utterance"] = "" else: last_conv["speaker"] = last_user last_conv["utterance"] = sen check_list.append(sen) des_flag = False break # Extracting the conversation info from dialogue. elif line[:8] == "Dialogue": # Hardcode alert! if last_part == "description" and len(last_conv["utterance"]) > 0: last_part = "dialogue" if data_lang == "zh": last_user = "病人" if data_lang == "en": last_user = "Patient" while True: line = f_in.readline().decode("utf-8") if (not line) or (line in ["\n", "\n\r"]): conv_flag = False last_user = "" last_list.append(copy.deepcopy(last_conv)) # To ensure close of conversation, only even number of sentences # are extracted last_turn = len(last_list) if int(last_turn / 2) > 0: temp = int(last_turn / 2) id_ += 1 last_dialog["file_name"] = filepath last_dialog["dialogue_id"] = dialogue_id last_dialog["dialogue_url"] = dialogue_url last_dialog["dialogue_turns"] = last_list[: temp * 2] yield id_, last_dialog break if data_lang == "zh": if line[:3] == "病人:" or line[:3] == "医生:": # Hardcode alert! user = line[:2] # Hardcode alert! line = f_in.readline().decode("utf-8") conv_flag = True # The elif block is to ensure that multi-line sentences are captured. # This has been observed only in english. if data_lang == "en": if line.strip() == "Patient:" or line.strip() == "Doctor:": # Hardcode alert! user = line.replace(":", "").rstrip() line = f_in.readline().decode("utf-8") conv_flag = True elif line[:2] != "id": # Hardcode alert! conv_flag = True # Continues till the next ID is parsed if conv_flag: sen = line.rstrip() if sen == "": continue if user == last_user: last_conv["utterance"] = last_conv["utterance"] + sen else: last_user = user last_list.append(copy.deepcopy(last_conv)) last_conv["utterance"] = sen last_conv["speaker"] = user