File size: 5,862 Bytes
18d335b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da21b0d
 
18d335b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cf1cf5
18d335b
 
 
 
 
 
 
 
 
da21b0d
18d335b
2cf1cf5
18d335b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cf1cf5
 
18d335b
 
 
 
 
 
 
 
 
 
 
 
 
 
2cf1cf5
 
 
 
 
 
 
 
 
 
 
18d335b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da21b0d
 
131c65a
18d335b
 
da21b0d
2cf1cf5
 
 
 
18d335b
 
 
 
 
 
 
 
2cf1cf5
18d335b
da21b0d
 
18d335b
 
da21b0d
 
 
131c65a
 
18d335b
2cf1cf5
 
 
18d335b
2cf1cf5
18d335b
2cf1cf5
 
 
 
18d335b
2cf1cf5
 
 
 
18d335b
2cf1cf5
131c65a
 
 
 
 
 
18d335b
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
# ---
# jupyter:
#   jupytext:
#     cell_metadata_filter: -all
#     custom_cell_magics: kql
#     text_representation:
#       extension: .py
#       format_name: percent
#       format_version: '1.3'
#       jupytext_version: 1.11.2
#   kernelspec:
#     display_name: arxiv-classifier-next
#     language: python
#     name: python3
# ---
# %% [markdown]
# Script for converting all 2023 corpus (with full text) to json format.

# %%
# 
# parse arguments
# 
from argparse import ArgumentParser
parser = ArgumentParser()
# parser.add_argument("--dataset", "-d", type=str, default="minor")
# parser.add_argument("--split", "-s", type=str, default="val")
parser.add_argument("--output_path", "-op", type=str, default="./")
parser.add_argument("--input_path", "-ip", type=str, default="./data",
                    help="Path to the input data files")
args, opt = parser.parse_known_args()

dataset = 'all2023' # args.dataset
# split = 'val' # args.split
output_path = args.output_path
input_path = args.input_path

# %%
# 
# Remaining imports
# 
import pandas as pd
import os
import sys
from tqdm import tqdm
from datetime import datetime
from util_preprocess import preprocess_primary_secondary

# %% [markdown]
# Rename columns to reflect standarized terminology:
# - Field: Bio/cs/physics
# - Subfield: Subcategories within each
#     - Primary subfield (bio., cs.LG): Given primary subfield, you can infer the field
#     - Secondary subfields: Includes primary subfield, but also includes any subfields that were tagged in the paper (1-5)
#
# Old terminology to standardized terminology translation:
# - Prime category = Primary subfield
# - Abstract category = secondary subfield
# - Major category = field

# %%
file_path = os.path.join(
    input_path,
    'raw',
    'all2023',
    'all-2023-v2.tsv'
)
save_dir = os.path.join(output_path, dataset)
os.makedirs(save_dir, exist_ok=True)
train_save_path = os.path.join(save_dir, "train.json")
test_save_path = os.path.join(save_dir, "test.json")
print("Reading from file: ", file_path)

FEATURES = [
    'paper_id', 
    'version', 
    'yymm', 
    'created', 
    'title', 
    'secondary_subfield', 
    'abstract', 
    'primary_subfield', 
    'field', 
    'fulltext'
]
def get_date(paper):
    # first get the arxiv id
    paper_id = paper['paper_id']
    # yy is the first two characters of the arxiv id
    yy = paper_id[:2]
    # mm is the next two characters of the arxiv id
    mm = paper_id[2:4]
    # return datatime object
    date_obj = datetime(year=int(f"20{yy}"), month=int(mm), day=1)
    # return date as string in the format YYYY-MM-DDTHH:MM:SS
    return date_obj #.strftime('%Y-%m-%dT%H:%M:%S')

def get_fulltext(row):
    filename = f"{row['paper_id']}v{row['version']}.txt"
    filepath = os.path.join(
        input_path, 
        'raw',
        'all2023',
        'fulltext', 
        row['paper_id'].split('.')[0], # get yymm subfolder
        filename,
    )
    try:
        with open(filepath, 'r') as f:
            fulltext = f.read()
    except FileNotFoundError:
        fulltext = None
    return fulltext

count_orig = []
count_isvalid = []
count_hasfulltext = []
# Ignore all quotes by setting quoting=3 (corresponds to csv.QUOTE_NONE)
for i, original_df in tqdm(enumerate(pd.read_csv(file_path, sep='\t', chunksize=10, dtype=str, quoting=3))):
    count_orig.append( len(original_df) )
    # set `yymm` column
    original_df.loc[:, 'yymm'] = original_df['paper_id'].apply(lambda x: x[:4])
    # set `created` column using yymm from the paper_id as a proxy
    original_df.loc[:, 'created'] = original_df.apply(lambda x: get_date(x), axis=1)
    # set non-existent features to empty string
    for feature in FEATURES:
        if feature not in original_df.columns:
            original_df[feature] = ""
    # convert categories to primary and secondary subfield
    original_df.loc[:, 'primary_subfield'] = original_df['categories'].apply(lambda x : x.split()[0])
    # keep the secondary_subfield a string, will be converted to list in preprocess_primary_secondary()
    original_df.loc[:, 'secondary_subfield'] = original_df['categories']
    # Apply preprocessing rules and add `field` column
    df = preprocess_primary_secondary(original_df)

    count_isvalid.append( len(df) )
    # Get fulltext for each paper from .txt files
    df.loc[:, 'fulltext'] = df.apply(get_fulltext, axis=1)
    # drop `categories` column
    df = df.drop(columns=['categories'])
    # print number of rows where fulltext is not None
    df = df.dropna(subset=['fulltext'])
    count_hasfulltext.append( len(df) )

    # assert that df has all the required columns
    assert all([feature in df.columns for feature in FEATURES]), f"Missing features in df: {FEATURES}"

    # convert all columns to string per huggingface requirements
    DATE_CUTOFF = datetime(2023, 7, 1)
    if i == 0:
        # save the rows with created date before 2023-06-01 to train.json
        df[df['created'] < DATE_CUTOFF].to_json(train_save_path, lines=True, orient="records") #, date_format='iso')
        # save the rows with created date after 2023-06-01 to test.json
        df[df['created'] >= DATE_CUTOFF].to_json(test_save_path, lines=True, orient="records") #, date_format='iso')
    else:
        # save the rows with created date before 2023-06-01 to train.json
        df[df['created'] < DATE_CUTOFF].to_json(train_save_path, lines=True, orient="records", mode='a')#, date_format='iso')
        # save the rows with created date after 2023-06-01 to test.json
        df[df['created'] >= DATE_CUTOFF].to_json(test_save_path, lines=True, orient="records", mode='a')#, date_format='iso')

# print("Saved to: ", save_path)
df_err = pd.DataFrame({
    'orig': count_orig,
    'isvalid': count_isvalid,
    'hasfulltext': count_hasfulltext,
})
df_err.to_csv(f"error_log.csv", index=False)
# %%