cathw commited on
Commit
38a8b3d
1 Parent(s): 1fcf9da

Upload reddit_climate_data.py

Browse files
Files changed (1) hide show
  1. reddit_climate_data.py +163 -0
reddit_climate_data.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """TODO: Add a description here."""
3
+
4
+
5
+ import csv
6
+ import json
7
+ import os
8
+ import logging
9
+
10
+
11
+ import datasets
12
+
13
+
14
+ # TODO: Add BibTeX citation
15
+ # Find for instance the citation on arxiv or on the dataset repo/website
16
+ _CITATION = """\
17
+ @InProceedings{huggingface:dataset,
18
+ title = {A great new dataset},
19
+ author={huggingface, Inc.
20
+ },
21
+ year={2024}
22
+ }
23
+ """
24
+
25
+ # TODO: Add description of the dataset here
26
+ # You can copy an official description
27
+ _DESCRIPTION = """\
28
+ This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
29
+ """
30
+
31
+ # TODO: Add a link to an official homepage for the dataset here
32
+ _HOMEPAGE = ""
33
+
34
+ # TODO: Add the licence for the dataset here if you can find it
35
+ _LICENSE = ""
36
+
37
+ # TODO: Add link to the official dataset URLs here
38
+ # The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
39
+ # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
40
+ _URLS = {
41
+ "reddit_climate": "cathw/reddit_climate_comment"
42
+ }
43
+
44
+ # TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
45
+ class NewDataset(datasets.GeneratorBasedBuilder):
46
+ """TODO: Short description of my dataset."""
47
+
48
+ VERSION = datasets.Version("1.1.0")
49
+
50
+ # This is an example of a dataset with multiple configurations.
51
+ # If you don't want/need to define several sub-sets in your dataset,
52
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
53
+
54
+ # If you need to make complex sub-parts in the datasets with configurable options
55
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
56
+ # BUILDER_CONFIG_CLASS = MyBuilderConfig
57
+
58
+ # You will be able to load one or the other configurations in the following list with
59
+ # data = datasets.load_dataset('my_dataset', 'first_domain')
60
+ # data = datasets.load_dataset('my_dataset', 'second_domain')
61
+ BUILDER_CONFIGS = [
62
+ datasets.BuilderConfig(name="reddit_climate", version=VERSION, description="This part of my dataset covers a first domain")
63
+ ]
64
+
65
+ DEFAULT_CONFIG_NAME = "reddit_climate" # It's not mandatory to have a default configuration. Just use one if it make sense.
66
+
67
+ def _info(self):
68
+
69
+ features = datasets.Features({
70
+ "Subreddit": datasets.Value("string"),
71
+ "Posts": datasets.Sequence({
72
+ "PostID": datasets.Value("int32"),
73
+ "PostTitle": datasets.Value("string"),
74
+ "Comments": datasets.Sequence({
75
+ "CommentID": datasets.Value("string"),
76
+ "Author": datasets.Value("string"),
77
+ "CommentBody": datasets.Value("string"),
78
+ "Timestamp": datasets.Value("string"),
79
+ "Upvotes": datasets.Value("int32"),
80
+ "NumberofReplies": datasets.Value("int32"),
81
+ }),
82
+ }),
83
+ })
84
+ return datasets.DatasetInfo(
85
+ # This is the description that will appear on the datasets page.
86
+ description=_DESCRIPTION,
87
+ # This defines the different columns of the dataset and their types
88
+ features=features, # Here we define them above because they are different between the two configurations
89
+ # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
90
+ # specify them. They'll be used if as_supervised=True in builder.as_dataset.
91
+ # supervised_keys=("sentence", "label"),
92
+ # Homepage of the dataset for documentation
93
+ homepage=_HOMEPAGE,
94
+ # License for the dataset if available
95
+ license=_LICENSE,
96
+ # Citation for the dataset
97
+ citation=_CITATION,
98
+ )
99
+
100
+ def _split_generators(self, dl_manager):
101
+ # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
102
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
103
+
104
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
105
+ # 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.
106
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
107
+ config_name = getattr(self.config, 'name', self.DEFAULT_CONFIG_NAME)
108
+ urls = _URLS.get(config_name, {}) # Get the URLs for the configuration name, if not found, return an empty dictionary
109
+ data_dir = dl_manager.download_and_extract(urls)
110
+ return [
111
+ datasets.SplitGenerator(
112
+ name=datasets.Split.TRAIN,
113
+ # These kwargs will be passed to _generate_examples
114
+ gen_kwargs={
115
+ "filepath": data_dir,
116
+ "split": "train",
117
+ },
118
+ ),
119
+ ]
120
+
121
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
122
+ def _generate_examples(self, filepath, split):
123
+ # This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
124
+ # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
125
+ with open(filepath, encoding="utf-8") as f:
126
+ data = json.load(f)
127
+ for idx, row in enumerate(data):
128
+ subreddit = row["Subreddit"]
129
+ posts = []
130
+ # Check if the "Posts" key is present in the current row
131
+ if "Posts" in row:
132
+ for post in row["Posts"]:
133
+ post_id = post["PostID"]
134
+ post_title = post["PostTitle"]
135
+ comments = []
136
+ for comment in post["Comments"]:
137
+ comment_id = comment["CommentID"]
138
+ author = comment["Author"]
139
+ comment_body = comment["CommentBody"]
140
+ timestamp = comment["Timestamp"]
141
+ upvotes = comment["Upvotes"]
142
+ number_of_replies = comment["NumberofReplies"]
143
+ comments.append({
144
+ "CommentID": comment_id,
145
+ "Author": author,
146
+ "CommentBody": comment_body,
147
+ "Timestamp": timestamp,
148
+ "Upvotes": upvotes,
149
+ "NumberofReplies": number_of_replies
150
+ })
151
+ posts.append({
152
+ "PostID": post_id,
153
+ "PostTitle": post_title,
154
+ "Comments": comments
155
+ })
156
+ else:
157
+ # Handle cases where the "Posts" key is missing
158
+ posts = None
159
+
160
+ yield idx, {
161
+ "Subreddit": subreddit,
162
+ "Posts": posts
163
+ }