cathw commited on
Commit
414148c
1 Parent(s): 8ae375b

Upload 4 files

Browse files
climate_data.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93fc0e5aacc47d0206cb2dac3dcf627494c4817171c63db8e300ee8cc1a3388c
3
+ size 16723047
comment_data.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4a15f498476cf271def33ae786f72ea7926e3bd1634aff6f7d166c9bfa94b0f
3
+ size 17846138
csvtransformerjson.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import pandas as pd
3
+
4
+ class CSVtoJSONTransformer:
5
+ def __init__(self, csv_reader):
6
+ self.csv_reader = csv_reader
7
+
8
+ def transform_to_json(self):
9
+ df = pd.DataFrame(self.csv_reader) # Convert csv_reader to DataFrame
10
+ df["Author"] = df["Author"].replace({pd.NA: None})
11
+ df["Comment Body"] = df["Comment Body"].replace({pd.NA: None})
12
+
13
+ # Define an empty list to store the transformed data
14
+ transformed_data = []
15
+
16
+ # Group the DataFrame by the 'Subreddit' column
17
+ grouped_df = df.groupby('Subreddit')
18
+
19
+ # Iterate through each subreddit group
20
+ for subreddit, group in grouped_df:
21
+ subreddit_data = {
22
+ "Subreddit": subreddit,
23
+ "Posts": []
24
+ }
25
+
26
+ # Iterate through each row in the subreddit group
27
+ for index, row in group.iterrows():
28
+ post_title = row['Post Title']
29
+ comment_body = row['Comment Body']
30
+ timestamp = row['Timestamp']
31
+ upvotes = row['Upvotes']
32
+ ID = row['ID']
33
+ author = row['Author']
34
+ replies = row['Number of Replies']
35
+
36
+ # Check if the post title already exists under the subreddit
37
+ post_exists = False
38
+ for post in subreddit_data["Posts"]:
39
+ if post['PostTitle'] == post_title:
40
+ post_exists = True
41
+ post['Comments'].append({
42
+ "CommentID": ID,
43
+ "Author": author,
44
+ "CommentBody": comment_body,
45
+ "Timestamp": timestamp,
46
+ "Upvotes": upvotes,
47
+ "NumberofReplies": replies
48
+ })
49
+ break
50
+
51
+ # If the post title does not exist, create a new entry
52
+ if not post_exists:
53
+ subreddit_data["Posts"].append({
54
+ "PostID": len(subreddit_data["Posts"]) + 1,
55
+ "PostTitle": post_title,
56
+ "Comments": [{
57
+ "CommentID": ID,
58
+ "Author": author,
59
+ "CommentBody": comment_body,
60
+ "Timestamp": timestamp,
61
+ "Upvotes": upvotes,
62
+ "NumberofReplies": replies
63
+ }]
64
+ })
65
+
66
+ # Append the subreddit data to the transformed data list
67
+ transformed_data.append(subreddit_data)
68
+
69
+ return transformed_data
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
+ import datasets
10
+ from csvtransformerjson import CSVtoJSONTransformer
11
+
12
+
13
+ # TODO: Add BibTeX citation
14
+ # Find for instance the citation on arxiv or on the dataset repo/website
15
+ _CITATION = """\
16
+ @InProceedings{huggingface:dataset,
17
+ title = {A great new dataset},
18
+ author={huggingface, Inc.
19
+ },
20
+ year={2024}
21
+ }
22
+ """
23
+
24
+ # TODO: Add description of the dataset here
25
+ # You can copy an official description
26
+ _DESCRIPTION = """\
27
+ This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
28
+ """
29
+
30
+ # TODO: Add a link to an official homepage for the dataset here
31
+ _HOMEPAGE = ""
32
+
33
+ # TODO: Add the licence for the dataset here if you can find it
34
+ _LICENSE = ""
35
+
36
+ # TODO: Add link to the official dataset URLs here
37
+ # The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
38
+ # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
39
+ _URLS = {
40
+ "reddit_climate": "cathw/comment_data"
41
+ }
42
+
43
+ # TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
44
+ class NewDataset(datasets.GeneratorBasedBuilder):
45
+ """TODO: Short description of my dataset."""
46
+
47
+ VERSION = datasets.Version("1.1.0")
48
+
49
+ # This is an example of a dataset with multiple configurations.
50
+ # If you don't want/need to define several sub-sets in your dataset,
51
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
52
+
53
+ # If you need to make complex sub-parts in the datasets with configurable options
54
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
55
+ # BUILDER_CONFIG_CLASS = MyBuilderConfig
56
+
57
+ # You will be able to load one or the other configurations in the following list with
58
+ # data = datasets.load_dataset('my_dataset', 'first_domain')
59
+ # data = datasets.load_dataset('my_dataset', 'second_domain')
60
+ BUILDER_CONFIGS = [
61
+ datasets.BuilderConfig(name="reddit_climate", version=VERSION, description="This part of my dataset covers a first domain")
62
+ ]
63
+
64
+ DEFAULT_CONFIG_NAME = "reddit_climate" # It's not mandatory to have a default configuration. Just use one if it make sense.
65
+
66
+ def _info(self):
67
+
68
+ features = datasets.Features({
69
+ "Subreddit": datasets.Value("string"),
70
+ "Posts": datasets.Sequence({
71
+ "PostID": datasets.Value("int32"),
72
+ "PostTitle": datasets.Value("string"),
73
+ "Comments": datasets.Sequence({
74
+ "CommentID": datasets.Value("string"),
75
+ "Author": datasets.Value("string"),
76
+ "CommentBody": datasets.Value("string"),
77
+ "Timestamp": datasets.Value("string"),
78
+ "Upvotes": datasets.Value("int32"),
79
+ "NumberofReplies": datasets.Value("int32"),
80
+ }),
81
+ }),
82
+ })
83
+ return datasets.DatasetInfo(
84
+ # This is the description that will appear on the datasets page.
85
+ description=_DESCRIPTION,
86
+ # This defines the different columns of the dataset and their types
87
+ features=features, # Here we define them above because they are different between the two configurations
88
+ # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
89
+ # specify them. They'll be used if as_supervised=True in builder.as_dataset.
90
+ # supervised_keys=("sentence", "label"),
91
+ # Homepage of the dataset for documentation
92
+ homepage=_HOMEPAGE,
93
+ # License for the dataset if available
94
+ license=_LICENSE,
95
+ # Citation for the dataset
96
+ citation=_CITATION,
97
+ )
98
+
99
+ def _split_generators(self, dl_manager):
100
+ # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
101
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
102
+
103
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
104
+ # 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.
105
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
106
+ config_name = getattr(self.config, 'name', self.DEFAULT_CONFIG_NAME)
107
+ urls = _URLS.get(config_name, {}) # Get the URLs for the configuration name, if not found, return an empty dictionary
108
+ data_dir = dl_manager.download_and_extract(urls)
109
+ return [
110
+ datasets.SplitGenerator(
111
+ name=datasets.Split.TRAIN,
112
+ # These kwargs will be passed to _generate_examples
113
+ gen_kwargs={
114
+ "filepath": data_dir,
115
+ "split": "train",
116
+ },
117
+ ),
118
+ ]
119
+
120
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
121
+ def _generate_examples(self, filepath, split):
122
+ # This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
123
+ # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
124
+ with open(filepath, encoding="utf-8") as f:
125
+ csv_reader = csv.reader(f)
126
+ data = CSVtoJSONTransformer(csv_reader)
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
+ }