-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate-statistics.py
More file actions
226 lines (190 loc) · 7.47 KB
/
update-statistics.py
File metadata and controls
226 lines (190 loc) · 7.47 KB
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
from pandarallel import pandarallel
pandarallel.initialize(
progress_bar=True
) # Set to False if you don’t want tqdm-style progress
import pandas as pd
from pathlib import Path
from tqdm import tqdm
def get_temp_file(directory):
"""
Generates a temporary file path based on a directory path.
Args:
directory (str): The directory path.
Returns:
str or None: The temporary file path, or None if the file does not exist.
"""
if directory[-1] == "/":
directory = directory[:-1]
file = directory.replace("/", "_")
output_filename = f"/bil/pscstaff/icaoberg/bil-inventory/.data/{file}.tsv"
if Path(output_filename).exists():
return output_filename
else:
return None
# Try importing humanize; install if not available
try:
import humanize
except ImportError:
import subprocess
subprocess.check_call(["pip", "install", "humanize"])
import humanize
# -------------------------------
# Load and validate input file
# -------------------------------
summary_file = Path("summary_metadata.tsv")
if not summary_file.exists():
raise FileNotFoundError(f"{summary_file} not found.")
df = pd.read_csv(summary_file, sep="\t")
# -------------------------------
# Rewrite temp_file if it starts with .data/
# -------------------------------
df["temp_file"] = df["bildirectory"].parallel_apply(get_temp_file)
# Ensure required columns are present
required_columns = ["temp_file", "bildid"]
for col in required_columns:
if col not in df.columns:
raise ValueError(f"'{col}' column not found in summary_metadata.tsv")
# -------------------------------
# Initialize missing columns
# -------------------------------
for col in ["number_of_files", "size", "md5_coverage"]:
if col not in df.columns:
df[col] = pd.NA
# Ensure correct dtypes
df["number_of_files"] = pd.to_numeric(df["number_of_files"], errors="coerce").astype(
"Int64"
)
df["size"] = pd.to_numeric(df["size"], errors="coerce").astype("Int64")
df["md5_coverage"] = pd.to_numeric(df["md5_coverage"], errors="coerce").astype(
"Float64"
)
if not "xxh64_coverage" in df.keys():
df["xxh64_coverage"] = None
if not "b2sum_coverage" in df.keys():
df["b2sum_coverage"] = None
# -------------------------------
# Define constants
# -------------------------------
save_interval = 250
output_path = Path("summary_metadata.tsv")
# -------------------------------
# Process each row
# -------------------------------
for idx, row in tqdm(df.iterrows(), total=len(df), desc="Processing metadata"):
already_done = not pd.isna(row["number_of_files"]) and not pd.isna(row["size"])
if already_done:
continue
temp_file_val = row["temp_file"]
if isinstance(temp_file_val, str) and temp_file_val.strip():
temp_path = Path(temp_file_val)
else:
print(f"Invalid or missing temp_file for row {idx}")
if temp_path.exists() and temp_path.is_file():
try:
temp_df = pd.read_csv(temp_path, sep="\t", low_memory=False)
if pd.isna(row["number_of_files"]):
df.at[idx, "number_of_files"] = int(len(temp_df))
if pd.isna(row["size"]) and "size" in temp_df.columns:
total_size = temp_df["size"].sum(min_count=1)
df.at[idx, "size"] = int(total_size) if pd.notna(total_size) else pd.NA
# md5
if pd.isna(row["md5_coverage"]):
if "md5" in temp_df.columns:
total = len(temp_df)
non_empty = temp_df["md5"].notna().sum()
coverage = (non_empty / total) * 100 if total > 0 else pd.NA
df.at[idx, "md5_coverage"] = round(coverage, 2)
else:
print(
f"'md5' column missing in {temp_path}, skipping md5_coverage calculation."
)
df.at[idx, "md5_coverage"] = None
# sha256
if pd.isna(row["sha256_coverage"]):
if "md5" in temp_df.columns:
total = len(temp_df)
non_empty = temp_df["sha256"].notna().sum()
coverage = (non_empty / total) * 100 if total > 0 else pd.NA
df.at[idx, "sha256_coverage"] = round(coverage, 2)
else:
print(
f"'sha256' column missing in {temp_path}, skipping sha256_coverage calculation."
)
df.at[idx, "sha256_coverage"] = None
# xxh64
if pd.isna(row["xxh64_coverage"]):
if "xxh64" in temp_df.columns:
total = len(temp_df)
non_empty = temp_df["xxh64"].notna().sum()
coverage = (non_empty / total) * 100 if total > 0 else pd.NA
df.at[idx, "xxh64_coverage"] = round(coverage, 2)
else:
print(
f"'xxh64' column missing in {temp_path}, skipping xxh64_coverage calculation."
)
df.at[idx, "xxh64_coverage"] = None
# b2sum
if pd.isna(row["b2sum_coverage"]):
if "b2sum" in temp_df.columns:
total = len(temp_df)
non_empty = temp_df["b2sum"].notna().sum()
coverage = (non_empty / total) * 100 if total > 0 else pd.NA
df.at[idx, "b2sum_coverage"] = round(coverage, 2)
else:
print(
f"'b2sum' column missing in {temp_path}, skipping b2sum_coverage calculation."
)
df.at[idx, "b2sum_coverage"] = None
# frequencies
import json as _json
df.at[idx, "frequencies"] = _json.dumps(
temp_df["extension"]
.dropna()
.value_counts()
.sort_values(ascending=False)
.to_dict()
)
# filetype
df.at[idx, "file_types"] = _json.dumps(
temp_df["filetype"]
.dropna()
.value_counts()
.sort_values(ascending=False)
.to_dict()
)
# mime-types
df.at[idx, "mime-types"] = _json.dumps(
temp_df["mime-type"]
.dropna()
.value_counts()
.sort_values(ascending=False)
.to_dict()
)
except Exception as e:
print(f"Error reading {temp_path}: {e}")
else:
print(f"File does not exist: {temp_path}")
if (idx + 1) % save_interval == 0:
df.to_csv(output_path, sep="\t", index=False)
print(f"Saved progress at row {idx + 1} to '{output_path}'")
# -------------------------------
# Compute pretty_size using humanize
# -------------------------------
df["pretty_size"] = df["size"].apply(
lambda x: humanize.naturalsize(x, binary=True) if pd.notna(x) else pd.NA
)
# -------------------------------
# Compute json_file paths if they exist
# -------------------------------
df["json_file"] = df["bildid"].apply(
lambda b: (
f"/bil/pscstaff/icaoberg/bil-inventory/json/{b}.json"
if Path(f"/bil/pscstaff/icaoberg/bil-inventory/json/{b}.json").exists()
else pd.NA
)
)
# -------------------------------
# Final write to disk
# -------------------------------
df.to_csv(output_path, sep="\t", index=False)
print(f"Final data written to '{output_path}'")