Custom_SQuAD / Custom_SQuAD.py
Serhii's picture
Update
33db8df
raw
history blame
10.1 kB
# coding=utf-8
# 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.
"""TODO: Add a description here."""
import csv
import json
import os
from typing import Sequence
import pandas as pd
import datasets
# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@inproceedings{liguori-etal-2021-shellcode,
title = "{S}hellcode{\_}{IA}32: A Dataset for Automatic Shellcode Generation",
author = "Liguori, Pietro and
Al-Hossami, Erfan and
Cotroneo, Domenico and
Natella, Roberto and
Cukic, Bojan and
Shaikh, Samira",
booktitle = "Proceedings of the 1st Workshop on Natural Language Processing for Programming (NLP4Prog 2021)",
month = aug,
year = "2021",
address = "Online",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2021.nlp4prog-1.7",
doi = "10.18653/v1/2021.nlp4prog-1.7",
pages = "58--64",
abstract = "We take the first step to address the task of automatically generating shellcodes, i.e., small pieces of code used as a payload in the exploitation of a software vulnerability, starting from natural language comments. We assemble and release a novel dataset (Shellcode{\_}IA32), consisting of challenging but common assembly instructions with their natural language descriptions. We experiment with standard methods in neural machine translation (NMT) to establish baseline performance levels on this task.",
}
"""
# TODO: Add description of the dataset here
# You can copy an official description
_DESCRIPTION = """\
Shellcode_IA32 is a dataset for shellcode generation from English intents. The shellcodes are compilable on Intel Architecture 32-bits.
"""
# TODO: Add a link to an official homepage for the dataset here
_HOMEPAGE = "https://github.com/dessertlab/Shellcode_IA32"
# TODO: Add the licence for the dataset here if you can find it
_LICENSE = "GNU GENERAL PUBLIC LICENSE"
# TODO: Add link to the official dataset URLs here
# The HuggingFace dataset library don't host the datasets but only point to the original files
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLs = {
'default': "https://raw.githubusercontent.com/dessertlab/Shellcode_IA32/main/Shellcode_IA32.tsv",
}
# TODO: Name of the dataset usually match the script name with CamelCase instead of snake_case
class ShellcodeIA32(datasets.GeneratorBasedBuilder):
"""Shellcode_IA32 a dataset for shellcode generation"""
VERSION = datasets.Version("1.1.0")
# This is an example of a dataset with multiple configurations.
# If you don't want/need to define several sub-sets in your dataset,
# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
# If you need to make complex sub-parts in the datasets with configurable options
# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
# BUILDER_CONFIG_CLASS = MyBuilderConfig
# You will be able to load one or the other configurations in the following list with
# data = datasets.load_dataset('my_dataset', 'first_domain')
# data = datasets.load_dataset('my_dataset', 'second_domain')
# BUILDER_CONFIGS = [
# datasets.BuilderConfig(name="default", version=VERSION, description="This part of my dataset covers the default train/test split"),
# #datasets.BuilderConfig(name="second_domain", version=VERSION, description="This part of my dataset covers a second domain"),
# ]
DEFAULT_CONFIG_NAME = "default" # It's not mandatory to have a default configuration. Just use one if it make sense.
def _info(self):
# TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
features = datasets.Features(
{
"id": datasets.Value("string"),
"title": datasets.Value("string"),
"context": datasets.Value("string"),
"question": datasets.Value("string"),
"answers": {
"text": datasets.Sequence(datasets.Value("string")),
"answer_start": datasets.Sequence(datasets.Value("int32"))
}
}
)
"""
features = datasets.Features(
{
"id": datasets.Value("string"),
"title": datasets.Value("string"),
"context": datasets.Value("string"),
"question": datasets.Value("string"),
"answers": {
"text": datasets.Sequence(datasets.Value("string")),
"answer_start": datasets.Sequence(datasets.Value("int32"))
}
}
)
"""
return datasets.DatasetInfo(
# This is the description that will appear on the datasets page.
description=_DESCRIPTION,
# This defines the different columns of the dataset and their types
features=features, # Here we define them above because they are different between the two configurations
# If there's a common (input, target) tuple from the features,
# specify them here. They'll be used if as_supervised=True in
# builder.as_dataset.
supervised_keys=None,
# Homepage of the dataset for documentation
homepage=_HOMEPAGE,
# License for the dataset if available
license=_LICENSE,
# Citation for the dataset
citation=_CITATION,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
# If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
# dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
# It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
# By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
my_urls = _URLs[self.config.name]
data_dir = dl_manager.download_and_extract("https://huggingface.co/datasets/Serhii/Custom_SQuAD/blob/main/Dataset.json")
data_dir = "/content/drive/MyDrive/datasets/custom_squad/Dataset.json"
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"filepath": os.path.join(data_dir),
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"filepath": os.path.join(data_dir),
"split": "test"
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"filepath": os.path.join(data_dir),
"split": "dev",
},
),
]
def _generate_examples(
self, filepath, split # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
):
""" Yields examples as (key, example) tuples. """
# This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
# The `key` is here for legacy reason (tfds) and is not important in itself.
"""This function returns the examples in the raw (text) form."""
print(f"FILEPATH ------------------ {filepath}")
df = pd.read_json(filepath, lines=True)
train = df.sample(frac = 0.8, random_state = 0)
test = df.drop(train.index)
dev = test.sample(frac = 0.5, random_state = 0)
test = test.drop(dev.index)
if split == 'train':
data = train
elif split == 'dev':
data = dev
elif split == 'test':
data = test
for idx, row in data.iterrows():
yield idx, {
"id": row["id"],
"title": "",
"context": row["context"],
"question": row["question"],
"answers": {
"text": row["answers"]["text"],
"answer_start": [0]
}
}
"""
for idx, row in data.iterrows():
yield idx, {
"id": row["id"],
"title": row["title"],
"context": row["context"],
"question": row["question"],
"answers": {
"text": row["answers"]["text"],
"answer_start": row["answers"]["answer_start"]
}
}
"""