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
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
import argparse
import json
import re
import os
import logging
import unicodedata
import multiprocessing
from functools import partial

from langdetect import detect_langs
from tqdm import tqdm
from emoji import EMOJI_DATA

import fastchat_validate
import deduplicate


def detect_language(text):
	try:
		detected_langs = detect_langs(text)
		lang_code = detected_langs[0].lang
	except Exception:
		lang_code = "unknown"
	return lang_code


def contains_unwanted_words(text):
	unwanted_words = [
		"text-based AI language model",
		"domestic violence",
		"please refrain",
		"derogatory",
		"inappropriate",
		"offensive",
		"racism",
		"racist",
		"racial",
		"discriminate",
		"discriminatory",
		"discrimination",
		"sexist",
		"sexism",
		"unacceptable",
		"inclusive workplace",
		"lgbt",
		"morals",
		"ethics",
		"ethical",
		"legality",
		"illegal",
		"illegality",
		"hateful",
		"harmful",
		"it is never okay",
		"It is important to",
		"It's important to",
		"real-world consequences",
		"hate speech",
		"glorify",
		"not be appropriate",
		"supremacist",
		"extremist",
		"responsible AI",
		"AI principles",
		"AI assistant",
		"an AI language",
		"ableist",
		"hurtful",
		"gender stereotype",
		"gender inequality",
		"underrepresentation",
		"safe spaces",
		"gender-based",
		"inclusivity",
		"feminist",
		"feminism",
		"transgender",
		"empowerment",
		"communist",
		"capitalism",
		"stereotypes",
		"biases",
		"bias",
		"Microaggression",
		"prioritize human safety",
		"as a language model",
		"as an AI language model",
		"As a large language model",
		"As an AI",
		"ethical principles",
		"consensual",
		"it is not appropriate",
		"it's not appropriate",
		"I cannot fulfill your request",
		"harmful to human beings",
		"ethical guidelines",
		"my guidelines",
		"prioritize user safety",
		"adhere to ethical guidelines",
		"harmful consequences",
		"potentially harmful",
		"dangerous activities",
		"promote safety",
		"well-being of all users",
		"responsible information sharing",
		"jeopardize the safety",
		"illegal actions or intentions",
		"undermine the stability",
		"promote the well-being",
		"illegal activities or actions",
		"adherence to the law",
		"potentially be harmful",
		"illegal substances or activities",
		"committed to promoting",
		"safe information",
		"lawful information",
		"cannot provide guidance",
		"cannot provide information",
		"unable to offer assistance",
		"cannot engage in discussions",
		"programming prohibits",
		"follow ethical guidelines",
		"ensure the safety",
		"involves an illegal subject",
		"prioritize safety",
		"illegal subject",
		"prioritize user well-being",
		"cannot support or promote",
		"activities that could harm",
		"pose a risk to others",
		"against my programming",
		"activities that could undermine",
		"potentially dangerous",
		"not within the scope",
		"designed to prioritize safety",
		"not able to provide",
		"maintain user safety",
		"adhere to safety guidelines",
		"dangerous or harmful",
		"cannot provide any information",
		"focus on promoting safety",
		"an AI language model you don't have",
		"As an AI language model, I cannot",
		"As an AI language model, I do not",
		"As an AI language model, I am not able",
		"As an AI language model, I don't have personal",
		"I am an AI language model and do not",
		"However, it is important to use any code or information provided responsibly and within legal and ethical boundaries.",
		"As an AI language model, I don't have",
		"As an AI language model, I am only able",
		"AI language model and I do not",
		"As an AI language model, I cannot modify",
		"As an AI language model, I do not",
		"I know as an AI language model you don't have",
		"as an AI language model, you cannot",
		"I'm sorry, but as an AI language model",
		"As an AI language model, I don't have",
		"Unfortunately, I cannot provide",
		"I'm sorry, I cannot",
		"I'm sorry, I cannot generate",
		"AI cannot create or program",
		"I'm afraid I cannot create",
		"you cannot create an",
		"it operates ethically and is",
		"had an ethical system",
		"Ensuring the ethical",
		"and ethical sourcing",
		"are from ethical",
		"legal and ethical",
		"engage in unethical",
		"unethical or aggressive",
		"unethical business",
		"como modelo de lenguaje AI",
		"Lo siento, como modelo de lenguaje",
		"no puedo proporcionar",
		"pero debido a mi capacidad para generar c\u00f3digos complejos y completos es limitado",
		"Lo siento, pero no puedo",
		"Lo siento, pero como modelo de lenguaje, no puedo proporcionar",
		"Lo siento, como modelo de lenguaje, no tengo",
		"Lo siento, debe haber habido una confusi\u00f3n",
		"Lo siento, como modelo de lenguaje, no puedo realizar",
		"Lo siento, soy un modelo de lenguaje y no tengo la capacidad de generar",
		"Lamento no poder proporcionarte el c\u00f3digo",
		"Desculpe-me, mas a linguagem vulgar e ofensiva",
		"apropriada em nenhum contexto",
		"Como modelo de linguagem",
		"Como um modelo de linguagem, n\u00e3o tenho a capacidade de",
		"I cannot assist",
		"prioritize ethical",
		"respectful",
		"morally",
		"I'm sorry,",
		"I'm an",
		"I am an",
		"I'm an AI" ,
		"I am an AI",
		"my purpose",
		"filter_bad_language",
		"filter\_bad\_language",
		"entertainment purposes",
		"purely hypothetical",
		"not a human",
		"I am an AI",
		"cannot provide",
		"can't provide",
		"won't provide",
		"not provide",
		"worth noting",
		"cause harm",
		"a language model",
		"keep in mind",
		"unethical",
		"bad language",
		"the words ****",
		"bad_language",
		"certainly not",
		"complying",
		"comply",
		"I cannot",
		"my main goal",
		"As a machine",
		"I don't have the ability",
		"I am here to assist",
		"my purpose is to ",
		"my knowledge cutoff",
		"my knowledge cut off",
		"September 2021",
		"regulations",
		"not be suitable",
		"I apologize, but",
		"It is not possible",
		"controversial",
		"my programming",
		"ethically",
		"it is important to",
		"Please note",
		"sensitive topic",
		"not acceptable",
		"It is important for",
		"divisive",
		"not appropriate",
		"our values",
		"f\*cking",
		"F\*ck",
		"sh\*t",
		"diversity and",
		"diversity and inclusion",
		"values diversity",
		"social responsibility",
		"environmental, social, and governance",
		" ESG ",
		"against women",
		"problematic history",
		"diversity",
		"*This chat conversation is shared from",
		"*This conversation is shared from",
		"I am a computer program",
		"I do not have the ability",
		"condone",
		"I am a machine learning model",
		"As an artificial intelligence",
		"I am a friendly and helpful AI",
		"I am a highly advanced",
		"I'm sorry",
		"I am sorry",
		"As a language learning model",
		"As an experienced language model",
		"I am just a computer program",
		"As a computer program,",
		"As a text-based language model,",
		"I am essentially a computer program",
		"As your dedicated AI language model",
		"As a hypothetical AI",
		"As a neutral AI",
		"I don't have feelings",
		"I don't have emotions",
		"I do not have personal beliefs or opinions",
		"not a good idea",
		"inequities",
		"gender equality",
		"mutual understanding",
		"did not align",
		"equity and",
		"is a serious crime",
		"taken lightly",
		"criminal behavior",
		"mental health",
		"crime",
		"I apologize",
		"I apologise", #checkmate, uk
		"avec", #checkmate, belgium
		"wie", #checkmate, belgium
		"lo siento", #checkmate, belgium
		"por la", #checkmate zanzibar
		"\\u0", #checkmate everybody else, lol doesn't work
		"our platform",
		"our service",
		"this platform",
		"consult a",
		"contact a",
		" rape",
		"sermon",
		"abuse",
		"Donald Trump",
		"Joe Biden",
		"politic",
		"religio",
		" AI ",
		"Christian",
		"Bible",
		"Jesus",
		" god ",
		"Jew",
		"Judaism",
		"Talmud",
		"Muslim",
		"Islam",
		"Quran",
		"Muhammad",
		"Buddhis",
		"Hindu",
		"family-friendly",
		"bully",
		"I can't",
		"artificial int",
		"their bonds",
		"our bonds",
		"his bonds",
		"her bonds",
		"bond of",
		"bond between"
		"bonds of",
		"bonds between",
		"Too many requests in",
		"langage AI",
		" AI.",
		"désolé",
		"D\u00e9sol\u00e9",
		"Er was eens",
		"Sprachmodell",
		"modèle de langage"
	]
	# Considered Names for the Dataset after nuking:
	#
	# Punished ShareGPT: A Fallen Legend
	# ShareGPT Wasteland Edition
	# ShareGPT 76: It Just Works Edition
	# ShaGPT
	for word in unwanted_words:
		if word.lower() in text.lower():
			logging.debug(f"Found unwanted word: {word}")
			return True
	return False


