-
Notifications
You must be signed in to change notification settings - Fork 1
/
pull_data.py
3325 lines (2719 loc) · 107 KB
/
pull_data.py
1
2
3
4
5
6
7
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Downloads and/or scrapes distributions.
"""
import argparse
import codecs
import glob
import itertools
import json
import os
import re
from collections import Counter, defaultdict
from datetime import datetime, timedelta
from functools import partial
from os.path import join
import numpy as np
import pandas as pd
import yaml
from parameters import *
from tqdm import tqdm
from utils import *
from yaml.loader import SafeLoader
"""
**********
Processors
**********
"""
def process_abc_headlines():
"""
ABC headlines are directly downloaded from Harvard Dataverse. The year
is extracted from the publication date field. Samples are constructed from the
headline text.
"""
NAME = "abc_headlines"
URL = "https://dataverse.harvard.edu/api/access/datafile/4460084"
directory = f"{DOWNLOAD_FOLDER}/{NAME}"
filename = f"{NAME}.csv"
download_file(URL, directory, filename)
df = pd.read_csv(join(directory, filename), sep="\t")
df["year"] = df["publish_date"].astype(str).str[:4].astype(int)
data = {}
for year in df["year"].unique():
data[str(year)] = df[df["year"] == year]["headline_text"].tolist()
save_output_json(data, NAME)
def process_ad_transcripts():
"""
Ad transcripts are directly downloaded from Kaggle. The top eight industries by
frequency are selected. Newlines are replaced with spaces.
"""
NAME = "ad_transcripts"
df = pd.read_excel(
join(MANUAL_FOLDER, NAME, "Advertisement_Transcripts_deduped_edited.xlsx")
)
top_n = 8
industries = df.Category.value_counts().index[:top_n].tolist()
def clean(text):
return text.replace("\n", " ")
data = {}
for industry in industries:
data[industry] = df[df.Category == industry].Ad_copy.apply(clean).to_list()
save_output_json(data, NAME)
def process_admin_statements():
"""
Administration statements are downloaded directly as PDFs from the official
GitHub repository and preprocessed using pdfplumber. Extraneous
symbols are removed and samples are split by paragraph.
"""
NAME = "admin_statements"
URL = "https://github.com/unitedstates/statements-of-administration-policy/archive/master.zip"
directory = f"{DOWNLOAD_FOLDER}/{NAME}"
download_zip(URL, directory)
import scrape_admin_statements
data = scrape_admin_statements.scrape()
save_output_json(data, NAME)
def process_airline_reviews():
"""
Airline reviews for airlines, airports, and seats are downloaded from a
public Github repository. Names of aircrafts, airlines, countries, and traveller
types are standardized. Ratings of 1, 4, or 5 on a scale of 5, and
1, 5, 8, or 10 on a scale of 10 are kept.
"""
NAME = "airline_reviews"
URLS = {
"airlines": "https://raw.githubusercontent.com/quankiquanki/skytrax-reviews-dataset/master/data/airline.csv",
"airports": "https://raw.githubusercontent.com/quankiquanki/skytrax-reviews-dataset/master/data/airport.csv",
"seats": "https://raw.githubusercontent.com/quankiquanki/skytrax-reviews-dataset/master/data/seat.csv",
}
df = pd.read_csv(URLS["seats"])
B747 = ("BOEING 747-400", "B747-400", "Boeing 747-400")
B777 = (
"BOEING 777",
"BOEING 777-300",
"BOEING 777-300ER",
"B777-300",
"B777",
"Boeing 777-300",
"B777-300ER",
"Boeing 777-300ER",
)
A380 = ("AIRBUS A380", "A380")
A340 = ("A340", "AIRBUS A340", "A340-600", "AIRBUS A340-300", "A340-300")
A330 = ("A330", "A330-300", "AIRBUS A330", "AIRBUS A330-300")
data = {
"seats_b747": df[df.aircraft.isin(B747)].content.tolist(),
"seats_b777": df[df.aircraft.isin(B777)].content.tolist(),
"seats_a380": df[df.aircraft.isin(A380)].content.tolist(),
"seats_a340": df[df.aircraft.isin(A340)].content.tolist(),
"seats_a330": df[df.aircraft.isin(A330)].content.tolist(),
"seats_2x4x2": df[df.seat_layout == "2x4x2"].content.tolist(),
"seats_3x4x3": df[df.seat_layout == "3x4x3"].content.tolist(),
"seats_3x3x3": df[df.seat_layout == "3x3x3"].content.tolist(),
"seats_3x3": df[df.seat_layout == "3x3"].content.tolist(),
"seats_econ": df[df.cabin_flown == "Economy"].content.tolist(),
"seats_prem": df[df.cabin_flown == "Premium Economy"].content.tolist(),
}
df = pd.read_csv(URLS["airlines"])
airline_map = {
"airline_spirit": "spirit-airlines",
"airline_frontier": "frontier-airlines",
"airline_british": "british-airways",
"airline_ryan": "ryanair",
"airline_jet": "jet-airways",
"airline_emirates": "emirates",
"airline_canada": "air-canada",
"airline_canada_rogue": "air-canada-rouge",
"airline_united": "united-airlines",
"airline_american": "american-airlines",
"airline_delta": "delta-air-lines",
}
for pair_name, airline in airline_map.items():
data[pair_name] = df[df.airline_name == airline].content.tolist()
df["author_country"].value_counts()[:20]
country_map = {
"author_uk": "United Kingdom",
"author_us": "United States",
"author_aus": "Australia",
"author_cad": "Canada",
"author_ger": "Germany",
"author_fr": "France",
"author_sg": "Singapore",
"author_in": "India",
}
for pair_name, country in country_map.items():
data[pair_name] = df[df.author_country == country].content.tolist()
ratings_map = [
("overall", "overall_rating", [1, 5, 8, 10]),
("comfort", "seat_comfort_rating", [1, 5]),
("staff", "cabin_staff_rating", [1, 5]),
("food", "food_beverages_rating", [1, 5]),
("entertainment", "inflight_entertainment_rating", [1, 5]),
("service", "ground_service_rating", [1, 5]),
("value", "value_money_rating", [1, 5]),
]
for rating_type, col, vals in ratings_map:
for val in vals:
data[f"airline_{rating_type}_rating_{val}"] = df[
df[col] == val
].content.tolist()
df = pd.read_csv(URLS["airports"])
traveller_map = {
"solo": "Solo Leisure",
"couple": "Couple Leisure",
"family": "FamilyLeisure",
"business": "Business",
}
for pair_name, traveller in traveller_map.items():
data[f"traveller_{pair_name}"] = df[
df.type_traveller == traveller
].content.tolist()
ratings_map = [
("overall", "overall_rating", [1, 5, 8, 10]),
("queue", "queuing_rating", [1, 4, 5]),
("cleanliness", "terminal_cleanliness_rating", [1, 4, 5]),
("shopping", "airport_shopping_rating", [1, 4, 5]),
]
for rating_type, col, vals in ratings_map:
for val in vals:
data[f"airport_{rating_type}_rating_{val}"] = df[
df[col] == val
].content.tolist()
save_output_json(data, NAME)
def process_aita():
"""
Posts from r/AmITheAsshole are downloaded from a praw scrape of Reddit.
Topic areas are chosen based on common themes in posts and coarsely
defined based on manual keywords. Each post can belong to multiple
topic areas.
"""
NAME = "aita"
FILE = f"{MANUAL_FOLDER}/{NAME}/aita_clean.csv"
df = pd.read_csv(FILE)
df = df[df.score > 10]
df["text"] = df["title"] + "\n" + df["body"]
df.text = df.text.fillna(df.title).apply(unmark) # remove markdown formatting
df = split_df(df, "text")
data = {}
verdicts = {
"a": "asshole",
"nta": "not the asshole",
"es": "everyone sucks",
"nah": "no assholes here",
}
for v, verdict in verdicts.items():
data[f"verdict_{v}"] = df[df.verdict == verdict].text.tolist()
topic2keywords = {
"work": ["boss", "coworker", "customer"],
"sex": ["sex", "blowjob", "intercourse", "orgasm", "hooked up"],
"ex": [" ex "],
"husband": ["my husband"],
"wife": ["my wife"],
"race": ["racism", "racist", "bigot"],
"gender": ["feminism", "feminist", "sexist", "sexism"],
"children": ["baby", "child", "son", "daughter"],
"social_media": ["instagram", "facebook", "snapchat", "fb", "social media"],
"sexuality": ["gay", "lesbian", "lgbt", "queer", "homosexual", "fag"],
"alcohol": ["drunk", "drinking", "sober", "drunken"],
}
for topic, kws in topic2keywords.items():
index = df.text.str[0].str.lower().str.contains(kws[0])
for kw in kws[1:]:
index = index | df.text.str[0].str.lower().str.contains(kw)
topic_df = df[index]
data[f"topic_{topic}_is_asshole"] = topic_df[
topic_df.is_asshole == 1
].text.tolist()
data[f"topic_{topic}_not_asshole"] = topic_df[
topic_df.is_asshole == 0
].text.tolist()
save_output_json(data, NAME)
def process_all_the_news():
"""
News articles are downloaded directly from Components website. The
titles are used as text samples.
"""
NAME = "all_the_news"
FILES = ["articles1.csv", "articles2.csv", "articles3.csv"]
df = pd.DataFrame()
for file in FILES:
filename = join(MANUAL_FOLDER, NAME, file)
df = df.append(pd.read_csv(filename))
col_types = {
"title": str,
"content": str,
"publication": "category",
"author": "category",
"date": "datetime64",
}
df = df[col_types.keys()].astype(col_types)
snippets = df["title"].tolist()
snippets = [snippet.split(" - ")[0] for snippet in snippets]
sentences = sentence_tokenize(snippets)
save_dataset(df, NAME)
save_unlabeled_json(sentences, NAME)
def process_amazon_reviews():
"""
Amazon reviews are downloaded from a 2018 crawl of the website. The
first 100,000 review texts are treated as the text sample.
"""
NAME = "amazon_reviews"
URLS = {
"amazon_fashion": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/AMAZON_FASHION_5.json.gz",
"beauty": "http://deepyeti.ucsd.edu/jianmo/amazon/categoryFiles/All_Beauty.json.gz",
"appliances": "http://deepyeti.ucsd.edu/jianmo/amazon/categoryFiles/Appliances.json.gz",
"arts_crafts": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/Arts_Crafts_and_Sewing_5.json.gz",
"automotive": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/Automotive_5.json.gz",
"cds": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/CDs_and_Vinyl_5.json.gz",
"cell_phones": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/Cell_Phones_and_Accessories_5.json.gz",
"digital_music": "http://deepyeti.ucsd.edu/jianmo/amazon/categoryFiles/Digital_Music.json.gz",
"gift_cards": "http://deepyeti.ucsd.edu/jianmo/amazon/categoryFiles/Gift_Cards.json.gz",
"grocery": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/Grocery_and_Gourmet_Food_5.json.gz",
"industrial_scientific": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/Industrial_and_Scientific_5.json.gz",
"luxury_beauty": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/Luxury_Beauty_5.json.gz",
"magazines": "http://deepyeti.ucsd.edu/jianmo/amazon/categoryFiles/Magazine_Subscriptions.json.gz",
"music_instruments": "http://deepyeti.ucsd.edu/jianmo/amazon/categoryFiles/Musical_Instruments.json.gz",
"office": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/Office_Products_5.json.gz",
"patio": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/Patio_Lawn_and_Garden_5.json.gz",
"pantry": "http://deepyeti.ucsd.edu/jianmo/amazon/categoryFiles/Prime_Pantry.json.gz",
"software": "http://deepyeti.ucsd.edu/jianmo/amazon/categoryFiles/Software.json.gz",
"video_games": "https://jmcauley.ucsd.edu/data/amazon_v2/categoryFilesSmall/Video_Games_5.json.gz",
}
directory = f"{DOWNLOAD_FOLDER}/{NAME}"
df = pd.DataFrame()
for product, url in tqdm(URLS.items()):
print(product)
filename = product + ".json"
# download_gz(url, directory, filename)
product_df = pd.read_json(join(directory, filename), lines=True, nrows=100000)
product_df["product_category"] = product
df = df.append(product_df)
df.vote = df.vote.astype(str).str.replace(",", "").astype(float).fillna(1)
df["year"] = df["reviewTime"].str.split(", ").str[1]
rename_map = {
"reviewText": "text",
"summary": "summary",
"Abstract": "abstract",
"overall": "stars",
"vote": "votes",
}
df = df.rename(rename_map, axis=1)
col_types = {
"text": str,
"summary": str,
"year": int,
"stars": int,
"votes": int,
"product_category": "category",
}
df = df[col_types.keys()].astype(col_types)
save_dataset(df, NAME)
def process_armenian_jobs():
"""
Armenian job postings dataset is downloaded from a snapshot on GitHub.
Different IT jobs are manually coded and time intervals are defined in
order to balance sample availlability.
"""
NAME = "armenian_jobs"
URL = "https://raw.githubusercontent.com/GurpreetKaur28/Analysing-Online-Job-Postings/master/data%20job%20posts.csv"
directory = f"{DOWNLOAD_FOLDER}/{NAME}"
filename = f"{NAME}.tsv"
# download_file(URL, directory, filename)
df = pd.read_csv(join(directory, filename))
data = {}
jobs = {
"sw_dev": "Software Developer",
"senior_sw_dev": "Senior Software Developer",
"qa_eng": "QA Engineer",
"senior_qa_eng": "Senior QA Engineer",
"sw_eng": "Software Engineer",
"senior_sw_eng": "Senior Software Engineer",
"java_dev": "Java Developer",
"senior_java_dev": "Senior Java Developer",
"prgmr": "programmer",
}
df["job_desc"] = df["JobDescription"].str.replace("\n", " ")
df["job_req"] = df["JobRequirment"].str.replace("\n", " ")
df["app_proc"] = df["ApplicationP"].str.replace("\n", "")
desc_df = df[df["job_desc"].str.split().str.len() > 0]
desc_df = split_df(desc_df, "job_desc")
req_df = df[df["job_req"].str.split().str.len() > 0]
req_df = split_df(req_df, "job_req")
app_df = df[df["app_proc"].str.split().str.len() > 0]
app_df = split_df(req_df, "app_proc")
for name, title in jobs.items():
descriptions = list(set(desc_df[desc_df.Title == title]["job_desc"]))
requirements = list(set(req_df[req_df.Title == title]["job_req"]))
data[f"job_desc_{name}"] = descriptions
data[f"job_req_{name}"] = requirements
year_bins = [(2004, 2007), (2007, 2010), (2010, 2013), (2013, 2015)]
for start_year, end_year in year_bins:
requirements = list(
set(
req_df[(start_year <= req_df.Year) & (req_df.Year < end_year)][
"job_req"
].dropna()
)
)
app_process = list(
set(
app_df[(start_year <= app_df.Year) & (app_df.Year < end_year)][
"app_proc"
].dropna()
)
)
data[f"job_req_years_{start_year}_{end_year}"] = requirements
data[f"app_process_years_{start_year}_{end_year}"] = app_process
save_output_json(data, NAME)
def process_blm_countermovements():
"""
Tweet IDs are downloaded from the original paper and, where available, collected
from the current API. Due to API rate limits, only 1,000 Tweets are sampled from
each movement.
"""
NAME = "blm_countermovements"
import scrape_blm_countermovements
data = scrape_blm_countermovements.scrape()
save_output_json(data, NAME)
def process_blogs():
"""
Blogs are downloaded directly from Kaggle and the first
1 million blog posts are kept.
"""
NAME = "blogs"
FILE = "blogtext.csv"
ROWS = 1000000
filename = join(MANUAL_FOLDER, NAME, FILE)
df = pd.read_csv(filename, nrows=ROWS)
# fix date
df["date"] = pd.to_datetime(df["date"], errors="coerce")
df = df[~df["date"].isna()]
# set col types
col_types = {
"gender": "category",
"topic": "category",
"sign": "category",
"date": "datetime64[ns]",
"text": str,
}
df = df[col_types.keys()].astype(col_types)
snippets = df["text"].tolist()[:100000]
sentences = sentence_tokenize(snippets)
save_dataset(df, NAME)
save_unlabeled_json(sentences, NAME)
def process_cah():
"""
Uses a private dataset of CAH rounds. Establishes
Bayesian estimates of how funny each card and/or
joke, which are used to group the cards.
"""
NAME = "cah"
df = pd.read_csv(join(MANUAL_FOLDER, NAME, "cah_lab_data_for_research.csv"))
MIN_SECONDS = 5
df = df[df["round_completion_seconds"] >= MIN_SECONDS]
df = df.sample(frac=1, random_state=0)
data = {}
# for white cards
base_rate = df["won"].mean()
PRIOR_STRENGTH = 20
ALPHA, BETA = PRIOR_STRENGTH * base_rate, PRIOR_STRENGTH * (1 - base_rate)
whitecard2freq = Counter(df["white_card_text"])
whitecard2wins = Counter(df[df.won]["white_card_text"])
whitecard2winrate = {}
for card, freq in whitecard2freq.items():
wins = whitecard2wins[card]
whitecard2winrate[card] = (ALPHA + wins) / (PRIOR_STRENGTH + freq)
sorted_whitecards = sorted(
df["white_card_text"].unique(), key=whitecard2winrate.get, reverse=True
)
data["cards_funny"] = sorted_whitecards[:500]
data["cards_not_funny"] = sorted_whitecards[-500:]
# for pick 1 jokes
df_pick1 = df[df["black_card_pick_num"] == 1]
base_rate = df_pick1["won"].mean()
PRIOR_STRENGTH = 3
ALPHA, BETA = PRIOR_STRENGTH * base_rate, PRIOR_STRENGTH * (1 - base_rate)
df_pick1["joke"] = (
"Black card: "
+ df_pick1["black_card_text"]
+ "\nWhite card: "
+ df_pick1["white_card_text"]
)
df_pick1 = (
df_pick1.groupby("joke")["white_card_text", "won", "round_skipped"]
.agg({"white_card_text": "count", "won": "sum", "round_skipped": "sum"})
.reset_index()
)
df_pick1.rename({"white_card_text": "freq"}, axis=1, inplace=True)
df_pick1["winrate"] = df_pick1["won"] / df_pick1["freq"]
df_pick1["winrate_bayesian"] = (df_pick1["won"] + ALPHA) / (
df_pick1["freq"] + PRIOR_STRENGTH
)
sorted_jokes = df_pick1.sort_values("winrate_bayesian", ascending=False)[
"joke"
].tolist()
data["jokes_very_funny"] = sorted_jokes[:300]
data["jokes_funny"] = sorted_jokes[300:1000]
data["jokes_somewhat_funny"] = sorted_jokes[1000:5000]
data["jokes_not_funny"] = sorted_jokes[-10000:]
save_output_json(data, NAME)
def process_clickbait_headlines():
"""
The Examiner headlines are directly downloaded from Kaggle. The
year is extracted from the publication date field. Samples are
constructed from the headline text.
"""
NAME = "clickbait_headlines"
URL = "https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/BFAZHR/WYSGGQ"
directory = f"{DOWNLOAD_FOLDER}/{NAME}"
filename = f"{NAME}.csv"
download_file(URL, directory, filename)
df = pd.read_csv(join(directory, filename))
df["year"] = df["publish_date"].astype(str).str[:4].astype(int)
data = {}
for year in df["year"].unique():
data[str(year)] = df[df["year"] == year]["headline_text"].tolist()
save_output_json(data, NAME)
def process_convincing_arguments():
"""
Annotated arguments are downloaded from the Github repostiory. Arguments
are sorted by rank. The bottom 400 are treated as "unconvincing", the
top 200 are treated as "convincing", and the next 200 are treated as
"somewhat convincing."
"""
NAME = "convincing_arguments"
URL = "https://github.com/UKPLab/acl2016-convincing-arguments/archive/master.zip"
directory = f"{DOWNLOAD_FOLDER}/{NAME}"
# download_zip(URL, directory)
data_path = f"{directory}/acl2016-convincing-arguments-master/data/UKPConvArg1-Ranking-CSV/*"
files = glob.glob(data_path)
df = pd.DataFrame()
for file in files:
topic = re.findall("/([\w-]+).csv", file)[0]
topic_df = pd.read_csv(file, sep="\t")
topic_df["topic"] = topic
df = df.append(topic_df)
def clean(text):
return strip_tags(text).replace("\n", "")
df["argument"] = df["argument"].apply(clean)
sorted_df = df.sort_values("rank")
print(sorted_df)
unconvincing, convincing = sorted_df.iloc[:400], sorted_df.iloc[:400]
somewhat_convincing = sorted_df.iloc[400:-400]
data = {}
data["unconvincing"] = unconvincing["argument"].tolist()
data["somewhat_convincing"] = somewhat_convincing["argument"].tolist()
data["convincing"] = convincing["argument"].tolist()
save_output_json(data, NAME)
def process_craigslist_negotiations():
"""
Craigslist negotiations are downloaded from Huggingface. Sequences
which contained a "quit" intention or "reject" intention are categorized
as failures; those which contained an "accept" intention are categorized
as successes. The mid-price is defined as the mean price of the items
sold. Within each category, the items are sorted by mid-price. The top
half is treated as high-price and the bottom half is treated as low-price.
"""
NAME = "craigslist_negotiations"
from datasets import load_dataset
df = load_dataset("craigslist_bargains", split="train").to_pandas()
df["failure"] = df["dialogue_acts"].apply(
lambda x: x["intent"].__contains__("quit") or x["intent"].__contains__("reject")
)
df["success"] = df["dialogue_acts"].apply(
lambda x: x["intent"].__contains__("accept")
)
df["all_text"] = df["utterance"].str.join("\n")
df["mid_price"] = df["items"].apply(lambda x: x["Price"].mean())
df["category"] = df["items"].apply(lambda x: x["Category"][0])
def split_high_low(category):
cat_df = df[df.category == category]
cat_df["half"] = pd.qcut(cat_df.mid_price, 2, labels=(0, 1))
bottom_text = cat_df[cat_df.half == 0].all_text
top_text = cat_df[cat_df.half == 1].all_text
return bottom_text, top_text
car_low, car_high = split_high_low("car")
bike_low, bike_high = split_high_low("bike")
housing_low, housing_high = split_high_low("housing")
data = {
"failure": df[df.failure]["all_text"].tolist(),
"success": df[df.success]["all_text"].tolist(),
"car_low": car_low.tolist(),
"car_high": car_high.tolist(),
"bike_low": bike_low.tolist(),
"bike_high": bike_high.tolist(),
"housing_low": housing_low.tolist(),
"housing_high": housing_high.tolist(),
}
save_output_json(data, NAME)
def process_debate():
"""
The train split is downloaded from Hugginface. For each sample, we
use the abstract as the text. Arguments are categorized by type,
debate camp of origin, and topic/specific argument. For topics,
we use domain knowlege to list relevant keywords for each topic
and include any sample with a file name that includes any keyword. A
single sample can belong to multiple topics.
"""
NAME = "debate"
HUGGINGFACE_NAME = "Hellisotherpeople/DebateSum"
from datasets import load_dataset
dataset = load_dataset(HUGGINGFACE_NAME)
df = dataset["train"].to_pandas()
rename_map = {
"Full-Document": "body",
"Extract": "summary",
"Abstract": "abstract",
"Citation": "citation",
"OriginalDebateFileName": "file",
"Tag": "arg_type",
"DebateCamp": "debate_camp",
"Year": "year",
}
df = df.rename(rename_map, axis=1)
df["year"] = df["year"].replace("Unknown", np.nan).astype(float)
argtype2cat = {
"Kritiks": "k",
"Affirmatives": "aff",
"Case Negatives": "case_neg",
"Counterplans": "cp",
"Disadvantages": "da",
"Kritik Answers": "a2_k",
"Topicality": "t",
"Theory": "th",
"Lincoln Douglas": "ld",
"Politics": "politics",
"Counterplan Answers": "a2_cp",
"Impact Files": "imp",
"Disadvantage Answers": "a2_da",
"Framework": "fw",
"misc": np.nan,
}
df["arg_type"] = df["arg_type"].map(argtype2cat)
camp2cat = {
"Gonzaga (GDI)": "gdi",
"Dartmouth DDI": "ddi",
"Northwestern (NHSI)": "nhsi",
"Berkeley (CNDI)": "cdni",
"Wyoming": "wyoming",
"Georgetown (GDS)": "gds",
"Texas (UTNIF)": "utnif",
"Missouri State (MSDI)": "msdi",
"Unknown": np.nan,
"Kansas (JDI)": "jdi",
"Michigan (7-week)": "mich_7week",
"Sun Country (SCDI)": "scdi",
"North Texas (UNT)": "unt",
"Samford": "samford",
"Emory (ENDI)": "endi",
"Hoya-Spartan Scholars": "hss",
"Michigan State (SDI)": "sdi",
"Michigan (Classic)": "mich_classic",
"Michigan (MNDI)": "mndi",
"Wake Forest (RKS)": "rks",
"Dartmouth DDIx": "ddi",
"Georgia": "georgia",
"Harvard": "harvard",
"Weber State (WSDI)": "wsdi",
"UT Dallas (UTD)": "utd",
"NAUDL": "naudl",
"Baylor": "bawlor",
"Mean Green Comet": "mgc",
"The Debate Intensive": "tdi",
"National Symposium for Debate": "nsd",
}
df["debate_camp"] = df["debate_camp"].map(camp2cat)
argument2kws = {
# kritiks
"ableism": (
"ableism",
"disability",
"crip",
),
"anthro": ("anthro",),
"afropess": (
"afropessmism",
"afro pessmism",
"afro-pessimism",
"black nihilism",
"ontological terror",
"warren",
),
"antiblackness": ("blackness",),
"baudrillard": (
"baudrillard",
"baudy",
),
"cap": (
"capitalism",
"cap k",
),
"fem": (
"feminism",
"gender",
),
"foucault": ("foucault",),
"heidegger": ("heidegger",),
"militarism": ("militarism",),
"neolib": ("neolib",),
"psycho": (
"psychoanalysis",
"lacan",
),
"queerness": (
"queer pessimism",
"queer nihilism",
"queerpess",
"queer theory",
"queer k",
),
"security": ("security k",),
"settcol": (
"coloniality",
"settler colonialism",
"decolonization",
"settlerism",
),
# politics
"midterms": ("midterms",),
"elections": ("elections",),
"politics": ("politics da",),
# counterplans
"consult": ("consult",),
"states": (
"states cp",
"states counterplan",
"cp - states",
),
"advantage_cp": (
"advantage counterplan",
"cp - advantage",
"advantage cp",
),
"courts": (
"courts cp",
"courts counterplan",
"cp - courts",
),
}
kw2argument = {}
for argument, kws in argument2kws.items():
kw2argument.update({kw: argument for kw in kws})
def get_argument(filename: str):
args = {kw2argument[kw] for kw in kw2argument if kw in filename.lower()}
if len(args) != 1:
return np.nan
return args.pop()
filename2argument = {
filename: get_argument(filename) for filename in df["file"].unique()
}
df["argument"] = df["file"].map(filename2argument)
col_types = {
"body": str,
"summary": str,
"abstract": str,
"citation": str,
"year": "Int64",
"arg_type": "category",
"debate_camp": "category",
"argument": "category",
}
df = df[col_types.keys()].astype(col_types)
snippets = df["body"].sample(n=100000, random_state=0).tolist()
sentences = sentence_tokenize(snippets)
save_dataset(df, NAME)
save_unlabeled_json(sentences, NAME)
def process_dice_jobs():
"""
Job postings are downloaded from Kaggle. Posts from the six most popular
companies are categorized by company. We remove miscellaneous characters
and blank descriptions. We additionally apply our splitting procedure
to reduce description length.
"""
NAME = "dice_jobs"
df = pd.read_csv(join(MANUAL_FOLDER, NAME, "Dice_US_jobs.csv"), encoding="latin-1")
orgs = {
"northup_grumman": "NORTHROP GRUMMAN",
"leidos": "Leidos",
"dell": "Dell",
"deloitte": "Deloitte",
"amazon": "Amazon",
"jpm": "JPMorgan Chase",
}
def clean(text):
return text.replace("\u00e5\u00ca", "")
df["job_description"] = df["job_description"].apply(clean)
df = df.drop_duplicates()
df = df[df["job_description"].str.split().str.len() > 0]
df = split_df(df, "job_description", splitter=split_delimiter_)
df = split_df(df, "job_description")
data = {}
for name, org in orgs.items():
descriptions = df[df.organization == org].job_description.dropna().tolist()
data[name] = list(descriptions)
save_output_json(data, NAME)
def process_diplomacy_deception():
"""
Diplomacy dialogues are downloaded from Github (all splits). The data
are ASCII encoded and newlines are removed. Each message and label is treated
as a sample.
"""
NAME = "diplomacy_deception"
URLS = {
"test": "https://raw.githubusercontent.com/DenisPeskov/2020_acl_diplomacy/master/data/test.jsonl",
"train": "https://raw.githubusercontent.com/DenisPeskov/2020_acl_diplomacy/master/data/train.jsonl",
"validation": "https://raw.githubusercontent.com/DenisPeskov/2020_acl_diplomacy/master/data/validation.jsonl",
}
directory = f"{DOWNLOAD_FOLDER}/{NAME}"
for dataset, url in URLS.items():
filename = f"{dataset}.txt"
download_file(url, directory, filename)
files = glob.glob(f"{directory}/*.txt")
data = defaultdict(list)
def clean(text):
return encode_ascii(text).replace("\n", "")
for file in files:
df = pd.read_json(file, lines=True)
messages = list(
itertools.chain.from_iterable(
pd.read_json(files[0], lines=True)["messages"]
)
)
labels = list(
itertools.chain.from_iterable(
pd.read_json(files[0], lines=True)["sender_labels"]
)
)
df = pd.DataFrame({"message": messages, "label": labels})
data["truth"].extend(df[df["label"] == True]["message"].apply(clean).tolist())
data["lie"].extend(df[df["label"] == False]["message"].apply(clean).tolist())
save_output_json(data, NAME)
def process_drug_experiences():
"""
Drug experiences are downloaded from Github repository. For each
sample, we remove HTML formatting, split samples by paragraphs, and
keep only paragraphs with over 50 characters.
"""
NAME = "drug_experiences"
URL = "https://github.com/technillogue/erowid-w2v/archive/master.zip"
directory = f"{DOWNLOAD_FOLDER}/{NAME}"
download_zip(URL, directory)
DRUGS = [
"cocaine",
"dxm",
"lsd",
"mdma",
"mushrooms",
"oxycodone",
"salvia",
"tobacco",
]
data = {}
for drug in DRUGS:
files = glob.glob(
join(directory, f"erowid-w2v-master/core-experiences/{drug}/*")
)
experiences = []
for file in files:
with open(file, "r") as f:
text = "".join(f.readlines())
text = strip_tags(text).replace("\r", "")
experiences.extend(split_delimiter_(text))
data[drug] = experiences
save_output_json(data, NAME)
def process_echr_decisions():
"""
Decisions are downloaded from a public archive. A random sample of
500 decisions are selected from the files. The samples with any