egrace479 commited on
Commit
71ad5b4
·
1 Parent(s): 137ddb8

Add script to match EOL citation data and missing owners to catalog.

Browse files
Files changed (1) hide show
  1. scripts/match_owners.py +215 -0
scripts/match_owners.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from tqdm import tqdm
3
+ from pathlib import Path
4
+ import argparse
5
+ import sys
6
+
7
+ # This file can be used on predicted-catalog or rarespecies-catalog by changing the CATALOG_PATH.
8
+ CATALOG_PATH = "data/catalog.csv"
9
+ LICENSE_COLS = ["treeoflife_id", "eol_content_id", "eol_page_id"]
10
+ EXPECTED_COLS = [
11
+ "EOL content ID",
12
+ "EOL page ID",
13
+ "Medium Source URL",
14
+ "EOL Full-Size Copy URL",
15
+ "License Name",
16
+ "Copyright Owner",
17
+ ]
18
+
19
+
20
+ def merge_dfs(df, media):
21
+ """
22
+ Function to process and merge the ToL catalog with the media manifest.
23
+
24
+ Parameters:
25
+ -----------
26
+ df - DataFrame composed of catalog entries, includes columns "treeoflife_id", "eol_content_id", and "eol_page_id".
27
+ media - DataFrame of EOL media manifest with EXPECTED_COLS.
28
+
29
+ Returns:
30
+ --------
31
+ cat_media - DataFrame with media manifest information attached to treeoflife_ids in catalog.
32
+
33
+ """
34
+ # Reduce to just EOL entries
35
+ eol_df = df.loc[df["eol_content_id"].notna()].copy()
36
+ eol_df = eol_df[LICENSE_COLS]
37
+
38
+ # Set content and page ID types to int64
39
+ eol_df = eol_df.astype({"eol_content_id": "int64", "eol_page_id": "int64"})
40
+ # Rename media versions to match (already int64)
41
+ media.rename(
42
+ columns={"EOL content ID": "eol_content_id", "EOL page ID": "eol_page_id"},
43
+ inplace=True,
44
+ )
45
+
46
+ # Merge dataframes on EOL content and page IDs
47
+ cat_media = pd.merge(
48
+ eol_df, media, how="inner", left_on=LICENSE_COLS[1:], right_on=LICENSE_COLS[1:]
49
+ )
50
+
51
+ return cat_media
52
+
53
+
54
+ def merge_owners(cat_media, owners):
55
+ """
56
+ Function to process and merge the owner fix DataFrame with cat_media for owner matching.
57
+
58
+ Parameters:
59
+ -----------
60
+ cat_media - DataFrame with media manifest information attached to treeoflife_ids in catalog.
61
+ owners - DataFrame of media manifest entries that had missing owners, updated with their information.
62
+
63
+ Returns:
64
+ --------
65
+ cat_owners - DataFrame with media manifest information from missing owners attached to treeoflife_ids.
66
+
67
+ """
68
+ # Rename owner EOL content and page IDs to match cat_media (already int64)
69
+ owners.rename(
70
+ columns={"EOL content ID": "eol_content_id", "EOL page ID": "eol_page_id"},
71
+ inplace=True,
72
+ )
73
+ # Set columns to merge on
74
+ merge_cols = list(owners.columns)[:5]
75
+ cat_owners = pd.merge(
76
+ cat_media, owners, how="inner", left_on=merge_cols, right_on=merge_cols
77
+ )
78
+
79
+ return cat_owners
80
+
81
+
82
+ def get_owners_titles(cat_media, cat_owners):
83
+ """
84
+ Function to attach owner names and image titles to catalog entries in cat_media.
85
+ Fills empty "Copyright Owner" and "Title" values with "not provided".
86
+
87
+ Parameters:
88
+ -----------
89
+ cat_media - DataFrame with media manifest information attached to treeoflife_ids in catalog.
90
+ cat_owners - DataFrame with media manifest information from missing owners attached to treeoflife_ids.
91
+
92
+ Returns:
93
+ --------
94
+ cat_media - DataFrame with media manifest information attached to treeoflife_ids in catalog with missing owners resolved.
95
+ """
96
+ missing_owners = [
97
+ tol_id
98
+ for tol_id in list(
99
+ cat_media.loc[cat_media["Copyright Owner"].isna(), "treeoflife_id"]
100
+ )
101
+ ]
102
+ for tol_id in tqdm(missing_owners):
103
+ temp = cat_owners.loc[cat_owners.treeoflife_id == tol_id]
104
+ copyright_owner = temp["Copyright Owner_y"].values
105
+ title = temp.title.values
106
+ cat_media.loc[
107
+ cat_media["treeoflife_id"] == tol_id, "Copyright Owner"
108
+ ] = copyright_owner
109
+ cat_media.loc[cat_media["treeoflife_id"] == tol_id, "title"] = title
110
+
111
+ # Print counts of licenses for which owner info was not resolved
112
+ print(
113
+ "Licenses still missing Copyright Owners: \n",
114
+ cat_media.loc[
115
+ cat_media["Copyright Owner"].isna(), "License Name"
116
+ ].value_counts(),
117
+ )
118
+
119
+ # Fill null "Copyright Owner" and "Title" values with "not provided"
120
+ cat_media["Copyright Owner"].fillna("not provided", inplace=True)
121
+ cat_media["title"].fillna("not provided", inplace=True)
122
+
123
+ return cat_media
124
+
125
+
126
+ def update_owners(df, media, owners, filepath):
127
+ """
128
+ Function to fetch and attach the missing owner and title information to EOL catalog entries and save catalog-media file.
129
+
130
+ Parameters:
131
+ -----------
132
+ df - DataFrame composed of catalog entries.
133
+ media - DataFrame of EOL media manifest.
134
+ owners - DataFrame of media manifest entries that had missing owners, updated with their information.
135
+ """
136
+ cat_media = merge_dfs(df, media)
137
+ cat_owners = merge_owners(cat_media, owners)
138
+ cat_media = get_owners_titles(cat_media, cat_owners)
139
+
140
+ # Save updated catalog media file to chosen location
141
+ cat_media.to_csv(filepath, index=False)
142
+
143
+
144
+ def main(media_csv, owner_csv, dest_dir):
145
+ # Check CSV compatibility
146
+ try:
147
+ print("Reading catalog CSV")
148
+ df = pd.read_csv(CATALOG_PATH, low_memory=False)
149
+
150
+ # Read in media manifest and owner fix CSVs with EOL content and page IDs as type "int64".
151
+ print("Reading media manifest CSV")
152
+ media = pd.read_csv(
153
+ media_csv,
154
+ dtype={"EOL content ID": "int64", "EOL page ID": "int64"},
155
+ low_memory=False,
156
+ )
157
+ print("Reading owner fix CSV")
158
+ owners = pd.read_csv(
159
+ owner_csv,
160
+ dtype={"EOL content ID": "int64", "EOL page ID": "int64"},
161
+ low_memory=False,
162
+ )
163
+ except Exception as e:
164
+ sys.exit(e)
165
+
166
+ # Check for columns
167
+ print("Processing data")
168
+ missing_media_cols = []
169
+ missing_owner_cols = []
170
+ for col in EXPECTED_COLS:
171
+ if col not in list(media.columns):
172
+ missing_media_cols.append(col)
173
+ if col not in list(owners.columns):
174
+ missing_owner_cols.append(col)
175
+ if len(missing_media_cols) > 0:
176
+ sys.exit(f"Media CSV does not have {missing_media_cols} columns.")
177
+ if len(missing_owner_cols) > 0:
178
+ sys.exit(f"Owners CSV does not have {missing_owner_cols} columns.")
179
+
180
+ # If split column included, remove "train_small" entries as they are duplicates from "train".
181
+ if "split" in list(df.columns):
182
+ df = df.loc[df.split != "train_small"]
183
+
184
+ # Check filepath given by user
185
+ dest_dir_path = Path(dest_dir)
186
+ if not dest_dir_path.is_absolute():
187
+ # Use ToL-EDA as reference folder
188
+ base_path = Path(__file__).parent.parent.resolve()
189
+ filepath = base_path / dest_dir_path
190
+ else:
191
+ filepath = dest_dir_path
192
+
193
+ filepath.mkdir(parents=True, exist_ok=True)
194
+
195
+ # Make and save updated manifest to chosen filepath
196
+ update_owners(df, media, owners, str(filepath / "catalog-media.csv"))
197
+
198
+
199
+ if __name__ == "__main__":
200
+ parser = argparse.ArgumentParser(description="Attach missing owner info to catalog")
201
+ parser.add_argument(
202
+ "-m", "--media_input_file", help="Path to the media manifest input CSV file"
203
+ )
204
+ parser.add_argument(
205
+ "-o", "--owner_input_file", help="Path to the owner fix input CSV file"
206
+ )
207
+ parser.add_argument(
208
+ "--output_path",
209
+ default="data",
210
+ required=False,
211
+ help="Path to the folder for output visualization files",
212
+ )
213
+ args = parser.parse_args()
214
+
215
+ main(args.media_input_file, args.owner_input_file, args.output_path)