p1atdev commited on
Commit
e7ea286
·
1 Parent(s): e62471e

Upload open2ch.py

Browse files
Files changed (1) hide show
  1. open2ch.py +358 -0
open2ch.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """おーぷん2ちゃんねる対話コーパス"""
15
+
16
+ from typing import Iterable
17
+
18
+ import csv
19
+ import os
20
+
21
+ import datasets as ds
22
+
23
+
24
+ _CITATION = """\
25
+ @inproceedings{open2chdlc2019,
26
+ title={おーぷん2ちゃんねる対話コーパスを用いた用例ベース対話システム},
27
+ author={稲葉 通将},
28
+ booktitle={第87回言語・音声理解と対話処理研究会(第10回対話システムシンポジウム), 人工知能学会研究会資料 SIG-SLUD-B902-33},
29
+ pages={129--132},
30
+ year={2019}
31
+ }
32
+ """
33
+
34
+ _DESCRIPTION = """\
35
+ おーぷん2ちゃんねるの「なんでも実況(ジュピター)」「ニュー速VIP」「ニュース速報+」の3つの掲示板をクロールして作成した対話コーパスの HuggingFace Datasets 変換版です。
36
+ """
37
+
38
+ _HOMEPAGE = "https://github.com/1never/open2ch-dialogue-corpus"
39
+
40
+ _LICENSE = "Apache-2.0"
41
+
42
+ _URLS = {
43
+ "corpus": "https://media.githubusercontent.com/media/1never/open2ch-dialogue-corpus/master/corpus.zip",
44
+ "ranking": "https://raw.githubusercontent.com/1never/open2ch-dialogue-corpus/master/ranking.zip",
45
+ "ng_words": "https://raw.githubusercontent.com/1never/open2ch-dialogue-corpus/master/data/ng_words.txt",
46
+ }
47
+
48
+
49
+ # Load corpus data from file
50
+ def load_corpus(filepath: str, ng_words: list[str] = []) -> Iterable[list]:
51
+ with open(filepath, "r", encoding="utf-8") as f:
52
+ reader = csv.reader(f, delimiter="\t")
53
+
54
+ for row in reader:
55
+ dialogue = []
56
+ should_skip = False
57
+
58
+ for i, content in enumerate(row):
59
+ for word in ng_words: # NG ワード含んでいたらスキップ
60
+ if word in content:
61
+ should_skip = True
62
+ break
63
+ if should_skip:
64
+ break
65
+
66
+ if i % 2 == 0:
67
+ dialogue.append(
68
+ {"speaker": 1, "content": content.replace("__BR__", "\n")}
69
+ )
70
+ else:
71
+ dialogue.append(
72
+ {"speaker": 2, "content": content.replace("__BR__", "\n")}
73
+ )
74
+
75
+ if should_skip:
76
+ continue
77
+
78
+ yield dialogue
79
+
80
+
81
+ # Load ranking data from file
82
+ def load_ranking(filepath: str, split: str) -> Iterable[dict]:
83
+ with open(os.path.join(filepath, f"{split}.tsv"), "r", encoding="utf-8") as f:
84
+ reader = csv.reader(f, delimiter="\t")
85
+
86
+ data = {
87
+ "dialogue": [],
88
+ "next": {},
89
+ "random": [],
90
+ }
91
+ dialogue_len = 0
92
+
93
+ for i, row in enumerate(reader):
94
+ if i % 10 == 0:
95
+ dialogue_len = len(row)
96
+ for j, content in enumerate(row[1:-1]): # [0] は使わない
97
+ if j % 2 == 0:
98
+ data["dialogue"].append(
99
+ {"speaker": 1, "content": content.replace("__BR__", "\n")}
100
+ )
101
+ else:
102
+ data["dialogue"].append(
103
+ {"speaker": 2, "content": content.replace("__BR__", "\n")}
104
+ )
105
+ data["next"] = {
106
+ "speaker": 1 if dialogue_len % 2 == 1 else 2,
107
+ "content": row[-1].replace("__BR__", "\n"),
108
+ }
109
+
110
+ elif i % 10 >= 1 and i % 10 <= 8:
111
+ data["random"].append(row[-1].replace("__BR__", "\n"))
112
+ elif i % 10 == 9:
113
+ data["random"].append(row[-1].replace("__BR__", "\n"))
114
+
115
+ yield data
116
+
117
+ data = {
118
+ "dialogue": [],
119
+ "next": {},
120
+ "random": [],
121
+ }
122
+ dialogue_len = 0
123
+
124
+
125
+ # Load NG words from file
126
+ def load_ng_words(filepath) -> list[str]:
127
+ data = []
128
+ with open(filepath, "r", encoding="utf-8") as f:
129
+ for line in f:
130
+ data.append(line.strip())
131
+ return data
132
+
133
+
134
+ class Open2chDataset(ds.GeneratorBasedBuilder):
135
+ OVER_SIZE_LIMIT = 6_000_000
136
+ csv.field_size_limit(OVER_SIZE_LIMIT)
137
+
138
+ VERSION = ds.Version("1.0.0")
139
+
140
+ BUILDER_CONFIGS = [
141
+ ds.BuilderConfig(
142
+ name="all-corpus",
143
+ version=VERSION,
144
+ description="All concatenated corpus data",
145
+ ),
146
+ ds.BuilderConfig(
147
+ name="livejupiter",
148
+ version=VERSION,
149
+ description="A subset of corpus data from livejupiter board",
150
+ ),
151
+ ds.BuilderConfig(
152
+ name="news4vip",
153
+ version=VERSION,
154
+ description="A subset of corpus data from news4vip board",
155
+ ),
156
+ ds.BuilderConfig(
157
+ name="newsplus",
158
+ version=VERSION,
159
+ description="A subset of corpus data from newsplus board",
160
+ ),
161
+ ds.BuilderConfig(
162
+ name="all-corpus-cleaned",
163
+ version=VERSION,
164
+ description="Cleaned version of all concatenated corpus data",
165
+ ),
166
+ ds.BuilderConfig(
167
+ name="livejupiter-cleaned",
168
+ version=VERSION,
169
+ description="Cleaned version of a subset of corpus data from livejupiter board",
170
+ ),
171
+ ds.BuilderConfig(
172
+ name="news4vip-cleaned",
173
+ version=VERSION,
174
+ description="Cleaned version of a subset of corpus data from news4vip board",
175
+ ),
176
+ ds.BuilderConfig(
177
+ name="newsplus-cleaned",
178
+ version=VERSION,
179
+ description="Cleaned version of a subset of corpus data from newsplus board",
180
+ ),
181
+ ds.BuilderConfig(
182
+ name="ranking",
183
+ version=VERSION,
184
+ description="Dataset for response ranking task",
185
+ ),
186
+ ]
187
+
188
+ DEFAULT_CONFIG_NAME = "all-corpus"
189
+
190
+ def _info(self):
191
+ if self.config.name in ["all-corpus", "all-corpus-cleaned"]:
192
+ features = ds.Features(
193
+ {
194
+ "dialogue": ds.Sequence(
195
+ {
196
+ "speaker": ds.Value("int8"), # 1 or 2
197
+ "content": ds.Value("string"),
198
+ }
199
+ ),
200
+ "board": ds.Value("string"),
201
+ }
202
+ )
203
+ elif self.config.name in [
204
+ "livejupiter",
205
+ "news4vip",
206
+ "newsplus",
207
+ "livejupiter-cleaned",
208
+ "news4vip-cleaned",
209
+ "newsplus-cleaned",
210
+ ]:
211
+ features = ds.Features(
212
+ {
213
+ "dialogue": ds.Sequence(
214
+ {
215
+ "speaker": ds.Value("int8"), # 1 or 2
216
+ "content": ds.Value("string"),
217
+ }
218
+ ),
219
+ }
220
+ )
221
+ elif self.config.name == "ranking":
222
+ features = ds.Features(
223
+ {
224
+ "dialogue": ds.Sequence(
225
+ {
226
+ "speaker": ds.Value("int8"), # 1 or 2
227
+ "content": ds.Value("string"),
228
+ }
229
+ ),
230
+ "next": { # 正しい返答
231
+ "speaker": ds.Value("int8"), # 1 or 2
232
+ "content": ds.Value("string"),
233
+ },
234
+ "random": ds.Sequence( # ランダムに選ばれた返答
235
+ ds.Value("string"),
236
+ ),
237
+ }
238
+ )
239
+ else:
240
+ raise ValueError("Invalid config name")
241
+
242
+ return ds.DatasetInfo(
243
+ description=_DESCRIPTION,
244
+ features=features,
245
+ homepage=_HOMEPAGE,
246
+ license=_LICENSE,
247
+ citation=_CITATION,
248
+ )
249
+
250
+ def _split_generators(self, dl_manager):
251
+ corpus_url = _URLS["corpus"]
252
+ ng_words_url = _URLS["ng_words"]
253
+
254
+ if self.config.name in ["all-corpus", "livejupiter", "news4vip", "newsplus"]:
255
+ data_dir = dl_manager.download_and_extract(corpus_url)
256
+
257
+ return [
258
+ ds.SplitGenerator(
259
+ name=ds.Split.TRAIN,
260
+ gen_kwargs={
261
+ "filepath": os.path.join(data_dir, "corpus"),
262
+ },
263
+ ),
264
+ ]
265
+ elif self.config.name in [
266
+ "all-corpus-cleaned",
267
+ "livejupiter-cleaned",
268
+ "news4vip-cleaned",
269
+ "newsplus-cleaned",
270
+ ]:
271
+ data_dir = dl_manager.download_and_extract(corpus_url)
272
+ ng_words_dir = dl_manager.download(ng_words_url)
273
+
274
+ return [
275
+ ds.SplitGenerator(
276
+ name=ds.Split.TRAIN,
277
+ gen_kwargs={
278
+ "filepath": os.path.join(data_dir, "corpus"),
279
+ "ng_words_path": ng_words_dir,
280
+ },
281
+ ),
282
+ ]
283
+ elif self.config.name == "ranking":
284
+ ranking_url = _URLS["ranking"]
285
+ data_dir = dl_manager.download_and_extract(ranking_url)
286
+
287
+ return [
288
+ ds.SplitGenerator(
289
+ name=ds.Split.TRAIN,
290
+ gen_kwargs={
291
+ "filepath": os.path.join(data_dir, "ranking"),
292
+ "split": "dev",
293
+ },
294
+ ),
295
+ ds.SplitGenerator(
296
+ name=ds.Split.TEST,
297
+ gen_kwargs={
298
+ "filepath": os.path.join(data_dir, "ranking"),
299
+ "split": "test",
300
+ },
301
+ ),
302
+ ]
303
+
304
+ def _generate_examples(
305
+ self,
306
+ filepath: str,
307
+ split: str = "train",
308
+ ng_words_path: str | None = None,
309
+ ):
310
+ livejupiter_path = os.path.join(filepath, "livejupiter.tsv")
311
+ news4vip_path = os.path.join(filepath, "news4vip.tsv")
312
+ newsplus_path = os.path.join(filepath, "newsplus.tsv")
313
+
314
+ ng_words = load_ng_words(ng_words_path) if ng_words_path is not None else []
315
+
316
+ if self.config.name == "all-corpus":
317
+ for i, data in enumerate(load_corpus(livejupiter_path, ng_words)):
318
+ yield f"livejupiter-{i}", {
319
+ "dialogue": data,
320
+ "board": "livejupiter",
321
+ }
322
+
323
+ for i, data in enumerate(load_corpus(news4vip_path, ng_words)):
324
+ yield f"news4vip-{i}", {
325
+ "dialogue": data,
326
+ "board": "news4vip",
327
+ }
328
+
329
+ for i, data in enumerate(load_corpus(newsplus_path, ng_words)):
330
+ yield f"newsplus-{i}", {
331
+ "dialogue": data,
332
+ "board": "newsplus",
333
+ }
334
+
335
+ elif self.config.name.startswith("livejupiter"):
336
+ for i, data in enumerate(load_corpus(livejupiter_path, ng_words)):
337
+ yield f"livejupiter-{i}", {
338
+ "dialogue": data,
339
+ }
340
+
341
+ elif self.config.name.startswith("news4vip"):
342
+ for i, data in enumerate(load_corpus(news4vip_path, ng_words)):
343
+ yield f"news4vip-{i}", {
344
+ "dialogue": data,
345
+ }
346
+
347
+ elif self.config.name.startswith("newsplus"):
348
+ for i, data in enumerate(load_corpus(newsplus_path, ng_words)):
349
+ yield f"newsplus-{i}", {
350
+ "dialogue": data,
351
+ }
352
+
353
+ elif self.config.name == "ranking":
354
+ for i, data in enumerate(load_ranking(filepath, split)):
355
+ yield f"ranking-{split}-{i}", data
356
+
357
+ else:
358
+ raise ValueError("Invalid config name")