zoher15 commited on
Commit
9720daa
·
verified ·
1 Parent(s): 85f7ea9

Upload dehydrated PluRule dataset and hydration scripts

Browse files
LICENSE ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 PluRule Authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ Note: this license covers the code in this repository only. The PluRule
26
+ benchmark dataset is distributed separately and is licensed under the terms
27
+ declared on its release (see the dataset's HuggingFace page). The underlying
28
+ moderator comments and submissions are drawn from the publicly archived
29
+ Pushshift Reddit corpus; their use is bound by Reddit's terms of service.
README.md ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: PluRule
3
+ language:
4
+ - en
5
+ multilinguality:
6
+ - multilingual
7
+ task_categories:
8
+ - text-classification
9
+ - image-text-to-text
10
+ tags:
11
+ - reddit
12
+ - moderation
13
+ - multimodal
14
+ - rule-violations
15
+ license: other
16
+ ---
17
+
18
+ # PluRule
19
+
20
+ **PluRule** is a multilingual, multimodal benchmark for detecting rule
21
+ violations when moderating pluralistic communities on social media.
22
+
23
+ This dataset repository contains the dehydrated clustered PluRule splits and
24
+ the hydrate scripts needed to reconstruct comment bodies, submissions, and
25
+ optional media from the Pushshift / Arctic Shift archives.
26
+
27
+ ## Files
28
+
29
+ ```text
30
+ data/
31
+ ├── train_dehydrated_clustered.json.zst
32
+ ├── val_dehydrated_clustered.json.zst
33
+ └── test_dehydrated_clustered.json.zst
34
+ ```
35
+
36
+ The released files contain IDs, metadata, rules, cluster labels, answer
37
+ options, and `[NEEDS_HYDRATION]` placeholders. Reddit text and media are not
38
+ redistributed directly.
39
+
40
+ ## Hydrate
41
+
42
+ Conda:
43
+
44
+ ```bash
45
+ conda env create -f environment-hydrate.yml
46
+ conda activate plurule-hydrate
47
+ ```
48
+
49
+ Without conda:
50
+
51
+ ```bash
52
+ python -m venv .venv
53
+ source .venv/bin/activate
54
+ pip install -r requirements-hydrate.txt
55
+ ```
56
+
57
+ You also need `aria2c` on `PATH` for torrent downloads.
58
+
59
+ Run from the dataset repository root:
60
+
61
+ ```bash
62
+ python hydrate/0_download.py
63
+ python hydrate/1_hydrate_dataset.py
64
+ python hydrate/2_download_media.py # optional
65
+ ```
66
+
67
+ After hydration, the reconstructed files are:
68
+
69
+ ```text
70
+ data/train_hydrated_clustered.json.zst
71
+ data/val_hydrated_clustered.json.zst
72
+ data/test_hydrated_clustered.json.zst
73
+ ```
74
+
75
+ For details and troubleshooting, see [`hydrate/README.md`](hydrate/README.md).
76
+
77
+ ## Citation
78
+
79
+ ```bibtex
80
+ @inproceedings{plurule2025,
81
+ title = {{PluRule: A Benchmark for Moderating Pluralistic Communities
82
+ on Social Media}},
83
+ author = {Kachwala, Zoher and Truong, Bao Tran and Muralidharan, Rasika and
84
+ Kwak, Haewoon and An, Jisun and Menczer, Filippo},
85
+ year = {2026},
86
+ booktitle = {Proc. ACL},
87
+ note = {Forthcoming},
88
+ }
89
+ ```
config.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Simple configuration for Reddit mod collection pipeline.
3
+
4
+ Edit the base directories below for your environment.
5
+ All other paths are generated automatically based on data flow.
6
+ """
7
+
8
+ import os
9
+ import multiprocessing
10
+
11
+ # =============================================================================
12
+ # BASE CONFIGURATION - Override via environment variables or edit here.
13
+ # =============================================================================
14
+ # Defaults: BASE_DATA = repo root; PUSHSHIFT_DATA = <BASE_DATA>/data/pushshift.
15
+ # Override with:
16
+ # export PLURULE_BASE_DATA=/your/working/dir
17
+ # export PLURULE_PUSHSHIFT_DATA=/your/pushshift/mirror
18
+
19
+ _REPO_ROOT = os.path.dirname(os.path.abspath(__file__))
20
+
21
+ BASE_DATA = os.environ.get("PLURULE_BASE_DATA", _REPO_ROOT)
22
+ PUSHSHIFT_DATA = os.environ.get(
23
+ "PLURULE_PUSHSHIFT_DATA", os.path.join(BASE_DATA, "data", "pushshift")
24
+ )
25
+ # Legacy Pushshift-dumps location (Stage 0 when fetching RC_*/RS_* style dumps).
26
+ # Keep consistent with PUSHSHIFT_DATA by default.
27
+ REDDIT_DATA = os.environ.get("PLURULE_REDDIT_DATA", PUSHSHIFT_DATA)
28
+
29
+ CREDENTIALS_DIR = os.path.join(_REPO_ROOT, "credentials")
30
+
31
+ # Processing settings
32
+ DATE_RANGE = ("2005-12", "2023-02") # (start, end) inclusive PushshiftDumps
33
+ MIN_RULES_FOR_MATCHING = 2 # Minimum rules needed for semantic matching (skip subreddits with ≤1 rule)
34
+ GOLD_PERCENTILE = 99.2 # Top 0.8% of similarity scores considered gold matches (Stage 3 Phase 2)
35
+ AMBIGUOUS_PERCENTILE = 98 # Top 2% of similarity scores considered ambiguous matches (Stage 3 Phase 2)
36
+ MIN_MATCHED_COMMENTS = 1 # Minimum matched comments for subreddit inclusion in Stage 3
37
+ MAX_MATCHED_COMMENTS = 500 # Max sample size for matched comments in Stage 3
38
+
39
+ # Stage 8: Dataset split configuration
40
+ # Note: No minimum threshold - all subreddits with ≥1 pair are included
41
+ # Split logic per subreddit:
42
+ # n=1: 1 test, 0 val, 0 train
43
+ # n=2: 1 test, 0 val, 1 train
44
+ # 3≤n<10: 1 test, 1 val, (n-2) train
45
+ # n≥10: 10% test, 10% val, 80% train (rounded, min 1 each)
46
+
47
+ EMBEDDING_MODEL = "Qwen/Qwen3-Embedding-8B" # Model used in Stage 3 for semantic matching
48
+ # Auto-detect number of CPU cores (use all available cores)
49
+ PROCESSES = multiprocessing.cpu_count()
50
+
51
+ # Alternative: Use 75% of available cores to leave some for system
52
+ # PROCESSES = max(1, int(multiprocessing.cpu_count() * 0.75))
53
+
54
+ # =============================================================================
55
+ # DATA FLOW MAPPING - Shows what each stage produces and consumes
56
+ # =============================================================================
57
+
58
+ DATA_FLOW = {
59
+ # Phase 1: Data Collection
60
+ 'stage0_download_data': {
61
+ 'name': 'Download Reddit Data from Internet Archive',
62
+ 'script': '0_download_data.py',
63
+ 'input_paths': [], # No inputs - downloads from internet
64
+ 'output_dir': 'reddit_data',
65
+ 'produces': [
66
+ 'comments/YYYY/RC_*.zst', # Reddit comment files organized by year
67
+ 'submissions/YYYY/RS_*.zst', # Reddit submission files organized by year
68
+ '../logs/stage0_download_log.json' # actually written to PATHS['logs']
69
+ ]
70
+ },
71
+
72
+ 'stage1_mod_comments': {
73
+ 'name': 'Collect Moderator Comments from Pushshift',
74
+ 'script': '1_collect_mod_comments.py',
75
+ 'input_paths': [], # Uses Pushshift data directly
76
+ 'output_dir': 'top_subreddits',
77
+ 'produces': [
78
+ '{subreddit}_mod_comments.jsonl.zst', # in PATHS['top_subreddits'], one per subreddit
79
+ '../../data/stage1_subreddit_mod_comment_rankings.json' # actually written to PATHS['data']
80
+ ],
81
+ 'notes': 'Reads Pushshift subreddit files, filters mod comments. Replaces old Stage 1 + Stage 3.'
82
+ },
83
+
84
+ 'stage2_top_sfw': {
85
+ 'name': 'Get SFW Subreddits with Minimum Mod Comments',
86
+ 'script': '2_get_top_sfw_subreddits.py',
87
+ 'input_files': ['stage1_subreddit_mod_comment_rankings.json'],
88
+ 'output_dir': 'data',
89
+ 'produces': ['stage2_sfw_subreddits_min_{MIN_MATCHED_COMMENTS}_comments.json'],
90
+ 'notes': 'Uses Reddit API to filter NSFW, collect subreddit metadata and rules'
91
+ },
92
+
93
+ # Phase 2: Comment Matching
94
+ # NOTE: Stage 3 (filter_and_consolidate) is now obsolete - Stage 1 directly outputs to top_subreddits/
95
+
96
+ 'stage3_match_rules': {
97
+ 'name': 'Match Comments to Rules (2-Phase: Similarity Matrices + Global Thresholds)',
98
+ 'script': '3_match_rules.py',
99
+ 'helper_scripts': ['utils/match_rules_bucket.py'],
100
+ 'input_paths': ['top_subreddits'],
101
+ 'input_files': [
102
+ 'stage2_sfw_subreddits_min_{MIN_MATCHED_COMMENTS}_comments.json'
103
+ ],
104
+ 'output_dir': 'matched_comments',
105
+ 'produces': [
106
+ '{subreddit}_match.jsonl.zst', # in PATHS['matched_comments']
107
+ '{subreddit}_stats.json', # in PATHS['matched_comments']
108
+ '{subreddit}_similarity_matrix.pt', # in PATHS['matched_comments']
109
+ 'cosine_similarity_distribution_all_percentiles.png', # in PATHS['matched_comments']
110
+ '../../data/stage3_matching_summary.json', # actually written to PATHS['data']
111
+ '../../data/stage3_subreddit_submission_ids.json' # actually written to PATHS['data']
112
+ ],
113
+ 'notes': 'Phase 1: Create similarity matrices using vLLM embeddings. Phase 2: Apply global percentile thresholds for matching. Filters ambiguous matches, ranks by JSD.'
114
+ },
115
+
116
+ # Phase 3: Thread Construction
117
+ 'stage4_collect_submission_comments': {
118
+ 'name': 'Collect and Organize Submission Comments from Pushshift',
119
+ 'script': '4_collect_submission_comments.py',
120
+ 'input_paths': [], # Uses Pushshift data directly
121
+ 'input_files': ['stage3_subreddit_submission_ids.json'],
122
+ 'output_dir': 'organized_comments',
123
+ 'produces': [
124
+ '{subreddit}/submission_{submission_id}.pkl', # one file per submission, inside per-subreddit subdir
125
+ '../../data/stage4_submission_comment_collection_stats.json' # actually written to PATHS['data']
126
+ ],
127
+ 'notes': '2-pass per subreddit: filter with process_zst_file_multi → deduplicate with [removed]/[deleted] preservation'
128
+ },
129
+
130
+ 'stage5_build_trees_and_threads': {
131
+ 'name': 'Build Comment Trees and Discussion Threads',
132
+ 'script': '5_build_trees_and_threads.py',
133
+ 'input_paths': ['organized_comments', 'matched_comments'],
134
+ 'input_files': [
135
+ 'stage2_sfw_subreddits_min_{MIN_MATCHED_COMMENTS}_comments.json',
136
+ 'stage3_matching_summary.json'
137
+ ],
138
+ 'output_dir': 'comment_trees',
139
+ 'alternate_output_dirs': ['discussion_threads'], # Also outputs here
140
+ 'produces': [
141
+ 'comment_trees/{subreddit}_comment_trees.pkl', # in PATHS['comment_trees']
142
+ 'discussion_threads/{subreddit}_discussion_threads.pkl', # in PATHS['discussion_threads']
143
+ '../../data/stage5_trees_and_threads_summary.json' # actually written to PATHS['data']
144
+ ],
145
+ 'notes': 'Builds trees (parent-child, depth levels), creates moderated/unmoderated pairs, requires 500+ pairs, ranks by JSD'
146
+ },
147
+
148
+ # Phase 4: Dataset Finalization
149
+ 'stage6_collect_submissions': {
150
+ 'name': 'Collect Submissions from Discussion Threads',
151
+ 'script': '6_collect_submissions.py',
152
+ 'input_paths': ['reddit_submissions'], # Pushshift submissions
153
+ 'input_files': ['stage5_trees_and_threads_summary.json'],
154
+ 'output_dir': 'submissions',
155
+ 'produces': [
156
+ '{subreddit}_submissions.zst', # in PATHS['submissions']
157
+ '../../data/stage6_submission_collection_stats.json' # actually written to PATHS['data']
158
+ ],
159
+ 'notes': '3-phase: extract IDs from stage 5 summary → process RS files from Pushshift → consolidate by subreddit'
160
+ },
161
+
162
+ 'stage7_collect_media': {
163
+ 'name': 'Collect Media for Submissions',
164
+ 'script': '7_collect_media.py',
165
+ 'input_paths': ['submissions'],
166
+ 'input_files': ['stage6_submission_collection_stats.json'],
167
+ 'output_dir': 'media',
168
+ 'produces': [
169
+ '{subreddit}/{submission_id}_{media_id}_{source}.{ext}', # Downloaded media files in PATHS['media']
170
+ '../../data/stage7_media_collection_stats.json', # actually written to PATHS['data']
171
+ '../../data/stage7_successful_submission_ids.json' # actually written to PATHS['data']
172
+ ],
173
+ 'notes': 'Priority: media_metadata → url → oembed → preview. Skips NSFW/crosspost/URL-only selfposts. Validates file types.'
174
+ },
175
+
176
+ 'stage8_create_datasets': {
177
+ 'name': 'Create Final Datasets (Hydrated + Dehydrated splits)',
178
+ 'script': '8_create_dehydrated_dataset.py',
179
+ 'input_paths': ['discussion_threads', 'comment_trees', 'submissions', 'media'],
180
+ 'input_files': [
181
+ 'stage2_sfw_subreddits_min_{MIN_MATCHED_COMMENTS}_comments.json',
182
+ 'stage7_successful_submission_ids.json',
183
+ 'stage1_subreddit_mod_comment_rankings.json',
184
+ 'stage3_matching_summary.json',
185
+ 'stage5_trees_and_threads_summary.json',
186
+ 'stage6_submission_collection_stats.json',
187
+ 'stage7_media_collection_stats.json'
188
+ ],
189
+ 'output_dir': 'data',
190
+ 'produces': [
191
+ 'train_hydrated.json.zst',
192
+ 'val_hydrated.json.zst',
193
+ 'test_hydrated.json.zst',
194
+ 'train_dehydrated.json.zst',
195
+ 'val_dehydrated.json.zst',
196
+ 'test_dehydrated.json.zst',
197
+ 'test_hydrated.json', # uncompressed test split
198
+ 'stage8_final_datasets_stats.json',
199
+ 'stage8_llm_verification_results.json',
200
+ 'stage8_thread_distribution_analysis.json'
201
+ ],
202
+ 'notes': 'Adaptive train/val/test splits per subreddit + Qwen3-30B LLM judge verification. Hydrated: full objects. Dehydrated: IDs with [NEEDS_HYDRATION] placeholders.'
203
+ },
204
+
205
+ # Phase 5: Clustering
206
+ 'stage9a_embed_clusters': {
207
+ 'name': 'Embed Subreddits and Rules for Clustering',
208
+ 'script': '9a_embed_clusters.py',
209
+ 'input_files': [
210
+ 'train_hydrated.json.zst',
211
+ 'val_hydrated.json.zst',
212
+ 'test_hydrated.json.zst',
213
+ 'stage2_sfw_subreddits_min_{MIN_MATCHED_COMMENTS}_comments.json'
214
+ ],
215
+ 'output_dir': 'embeddings',
216
+ 'produces': [
217
+ 'all_subreddit_embeddings.tsv',
218
+ 'all_subreddit_metadata.tsv',
219
+ 'all_rule_embeddings.tsv',
220
+ 'all_rule_metadata.tsv'
221
+ ],
222
+ 'notes': 'Creates embeddings using vLLM for subreddits (title+description) and rules (rule_comprehensive text).'
223
+ },
224
+
225
+ 'stage9b_cluster_embeddings': {
226
+ 'name': 'Cluster Embeddings with UMAP + HDBSCAN',
227
+ 'script': '9b_cluster_embeddings.py',
228
+ 'input_paths': ['embeddings'],
229
+ 'output_dir': 'clustering',
230
+ 'alternate_output_dirs': ['embeddings'], # reduced TSVs + updated metadata go here
231
+ 'produces': [
232
+ 'clustering/subreddit_grid_search_results.json',
233
+ 'clustering/rule_grid_search_results.json',
234
+ 'embeddings/all_subreddit_embeddings_reduced.tsv',
235
+ 'embeddings/all_rule_embeddings_reduced.tsv',
236
+ 'embeddings/all_subreddit_metadata.tsv', # MUTATED in place: cluster_id, cluster_label columns added
237
+ 'embeddings/all_rule_metadata.tsv' # MUTATED in place: cluster_id, cluster_label columns added
238
+ ],
239
+ 'notes': 'Grid search for optimal UMAP + HDBSCAN parameters. Reduced embeddings + augmented metadata are written back into PATHS["embeddings"]; only grid_search results live in PATHS["clustering"].'
240
+ },
241
+
242
+ 'stage9c_label_clusters': {
243
+ 'name': 'Label Clusters with LLM',
244
+ 'script': '9c_label_clusters.py',
245
+ 'input_paths': ['embeddings', 'clustering'],
246
+ 'output_dir': 'clustering',
247
+ 'produces': [
248
+ 'subreddit_cluster_labels.json',
249
+ 'rule_cluster_labels.json',
250
+ 'subreddit_cluster_analysis.txt',
251
+ 'rule_cluster_analysis.txt'
252
+ ],
253
+ 'notes': 'Uses LLM to generate semantic labels for each cluster via majority voting.'
254
+ },
255
+
256
+ 'stage9d_reapply_cluster_labels': {
257
+ 'name': 'Reapply/Override Cluster Labels',
258
+ 'script': '9d_reapply_cluster_labels.py',
259
+ 'input_paths': ['embeddings', 'clustering'],
260
+ 'output_dir': 'clustering',
261
+ 'produces': [
262
+ 'subreddit_cluster_labels.json',
263
+ 'rule_cluster_labels.json'
264
+ ],
265
+ 'notes': 'Optional manual step to apply label overrides and merge clusters.'
266
+ },
267
+
268
+ # Phase 6: Final Assignment and Evaluation
269
+ 'stage10_assign_cluster_labels': {
270
+ 'name': 'Assign Cluster Labels to Dataset',
271
+ 'script': '10_assign_cluster_labels.py',
272
+ 'input_paths': ['embeddings'],
273
+ 'input_files': [
274
+ 'train_hydrated.json.zst',
275
+ 'val_hydrated.json.zst',
276
+ 'test_hydrated.json.zst'
277
+ ],
278
+ 'output_dir': 'data',
279
+ 'produces': [
280
+ 'train_hydrated_clustered.json.zst',
281
+ 'val_hydrated_clustered.json.zst',
282
+ 'test_hydrated_clustered.json.zst',
283
+ 'train_dehydrated_clustered.json.zst',
284
+ 'val_dehydrated_clustered.json.zst',
285
+ 'test_dehydrated_clustered.json.zst',
286
+ 'test_hydrated_clustered.json', # uncompressed
287
+ 'stage10_cluster_assignment_stats.json',
288
+ 'stage10_dataset_stats_table.tex' # LaTeX table for paper
289
+ ],
290
+ 'notes': 'Assigns cluster labels to all thread pairs in the dataset based on embedding metadata.'
291
+ }
292
+
293
+ # Human evaluation scripts live in eval/human_eval/ (not pipeline stages).
294
+ }
295
+
296
+ # =============================================================================
297
+ # AUTO-GENERATED PATHS - Don't edit these
298
+ # =============================================================================
299
+
300
+ def _generate_paths():
301
+ """Generate all paths based on base directories and data flow."""
302
+ paths = {
303
+ # Input data sources
304
+ 'reddit_comments': f"{REDDIT_DATA}/comments",
305
+ 'reddit_submissions': f"{REDDIT_DATA}/submissions",
306
+ 'reddit_data': f"{REDDIT_DATA}", # Base directory for downloaded data
307
+
308
+ # Base output directories
309
+ 'data': f"{BASE_DATA}/data",
310
+ 'logs': f"{BASE_DATA}/logs",
311
+
312
+ # Stage output directories (auto-generated from DATA_FLOW)
313
+ 'mod_comments': f"{BASE_DATA}/data/mod_comments",
314
+ 'top_subreddits': f"{BASE_DATA}/output/top_subreddits",
315
+ 'matched_comments': f"{BASE_DATA}/output/matched_comments",
316
+ 'matched_comments_sample': f"{BASE_DATA}/output/matched_comments_sample",
317
+ 'submission_comments': f"{BASE_DATA}/data/submission_comments",
318
+ 'organized_comments': f"{BASE_DATA}/output/organized_comments",
319
+ 'comment_trees': f"{BASE_DATA}/output/comment_trees",
320
+ 'discussion_threads': f"{BASE_DATA}/output/discussion_threads",
321
+ 'submissions': f"{BASE_DATA}/output/submissions",
322
+ 'media': f"{BASE_DATA}/output/media",
323
+ 'final_dataset': f"{BASE_DATA}/output/final_dataset",
324
+ 'embeddings': f"{BASE_DATA}/output/embeddings",
325
+ 'clustering': f"{BASE_DATA}/output/clustering",
326
+ 'evaluation': f"{BASE_DATA}/data/evaluation"
327
+ }
328
+
329
+ return paths
330
+
331
+ PATHS = _generate_paths()
332
+
333
+ # =============================================================================
334
+ # UTILITY FUNCTIONS
335
+ # =============================================================================
336
+
337
+ def get_stage_info(stage_num):
338
+ """Get information for a specific stage number (0-13)."""
339
+ stage_key = f"stage{stage_num}_" + list(DATA_FLOW.keys())[stage_num].split('_', 1)[1]
340
+ return DATA_FLOW.get(stage_key)
341
+
342
+ def get_input_paths_for_stage(stage_num):
343
+ """Get resolved input paths for a stage."""
344
+ stage_info = get_stage_info(stage_num)
345
+ if not stage_info:
346
+ return []
347
+
348
+ input_paths = []
349
+
350
+ # Add directory paths
351
+ for path_key in stage_info.get('input_paths', []):
352
+ input_paths.append(PATHS[path_key])
353
+
354
+ # Add specific files
355
+ for file_name in stage_info.get('input_files', []):
356
+ # Substitute template variables
357
+ resolved_file_name = file_name.format(
358
+ MIN_MATCHED_COMMENTS=MIN_MATCHED_COMMENTS
359
+ )
360
+ input_paths.append(os.path.join(PATHS['data'], resolved_file_name))
361
+
362
+ return input_paths
363
+
364
+ def get_output_path_for_stage(stage_num):
365
+ """Get resolved output path for a stage."""
366
+ stage_info = get_stage_info(stage_num)
367
+ if not stage_info:
368
+ return None
369
+
370
+ output_dir = stage_info.get('output_dir')
371
+ return PATHS.get(output_dir)
372
+
373
+ def create_directories():
374
+ """Create necessary output directories (excludes read-only input paths)."""
375
+ # Skip input directories that should already exist
376
+ skip_paths = {'reddit_comments', 'reddit_submissions', 'reddit_data'}
377
+
378
+ for name, path in PATHS.items():
379
+ if name not in skip_paths:
380
+ os.makedirs(path, exist_ok=True)
381
+
382
+ def validate_stage_inputs(stage_num):
383
+ """Check if inputs exist for a stage."""
384
+ input_paths = get_input_paths_for_stage(stage_num)
385
+
386
+ for path in input_paths:
387
+ if os.path.isfile(path):
388
+ if not os.path.exists(path):
389
+ return False, f"Missing file: {path}"
390
+ elif os.path.isdir(path):
391
+ if not os.path.exists(path) or not os.listdir(path):
392
+ return False, f"Missing or empty directory: {path}"
393
+ else:
394
+ return False, f"Path doesn't exist: {path}"
395
+
396
+ return True, "All inputs available"
397
+
398
+ def print_pipeline_status():
399
+ """Print status of entire pipeline."""
400
+ print("Reddit Mod Collection Pipeline Status")
401
+ print("=" * 80)
402
+ print()
403
+
404
+ for i in range(0, 11): # Now 0-10 stages (including stage 10)
405
+ stage_info = get_stage_info(i)
406
+ if stage_info:
407
+ valid, msg = validate_stage_inputs(i)
408
+ output_path = get_output_path_for_stage(i)
409
+ output_exists = os.path.exists(output_path) if output_path else False
410
+
411
+ status = "✓" if valid else "✗"
412
+ output_status = "✓" if output_exists else "✗"
413
+
414
+ print(f"Stage {i:2d}: {stage_info['name']}")
415
+ print(f" Script: {stage_info.get('script', 'N/A')}")
416
+ print(f" Input: {status} | Output: {output_status}")
417
+ if not valid:
418
+ print(f" Issue: {msg}")
419
+ if stage_info.get('notes'):
420
+ print(f" Notes: {stage_info['notes']}")
421
+ print()
422
+
423
+ print("=" * 80)
424
+
425
+ if __name__ == "__main__":
426
+ # When run directly, show pipeline status
427
+ create_directories()
428
+ print_pipeline_status()
data/test_dehydrated_clustered.json.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:019634000115a5b7d3271a95d205ca6d76800cf6045ec4486fd897cc1c5ecd38
3
+ size 4671263
data/train_dehydrated_clustered.json.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:235937388c3d0ebae7334c2fed2ae0e5f2fa286263a2bab704097af24b252803
3
+ size 3853781
data/val_dehydrated_clustered.json.zst ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:53a5f5144fca20229320cc026863a8beaff735444c3c453dcec48a7b9f205734
3
+ size 1548607
environment-hydrate.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Conda environment for PluRule hydration (hydrate/).
2
+ #
3
+ # Setup:
4
+ # conda env create -f environment-hydrate.yml
5
+ # conda activate plurule-hydrate
6
+ # python hydrate/0_download.py
7
+
8
+ name: plurule-hydrate
9
+ channels:
10
+ - conda-forge
11
+ dependencies:
12
+ - python>=3.10
13
+ - aria2
14
+ - pip
15
+ - pip:
16
+ - zstandard>=0.21.0
17
+ - orjson>=3.9.0
18
+ - tqdm>=4.65.0
19
+ - requests>=2.31.0
20
+ - torf>=4.2.0
hydrate/0_download.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PluRule Hydrate Step 0: Download the Pushshift subset needed to hydrate the benchmark.
4
+
5
+ Reads the dehydrated PluRule dataset, determines which per-subreddit comment
6
+ and submission files are referenced (~3,978 files for ~1,989 subreddits), and
7
+ fetches just those from the academictorrents Pushshift/Arctic Shift archive via
8
+ aria2c. Output layout is first-letter buckets (`<output-dir>/<letter>/<Sub>_...zst`)
9
+ to match the existing pipeline layout.
10
+
11
+ Modes:
12
+ (default) Download via torrent
13
+ --from-dir X Skip download; build manifest from an existing local mirror at X
14
+ --dry-run Print torrent match report, no download
15
+
16
+ Usage:
17
+ python hydrate/0_download.py
18
+ python hydrate/0_download.py --dry-run
19
+ python hydrate/0_download.py --from-dir /gpfs/.../Arcticshift/Subreddits/subreddits
20
+ python hydrate/0_download.py --output-dir /mnt/big/pushshift
21
+ """
22
+
23
+ import argparse
24
+ import json
25
+ import sys
26
+ from pathlib import Path
27
+ from typing import Dict, Set
28
+
29
+ sys.path.append(str(Path(__file__).resolve().parent.parent))
30
+
31
+ from config import PUSHSHIFT_DATA
32
+ from utils.files import read_compressed_json
33
+ from utils.logging import setup_stage_logger
34
+ from utils.pushshift_download import (
35
+ PUSHSHIFT_TORRENT_URL,
36
+ check_aria2c,
37
+ ensure_torrent,
38
+ match_basenames,
39
+ parse_torrent,
40
+ reorganize_to_letter_buckets,
41
+ run_aria2c,
42
+ scan_local_files,
43
+ )
44
+
45
+ SPLITS = ("train", "val", "test")
46
+
47
+
48
+ def collect_subreddits(dataset_dir: Path, logger) -> Set[str]:
49
+ """Union of subreddit names referenced across all three dehydrated splits."""
50
+ subs: Set[str] = set()
51
+ for split in SPLITS:
52
+ path = dataset_dir / f"{split}_dehydrated_clustered.json.zst"
53
+ if not path.exists():
54
+ logger.error(f"Missing dataset file: {path}")
55
+ sys.exit(1)
56
+ data = read_compressed_json(str(path))
57
+ for entry in data.get("subreddits", []):
58
+ name = (entry.get("subreddit") or "").lower().strip()
59
+ if name:
60
+ subs.add(name)
61
+ return subs
62
+
63
+
64
+ def required_basenames(subreddits: Set[str]) -> Set[str]:
65
+ """Two files per subreddit (comments + submissions)."""
66
+ files: Set[str] = set()
67
+ for sub in subreddits:
68
+ files.add(f"{sub}_comments.zst")
69
+ files.add(f"{sub}_submissions.zst")
70
+ return files
71
+
72
+
73
+ def _write_manifest(output_dir: Path, manifest: Dict) -> Path:
74
+ path = output_dir / "hydrate_manifest.json"
75
+ with open(path, "w") as f:
76
+ json.dump(manifest, f, indent=2)
77
+ return path
78
+
79
+
80
+ def _log_summary(logger, required: int, present: int, missing: int, manifest_path: Path) -> None:
81
+ logger.info("📊 Summary")
82
+ logger.info(f" required: {required}")
83
+ logger.info(f" present: {present}")
84
+ logger.info(f" missing: {missing}")
85
+ logger.info(f" manifest: {manifest_path}")
86
+
87
+
88
+ def main() -> int:
89
+ parser = argparse.ArgumentParser(
90
+ description="Download the Pushshift subset referenced by the dehydrated PluRule dataset."
91
+ )
92
+ parser.add_argument(
93
+ "--dataset-dir", type=Path, default=Path("./data"),
94
+ help="Directory containing {train,val,test}_dehydrated_clustered.json.zst",
95
+ )
96
+ parser.add_argument(
97
+ "--output-dir", type=Path, default=Path(PUSHSHIFT_DATA),
98
+ help=f"Destination (default from config.PUSHSHIFT_DATA: {PUSHSHIFT_DATA})",
99
+ )
100
+ parser.add_argument(
101
+ "--torrent-file", type=Path, default=None,
102
+ help="Pre-downloaded .torrent file (skip fetch from academictorrents.com)",
103
+ )
104
+ parser.add_argument(
105
+ "--dry-run", action="store_true",
106
+ help="Preview torrent matches without downloading",
107
+ )
108
+ parser.add_argument(
109
+ "--from-dir", type=Path, default=None,
110
+ help="Skip torrent; build manifest from an existing local mirror.",
111
+ )
112
+ args = parser.parse_args()
113
+
114
+ args.output_dir.mkdir(parents=True, exist_ok=True)
115
+
116
+ logger = setup_stage_logger("hydrate0_download")
117
+ logger.info("=" * 60)
118
+ logger.info("🚀 Hydrate Step 0: Download Pushshift subset")
119
+ logger.info("=" * 60)
120
+
121
+ # 1. Collect needed basenames from dehydrated dataset
122
+ logger.info(f"📋 Collecting subreddits from dehydrated datasets in {args.dataset_dir}...")
123
+ subreddits = collect_subreddits(args.dataset_dir, logger)
124
+ needed = required_basenames(subreddits)
125
+ logger.info(f" {len(subreddits)} unique subreddits → {len(needed)} files required")
126
+
127
+ # 2a. --from-dir fast path: build manifest from existing mirror
128
+ if args.from_dir is not None:
129
+ if not args.from_dir.exists():
130
+ logger.error(f"--from-dir not found: {args.from_dir}")
131
+ sys.exit(1)
132
+ logger.info(f"📁 Scanning existing mirror at {args.from_dir}...")
133
+ present, missing, basename_to_path = scan_local_files(args.from_dir, needed)
134
+
135
+ manifest = {
136
+ "dataset_dir": str(args.dataset_dir),
137
+ "output_dir": str(args.output_dir),
138
+ "source": "from-dir",
139
+ "source_dir": str(args.from_dir),
140
+ "subreddits_count": len(subreddits),
141
+ "files_required_count": len(needed),
142
+ "files_present_count": len(present),
143
+ "files_missing_in_source": sorted(missing),
144
+ "basename_to_path": basename_to_path,
145
+ }
146
+ manifest_path = _write_manifest(args.output_dir, manifest)
147
+ _log_summary(logger, len(needed), len(present), len(missing), manifest_path)
148
+ if missing and len(missing) <= 20:
149
+ logger.warning(f" missing list: {sorted(missing)}")
150
+ elif missing:
151
+ logger.warning(f" missing sample: {sorted(missing)[:20]} ... (+{len(missing) - 20} more)")
152
+ return 0
153
+
154
+ # 2b. Torrent path
155
+ torrent_path = args.torrent_file or (args.output_dir / "pushshift.torrent")
156
+ if args.torrent_file is None:
157
+ ensure_torrent(torrent_path, PUSHSHIFT_TORRENT_URL)
158
+ elif not torrent_path.exists():
159
+ logger.error(f"Torrent file not found: {torrent_path}")
160
+ sys.exit(1)
161
+
162
+ logger.info("🔎 Matching required files against torrent contents...")
163
+ all_files = parse_torrent(torrent_path)
164
+ matched, missing_in_torrent = match_basenames(all_files, needed)
165
+ logger.info(f" matched: {len(matched)} / not in torrent: {len(missing_in_torrent)}")
166
+ if missing_in_torrent and len(missing_in_torrent) <= 20:
167
+ logger.warning(f" missing: {sorted(missing_in_torrent)}")
168
+ elif missing_in_torrent:
169
+ logger.warning(f" missing sample: {sorted(missing_in_torrent)[:20]} ... "
170
+ f"(+{len(missing_in_torrent) - 20} more)")
171
+
172
+ manifest: Dict = {
173
+ "dataset_dir": str(args.dataset_dir),
174
+ "output_dir": str(args.output_dir),
175
+ "source": "torrent",
176
+ "torrent_file": str(torrent_path),
177
+ "torrent_url": PUSHSHIFT_TORRENT_URL if args.torrent_file is None else None,
178
+ "subreddits_count": len(subreddits),
179
+ "files_required_count": len(needed),
180
+ "files_matched_count": len(matched),
181
+ "files_missing_in_torrent": sorted(missing_in_torrent),
182
+ }
183
+
184
+ if args.dry_run:
185
+ manifest["torrent_relative_paths"] = {b: p for b, (_, p) in matched.items()}
186
+ path = args.output_dir / "hydrate_manifest_dry_run.json"
187
+ with open(path, "w") as f:
188
+ json.dump(manifest, f, indent=2)
189
+ logger.info(f"✅ Dry run complete: {path}")
190
+ for _, (idx, rel) in list(matched.items())[:3]:
191
+ logger.info(f" [{idx:>5}] {rel}")
192
+ return 0
193
+
194
+ if not matched:
195
+ logger.error("No files matched in torrent; nothing to download.")
196
+ sys.exit(1)
197
+
198
+ # 3. Check what's already in letter-bucket layout (re-run skip)
199
+ logger.info(f"🔎 Checking existing files in {args.output_dir}...")
200
+ present, missing_to_dl, _ = scan_local_files(args.output_dir, set(matched.keys()))
201
+ logger.info(f" already present: {len(present)} / still need: {len(missing_to_dl)}")
202
+
203
+ if missing_to_dl:
204
+ check_aria2c()
205
+ logger.info(f"🚀 aria2c: downloading to {args.output_dir}")
206
+ rc = run_aria2c(torrent_path, [i for i, _ in matched.values()], args.output_dir)
207
+ if rc != 0:
208
+ logger.warning(f"⚠️ aria2c exited with code {rc} (partial set may still have downloaded)")
209
+
210
+ # 4. Reorganize freshly-downloaded files into letter buckets
211
+ logger.info("🗂️ Reorganizing into first-letter bucket layout...")
212
+ _, _, downloaded_map = scan_local_files(args.output_dir, set(matched.keys()))
213
+ reorganize_to_letter_buckets(args.output_dir, downloaded_map)
214
+ else:
215
+ logger.info("✓ All needed files already present; skipping aria2c.")
216
+
217
+ # 5. Re-verify and write manifest (authoritative after any moves)
218
+ present_final, missing_final, verified_map = scan_local_files(args.output_dir, needed)
219
+ manifest["files_downloaded_count"] = len(present_final)
220
+ manifest["files_missing_after_download"] = sorted(missing_final)
221
+ manifest["basename_to_path"] = verified_map
222
+ manifest_path = _write_manifest(args.output_dir, manifest)
223
+ _log_summary(logger, len(needed), len(present_final),
224
+ len(missing_final) + len(missing_in_torrent), manifest_path)
225
+
226
+ return 0 if not missing_final else 1
227
+
228
+
229
+ if __name__ == "__main__":
230
+ sys.exit(main())
hydrate/1_hydrate_dataset.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PluRule Hydrate Step 1: Fill [NEEDS_HYDRATION] placeholders.
4
+
5
+ Reads the dehydrated PluRule dataset + the Pushshift subset produced by
6
+ hydrate/0_download.py, writes hydrated JSON.zst files whose structure matches
7
+ what pipeline/10_assign_cluster_labels.py's hydrated output produces -- except
8
+ that `media_files` paths remain placeholders until hydrate/2_download_media.py
9
+ runs.
10
+
11
+ Subreddits appear across multiple splits (every sub appears in test, many
12
+ in val/train), so we hydrate subreddit-centric rather than split-centric:
13
+ each Pushshift zst file is streamed exactly once, and the extracted
14
+ submissions/comments are distributed to whichever split(s) need them.
15
+
16
+ Per unique subreddit we:
17
+ 1. Union the comment + submission IDs referenced across all splits.
18
+ 2. Stream `{sub}_comments.zst` once, keep only matching IDs.
19
+ 3. Stream `{sub}_submissions.zst` once, keep only matching IDs.
20
+ 4. Fill placeholders in every split's copy of the sub_data.
21
+ 5. Missing IDs become {"hydration_status": "missing", "id": ...}.
22
+ 6. Subreddits whose Pushshift files are absent from the manifest get
23
+ `hydration_status: "source_unavailable"` on every split's sub_data.
24
+
25
+ Usage:
26
+ python hydrate/1_hydrate_dataset.py
27
+ python hydrate/1_hydrate_dataset.py --splits test
28
+ python hydrate/1_hydrate_dataset.py --num-workers 8
29
+ """
30
+
31
+ import argparse
32
+ import json
33
+ import sys
34
+ import time
35
+ from collections import defaultdict
36
+ from multiprocessing import Pool
37
+ from pathlib import Path
38
+ from typing import Any, Dict, List, Set, Tuple
39
+
40
+ # Add repo root to path (for utils/)
41
+ sys.path.append(str(Path(__file__).resolve().parent.parent))
42
+
43
+ try:
44
+ import zstandard
45
+ from tqdm import tqdm
46
+ except ImportError as e:
47
+ sys.exit(
48
+ f"Missing dependency: {e.name}.\n"
49
+ f"Install hydrate requirements: pip install -r requirements-hydrate.txt"
50
+ )
51
+
52
+ from config import PROCESSES, PUSHSHIFT_DATA
53
+ from utils.files import json_loads, read_compressed_json, write_compressed_json
54
+ from utils.logging import setup_stage_logger
55
+
56
+ SPLITS = ("train", "val", "test")
57
+
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # Streaming reader
61
+ # ---------------------------------------------------------------------------
62
+
63
+ _READ_CHUNK = 1 << 24 # 16 MB — matches utils.files.read_and_decode
64
+
65
+
66
+ def iter_zst_jsonl(path: str):
67
+ """Yield parsed JSON objects from a .zst-compressed JSONL file.
68
+
69
+ Bytes-based line split (safe because '\\n' = 0x0A is never inside a
70
+ multibyte UTF-8 sequence). Uses a mutable `bytearray` buffer with a
71
+ cursor to avoid repeated slice allocation.
72
+ """
73
+ with open(path, "rb") as f:
74
+ dctx = zstandard.ZstdDecompressor(max_window_size=2**31)
75
+ with dctx.stream_reader(f) as reader:
76
+ buf = bytearray()
77
+ while True:
78
+ chunk = reader.read(_READ_CHUNK)
79
+ if not chunk:
80
+ break
81
+ buf.extend(chunk)
82
+ start = 0
83
+ n = len(buf)
84
+ while start < n:
85
+ nl = buf.find(b"\n", start)
86
+ if nl < 0:
87
+ break
88
+ if nl > start:
89
+ try:
90
+ yield json_loads(bytes(buf[start:nl]))
91
+ except Exception:
92
+ pass
93
+ start = nl + 1
94
+ if start:
95
+ del buf[:start]
96
+ if buf:
97
+ try:
98
+ yield json_loads(bytes(buf))
99
+ except Exception:
100
+ pass
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # Per-subreddit helpers
105
+ # ---------------------------------------------------------------------------
106
+
107
+ def _collect_needed_ids(sub_data: Dict) -> Tuple[Set[str], Set[str]]:
108
+ """Union of comment IDs and submission IDs referenced by one sub_data entry."""
109
+ comment_ids: Set[str] = set()
110
+ submission_ids: Set[str] = set(sub_data.get("submissions", {}).keys())
111
+
112
+ for pair in sub_data.get("thread_pairs", []):
113
+ mid = pair.get("mod_comment_id")
114
+ if mid:
115
+ comment_ids.add(mid)
116
+ for tid in pair.get("violating_thread_ids") or []:
117
+ if tid:
118
+ comment_ids.add(tid)
119
+ for tid in pair.get("compliant_thread_ids") or []:
120
+ if tid:
121
+ comment_ids.add(tid)
122
+ return comment_ids, submission_ids
123
+
124
+
125
+ def _extract_by_id(path: str, id_field: str, needed: Set[str]) -> Dict[str, Dict]:
126
+ """Stream a .zst JSONL file; return {id: obj} for ids in `needed`. Early-exits once full."""
127
+ out: Dict[str, Dict] = {}
128
+ if not needed:
129
+ return out
130
+ target = len(needed)
131
+ for obj in iter_zst_jsonl(path):
132
+ oid = obj.get(id_field)
133
+ if oid in needed and oid not in out:
134
+ out[oid] = obj
135
+ if len(out) == target:
136
+ break
137
+ return out
138
+
139
+
140
+ def _fill_sub_data(
141
+ sub_data: Dict,
142
+ comments_by_id: Dict[str, Dict],
143
+ submissions_by_id: Dict[str, Dict],
144
+ split_counts: Dict[str, Any],
145
+ ) -> None:
146
+ """Fill [NEEDS_HYDRATION] placeholders in one sub_data in place."""
147
+ # Submissions
148
+ for sid, entry in sub_data.get("submissions", {}).items():
149
+ obj = submissions_by_id.get(sid)
150
+ if obj is not None:
151
+ entry["submission_object"] = obj
152
+ split_counts["hydrated_submissions"] += 1
153
+ else:
154
+ entry["submission_object"] = {"hydration_status": "missing", "id": sid}
155
+ split_counts["missing_submissions"] += 1
156
+
157
+ # Thread pairs
158
+ for pair in sub_data.get("thread_pairs", []):
159
+ # Mod comment
160
+ mid = pair.get("mod_comment_id")
161
+ mod_obj = comments_by_id.get(mid) if mid else None
162
+ if mod_obj is not None:
163
+ pair["mod_comment"] = mod_obj
164
+ split_counts["hydrated_comments"] += 1
165
+ else:
166
+ pair["mod_comment"] = {"hydration_status": "missing", "id": mid}
167
+ split_counts["missing_comments"] += 1
168
+
169
+ # Threads (root -> leaf, matching Stage 5 output)
170
+ for mode in ("violating", "compliant"):
171
+ ids = pair.get(f"{mode}_thread_ids") or []
172
+ thread: List[Dict] = []
173
+ for level, cid in enumerate(ids):
174
+ obj = comments_by_id.get(cid)
175
+ if obj is not None:
176
+ c = dict(obj)
177
+ c["level"] = level
178
+ thread.append(c)
179
+ split_counts["hydrated_comments"] += 1
180
+ else:
181
+ thread.append({"hydration_status": "missing", "id": cid, "level": level})
182
+ split_counts["missing_comments"] += 1
183
+ pair[f"{mode}_thread"] = thread
184
+
185
+
186
+ def hydrate_subreddit_unified(args: Tuple[str, List[Dict], List[Tuple[str, int]], str, str, Set[str], Set[str]]
187
+ ) -> Tuple[str, List[Dict], List[Tuple[str, int]], Dict[str, Any]]:
188
+ """
189
+ Stream Pushshift files once for a subreddit, fill every split's sub_data copy.
190
+
191
+ Returns (name, hydrated_sub_dicts, placements, stats).
192
+ `placements[i]` is (split, pos) in splits_data[split]["subreddits"] that sub_dicts[i] came from.
193
+ """
194
+ name, sub_dicts, placements, c_path, s_path, c_ids, s_ids = args
195
+
196
+ comments_by_id = _extract_by_id(c_path, "id", c_ids) if c_ids else {}
197
+ submissions_by_id = _extract_by_id(s_path, "id", s_ids) if s_ids else {}
198
+
199
+ stats: Dict[str, Any] = {
200
+ "subreddit": name,
201
+ "splits": [s for s, _ in placements],
202
+ "per_split": {},
203
+ }
204
+
205
+ for (split, _pos), sub_data in zip(placements, sub_dicts):
206
+ per = {
207
+ "hydrated_submissions": 0, "missing_submissions": 0,
208
+ "hydrated_comments": 0, "missing_comments": 0,
209
+ }
210
+ _fill_sub_data(sub_data, comments_by_id, submissions_by_id, per)
211
+ stats["per_split"][split] = per
212
+
213
+ return name, sub_dicts, placements, stats
214
+
215
+
216
+ # ---------------------------------------------------------------------------
217
+ # Orchestration
218
+ # ---------------------------------------------------------------------------
219
+
220
+ def load_manifest(pushshift_dir: Path, logger) -> Dict[str, str]:
221
+ """Load basename -> absolute path map written by hydrate/0_download.py."""
222
+ manifest_path = pushshift_dir / "hydrate_manifest.json"
223
+ if not manifest_path.exists():
224
+ logger.error(
225
+ f"Manifest not found: {manifest_path}. Run hydrate/0_download.py first."
226
+ )
227
+ sys.exit(1)
228
+ with open(manifest_path) as f:
229
+ m = json.load(f)
230
+ b2p = m.get("basename_to_path", {})
231
+ if not b2p:
232
+ logger.error(
233
+ f"{manifest_path} has no `basename_to_path`. Re-run hydrate/0_download.py."
234
+ )
235
+ sys.exit(1)
236
+ return b2p
237
+
238
+
239
+ def main() -> int:
240
+ parser = argparse.ArgumentParser(
241
+ description="Hydrate the PluRule dehydrated dataset using downloaded Pushshift files."
242
+ )
243
+ parser.add_argument("--dataset-dir", type=Path, default=Path("./data"))
244
+ parser.add_argument("--pushshift-dir", type=Path, default=Path(PUSHSHIFT_DATA),
245
+ help=f"Directory containing hydrate_manifest.json (default: {PUSHSHIFT_DATA})")
246
+ parser.add_argument("--output-dir", type=Path, default=Path("./data"))
247
+ parser.add_argument(
248
+ "--splits", nargs="+", choices=SPLITS, default=list(SPLITS),
249
+ help="Splits to hydrate (default: all)",
250
+ )
251
+ parser.add_argument(
252
+ "--num-workers", type=int, default=PROCESSES,
253
+ help=f"Parallel workers (default: {PROCESSES}, from config.PROCESSES). "
254
+ f"Recommend 8-16 for I/O-bound work on network filesystems.",
255
+ )
256
+ args = parser.parse_args()
257
+
258
+ args.output_dir.mkdir(parents=True, exist_ok=True)
259
+
260
+ logger = setup_stage_logger("hydrate1_hydrate_dataset")
261
+ logger.info("=" * 60)
262
+ logger.info("🚀 Hydrate Step 1: Fill [NEEDS_HYDRATION] placeholders")
263
+ logger.info("=" * 60)
264
+
265
+ # 1. Load manifest
266
+ logger.info(f"📋 Loading manifest from {args.pushshift_dir}...")
267
+ basename_to_path = load_manifest(args.pushshift_dir, logger)
268
+ logger.info(f" {len(basename_to_path)} Pushshift files available")
269
+
270
+ # 2. Load ALL selected splits upfront
271
+ splits_data: Dict[str, Dict] = {}
272
+ for split in args.splits:
273
+ path = args.dataset_dir / f"{split}_dehydrated_clustered.json.zst"
274
+ if not path.exists():
275
+ logger.warning(f"⚠️ Skipping {split}: {path} not found")
276
+ continue
277
+ logger.info(f"📂 Loading {path}")
278
+ splits_data[split] = read_compressed_json(str(path))
279
+
280
+ if not splits_data:
281
+ logger.error("No split files loaded")
282
+ sys.exit(1)
283
+
284
+ # 3. Build cross-split index: subreddit -> [(split, pos, sub_data_ref), ...]
285
+ by_subreddit: Dict[str, List[Tuple[str, int, Dict]]] = defaultdict(list)
286
+ for split, data in splits_data.items():
287
+ for pos, sub_data in enumerate(data.get("subreddits", [])):
288
+ name = (sub_data.get("subreddit") or "").lower()
289
+ if name:
290
+ by_subreddit[name].append((split, pos, sub_data))
291
+
292
+ n_unique = len(by_subreddit)
293
+ n_entries = sum(len(v) for v in by_subreddit.values())
294
+ logger.info(f" {n_unique} unique subreddits across {n_entries} split entries "
295
+ f"(saves {n_entries - n_unique} redundant stream passes)")
296
+
297
+ # 4. Build tasks (one per unique subreddit)
298
+ tasks = []
299
+ source_unavailable: List[str] = []
300
+ task_sizes: List[int] = [] # parallels `tasks`; comments-file bytes
301
+
302
+ for name, entries in by_subreddit.items():
303
+ c_path = basename_to_path.get(f"{name}_comments.zst")
304
+ s_path = basename_to_path.get(f"{name}_submissions.zst")
305
+ if not c_path or not s_path:
306
+ for _split, _pos, sub_data in entries:
307
+ sub_data["hydration_status"] = "source_unavailable"
308
+ source_unavailable.append(name)
309
+ continue
310
+
311
+ all_c_ids: Set[str] = set()
312
+ all_s_ids: Set[str] = set()
313
+ for _split, _pos, sub_data in entries:
314
+ c, s = _collect_needed_ids(sub_data)
315
+ all_c_ids |= c
316
+ all_s_ids |= s
317
+
318
+ sub_dicts = [sd for _, _, sd in entries]
319
+ placements = [(split, pos) for split, pos, _ in entries]
320
+ tasks.append((name, sub_dicts, placements, c_path, s_path, all_c_ids, all_s_ids))
321
+ task_sizes.append(0) # filled in next step
322
+
323
+ if source_unavailable:
324
+ logger.warning(f"⚠️ {len(source_unavailable)} subreddits have no Pushshift source "
325
+ f"(marked `hydration_status: source_unavailable`)")
326
+
327
+ # 4b. Stat comments files in parallel and sort tasks largest-first (LPT heuristic).
328
+ # Streaming the whole comments file is the dominant cost; dispatching biggest
329
+ # tasks first keeps workers saturated to the end rather than finishing one
330
+ # huge subreddit alone while everyone else idles.
331
+ import os as _os
332
+ from concurrent.futures import ThreadPoolExecutor as _TPE
333
+
334
+ logger.info(f"📏 Stat-ing {len(tasks)} comments files to sort largest-first...")
335
+ t_stat = time.time()
336
+
337
+ def _stat(path: str) -> int:
338
+ try:
339
+ return _os.path.getsize(path)
340
+ except OSError:
341
+ return 0
342
+
343
+ with _TPE(max_workers=32) as _p:
344
+ task_sizes = list(_p.map(lambda t: _stat(t[3]), tasks))
345
+ logger.info(f" done in {time.time() - t_stat:.1f}s")
346
+
347
+ order = sorted(range(len(tasks)), key=lambda i: task_sizes[i], reverse=True)
348
+ tasks = [tasks[i] for i in order]
349
+ task_sizes = [task_sizes[i] for i in order]
350
+ if tasks:
351
+ top5 = ", ".join(f"r/{tasks[i][0]} ({task_sizes[i] / (1 << 30):.1f} GB)"
352
+ for i in range(min(5, len(tasks))))
353
+ logger.info(f" largest first: {top5}")
354
+
355
+ # 5. Parallel hydration
356
+ logger.info(f"🚀 Hydrating {len(tasks)} unique subreddits ({args.num_workers} workers)...")
357
+ t0 = time.time()
358
+
359
+ # Aggregate per-split stats across all subreddits
360
+ totals_by_split: Dict[str, Dict[str, int]] = {
361
+ split: {"hydrated_submissions": 0, "missing_submissions": 0,
362
+ "hydrated_comments": 0, "missing_comments": 0}
363
+ for split in splits_data
364
+ }
365
+
366
+ with Pool(args.num_workers) as pool, tqdm(total=len(tasks), desc="subreddits") as pbar:
367
+ for name, hydrated_dicts, placements, stats in pool.imap_unordered(
368
+ hydrate_subreddit_unified, tasks):
369
+ # Replace sub_data in each split (pickling lost the by-reference link)
370
+ for (split, pos), hydrated in zip(placements, hydrated_dicts):
371
+ splits_data[split]["subreddits"][pos] = hydrated
372
+ # Accumulate per-split totals
373
+ for split, per in stats["per_split"].items():
374
+ for k, v in per.items():
375
+ totals_by_split[split][k] += v
376
+ pbar.update(1)
377
+
378
+ elapsed = time.time() - t0
379
+ logger.info(f"✅ Hydrated in {elapsed:.1f}s")
380
+
381
+ # 6. Write each split
382
+ summary: Dict[str, Any] = {
383
+ "hydration_date": time.strftime("%Y-%m-%d %H:%M:%S"),
384
+ "dataset_dir": str(args.dataset_dir),
385
+ "pushshift_dir": str(args.pushshift_dir),
386
+ "output_dir": str(args.output_dir),
387
+ "unique_subreddits": n_unique,
388
+ "split_entries": n_entries,
389
+ "source_unavailable_count": len(source_unavailable),
390
+ "source_unavailable": source_unavailable,
391
+ "hydration_elapsed_s": round(elapsed, 1),
392
+ "splits": {},
393
+ }
394
+
395
+ for split, data in splits_data.items():
396
+ data.setdefault("metadata", {})
397
+ data["metadata"]["hydrated_from"] = "dehydrated_clustered"
398
+ data["metadata"]["hydration_date"] = time.strftime("%Y-%m-%d %H:%M:%S")
399
+ data["metadata"].pop("instructions", None)
400
+
401
+ out_path = args.output_dir / f"{split}_hydrated_clustered.json.zst"
402
+ size_mb = write_compressed_json(data, str(out_path))
403
+
404
+ totals = totals_by_split[split]
405
+ logger.info(f"💾 {split}: {out_path} ({size_mb:.1f} MB) — "
406
+ f"subs:{totals['hydrated_submissions']:,}/{totals['missing_submissions']:,} miss, "
407
+ f"cmts:{totals['hydrated_comments']:,}/{totals['missing_comments']:,} miss")
408
+
409
+ summary["splits"][split] = {
410
+ "output": str(out_path),
411
+ "size_mb": round(size_mb, 1),
412
+ "totals": totals,
413
+ }
414
+
415
+ summary_path = args.output_dir / "hydrate_summary.json"
416
+ with open(summary_path, "w") as f:
417
+ json.dump(summary, f, indent=2)
418
+ logger.info(f"📊 Summary: {summary_path}")
419
+
420
+ # Partial hydration is acceptable; exit 0 regardless.
421
+ return 0
422
+
423
+
424
+ if __name__ == "__main__":
425
+ sys.exit(main())
hydrate/2_download_media.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ PluRule Hydrate Step 2: Download media for hydrated submissions.
4
+
5
+ Iterates the hydrated JSON.zst files produced by hydrate/1_hydrate_dataset.py,
6
+ downloads each submission's media via the shared `utils.media` helper, and
7
+ writes the actual local file paths back into each submission's `media_files`
8
+ (replacing the `[NEEDS_HYDRATION]` placeholders).
9
+
10
+ Priority hierarchy and filtering rules match pipeline/7_collect_media.py
11
+ (same shared helper). Media downloads are best-effort — dead URLs are
12
+ expected and don't abort the script; failures are counted and reported.
13
+
14
+ Usage:
15
+ python hydrate/2_download_media.py
16
+ python hydrate/2_download_media.py --splits test
17
+ python hydrate/2_download_media.py --num-workers 8
18
+ """
19
+
20
+ import argparse
21
+ import json
22
+ import os
23
+ import sys
24
+ import time
25
+ from collections import defaultdict
26
+ from concurrent.futures import ThreadPoolExecutor, as_completed
27
+ from pathlib import Path
28
+ from typing import Any, Dict, List, Tuple
29
+
30
+ sys.path.append(str(Path(__file__).resolve().parent.parent))
31
+
32
+ try:
33
+ from tqdm import tqdm
34
+ except ImportError as e:
35
+ sys.exit(
36
+ f"Missing dependency: {e.name}.\n"
37
+ f"Install hydrate requirements: pip install -r requirements-hydrate.txt"
38
+ )
39
+
40
+ from utils.files import read_compressed_json, write_compressed_json
41
+ from utils.logging import setup_stage_logger
42
+ from utils.media import categorize_error, create_session, download_submission_media
43
+
44
+ SPLITS = ("train", "val", "test")
45
+
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # Per-submission worker (thread-pool; I/O-bound HTTP)
49
+ # ---------------------------------------------------------------------------
50
+
51
+ def _download_one(args: Tuple[Dict, str]) -> Dict[str, Any]:
52
+ """Download media for one submission; per-thread requests.Session."""
53
+ submission_obj, media_dir = args
54
+ session = _thread_local_session()
55
+ return download_submission_media(submission_obj, media_dir, session)
56
+
57
+
58
+ # ThreadPoolExecutor workers don't persist locals; use module-level cache keyed
59
+ # by thread id so each worker reuses one Session across its tasks.
60
+ import threading
61
+ _SESSIONS = threading.local()
62
+
63
+
64
+ def _thread_local_session():
65
+ s = getattr(_SESSIONS, "session", None)
66
+ if s is None:
67
+ s = create_session()
68
+ _SESSIONS.session = s
69
+ return s
70
+
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # Split driver
74
+ # ---------------------------------------------------------------------------
75
+
76
+ def hydrate_split_media(
77
+ split: str,
78
+ dataset_dir: Path,
79
+ media_root: Path,
80
+ num_workers: int,
81
+ skip_existing: bool,
82
+ logger,
83
+ ) -> Dict[str, Any]:
84
+ """Update media_files in a hydrated split in place; return stats."""
85
+ in_path = dataset_dir / f"{split}_hydrated_clustered.json.zst"
86
+ if not in_path.exists():
87
+ logger.warning(f"⚠️ Skipping {split}: {in_path} not found")
88
+ return {}
89
+
90
+ logger.info(f"📂 Loading {in_path}")
91
+ data = read_compressed_json(str(in_path))
92
+
93
+ # Collect tasks: (subreddit_idx, submission_id, submission_obj, media_dir)
94
+ tasks: List[Tuple[int, str, Dict, str]] = []
95
+ skipped_cached = 0
96
+
97
+ for sub_idx, sub_data in enumerate(data.get("subreddits", [])):
98
+ if sub_data.get("hydration_status") == "source_unavailable":
99
+ continue
100
+ subreddit = (sub_data.get("subreddit") or "").lower().strip()
101
+ if not subreddit:
102
+ continue
103
+ media_dir = str(media_root / subreddit)
104
+
105
+ for sub_id, entry in sub_data.get("submissions", {}).items():
106
+ sub_obj = entry.get("submission_object")
107
+ if not isinstance(sub_obj, dict):
108
+ continue
109
+ if sub_obj.get("hydration_status") == "missing":
110
+ continue
111
+
112
+ existing = entry.get("media_files") or []
113
+ already_on_disk = [p for p in existing if isinstance(p, str) and os.path.exists(p)]
114
+ expected = entry.get("num_media", 0)
115
+ if skip_existing and len(already_on_disk) >= expected > 0:
116
+ entry["media_files"] = already_on_disk
117
+ skipped_cached += 1
118
+ continue
119
+
120
+ tasks.append((sub_idx, sub_id, sub_obj, media_dir))
121
+
122
+ if skipped_cached:
123
+ logger.info(f" ✓ {skipped_cached} submissions already have media on disk (skip-existing)")
124
+ logger.info(f" {len(tasks)} submissions to process")
125
+
126
+ if not tasks:
127
+ out_path = dataset_dir / f"{split}_hydrated_clustered.json.zst"
128
+ size_mb = write_compressed_json(data, str(out_path))
129
+ return {
130
+ "split": split, "output": str(out_path), "size_mb": round(size_mb, 1),
131
+ "submissions_processed": 0, "files_downloaded": 0,
132
+ "status_breakdown": {}, "error_breakdown": {},
133
+ }
134
+
135
+ # Parallel downloads. HTTP is I/O-bound → threads, not processes.
136
+ status_counts: Dict[str, int] = defaultdict(int)
137
+ error_counts: Dict[str, int] = defaultdict(int)
138
+ total_files = 0
139
+ submissions: Dict[str, int] = {"processed": 0}
140
+ t0 = time.time()
141
+
142
+ with ThreadPoolExecutor(max_workers=num_workers) as pool, \
143
+ tqdm(total=len(tasks), desc=f"{split} media", unit="sub") as pbar:
144
+ futures = {
145
+ pool.submit(_download_one, (sub_obj, media_dir)): (sub_idx, sub_id)
146
+ for sub_idx, sub_id, sub_obj, media_dir in tasks
147
+ }
148
+ for future in as_completed(futures):
149
+ sub_idx, sub_id = futures[future]
150
+ try:
151
+ result = future.result()
152
+ except Exception as e:
153
+ error_counts[categorize_error(str(e))] += 1
154
+ pbar.update(1)
155
+ continue
156
+
157
+ status_counts[result["status"]] += 1
158
+ total_files += result["files_downloaded"]
159
+ submissions["processed"] += 1
160
+
161
+ for err in result.get("errors", []):
162
+ error_counts[categorize_error(err)] += 1
163
+
164
+ # Update media_files paths in place
165
+ entry = data["subreddits"][sub_idx]["submissions"][sub_id]
166
+ entry["media_files"] = result["file_paths"]
167
+
168
+ pbar.update(1)
169
+
170
+ elapsed = time.time() - t0
171
+ logger.info(f" ✅ {submissions['processed']} submissions, {total_files} files in {elapsed:.1f}s")
172
+
173
+ # Write updated hydrated JSON
174
+ data.setdefault("metadata", {})
175
+ data["metadata"]["media_hydrated_date"] = time.strftime("%Y-%m-%d %H:%M:%S")
176
+ out_path = dataset_dir / f"{split}_hydrated_clustered.json.zst"
177
+ size_mb = write_compressed_json(data, str(out_path))
178
+ logger.info(f"💾 {out_path} ({size_mb:.1f} MB)")
179
+
180
+ return {
181
+ "split": split,
182
+ "output": str(out_path),
183
+ "size_mb": round(size_mb, 1),
184
+ "submissions_processed": submissions["processed"],
185
+ "files_downloaded": total_files,
186
+ "status_breakdown": dict(status_counts),
187
+ "error_breakdown": dict(sorted(error_counts.items(), key=lambda x: -x[1])[:20]),
188
+ "processing_time_seconds": round(elapsed, 1),
189
+ }
190
+
191
+
192
+ # ---------------------------------------------------------------------------
193
+ # Main
194
+ # ---------------------------------------------------------------------------
195
+
196
+ def main() -> int:
197
+ parser = argparse.ArgumentParser(
198
+ description="Download media for hydrated PluRule submissions."
199
+ )
200
+ parser.add_argument(
201
+ "--dataset-dir", type=Path, default=Path("./data"),
202
+ help="Directory containing {split}_hydrated_clustered.json.zst",
203
+ )
204
+ parser.add_argument(
205
+ "--media-dir", type=Path, default=Path("./data/media"),
206
+ help="Root directory for downloaded media (per-subreddit subdirs auto-created)",
207
+ )
208
+ parser.add_argument(
209
+ "--splits", nargs="+", choices=SPLITS, default=list(SPLITS),
210
+ )
211
+ parser.add_argument(
212
+ "--num-workers", type=int, default=16,
213
+ help="Parallel HTTP workers (threads, I/O-bound). Default 16.",
214
+ )
215
+ parser.add_argument(
216
+ "--skip-existing", action="store_true",
217
+ help="Skip submissions whose expected media files already exist on disk.",
218
+ )
219
+ args = parser.parse_args()
220
+
221
+ args.media_dir.mkdir(parents=True, exist_ok=True)
222
+
223
+ logger = setup_stage_logger("hydrate2_download_media")
224
+ logger.info("=" * 60)
225
+ logger.info("🚀 Hydrate Step 2: Download submission media")
226
+ logger.info("=" * 60)
227
+
228
+ all_stats: Dict[str, Dict] = {}
229
+ totals = {"submissions_processed": 0, "files_downloaded": 0}
230
+ start = time.time()
231
+
232
+ for split in args.splits:
233
+ stats = hydrate_split_media(
234
+ split, args.dataset_dir, args.media_dir,
235
+ args.num_workers, args.skip_existing, logger,
236
+ )
237
+ if not stats:
238
+ continue
239
+ all_stats[split] = stats
240
+ totals["submissions_processed"] += stats.get("submissions_processed", 0)
241
+ totals["files_downloaded"] += stats.get("files_downloaded", 0)
242
+
243
+ elapsed = time.time() - start
244
+
245
+ summary = {
246
+ "media_hydration_date": time.strftime("%Y-%m-%d %H:%M:%S"),
247
+ "dataset_dir": str(args.dataset_dir),
248
+ "media_dir": str(args.media_dir),
249
+ "splits": list(all_stats.keys()),
250
+ "totals": totals,
251
+ "total_time_seconds": round(elapsed, 1),
252
+ "per_split": all_stats,
253
+ }
254
+
255
+ summary_path = args.dataset_dir / "hydrate_media_summary.json"
256
+ with open(summary_path, "w") as f:
257
+ json.dump(summary, f, indent=2)
258
+
259
+ logger.info("📊 Summary")
260
+ logger.info(f" processed: {totals['submissions_processed']:,} submissions")
261
+ logger.info(f" files downloaded:{totals['files_downloaded']:,}")
262
+ logger.info(f" time: {elapsed:.1f}s")
263
+ logger.info(f" summary: {summary_path}")
264
+
265
+ return 0
266
+
267
+
268
+ if __name__ == "__main__":
269
+ sys.exit(main())
hydrate/README.md ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hydrating PluRule
2
+
3
+ This directory contains the three scripts a user runs to **reconstitute the full
4
+ PluRule benchmark** from the released dehydrated dataset.
5
+
6
+ If you instead want to rebuild PluRule from scratch starting from the raw
7
+ Pushshift archives, see [`../pipeline/README.md`](../pipeline/README.md).
8
+
9
+ ## Why hydration?
10
+
11
+ The released dataset ships only IDs, metadata, rules, cluster labels, and answer
12
+ options — every comment body, submission, and media file is replaced with a
13
+ `[NEEDS_HYDRATION]` placeholder. This keeps the distribution small and avoids
14
+ redistributing Reddit content that originates from the Pushshift archives. To
15
+ run the benchmark you first populate those placeholders from a local Pushshift
16
+ mirror (which you download from Academic Torrents) and then download the
17
+ submission media.
18
+
19
+ ## Prerequisites
20
+
21
+ - Python **3.10+**
22
+ - `aria2c` on `PATH` (for torrent download)
23
+ - A BitTorrent port open in your firewall
24
+ - **Disk**: plan for several hundred GB to ~1–2 TB for the Pushshift subset.
25
+ Large subreddits (`r/askreddit`, `r/worldnews`, …) contribute most of the
26
+ volume; small subreddits are tens of MB each.
27
+ - **Bandwidth**: torrent throughput depends on seeders; budget several hours.
28
+
29
+ ### Install
30
+
31
+ The quickest path uses the bundled conda env (pulls `aria2` from conda-forge so
32
+ you don't need root):
33
+
34
+ ```bash
35
+ conda env create -f ../environment-hydrate.yml
36
+ conda activate plurule-hydrate
37
+ ```
38
+
39
+ If you already have a Python environment, install the minimal hydrate deps
40
+ from the yml's `pip:` section (`zstandard`, `orjson`, `tqdm`, `requests`,
41
+ `torf`) and make sure `aria2c` is on PATH:
42
+
43
+ ```
44
+ Debian/Ubuntu: sudo apt install aria2
45
+ macOS: brew install aria2
46
+ Fedora/CentOS: sudo dnf install aria2
47
+ No root: conda install -c conda-forge aria2
48
+ ```
49
+
50
+ ### Get the dehydrated dataset
51
+
52
+ Place the three dehydrated split files under `./data/`:
53
+
54
+ ```
55
+ data/
56
+ ├── train_dehydrated_clustered.json.zst
57
+ ├── val_dehydrated_clustered.json.zst
58
+ └── test_dehydrated_clustered.json.zst
59
+ ```
60
+
61
+ <!-- TODO: replace with the HuggingFace / Zenodo URL once the dataset is published -->
62
+
63
+ ## Quick start
64
+
65
+ Three steps, from repo root:
66
+
67
+ ```bash
68
+ # 1. Download the Pushshift subset referenced by the dataset (~3,978 files)
69
+ python hydrate/0_download.py
70
+
71
+ # 2. Fill every [NEEDS_HYDRATION] placeholder using the downloaded archives
72
+ python hydrate/1_hydrate_dataset.py
73
+
74
+ # 3. (Optional) Download submission images
75
+ python hydrate/2_download_media.py
76
+ ```
77
+
78
+ After step 1 the Pushshift subset lives under the path configured in
79
+ `config.PUSHSHIFT_DATA`. After step 2 you have
80
+ `data/{train,val,test}_hydrated_clustered.json.zst`. After step 3 those same
81
+ files have their `media_files` arrays populated with local paths.
82
+
83
+ ---
84
+
85
+ ## 0. `0_download.py` — fetch the Pushshift subset
86
+
87
+ Reads the dehydrated splits, computes the set of per-subreddit comment and
88
+ submission files referenced (~3,978 files across ~1,989 subreddits), fetches
89
+ only those from the Arctic Shift / Pushshift
90
+ [academictorrent](https://academictorrents.com/details/3e3f64dee22dc304cdd2546254ca1f8e8ae542b4)
91
+ via `aria2c`, and reorganizes them into a first-letter bucket layout:
92
+
93
+ ```
94
+ <output-dir>/
95
+ ├── a/
96
+ │ ├── askreddit_comments.zst
97
+ │ ├── askreddit_submissions.zst
98
+ │ └── …
99
+ ├── b/
100
+ │ └── …
101
+ └── hydrate_manifest.json
102
+ ```
103
+
104
+ ### Common invocations
105
+
106
+ ```bash
107
+ # Default (reads ./data, writes to config.PUSHSHIFT_DATA)
108
+ python hydrate/0_download.py
109
+
110
+ # Preview torrent match without downloading
111
+ python hydrate/0_download.py --dry-run
112
+
113
+ # Custom output directory
114
+ python hydrate/0_download.py --output-dir /mnt/big/pushshift
115
+
116
+ # Skip the torrent; build manifest from an existing local mirror
117
+ python hydrate/0_download.py --from-dir /gpfs/.../Arcticshift/Subreddits/subreddits
118
+ ```
119
+
120
+ ### Flags
121
+
122
+ | Flag | Default | Purpose |
123
+ |---|---|---|
124
+ | `--dataset-dir` | `./data` | where the three `*_dehydrated_clustered.json.zst` files live |
125
+ | `--output-dir` | `config.PUSHSHIFT_DATA` | destination for Pushshift files |
126
+ | `--torrent-file` | *(fetched)* | use a pre-downloaded `.torrent` instead of the Academic Torrents URL |
127
+ | `--dry-run` | off | preview match report without downloading |
128
+ | `--from-dir` | *(off)* | skip torrent; use an existing local mirror |
129
+
130
+ ### What it writes
131
+
132
+ - Downloaded files under `<output-dir>/<letter>/`
133
+ - `<output-dir>/hydrate_manifest.json` — `basename_to_path` map consumed by step 1
134
+ - `<output-dir>/pushshift.torrent` — cached `.torrent` so re-runs don't re-fetch
135
+
136
+ ### Resuming
137
+
138
+ `aria2c` keeps `.aria2` control files next to each download. Re-running the
139
+ script picks up where it left off. Files already in the letter-bucket layout
140
+ are detected and not re-downloaded.
141
+
142
+ ### Subreddits missing from the torrent
143
+
144
+ Expect a small tail (<2%) of subreddits in the dataset that aren't in this
145
+ particular torrent snapshot (renamed, banned, or post-cutoff subs). The script
146
+ reports them and writes their names to `hydrate_manifest.json`; step 1 marks
147
+ those subreddits with `hydration_status: source_unavailable`.
148
+
149
+ ---
150
+
151
+ ## 1. `1_hydrate_dataset.py` — fill the placeholders
152
+
153
+ Streams each Pushshift file exactly **once** across all three splits (most
154
+ subreddits appear in multiple splits), extracts only the referenced comment
155
+ and submission IDs, and fills the placeholders in each split's JSON.
156
+
157
+ ### Run
158
+
159
+ ```bash
160
+ # Default (reads ./data + config.PUSHSHIFT_DATA, writes ./data)
161
+ python hydrate/1_hydrate_dataset.py
162
+
163
+ # Only one split
164
+ python hydrate/1_hydrate_dataset.py --splits test
165
+
166
+ # Tune parallelism (default from config.PROCESSES)
167
+ python hydrate/1_hydrate_dataset.py --num-workers 16
168
+ ```
169
+
170
+ ### Flags
171
+
172
+ | Flag | Default | Purpose |
173
+ |---|---|---|
174
+ | `--dataset-dir` | `./data` | input dehydrated files |
175
+ | `--pushshift-dir` | `config.PUSHSHIFT_DATA` | where `hydrate_manifest.json` lives |
176
+ | `--output-dir` | `./data` | output hydrated files |
177
+ | `--splits` | all | subset of {train, val, test} |
178
+ | `--num-workers` | `config.PROCESSES` | parallel subreddit workers |
179
+
180
+ ### How it fills things
181
+
182
+ | Placeholder in dehydrated JSON | Filled by step 1 from |
183
+ |---|---|
184
+ | `submissions[sid].submission_object` | `{sub}_submissions.zst` |
185
+ | `thread_pairs[i].mod_comment` | `{sub}_comments.zst` (id = `mod_comment_id`) |
186
+ | `thread_pairs[i].violating_thread` | root→leaf walk of `violating_thread_ids` |
187
+ | `thread_pairs[i].compliant_thread` | root→leaf walk of `compliant_thread_ids` |
188
+ | `submissions[sid].media_files` | **not filled** — see step 2 |
189
+
190
+ Missing IDs (the Pushshift archive doesn't contain them) become
191
+ `{"hydration_status": "missing", "id": ...}` instead of aborting the script.
192
+ Subreddits whose Pushshift files aren't in the manifest have a
193
+ `hydration_status: "source_unavailable"` flag set on their `sub_data`; their
194
+ thread pairs are left with placeholders in place. Partial hydration is fine for
195
+ these data-quality cases, and the script records them in the summary instead
196
+ of aborting.
197
+
198
+ ### Output
199
+
200
+ - `./data/{train,val,test}_hydrated_clustered.json.zst` — same schema as
201
+ `pipeline/10_assign_cluster_labels.py`'s hydrated output
202
+ - `./data/hydrate_summary.json` — per-split counts + list of
203
+ source-unavailable subreddits
204
+
205
+ ---
206
+
207
+ ## 2. `2_download_media.py` — submission images (optional)
208
+
209
+ For each hydrated submission, follows the priority hierarchy
210
+ (`media_metadata` → `url` → `oembed` → `preview`), validates Content-Type,
211
+ caps files at 50 MB, and writes actual local paths into each submission's
212
+ `media_files` array in the hydrated JSON.
213
+
214
+ This step reuses the same extraction + download logic as
215
+ `pipeline/7_collect_media.py` via `utils/media.py`.
216
+
217
+ ### Run
218
+
219
+ ```bash
220
+ # Default
221
+ python hydrate/2_download_media.py
222
+
223
+ # Only test split, more parallelism
224
+ python hydrate/2_download_media.py --splits test --num-workers 32
225
+
226
+ # Skip submissions whose media is already on disk
227
+ python hydrate/2_download_media.py --skip-existing
228
+ ```
229
+
230
+ ### Flags
231
+
232
+ | Flag | Default | Purpose |
233
+ |---|---|---|
234
+ | `--dataset-dir` | `./data` | hydrated files from step 1 |
235
+ | `--media-dir` | `./data/media` | where images land (per-subreddit subdirs) |
236
+ | `--splits` | all | subset of {train, val, test} |
237
+ | `--num-workers` | 16 | HTTP threads (I/O-bound; threads, not processes) |
238
+ | `--skip-existing` | off | keep existing `media_files` paths that still exist on disk |
239
+
240
+ ### What to expect
241
+
242
+ - Media is **best-effort**. Many historical Reddit URLs are dead or rate-limit.
243
+ A 60–80% success rate is typical. The benchmark works fine without 100%
244
+ media coverage; models that don't consume images are unaffected.
245
+ - Videos, crossposts, and NSFW submissions are skipped at the top (same rule
246
+ as the pipeline).
247
+ - Files are named `{submission_id}_{media_id}.{ext}` or
248
+ `{submission_id}_{index}_{safe_media_id}.{ext}` for gallery items.
249
+
250
+ ### Output
251
+
252
+ - `./data/media/<subreddit>/<submission_id>_*.{jpg,png,gif,webp,bmp}`
253
+ - Each `submission.media_files` array in the hydrated JSON now holds real paths
254
+ - `./data/hydrate_media_summary.json` — per-split status / error counts
255
+
256
+ ---
257
+
258
+ ## Output format
259
+
260
+ After all three steps, each `{split}_hydrated_clustered.json.zst` matches the
261
+ schema produced by `pipeline/10_assign_cluster_labels.py`:
262
+
263
+ ```jsonc
264
+ {
265
+ "metadata": { /* split-level, hydration dates, version */ },
266
+ "subreddits": [
267
+ {
268
+ "subreddit": "excel",
269
+ "title": "...",
270
+ "description": "...",
271
+ "language": "en",
272
+ "rules": [ /* full rule objects with cluster ids */ ],
273
+ "subreddit_cluster_id": 2,
274
+ "subreddit_cluster_label": "tech communities",
275
+ "submissions": {
276
+ "<submission_id>": {
277
+ "submission_object": { /* full submission JSON */ },
278
+ "num_media": 1,
279
+ "media_files": ["data/media/excel/<id>_direct.png"]
280
+ }
281
+ },
282
+ "thread_pairs": [
283
+ {
284
+ "mod_comment_id": "...",
285
+ "mod_comment": { /* full comment */ },
286
+ "violating_thread": [ /* root→leaf comments, each with level */ ],
287
+ "compliant_thread": [ /* same */ ],
288
+ "violating_answer_options": [ /* shuffled MCQ */ ],
289
+ "violating_correct_answer": "(c)",
290
+ "compliant_answer_options": [ /* shuffled MCQ */ ],
291
+ "compliant_correct_answer": "(b)",
292
+ "metadata": {
293
+ "rule": "No low-effort posts",
294
+ "rule_cluster_id": 5,
295
+ "rule_cluster_label": "spam / self-promotion",
296
+ /* plus similarity score, depths, scores, ancestor IDs, … */
297
+ }
298
+ }
299
+ ]
300
+ }
301
+ ]
302
+ }
303
+ ```
304
+
305
+ ## Re-running
306
+
307
+ All three scripts are safe to re-run:
308
+
309
+ - Step 0: `aria2c` resumes from `.aria2` control files. Files already in the
310
+ letter-bucket layout are detected and skipped.
311
+ - Step 1: overwrites `*_hydrated_clustered.json.zst` each run.
312
+ - Step 2: with `--skip-existing`, submissions whose media already exists on
313
+ disk are not re-downloaded.
314
+
315
+ ## Troubleshooting
316
+
317
+ | Symptom | Likely cause / fix |
318
+ |---|---|
319
+ | `aria2c not found` | install it (see Prerequisites) |
320
+ | Step 0 very slow | few seeders for some files; try again later, or use `--from-dir` with a local mirror |
321
+ | Step 1 OOMs on a big subreddit | use `--num-workers 1`; the streaming hydrator caps per-subreddit memory at only the needed IDs, not the full file — if you still OOM, file an issue |
322
+ | Step 1 reports many missing IDs for one sub | that subreddit's Pushshift file is truncated or corrupt; re-download just that pair via `aria2c --torrent-file=... --select-file=<idx>` |
323
+ | Step 2 dies with 429s | lower `--num-workers`, the retry logic backs off but heavy parallelism against single hosts (e.g. Imgur) can trip limits |
324
+ | `hydration_status: source_unavailable` on several subs | those subs aren't in the Pushshift torrent snapshot — expected for a small tail of renamed/banned subreddits |
requirements-hydrate.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ zstandard>=0.21.0
2
+ orjson>=3.9.0
3
+ tqdm>=4.65.0
4
+ requests>=2.31.0
5
+ torf>=4.2.0
utils/files.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File processing utilities for Reddit data pipeline.
3
+
4
+ Provides shared functions for reading/writing compressed files,
5
+ filtering by date, and parallel processing.
6
+ """
7
+
8
+ import os
9
+ import zstandard
10
+ import json
11
+ import time
12
+ import multiprocessing
13
+ from typing import Callable, List, Tuple, Dict, Any
14
+
15
+
16
+
17
+
18
+ # JSON parsing with fallback
19
+ try:
20
+ import orjson
21
+ json_loads = orjson.loads
22
+ json_dumps = lambda obj: orjson.dumps(obj).decode('utf-8')
23
+ json_dumps_pretty = lambda obj: orjson.dumps(obj, option=orjson.OPT_INDENT_2).decode('utf-8')
24
+ except ImportError:
25
+ try:
26
+ import ujson
27
+ json_loads = ujson.loads
28
+ json_dumps = ujson.dumps
29
+ json_dumps_pretty = lambda obj: ujson.dumps(obj, indent=2)
30
+ except ImportError:
31
+ json_loads = json.loads
32
+ json_dumps = json.dumps
33
+ json_dumps_pretty = lambda obj: json.dumps(obj, indent=2)
34
+
35
+
36
+ def read_and_decode(reader, chunk_size=2**24, max_window_size=(2**29)*2, previous_chunk=None, bytes_read=0):
37
+ """Recursively decompress and decode chunks with error handling."""
38
+ chunk = reader.read(chunk_size)
39
+ bytes_read += chunk_size
40
+
41
+ if previous_chunk is not None:
42
+ chunk = previous_chunk + chunk
43
+
44
+ try:
45
+ return chunk.decode()
46
+ except UnicodeDecodeError:
47
+ if bytes_read > max_window_size:
48
+ raise UnicodeError(f"Unable to decode frame after reading {bytes_read:,} bytes")
49
+ return read_and_decode(reader, chunk_size, max_window_size, chunk, bytes_read)
50
+
51
+
52
+ def process_zst_file(input_file: str, output_file: str, line_processor: Callable[[str], bool],
53
+ progress_interval: int = 10_000_000, logger=None) -> Dict[str, int]:
54
+ """
55
+ Process a compressed file line by line with single output.
56
+
57
+ Args:
58
+ input_file: Path to input .zst file
59
+ output_file: Path to output .zst file
60
+ line_processor: Function that takes a line and returns True if it should be kept
61
+ progress_interval: Log progress every N lines
62
+ logger: Optional logger for progress messages (if None, uses print)
63
+
64
+ Returns:
65
+ Dictionary with processing statistics
66
+ """
67
+ def single_output_processor(line: str, processors: Dict) -> Dict[str, Any]:
68
+ """Simple wrapper for single output compatibility."""
69
+ if line_processor(line):
70
+ return {'matched': True, 'output_files': [output_file], 'data': line}
71
+ return {'matched': False}
72
+
73
+ return process_zst_file_multi(input_file, single_output_processor, {}, progress_interval, logger)
74
+
75
+
76
+ def process_zst_file_multi(input_file: str, line_processor: Callable[[str, Dict], Dict[str, Any]],
77
+ processor_state: Dict[str, Any], progress_interval: int = 10_000_000, logger=None) -> Dict[str, int]:
78
+ """
79
+ Process a compressed file line by line with multi-output support.
80
+
81
+ Args:
82
+ input_file: Path to input .zst file
83
+ line_processor: Function that takes (line, state) and returns:
84
+ {'matched': bool, 'output_files': List[str], 'data': Any, 'state_updates': Dict}
85
+ or {'matched': False} for skipped lines
86
+ processor_state: Mutable state dict passed to line_processor
87
+ progress_interval: Log progress every N lines
88
+ logger: Optional logger for progress messages (if None, uses print)
89
+
90
+ Returns:
91
+ Dictionary with processing statistics including per-output stats
92
+ """
93
+ stats = {
94
+ "lines_processed": 0,
95
+ "lines_matched": 0,
96
+ "error_lines": 0,
97
+ "output_stats": {}
98
+ }
99
+ start_time = time.time()
100
+
101
+ file_size = os.path.getsize(input_file)
102
+ msg = f"Processing {os.path.basename(input_file)} ({file_size / (1024**3):.1f} GB)"
103
+ if logger:
104
+ logger.info(msg)
105
+ else:
106
+ print(msg)
107
+
108
+ # Track open writers for multiple outputs
109
+ open_writers = {}
110
+
111
+ try:
112
+ # Open input file
113
+ with open(input_file, 'rb') as f:
114
+ reader = zstandard.ZstdDecompressor(max_window_size=2**31).stream_reader(f)
115
+
116
+ buffer = ''
117
+ while True:
118
+ chunk = read_and_decode(reader)
119
+ if not chunk:
120
+ break
121
+
122
+ lines = (buffer + chunk).split("\n")
123
+
124
+ for line in lines[:-1]:
125
+ if line.strip():
126
+ stats["lines_processed"] += 1
127
+
128
+ # Progress logging
129
+ if stats["lines_processed"] % progress_interval == 0:
130
+ elapsed = time.time() - start_time
131
+ rate = stats["lines_processed"] / elapsed if elapsed > 0 else 0
132
+ progress_msg = (f" Progress: {stats['lines_processed']:,} lines, "
133
+ f"{stats['lines_matched']:,} matched ({rate:,.0f} lines/sec)")
134
+ if logger:
135
+ logger.info(progress_msg)
136
+ else:
137
+ print(progress_msg)
138
+
139
+ try:
140
+ result = line_processor(line.strip(), processor_state)
141
+
142
+ if result.get('matched', False):
143
+ output_files = result.get('output_files', [])
144
+ data = result.get('data', line.strip())
145
+
146
+ # Write to each specified output file
147
+ for output_file in output_files:
148
+ # Lazy-open writers
149
+ if output_file not in open_writers:
150
+ ensure_directory(output_file)
151
+ file_handle = open(output_file, 'wb')
152
+ open_writers[output_file] = zstandard.ZstdCompressor(level=3, threads=4).stream_writer(file_handle)
153
+ stats["output_stats"][output_file] = 0
154
+
155
+ # Write data
156
+ writer = open_writers[output_file]
157
+ if isinstance(data, str):
158
+ writer.write(data.encode('utf-8'))
159
+ else:
160
+ writer.write(json_dumps(data).encode('utf-8'))
161
+ writer.write(b'\n')
162
+
163
+ stats["output_stats"][output_file] += 1
164
+
165
+ # Update processor state if provided
166
+ state_updates = result.get('state_updates', {})
167
+ processor_state.update(state_updates)
168
+
169
+ stats["lines_matched"] += 1
170
+
171
+ except Exception:
172
+ stats["error_lines"] += 1
173
+
174
+ buffer = lines[-1]
175
+
176
+ reader.close()
177
+
178
+ # Close all writers
179
+ for output_file, writer in open_writers.items():
180
+ writer.close()
181
+
182
+ except Exception as e:
183
+ # Ensure all writers are closed on error
184
+ for writer in open_writers.values():
185
+ try:
186
+ writer.close()
187
+ except:
188
+ pass
189
+ msg = f"Error processing {input_file}: {e}"
190
+ if logger:
191
+ logger.error(msg)
192
+ else:
193
+ print(msg)
194
+ raise
195
+
196
+ elapsed = time.time() - start_time
197
+ rate = stats["lines_processed"] / elapsed if elapsed > 0 else 0
198
+ msg = (f"Completed {os.path.basename(input_file)}: {stats['lines_processed']:,} lines, "
199
+ f"{stats['lines_matched']:,} matched in {elapsed:.1f}s ({rate:,.0f} lines/sec)")
200
+ if logger:
201
+ logger.info(msg)
202
+ else:
203
+ print(msg)
204
+
205
+ return stats
206
+
207
+
208
+ def read_zst_lines(file_path: str, max_lines: int = None) -> List[str]:
209
+ """
210
+ Read lines from a compressed file.
211
+
212
+ Args:
213
+ file_path: Path to .zst file
214
+ max_lines: Maximum number of lines to read (None = all)
215
+
216
+ Returns:
217
+ List of lines (strings)
218
+ """
219
+ lines = []
220
+ lines_read = 0
221
+
222
+ with open(file_path, 'rb') as f:
223
+ reader = zstandard.ZstdDecompressor(max_window_size=2**31).stream_reader(f)
224
+
225
+ buffer = ''
226
+ while True:
227
+ chunk = read_and_decode(reader)
228
+ if not chunk:
229
+ break
230
+
231
+ chunk_lines = (buffer + chunk).split("\n")
232
+
233
+ for line in chunk_lines[:-1]:
234
+ if line.strip():
235
+ lines.append(line.strip())
236
+ lines_read += 1
237
+
238
+ if max_lines and lines_read >= max_lines:
239
+ reader.close()
240
+ return lines
241
+
242
+ buffer = chunk_lines[-1]
243
+
244
+ reader.close()
245
+
246
+ return lines
247
+
248
+
249
+ def write_json_file(data: Any, file_path: str, pretty: bool = False):
250
+ """Write data to JSON file.
251
+
252
+ Args:
253
+ data: Data to write
254
+ file_path: Path to write to
255
+ pretty: If True, use indentation for readability (for stats/summary files)
256
+ If False, use compact format (for data files like comments/submissions)
257
+ """
258
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
259
+
260
+ with open(file_path, 'w') as f:
261
+ if pretty:
262
+ f.write(json_dumps_pretty(data))
263
+ else:
264
+ f.write(json_dumps(data))
265
+
266
+
267
+ def read_json_file(file_path: str) -> Any:
268
+ """Read data from JSON file."""
269
+ with open(file_path, 'r') as f:
270
+ return json.loads(f.read())
271
+
272
+
273
+ def get_files_in_date_range(folder: str, prefix: str, date_range: Tuple[str, str], logger=None) -> List[str]:
274
+ """
275
+ Get files in a folder that match prefix and fall within date range.
276
+ Searches recursively through subdirectories.
277
+
278
+ Args:
279
+ folder: Directory to search (searches recursively)
280
+ prefix: File prefix (e.g., "RC_", "RS_")
281
+ date_range: Tuple of (start_date, end_date) in YYYY-MM format
282
+ logger: Optional logger for messages (if None, uses print)
283
+
284
+ Returns:
285
+ List of file paths sorted by date (newest first)
286
+ """
287
+ import glob
288
+
289
+ if not os.path.exists(folder):
290
+ msg = f"Warning: Directory {folder} does not exist"
291
+ if logger:
292
+ logger.warning(msg)
293
+ else:
294
+ print(msg)
295
+ return []
296
+
297
+ start_date, end_date = date_range
298
+ files = []
299
+
300
+ # Search recursively for files matching pattern
301
+ pattern = os.path.join(folder, '**', f'{prefix}*.zst')
302
+
303
+ for file_path in glob.glob(pattern, recursive=True):
304
+ filename = os.path.basename(file_path)
305
+
306
+ # Skip corrupted files
307
+ if filename.endswith('corrupted.zst'):
308
+ continue
309
+
310
+ # Check if filename matches expected pattern
311
+ if filename.startswith(prefix) and filename.endswith('.zst'):
312
+ try:
313
+ # Extract date from filename (e.g., RC_2023-01.zst -> 2023-01)
314
+ date_part = filename.split('_')[1].split('.')[0]
315
+
316
+ if start_date <= date_part <= end_date:
317
+ files.append(file_path)
318
+
319
+ except (IndexError, ValueError):
320
+ msg = f"Warning: Could not parse date from filename: {filename}"
321
+ if logger:
322
+ logger.warning(msg)
323
+ else:
324
+ print(msg)
325
+
326
+ # Sort by date (newest first)
327
+ files.sort(reverse=True)
328
+ msg = f"Found {len(files)} {prefix} files in date range {start_date} to {end_date}"
329
+ if logger:
330
+ logger.info(msg)
331
+ else:
332
+ print(msg)
333
+
334
+ return files
335
+
336
+
337
+ def process_files_parallel(files: List[str], process_func: Callable, processes: int = None, logger=None) -> List[Any]:
338
+ """
339
+ Process multiple files in parallel.
340
+
341
+ Args:
342
+ files: List of file paths or argument tuples
343
+ process_func: Function to process each file
344
+ processes: Number of parallel processes (default: from config)
345
+ logger: Optional logger for messages (if None, uses print)
346
+
347
+ Returns:
348
+ List of results from processing
349
+ """
350
+ if processes is None:
351
+ from config import PROCESSES
352
+ processes = PROCESSES
353
+
354
+ msg = f"Processing {len(files)} files with {processes} processes"
355
+ if logger:
356
+ logger.info(msg)
357
+ else:
358
+ print(msg)
359
+ start_time = time.time()
360
+
361
+ with multiprocessing.Pool(processes=processes) as pool:
362
+ results = pool.map(process_func, files)
363
+
364
+ elapsed = time.time() - start_time
365
+ msg = f"Parallel processing completed in {elapsed:.1f}s"
366
+ if logger:
367
+ logger.info(msg)
368
+ else:
369
+ print(msg)
370
+
371
+ return results
372
+
373
+
374
+ def get_file_size_gb(file_path: str) -> float:
375
+ """Get file size in GB."""
376
+ return os.path.getsize(file_path) / (1024**3)
377
+
378
+
379
+ def write_zst_lines(file_path: str, lines: List[str], level: int = 3, threads: int = 4):
380
+ """
381
+ Write lines to a compressed file.
382
+
383
+ Args:
384
+ file_path: Path to output .zst file
385
+ lines: List of strings to write (one per line)
386
+ level: Compression level (1-22, default 3)
387
+ threads: Number of threads for compression (default 4)
388
+ """
389
+ ensure_directory(file_path)
390
+
391
+ with open(file_path, 'wb') as f:
392
+ compressor = zstandard.ZstdCompressor(level=level, threads=threads)
393
+ with compressor.stream_writer(f) as writer:
394
+ for line in lines:
395
+ writer.write(line.encode('utf-8'))
396
+ writer.write(b'\n')
397
+
398
+
399
+ def write_zst_json_objects(file_path: str, objects: List[Any], level: int = 3, threads: int = 4):
400
+ """
401
+ Write JSON objects to a compressed file.
402
+
403
+ Args:
404
+ file_path: Path to output .zst file
405
+ objects: List of objects to write as JSON (one per line)
406
+ level: Compression level (1-22, default 3)
407
+ threads: Number of threads for compression (default 4)
408
+ """
409
+ ensure_directory(file_path)
410
+
411
+ with open(file_path, 'wb') as f:
412
+ compressor = zstandard.ZstdCompressor(level=level, threads=threads)
413
+ with compressor.stream_writer(f) as writer:
414
+ for obj in objects:
415
+ json_line = json_dumps(obj)
416
+ writer.write(json_line.encode('utf-8'))
417
+ writer.write(b'\n')
418
+
419
+
420
+ def ensure_directory(file_path: str):
421
+ """Ensure directory exists for a file path."""
422
+ directory = os.path.dirname(file_path)
423
+ if directory:
424
+ os.makedirs(directory, exist_ok=True)
425
+
426
+
427
+ def write_compressed_json(data: Any, file_path: str, level: int = 3, logger=None) -> float:
428
+ """
429
+ Write a JSON object to a compressed file.
430
+
431
+ Args:
432
+ data: Data to write (will be serialized to JSON)
433
+ file_path: Path to output .zst file
434
+ level: Compression level (1-22, default 3)
435
+ logger: Optional logger for messages
436
+
437
+ Returns:
438
+ Size of compressed file in MB
439
+ """
440
+ ensure_directory(file_path)
441
+
442
+ with open(file_path, 'wb') as f:
443
+ cctx = zstandard.ZstdCompressor(level=level)
444
+ with cctx.stream_writer(f) as compressor:
445
+ try:
446
+ # Try orjson/ujson first (faster)
447
+ json_str = json_dumps(data)
448
+ except (TypeError, ValueError):
449
+ # Fall back to standard json.dumps if orjson fails (e.g., non-string dict keys)
450
+ json_str = json.dumps(data)
451
+ compressor.write(json_str.encode('utf-8'))
452
+
453
+ size_mb = os.path.getsize(file_path) / (1024 * 1024)
454
+
455
+ if logger:
456
+ logger.info(f" ✅ {file_path} ({size_mb:.1f} MB)")
457
+
458
+ return size_mb
459
+
460
+
461
+ def read_compressed_json(file_path: str, logger=None) -> Any:
462
+ """
463
+ Read a JSON object from a compressed file.
464
+
465
+ Args:
466
+ file_path: Path to input .zst file
467
+ logger: Optional logger for messages
468
+
469
+ Returns:
470
+ Deserialized JSON data
471
+ """
472
+ if logger:
473
+ logger.info(f" Loading {file_path}...")
474
+
475
+ with open(file_path, 'rb') as f:
476
+ dctx = zstandard.ZstdDecompressor()
477
+ with dctx.stream_reader(f) as reader:
478
+ data = json_loads(reader.read().decode('utf-8'))
479
+
480
+ return data
utils/logging.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Centralized logging utilities for Reddit mod collection pipeline.
3
+ Simple unified logger that works for both main process and multiprocessing.
4
+ """
5
+
6
+ import logging
7
+ import multiprocessing
8
+ import os
9
+ import re
10
+ from datetime import datetime
11
+ from pathlib import Path
12
+ from utils.files import ensure_directory
13
+
14
+
15
+ def setup_stage_logger(stage_name: str, log_level: str = "INFO", worker_identifier: str = None) -> logging.Logger:
16
+ """
17
+ Set up a unified logger for a pipeline stage that works with multiprocessing.
18
+ Creates stage-specific directories and separate logs for main vs worker processes.
19
+
20
+ Args:
21
+ stage_name: Name of the stage (e.g., "stage1_collect_mod_comments")
22
+ log_level: Logging level (DEBUG, INFO, WARNING, ERROR)
23
+ worker_identifier: Meaningful name for worker (e.g., "RC_2023-02", "askreddit").
24
+ If provided, creates worker log; if None, creates main log.
25
+
26
+ Returns:
27
+ Configured logger instance that works in both main and worker processes
28
+ """
29
+ from config import PATHS
30
+
31
+ # Extract stage number from stage_name (e.g., "stage1_collect_mod_comments" -> "1")
32
+ stage_match = re.match(r'stage(\d+)_', stage_name)
33
+ stage_num = stage_match.group(1) if stage_match else "unknown"
34
+
35
+ # Create stage-specific log directory using full stage name
36
+ base_log_dir = Path(PATHS['logs'])
37
+ stage_log_dir = base_log_dir / stage_name
38
+ stage_log_dir.mkdir(parents=True, exist_ok=True)
39
+
40
+ # Create timestamp for log file
41
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
42
+
43
+ # Simple naming for main vs worker processes
44
+ if worker_identifier:
45
+ # Use meaningful worker identifier (e.g., "RC_2023-02", "askreddit", "subreddits/askreddit")
46
+ log_file = stage_log_dir / f"{worker_identifier}_{timestamp}.log"
47
+ # Ensure parent directory exists for the log file (handles subdirectories in worker_identifier)
48
+ ensure_directory(str(log_file))
49
+ else:
50
+ log_file = stage_log_dir / f"main_{timestamp}.log"
51
+
52
+ # Create logger with process-safe name
53
+ if worker_identifier:
54
+ logger_name = f"{stage_name}_{worker_identifier}"
55
+ else:
56
+ logger_name = f"{stage_name}_main"
57
+ logger = logging.getLogger(logger_name)
58
+ logger.setLevel(getattr(logging, log_level.upper()))
59
+
60
+ # Clear any existing handlers to avoid duplicates
61
+ logger.handlers.clear()
62
+
63
+ # Create formatters with process info
64
+ file_formatter = logging.Formatter(
65
+ '%(asctime)s - PID:%(process)d - %(levelname)s - %(message)s',
66
+ datefmt='%Y-%m-%d %H:%M:%S'
67
+ )
68
+
69
+ console_formatter = logging.Formatter(
70
+ 'PID:%(process)d - %(levelname)s - %(message)s'
71
+ )
72
+
73
+ # Thread-safe file handler (multiple processes can write to same file)
74
+ file_handler = logging.FileHandler(log_file, encoding='utf-8')
75
+ file_handler.setLevel(logging.DEBUG) # Log everything to file
76
+ file_handler.setFormatter(file_formatter)
77
+
78
+ # Note: Using default file handler locking for multiprocessing safety
79
+ logger.addHandler(file_handler)
80
+
81
+ # Console handler (for real-time feedback)
82
+ console_handler = logging.StreamHandler()
83
+ console_handler.setLevel(getattr(logging, log_level.upper()))
84
+ console_handler.setFormatter(console_formatter)
85
+ logger.addHandler(console_handler)
86
+
87
+ # Log the initialization
88
+ if worker_identifier:
89
+ logger.info(f"Worker logger initialized for {stage_name} ({worker_identifier})")
90
+ else:
91
+ logger.info(f"Main logger initialized for {stage_name}")
92
+ logger.info(f"Log file: {log_file}")
93
+
94
+ return logger
95
+
96
+
97
+ def get_stage_logger(stage_num: int, stage_description: str = None, worker_identifier: str = None) -> logging.Logger:
98
+ """
99
+ Get a logger for a specific stage number.
100
+
101
+ Args:
102
+ stage_num: Stage number (0-9)
103
+ stage_description: Optional description for the stage
104
+ worker_identifier: Meaningful name for worker (e.g., "RC_2023-02", "askreddit").
105
+ If provided, creates worker log; if None, creates main log.
106
+
107
+ Returns:
108
+ Configured logger instance
109
+ """
110
+ if stage_description:
111
+ stage_name = f"stage{stage_num}_{stage_description}"
112
+ else:
113
+ stage_name = f"stage{stage_num}"
114
+
115
+ return setup_stage_logger(stage_name, worker_identifier=worker_identifier)
116
+
117
+
118
+ def log_stage_start(logger: logging.Logger, stage_num: int, stage_name: str):
119
+ """Log the start of a pipeline stage."""
120
+ logger.info("=" * 60)
121
+ logger.info(f"🚀 Stage {stage_num}: {stage_name}")
122
+ logger.info("=" * 60)
123
+
124
+
125
+ def log_stage_end(logger: logging.Logger, stage_num: int, success: bool = True, elapsed_time: float = None):
126
+ """Log the end of a pipeline stage."""
127
+ status = "✅ COMPLETED" if success else "❌ FAILED"
128
+ time_str = f" in {elapsed_time:.1f}s" if elapsed_time else ""
129
+ logger.info(f"{status}: Stage {stage_num}{time_str}")
130
+ logger.info("=" * 60)
131
+
132
+
133
+ def log_progress(logger: logging.Logger, current: int, total: int, item_name: str = "items"):
134
+ """Log progress with percentage."""
135
+ percentage = (current / total) * 100 if total > 0 else 0
136
+ logger.info(f"📊 Progress: {current:,}/{total:,} {item_name} ({percentage:.1f}%)")
137
+
138
+
139
+ def log_stats(logger: logging.Logger, stats_dict: dict, title: str = "Statistics"):
140
+ """Log statistics in a formatted way."""
141
+ logger.info(f"📈 {title}:")
142
+ for key, value in stats_dict.items():
143
+ if isinstance(value, (int, float)):
144
+ logger.info(f" {key}: {value:,}")
145
+ else:
146
+ logger.info(f" {key}: {value}")
147
+
148
+
149
+ def log_error_and_continue(logger: logging.Logger, error: Exception, context: str = ""):
150
+ """Log an error but continue processing."""
151
+ context_str = f" in {context}" if context else ""
152
+ logger.error(f"❌ Error{context_str}: {str(error)}")
153
+ logger.debug(f"Full traceback{context_str}:", exc_info=True)
154
+
155
+
156
+ def log_file_operation(logger: logging.Logger, operation: str, file_path: str, success: bool = True):
157
+ """Log file operations (read, write, etc.)."""
158
+ status = "✅" if success else "❌"
159
+ logger.debug(f"{status} {operation}: {file_path}")
utils/media.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shared media extraction and download helpers.
3
+
4
+ Used by:
5
+ - pipeline/7_collect_media.py (end-to-end reconstruction, iterates per-subreddit
6
+ submission .zst files)
7
+ - hydrate/2_download_media.py (benchmark hydration, iterates submissions embedded
8
+ in hydrated JSON.zst files)
9
+
10
+ Priority hierarchy for URL extraction (early-stopping):
11
+ 1. `media_metadata` — gallery / inline images (1-N items)
12
+ 2. `url` — direct image posts
13
+ 3. `oembed` — video thumbnails
14
+ 4. `preview` — Reddit-cached preview images
15
+
16
+ Downloads are validated (Content-Type allowlist) and capped at MAX_FILE_SIZE.
17
+ NSFW / crosspost / video submissions are skipped at the top of
18
+ `download_submission_media`.
19
+ """
20
+
21
+ import os
22
+ import time
23
+ import urllib.parse
24
+ from typing import Any, Dict, List, Optional, Tuple
25
+
26
+ import requests
27
+ from requests.adapters import HTTPAdapter
28
+ from urllib3.util.retry import Retry
29
+
30
+ from utils.files import ensure_directory
31
+
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Constants
35
+ # ---------------------------------------------------------------------------
36
+
37
+ USER_AGENT = "reddit_research_media_collector/1.0"
38
+
39
+ # Download limits
40
+ DOWNLOAD_TIMEOUT = 15 # seconds per request
41
+ MAX_FILE_SIZE = 50 * 1024 * 1024 # 50 MB hard cap
42
+ REQUEST_DELAY = 0.1 # between downloads for one submission
43
+
44
+ # Domain / extension allowlists
45
+ VIDEO_DOMAINS = frozenset([
46
+ 'v.redd.it', 'youtube.com', 'youtu.be', 'vimeo.com',
47
+ 'streamable.com', 'twitch.tv', 'clips.twitch.tv',
48
+ 'tiktok.com', 'instagram.com', 'dailymotion.com',
49
+ ])
50
+
51
+ EXTENSIONLESS_MEDIA_HOSTS = frozenset([
52
+ 'imgur.com', 'i.imgur.com', 'giphy.com', 'gfycat.com',
53
+ ])
54
+
55
+ IMAGE_EXTENSIONS = frozenset(['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'])
56
+
57
+ VALID_CONTENT_TYPES = frozenset([
58
+ 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp',
59
+ ])
60
+
61
+ CONTENT_TYPE_TO_EXT = {
62
+ 'image/jpeg': '.jpg',
63
+ 'image/png': '.png',
64
+ 'image/gif': '.gif',
65
+ 'image/webp': '.webp',
66
+ 'image/bmp': '.bmp',
67
+ }
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # URL helpers
72
+ # ---------------------------------------------------------------------------
73
+
74
+ def extract_extension_from_url(url: str) -> Optional[str]:
75
+ """Extract image extension from URL path (no dot)."""
76
+ try:
77
+ path = urllib.parse.urlparse(url).path.lower()
78
+ if '.' in path:
79
+ ext = path.split('.')[-1]
80
+ if ext in IMAGE_EXTENSIONS:
81
+ return ext
82
+ except Exception:
83
+ pass
84
+ return None
85
+
86
+
87
+ def is_video_domain(url: str) -> bool:
88
+ try:
89
+ domain = urllib.parse.urlparse(url).netloc.lower()
90
+ return any(vd in domain for vd in VIDEO_DOMAINS)
91
+ except Exception:
92
+ return False
93
+
94
+
95
+ def is_likely_media_url(url: str) -> bool:
96
+ """True if the URL likely points to a downloadable image."""
97
+ try:
98
+ parsed = urllib.parse.urlparse(url)
99
+ domain = parsed.netloc.lower()
100
+ path = parsed.path.lower()
101
+
102
+ if is_video_domain(url) or 'reddit.com/gallery/' in url:
103
+ return False
104
+
105
+ if 'reddit.com' in domain and 'i.redd.it' not in domain:
106
+ return False
107
+
108
+ if '.' in path and path.split('.')[-1] in IMAGE_EXTENSIONS:
109
+ return True
110
+
111
+ return any(host in domain for host in EXTENSIONLESS_MEDIA_HOSTS)
112
+ except Exception:
113
+ return False
114
+
115
+
116
+ def sanitize_media_id(media_id: str, max_length: int = 50) -> str:
117
+ return media_id.replace('|', '_').replace('/', '_').replace('\\', '_')[:max_length]
118
+
119
+
120
+ def categorize_error(error_msg: str) -> str:
121
+ lower = error_msg.lower()
122
+ if '404' in error_msg or 'not found' in lower:
123
+ return '404_not_found'
124
+ if '403' in error_msg or 'forbidden' in lower:
125
+ return '403_forbidden'
126
+ if '429' in error_msg or 'too many' in lower:
127
+ return '429_rate_limited'
128
+ if 'timeout' in lower:
129
+ return 'timeout'
130
+ if 'connection' in lower:
131
+ return 'connection_error'
132
+ if 'ssl' in lower or 'certificate' in lower:
133
+ return 'ssl_error'
134
+ if 'content-type' in lower:
135
+ return 'invalid_content_type'
136
+ return 'other_error'
137
+
138
+
139
+ # ---------------------------------------------------------------------------
140
+ # Session / file download
141
+ # ---------------------------------------------------------------------------
142
+
143
+ def create_session() -> requests.Session:
144
+ """HTTP session with bounded retry for transient server errors."""
145
+ session = requests.Session()
146
+ retry = Retry(
147
+ total=2,
148
+ backoff_factor=0.5,
149
+ status_forcelist=[429, 500, 502, 503, 504],
150
+ allowed_methods=["GET"],
151
+ )
152
+ adapter = HTTPAdapter(max_retries=retry)
153
+ session.mount("http://", adapter)
154
+ session.mount("https://", adapter)
155
+ session.headers.update({'User-Agent': USER_AGENT})
156
+ return session
157
+
158
+
159
+ def download_file(url: str, output_path: str, session: requests.Session) -> Dict[str, Any]:
160
+ """
161
+ Download `url` to `output_path` with Content-Type validation + size cap.
162
+
163
+ Returns: {'success': bool, 'file_size': int, 'extension': str, 'error': str}
164
+ """
165
+ try:
166
+ response = session.get(url, stream=True, timeout=DOWNLOAD_TIMEOUT)
167
+ response.raise_for_status()
168
+
169
+ content_type = response.headers.get('Content-Type', '').lower().split(';')[0].strip()
170
+ if content_type not in VALID_CONTENT_TYPES:
171
+ return {'success': False, 'error': f'Invalid Content-Type: {content_type}'}
172
+
173
+ extension = CONTENT_TYPE_TO_EXT.get(content_type, '.jpg')
174
+
175
+ ensure_directory(output_path)
176
+ file_size = 0
177
+ with open(output_path, 'wb') as f:
178
+ for chunk in response.iter_content(chunk_size=8192):
179
+ if chunk:
180
+ file_size += len(chunk)
181
+ if file_size > MAX_FILE_SIZE:
182
+ os.remove(output_path)
183
+ return {'success': False, 'error': 'File too large'}
184
+ f.write(chunk)
185
+
186
+ return {'success': True, 'file_size': file_size, 'extension': extension}
187
+
188
+ except requests.exceptions.Timeout:
189
+ if os.path.exists(output_path):
190
+ os.remove(output_path)
191
+ return {'success': False, 'error': 'Timeout'}
192
+
193
+ except requests.exceptions.HTTPError as e:
194
+ if os.path.exists(output_path):
195
+ os.remove(output_path)
196
+ return {'success': False, 'error': str(e)}
197
+
198
+ except Exception as e:
199
+ if os.path.exists(output_path):
200
+ os.remove(output_path)
201
+ return {'success': False, 'error': f'Download error: {str(e)[:50]}'}
202
+
203
+
204
+ # ---------------------------------------------------------------------------
205
+ # URL extraction (priority hierarchy)
206
+ # ---------------------------------------------------------------------------
207
+
208
+ def is_video_submission(submission: Dict) -> bool:
209
+ if submission.get('is_video'):
210
+ return True
211
+ url = submission.get('url', '')
212
+ if url and is_video_domain(url):
213
+ return True
214
+ media_metadata = submission.get('media_metadata')
215
+ if media_metadata:
216
+ for info in media_metadata.values():
217
+ if info.get('e') in ['Video', 'RedditVideo']:
218
+ return True
219
+ return False
220
+
221
+
222
+ def make_media_item(url: str, media_id: str, source: str, index: Optional[int] = None) -> Dict:
223
+ url = url.replace('&amp;', '&')
224
+ item = {
225
+ 'url': url,
226
+ 'media_id': media_id,
227
+ 'source': source,
228
+ 'extension_hint': extract_extension_from_url(url),
229
+ }
230
+ if index is not None:
231
+ item['index'] = index
232
+ return item
233
+
234
+
235
+ def extract_media_metadata_urls(submission: Dict) -> List[Dict]:
236
+ media_metadata = submission.get('media_metadata', {})
237
+ if not media_metadata:
238
+ return []
239
+ urls = []
240
+ for idx, (media_id, info) in enumerate(media_metadata.items()):
241
+ if info.get('e') == 'Image' and 's' in info and 'u' in info['s']:
242
+ urls.append(make_media_item(info['s']['u'], media_id, 'media_metadata', idx))
243
+ return urls
244
+
245
+
246
+ def extract_url_field(submission: Dict) -> List[Dict]:
247
+ url = submission.get('url', '')
248
+ if url and is_likely_media_url(url):
249
+ return [make_media_item(url, 'direct', 'url')]
250
+ return []
251
+
252
+
253
+ def extract_oembed_url(submission: Dict) -> List[Dict]:
254
+ media = submission.get('media') or submission.get('secure_media')
255
+ if media and 'oembed' in media:
256
+ thumb = media['oembed'].get('thumbnail_url')
257
+ if thumb:
258
+ return [make_media_item(thumb, 'oembed', 'oembed')]
259
+ return []
260
+
261
+
262
+ def extract_preview_url(submission: Dict) -> List[Dict]:
263
+ preview = submission.get('preview')
264
+ if not preview or submission.get('is_self'):
265
+ return []
266
+ try:
267
+ url = preview['images'][0]['source'].get('url')
268
+ if url:
269
+ return [make_media_item(url, 'preview', 'preview')]
270
+ except (KeyError, TypeError, IndexError):
271
+ pass
272
+ return []
273
+
274
+
275
+ def extract_download_urls(submission: Dict) -> Tuple[List[Dict], Optional[str]]:
276
+ """Priority hierarchy with early stop."""
277
+ for extractor, source in [
278
+ (extract_media_metadata_urls, 'media_metadata'),
279
+ (extract_url_field, 'url'),
280
+ (extract_oembed_url, 'oembed'),
281
+ (extract_preview_url, 'preview'),
282
+ ]:
283
+ urls = extractor(submission)
284
+ if urls:
285
+ return urls, source
286
+ return [], None
287
+
288
+
289
+ # ---------------------------------------------------------------------------
290
+ # Top-level per-submission driver
291
+ # ---------------------------------------------------------------------------
292
+
293
+ def download_submission_media(submission: Dict, media_dir: str,
294
+ session: requests.Session) -> Dict[str, Any]:
295
+ """
296
+ Download every media URL for one submission.
297
+
298
+ Skips NSFW, crosspost, and video submissions at the top.
299
+ Filenames: `{media_dir}/{submission_id}_{media_id}.{ext}` (direct/oembed/preview)
300
+ or `{media_dir}/{submission_id}_{index}_{safe_media_id}.{ext}` (gallery).
301
+
302
+ Returns:
303
+ {
304
+ 'submission_id': str,
305
+ 'status': 'complete' | 'partial' | 'failed' | 'no_media'
306
+ | 'skipped_nsfw' | 'skipped_crosspost',
307
+ 'files_downloaded': int,
308
+ 'file_paths': List[str], # absolute paths of successful downloads
309
+ 'source': str | None,
310
+ 'is_video': bool,
311
+ 'errors': List[str],
312
+ }
313
+ """
314
+ submission_id = submission.get('id', 'unknown')
315
+
316
+ if submission.get('over_18') or submission.get('over18'):
317
+ return {
318
+ 'submission_id': submission_id, 'status': 'skipped_nsfw',
319
+ 'files_downloaded': 0, 'file_paths': [], 'errors': [],
320
+ }
321
+ if submission.get('crosspost_parent_list') or submission.get('crosspost_parent'):
322
+ return {
323
+ 'submission_id': submission_id, 'status': 'skipped_crosspost',
324
+ 'files_downloaded': 0, 'file_paths': [], 'errors': [],
325
+ }
326
+
327
+ urls, source = extract_download_urls(submission)
328
+ is_video = is_video_submission(submission)
329
+
330
+ if not urls:
331
+ return {
332
+ 'submission_id': submission_id, 'status': 'no_media',
333
+ 'files_downloaded': 0, 'file_paths': [], 'is_video': is_video,
334
+ 'errors': [],
335
+ }
336
+
337
+ successful = 0
338
+ file_paths: List[str] = []
339
+ errors: List[str] = []
340
+
341
+ for url_info in urls:
342
+ url = url_info['url']
343
+ media_id = url_info['media_id']
344
+ ext_hint = url_info.get('extension_hint')
345
+
346
+ if media_id in ('direct', 'oembed', 'preview'):
347
+ filename_base = f"{submission_id}_{media_id}"
348
+ else:
349
+ idx = url_info.get('index', 0)
350
+ safe_id = sanitize_media_id(media_id)
351
+ filename_base = f"{submission_id}_{idx}_{safe_id}"
352
+
353
+ if ext_hint:
354
+ cached = os.path.join(media_dir, f"{filename_base}.{ext_hint}")
355
+ if os.path.exists(cached):
356
+ successful += 1
357
+ file_paths.append(cached)
358
+ continue
359
+
360
+ temp_path = os.path.join(media_dir, f"{filename_base}.tmp")
361
+ result = download_file(url, temp_path, session)
362
+
363
+ if result['success']:
364
+ final_path = os.path.join(media_dir, f"{filename_base}{result['extension']}")
365
+ if os.path.exists(temp_path):
366
+ os.rename(temp_path, final_path)
367
+ successful += 1
368
+ file_paths.append(final_path)
369
+ else:
370
+ errors.append(result['error'])
371
+
372
+ time.sleep(REQUEST_DELAY)
373
+
374
+ expected = len(urls)
375
+ if successful == expected:
376
+ status = 'complete'
377
+ elif successful > 0:
378
+ status = 'partial'
379
+ else:
380
+ status = 'failed'
381
+
382
+ return {
383
+ 'submission_id': submission_id,
384
+ 'status': status,
385
+ 'files_downloaded': successful,
386
+ 'file_paths': file_paths,
387
+ 'source': source,
388
+ 'is_video': is_video,
389
+ 'errors': errors,
390
+ }
utils/pushshift_download.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shared helpers for fetching the Pushshift/Arctic Shift subreddit torrent.
3
+
4
+ Used by:
5
+ - pipeline/0_download_data.py (full torrent → PUSHSHIFT_DATA)
6
+ - hydrate/0_download.py (subset referenced by dehydrated dataset)
7
+
8
+ Normalises on-disk layout to `<root>/<first-letter>/<Subreddit>_{comments,submissions}.zst`
9
+ regardless of where the files came from (torrent native shards or a pre-existing
10
+ local mirror), so downstream pipeline stages can look up files consistently via
11
+ `<PUSHSHIFT_DATA>/<letter>/<sub>_comments.zst`.
12
+ """
13
+
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import Dict, Iterable, List, Optional, Set, Tuple
20
+
21
+ try:
22
+ import requests
23
+ import torf
24
+ from tqdm import tqdm
25
+ except ImportError as e:
26
+ raise ImportError(
27
+ f"utils.pushshift_download requires `requests`, `torf`, and `tqdm` "
28
+ f"(missing: {e.name}). Install: pip install -r requirements-hydrate.txt"
29
+ )
30
+
31
+
32
+ PUSHSHIFT_INFOHASH = "3e3f64dee22dc304cdd2546254ca1f8e8ae542b4"
33
+ PUSHSHIFT_TORRENT_URL = (
34
+ f"https://academictorrents.com/download/{PUSHSHIFT_INFOHASH}.torrent"
35
+ )
36
+
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Torrent metadata
40
+ # ---------------------------------------------------------------------------
41
+
42
+ def _decode(x):
43
+ """bencode values come back as bytes; normalise to str."""
44
+ return x.decode("utf-8", errors="replace") if isinstance(x, bytes) else x
45
+
46
+
47
+ def fetch_torrent(url: str, dest: Path) -> None:
48
+ """Download .torrent metadata to `dest`."""
49
+ dest.parent.mkdir(parents=True, exist_ok=True)
50
+ resp = requests.get(url, stream=True, timeout=60)
51
+ resp.raise_for_status()
52
+ with open(dest, "wb") as f:
53
+ for chunk in resp.iter_content(1 << 16):
54
+ f.write(chunk)
55
+
56
+
57
+ def ensure_torrent(torrent_path: Path, fallback_url: str = PUSHSHIFT_TORRENT_URL) -> Path:
58
+ """Return a usable .torrent path. Fetches from `fallback_url` if missing."""
59
+ if torrent_path.exists() and torrent_path.stat().st_size > 0:
60
+ print(f"📄 Using cached torrent: {torrent_path}")
61
+ return torrent_path
62
+ print(f"📥 Fetching torrent from {fallback_url}")
63
+ fetch_torrent(fallback_url, torrent_path)
64
+ return torrent_path
65
+
66
+
67
+ def parse_torrent(torrent_path: Path) -> List[Tuple[int, str, str]]:
68
+ """
69
+ Return [(1-based index, basename_lower, relative_path)] for every file in the torrent.
70
+
71
+ Uses raw metainfo iteration (orders of magnitude faster than torf's File tree).
72
+ """
73
+ print(" parsing torrent metadata...")
74
+ t = torf.Torrent.read(str(torrent_path))
75
+ info = t.metainfo.get("info", {})
76
+ files_meta = info.get("files")
77
+
78
+ out: List[Tuple[int, str, str]] = []
79
+
80
+ if files_meta is None:
81
+ # Single-file torrent
82
+ basename = _decode(info.get("name", ""))
83
+ if basename:
84
+ out.append((1, basename.lower(), basename))
85
+ return out
86
+
87
+ print(f" torrent contains {len(files_meta):,} file entries")
88
+ for idx, f in enumerate(files_meta, start=1):
89
+ path_parts = f.get("path") or f.get(b"path") or []
90
+ if not path_parts:
91
+ continue
92
+ rel_path = "/".join(_decode(p) for p in path_parts)
93
+ basename_lower = _decode(path_parts[-1]).lower()
94
+ out.append((idx, basename_lower, rel_path))
95
+ return out
96
+
97
+
98
+ def match_basenames(
99
+ all_files: Iterable[Tuple[int, str, str]],
100
+ needed: Optional[Set[str]] = None,
101
+ ) -> Tuple[Dict[str, Tuple[int, str]], Set[str]]:
102
+ """
103
+ Filter parsed torrent entries by a `needed` basename set (all lowercase).
104
+
105
+ If `needed` is None, returns every entry (full-torrent mode).
106
+ Returns (basename_lower -> (index, rel_path), missing-needed set).
107
+ """
108
+ matched: Dict[str, Tuple[int, str]] = {}
109
+ for idx, basename_lower, rel_path in all_files:
110
+ if needed is None or basename_lower in needed:
111
+ matched[basename_lower] = (idx, rel_path)
112
+ missing = set() if needed is None else (needed - set(matched.keys()))
113
+ return matched, missing
114
+
115
+
116
+ # ---------------------------------------------------------------------------
117
+ # aria2c driver
118
+ # ---------------------------------------------------------------------------
119
+
120
+ def check_aria2c() -> None:
121
+ """Abort with install instructions if aria2c isn't on PATH."""
122
+ if shutil.which("aria2c") is None:
123
+ sys.exit(
124
+ "aria2c not found. Install it first:\n"
125
+ " conda (no root): conda install -c conda-forge aria2\n"
126
+ " Debian/Ubuntu: sudo apt install aria2\n"
127
+ " macOS: brew install aria2\n"
128
+ " Fedora/CentOS: sudo dnf install aria2\n"
129
+ "Or download the .torrent manually in any BitTorrent client that supports "
130
+ "file selection (qBittorrent, Transmission)."
131
+ )
132
+
133
+
134
+ def run_aria2c(
135
+ torrent_path: Path,
136
+ indices: Optional[List[int]],
137
+ output_dir: Path,
138
+ ) -> int:
139
+ """
140
+ Invoke aria2c. Returns exit code.
141
+
142
+ If `indices` is None → download all files in the torrent.
143
+ Else → pass `--select-file=i,j,...` (1-based).
144
+ """
145
+ cmd = [
146
+ "aria2c",
147
+ f"--torrent-file={torrent_path}",
148
+ f"--dir={output_dir}",
149
+ "--seed-time=0",
150
+ "--max-connection-per-server=16",
151
+ "--split=16",
152
+ "--continue=true",
153
+ "--file-allocation=none",
154
+ "--bt-save-metadata=false",
155
+ "--bt-remove-unselected-file=true",
156
+ "--console-log-level=warn",
157
+ "--summary-interval=30",
158
+ ]
159
+ if indices is not None:
160
+ cmd.insert(2, f"--select-file=" + ",".join(str(i) for i in sorted(indices)))
161
+ return subprocess.run(cmd).returncode
162
+
163
+
164
+ # ---------------------------------------------------------------------------
165
+ # Layout: first-letter buckets
166
+ # ---------------------------------------------------------------------------
167
+
168
+ def _first_bucket_for(sub_or_basename: str) -> str:
169
+ """First-letter bucket for a subreddit or basename. '_' for non-alphanumeric."""
170
+ head = sub_or_basename.split("_", 1)[0]
171
+ if not head:
172
+ return "_"
173
+ c = head[0].lower()
174
+ return c if c.isalnum() else "_"
175
+
176
+
177
+ def reorganize_to_letter_buckets(
178
+ output_dir: Path,
179
+ basename_to_current_path: Dict[str, str],
180
+ cleanup_empty_dirs: bool = True,
181
+ ) -> Dict[str, str]:
182
+ """
183
+ Move files into `<output_dir>/<first-letter>/<filename>` layout.
184
+ Same-filesystem renames are instantaneous. Returns updated map.
185
+ """
186
+ output_dir = Path(output_dir)
187
+ new_map: Dict[str, str] = {}
188
+ moved = already = 0
189
+
190
+ for basename_lower, current_path in basename_to_current_path.items():
191
+ current = Path(current_path)
192
+ target_dir = output_dir / _first_bucket_for(basename_lower)
193
+ target_dir.mkdir(exist_ok=True)
194
+ # Preserve original filename casing.
195
+ target = target_dir / current.name
196
+
197
+ try:
198
+ same = current.resolve() == target.resolve()
199
+ except FileNotFoundError:
200
+ same = False
201
+
202
+ if same:
203
+ new_map[basename_lower] = str(target)
204
+ already += 1
205
+ continue
206
+
207
+ if target.exists():
208
+ # Duplicate: prefer the target location, remove the stray.
209
+ if current.exists():
210
+ try:
211
+ current.unlink()
212
+ except OSError:
213
+ pass
214
+ new_map[basename_lower] = str(target)
215
+ already += 1
216
+ continue
217
+
218
+ try:
219
+ current.rename(target)
220
+ except OSError:
221
+ # Cross-filesystem fallback
222
+ shutil.move(str(current), str(target))
223
+ new_map[basename_lower] = str(target)
224
+ moved += 1
225
+
226
+ if cleanup_empty_dirs:
227
+ for entry in os.scandir(output_dir):
228
+ if not entry.is_dir(follow_symlinks=False):
229
+ continue
230
+ if len(entry.name) == 1: # keep letter buckets
231
+ continue
232
+ try:
233
+ os.rmdir(entry.path) # non-empty dirs raise OSError; we ignore
234
+ except OSError:
235
+ pass
236
+
237
+ print(f" reorganized: {moved} moved, {already} already in place")
238
+ return new_map
239
+
240
+
241
+ def scan_local_files(
242
+ source_dir: Path,
243
+ needed: Optional[Set[str]] = None,
244
+ ) -> Tuple[List[str], List[str], Dict[str, str]]:
245
+ """
246
+ Enumerate files in a local mirror.
247
+
248
+ Fast path: first-letter bucket layout → ~36 `os.scandir` calls.
249
+ Falls back to full `os.walk` if no letter buckets detected.
250
+
251
+ Returns (present_basenames, missing_basenames, basename_lower -> abs path).
252
+ If `needed` is None → every file found; `missing` is empty.
253
+ """
254
+ source_dir = Path(source_dir)
255
+ if not source_dir.exists():
256
+ return [], sorted(needed or []), {}
257
+
258
+ try:
259
+ top_dirs = [e for e in os.scandir(source_dir) if e.is_dir(follow_symlinks=False)]
260
+ except OSError as e:
261
+ raise RuntimeError(f"Cannot scan {source_dir}: {e}")
262
+
263
+ letter_buckets = [e for e in top_dirs if len(e.name) == 1]
264
+ basename_to_path: Dict[str, str] = {}
265
+
266
+ if letter_buckets:
267
+ print(f" detected first-letter bucket layout ({len(letter_buckets)} buckets)")
268
+ try:
269
+ bucket_iter = tqdm(letter_buckets, desc=" scanning buckets", unit="bucket")
270
+ except Exception:
271
+ bucket_iter = letter_buckets
272
+ for bucket in bucket_iter:
273
+ try:
274
+ with os.scandir(bucket.path) as it:
275
+ for entry in it:
276
+ if entry.is_file(follow_symlinks=False):
277
+ basename_to_path[entry.name.lower()] = entry.path
278
+ except OSError:
279
+ continue
280
+ else:
281
+ print(" no bucket layout detected; full recursive walk...")
282
+ for root, _, files in os.walk(source_dir):
283
+ for f in files:
284
+ basename_to_path[f.lower()] = os.path.join(root, f)
285
+
286
+ if needed is None:
287
+ return sorted(basename_to_path.keys()), [], basename_to_path
288
+
289
+ present = [b for b in needed if b in basename_to_path]
290
+ missing = [b for b in needed if b not in basename_to_path]
291
+ kept = {b: basename_to_path[b] for b in present}
292
+ return present, missing, kept