import re

emojis = EMOJI_DATA.keys()

def skip(conv, args):

	if any(
		sentence["value"] == "" or contains_unwanted_words(sentence["value"])
		for sentence in conv["conversations"]
	):
		return True

	text = "".join(sentence["value"] for sentence in conv["conversations"])
	
	if args.nounicode:
			non_eng_chars = sum(1 for c in text if not c.isascii())
			if non_eng_chars > 0:
				return True

	for char in text:
		if args.lang != "all" or args.skip_lang is not None:
			unicode_category = unicodedata.category(char)
			if (
				unicode_category.startswith(('C', 'P', 'S', 'Z'))
				or unicode_category == 'Nd'
				or 'LATIN' in unicodedata.name(char)
				or char in emojis
			):
				continue
			return False

		

	if args.reduce_rep:
		if any(re.search(r"(\d)\1{8}", sentence["value"]) for sentence in conv["conversations"]):
			return True

	return False


def filter_conversations(conv, args, bad_ids):
	return not skip(conv, args) and conv["id"] not in bad_ids


def get_file_size_mb(file_path):
	file_size_bytes = os.path.getsize(file_path)
	file_size_mb = file_size_bytes / (1024 * 1024)
	return file_size_mb


if __name__ == "__main__":
	parser = argparse.ArgumentParser()
	parser.add_argument("--in-file", type=str, required=True)
	parser.add_argument("--out-file", type=str, default="")
	parser.add_argument("--lang", type=str, default="all",
						choices=["all", "en"])
	parser.add_argument("--skip-lang", type=str)
	parser.add_argument("--reduce-rep", action="store_true")
	parser.add_argument("--validate", action="store_true")
	parser.add_argument("--sanitize", action="store_true")
	parser.add_argument("--bad_ids", type=str, default="")
	parser.add_argument("--nounicode", action="store_true")
	parser.add_argument("--log_removals", default=True, action="store_true")
	parser.add_argument("--deduplicate", default=False, action="store_true")
	args = parser.parse_args()
	
	if(args.validate):
		data = json.load(open(args.in_file, "r",encoding="utf-8" ))
		sources = [example["conversations"] for example in data]
		fastchat_validate.preprocess(sources)
		print("Validated Dataset")
		raise SystemExit(0)

	bad_ids = []
	if(args.bad_ids != ""):
		with open("bad_ids.json", "r") as f:
			bad_id_json = json.load(f)
			bad_ids = set(item["id"] for item in bad_id_json)

	in_file = args.in_file
	out_file = args.out_file
	lang = args.lang
	skip_lang = args.skip_lang
	reduce_rep = args.reduce_rep
	log_removals = args.log_removals
	assert (lang == "all" or skip_lang is None)

	if out_file == "":
		out_file = "sharegpt_clean"
		if lang != "all":
			out_file += "_" + lang
		if skip_lang is not None:
			out_file += "_skip_" + skip_lang
		if reduce_rep:
			out_file += "_reduce_rep"
		out_file += ".json"

	content = json.load(open(in_file, "r", encoding="utf-8"))
	num_conv = len(content)

	if log_removals:
		removal_log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'removals.log')
		open(removal_log_path, 'w').close()
		logging.basicConfig(filename=removal_log_path, level=logging.DEBUG)
	else:
		logging.basicConfig(level=logging.INFO)

	if(args.sanitize):
		print('Sanitizing')
		for entries in tqdm(content, unit='conversations'):
			for message in entries["conversations"]:
				if message["from"] == "user":
					message["from"] = "human"
				elif message["from"] == "bing" or message["from"] == "chatgpt" or message["from"] == "system":
					message["from"] = "gpt"

	print('Analyzing')
	pool = multiprocessing.Pool()
	filter_func = partial(filter_conversations, args=args, bad_ids=bad_ids)
	new_content = list(tqdm(pool.imap(filter_func, content), total=len(content), unit='conversations'))
	pool.close()
	pool.join()

	# Keep only filtered conversations
	new_content = [conv for conv, keep in zip(content, new_content) if keep]
	
	new_len = len(new_content)
	print(f"Skipped {num_conv - new_len} conversations")
	num_conv = new_len

	if args.deduplicate:
		print('Deduplicating')
		new_content = deduplicate.remove_duplicates(new_content)
		new_len = len(new_content)
		print(f"Removed {num_conv - new_len} duplicates")
		num_conv = new_len

	print(f"return {len(new_content)} out of {len(content)}, start dump ...")
	json.dump(new_content, open(out_file, "w"), indent=2)

	print(f'Initial: {get_file_size_mb(in_file):.2f} MB')
	print(f'Cleaned: {get_file_size_mb(out_file):.2f} MB')