@auscera/socialscrape 0.0.0-stage → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +111 -2
  2. package/bin/socialscrape.mjs +115 -0
  3. package/engine/README.md +243 -0
  4. package/engine/SKILL.md +194 -0
  5. package/engine/agent.py +665 -0
  6. package/engine/batch_manager.py +622 -0
  7. package/engine/cli.py +23 -0
  8. package/engine/handlers.py +1109 -0
  9. package/engine/plugins/__init__.py +77 -0
  10. package/engine/plugins/instagram-scrape/README.md +164 -0
  11. package/engine/plugins/instagram-scrape/SKILL.md +53 -0
  12. package/engine/plugins/instagram-scrape/cli.py +176 -0
  13. package/engine/plugins/instagram-scrape/core.py +408 -0
  14. package/engine/plugins/instagram-scrape/plugin.json +42 -0
  15. package/engine/plugins/linkedin-scrape/README.md +143 -0
  16. package/engine/plugins/linkedin-scrape/SKILL.md +47 -0
  17. package/engine/plugins/linkedin-scrape/cli.py +126 -0
  18. package/engine/plugins/linkedin-scrape/core.py +188 -0
  19. package/engine/plugins/linkedin-scrape/plugin.json +36 -0
  20. package/engine/plugins/meta-ad-library-scraper/README.md +127 -0
  21. package/engine/plugins/meta-ad-library-scraper/SKILL.md +44 -0
  22. package/engine/plugins/meta-ad-library-scraper/cli.py +161 -0
  23. package/engine/plugins/meta-ad-library-scraper/core.py +348 -0
  24. package/engine/plugins/meta-ad-library-scraper/plugin.json +44 -0
  25. package/engine/plugins/pinterest-scraper/README.md +150 -0
  26. package/engine/plugins/pinterest-scraper/SKILL.md +45 -0
  27. package/engine/plugins/pinterest-scraper/cli.py +193 -0
  28. package/engine/plugins/pinterest-scraper/core.py +420 -0
  29. package/engine/plugins/pinterest-scraper/plugin.json +40 -0
  30. package/engine/plugins/reddit-discussion-scraper/README.md +162 -0
  31. package/engine/plugins/reddit-discussion-scraper/SKILL.md +52 -0
  32. package/engine/plugins/reddit-discussion-scraper/cli.py +218 -0
  33. package/engine/plugins/reddit-discussion-scraper/core.py +546 -0
  34. package/engine/plugins/reddit-discussion-scraper/plugin.json +46 -0
  35. package/engine/plugins/shared/__init__.py +15 -0
  36. package/engine/plugins/shared/paths.py +90 -0
  37. package/engine/plugins/shared/process_runner.py +169 -0
  38. package/engine/plugins/shared/session_manager.py +287 -0
  39. package/engine/plugins/threads-scraper/README.md +139 -0
  40. package/engine/plugins/threads-scraper/SKILL.md +43 -0
  41. package/engine/plugins/threads-scraper/cli.py +178 -0
  42. package/engine/plugins/threads-scraper/core.py +460 -0
  43. package/engine/plugins/threads-scraper/plugin.json +40 -0
  44. package/engine/plugins/tiktok-scrape/README.md +158 -0
  45. package/engine/plugins/tiktok-scrape/SKILL.md +51 -0
  46. package/engine/plugins/tiktok-scrape/cli.py +163 -0
  47. package/engine/plugins/tiktok-scrape/core.py +313 -0
  48. package/engine/plugins/tiktok-scrape/plugin.json +40 -0
  49. package/engine/plugins/twitter-scrape/README.md +158 -0
  50. package/engine/plugins/twitter-scrape/SKILL.md +50 -0
  51. package/engine/plugins/twitter-scrape/cli.py +153 -0
  52. package/engine/plugins/twitter-scrape/core.py +254 -0
  53. package/engine/plugins/twitter-scrape/plugin.json +40 -0
  54. package/engine/plugins/youtube-scrape/README.md +199 -0
  55. package/engine/plugins/youtube-scrape/SKILL.md +115 -0
  56. package/engine/plugins/youtube-scrape/cli.py +340 -0
  57. package/engine/plugins/youtube-scrape/core.py +829 -0
  58. package/engine/plugins/youtube-scrape/plugin.json +48 -0
  59. package/engine/requirements.txt +8 -0
  60. package/engine/socialscrape_cli.py +500 -0
  61. package/engine/storage.py +570 -0
  62. package/engine/ui.py +690 -0
  63. package/package.json +27 -3
@@ -0,0 +1,622 @@
1
+ """
2
+ SocialScrape Batch Processing, Checkpointing & Fail-Safe Recovery Engine (`batch_manager.py`).
3
+ Handles bulk target extraction with persistent JSON state checkpointing,
4
+ exponential backoff retries, jitter throttling, and fail-safe resumption.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import re
11
+ import sys
12
+ import csv
13
+ import time
14
+ import json
15
+ import random
16
+ import subprocess
17
+ from pathlib import Path
18
+ from dataclasses import dataclass, field, asdict
19
+ from typing import List, Dict, Any, Optional, Tuple, Callable
20
+
21
+ from rich.table import Table
22
+ from rich.panel import Panel
23
+ from rich.text import Text
24
+
25
+ from storage import get_root_dir, get_plugins_dir, get_outputs_dir, get_state_dir
26
+ from ui import (
27
+ console,
28
+ COLOR_TEXT,
29
+ COLOR_MUTED,
30
+ COLOR_PRIMARY,
31
+ COLOR_ACCENT,
32
+ COLOR_BORDER,
33
+ render_action_card,
34
+ )
35
+
36
+ ROOT_DIR = get_root_dir()
37
+ PLUGINS_DIR = get_plugins_dir()
38
+ BATCHES_DIR = get_root_dir() / "batches"
39
+ BATCHES_DIR.mkdir(parents=True, exist_ok=True)
40
+
41
+ PLUGIN_CLI_MAP: Dict[str, str] = {
42
+ "youtube": "youtube-scrape",
43
+ "youtube_scrape": "youtube-scrape",
44
+ "youtube-scrape": "youtube-scrape",
45
+ "instagram": "instagram-scrape",
46
+ "instagram_scrape": "instagram-scrape",
47
+ "instagram-scrape": "instagram-scrape",
48
+ "tiktok": "tiktok-scrape",
49
+ "tiktok_scrape": "tiktok-scrape",
50
+ "tiktok-scrape": "tiktok-scrape",
51
+ "linkedin": "linkedin-scrape",
52
+ "linkedin_scrape": "linkedin-scrape",
53
+ "linkedin-scrape": "linkedin-scrape",
54
+ "twitter": "twitter-scrape",
55
+ "twitter_scrape": "twitter-scrape",
56
+ "twitter-scrape": "twitter-scrape",
57
+ "reddit": "reddit-discussion-scraper",
58
+ "reddit_scrape": "reddit-discussion-scraper",
59
+ "reddit-discussion-scraper": "reddit-discussion-scraper",
60
+ "threads": "threads-scraper",
61
+ "threads_scrape": "threads-scraper",
62
+ "threads-scraper": "threads-scraper",
63
+ "pinterest": "pinterest-scraper",
64
+ "pinterest_scrape": "pinterest-scraper",
65
+ "pinterest-scraper": "pinterest-scraper",
66
+ "meta": "meta-ad-library-scraper",
67
+ "meta_ads_scrape": "meta-ad-library-scraper",
68
+ "meta-ad-library-scraper": "meta-ad-library-scraper",
69
+ }
70
+
71
+
72
+ def load_targets_from_file(file_path: Path | str) -> List[str]:
73
+ """
74
+ Parses URLs, usernames, or queries from .txt, .csv, or .md files.
75
+ Deduplicates while preserving order and strips comments/empty lines.
76
+ """
77
+ path = Path(file_path).resolve()
78
+ if not path.exists():
79
+ raise FileNotFoundError(f"Input file not found: {path}")
80
+
81
+ targets: List[str] = []
82
+ seen = set()
83
+
84
+ suffix = path.suffix.lower()
85
+
86
+ if suffix == ".csv":
87
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
88
+ reader = csv.reader(f)
89
+ header_checked = False
90
+ target_col_idx = 0
91
+
92
+ for row in reader:
93
+ if not row:
94
+ continue
95
+ if not header_checked:
96
+ header_lower = [col.strip().lower() for col in row]
97
+ for idx, h in enumerate(header_lower):
98
+ if h in ("url", "target", "link", "handle", "username", "id", "keyword"):
99
+ target_col_idx = idx
100
+ break
101
+ header_checked = True
102
+ if any(h in ("url", "target", "link", "handle", "username") for h in header_lower):
103
+ continue
104
+
105
+ if len(row) > target_col_idx:
106
+ val = row[target_col_idx].strip()
107
+ if val and val not in seen and not val.startswith("#"):
108
+ seen.add(val)
109
+ targets.append(val)
110
+
111
+ else:
112
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
113
+ for line in f:
114
+ clean = line.strip()
115
+ if not clean or clean.startswith("#"):
116
+ continue
117
+
118
+ md_links = re.findall(r"\[.*?\]\((https?://[^\s\)]+)\)", clean)
119
+ if md_links:
120
+ for link in md_links:
121
+ if link not in seen:
122
+ seen.add(link)
123
+ targets.append(link)
124
+ continue
125
+
126
+ urls = re.findall(r"(https?://[^\s\)\*\<\>\"']+)", clean)
127
+ if urls:
128
+ for u in urls:
129
+ if u not in seen:
130
+ seen.add(u)
131
+ targets.append(u)
132
+ else:
133
+ if clean not in seen:
134
+ seen.add(clean)
135
+ targets.append(clean)
136
+
137
+ return targets
138
+
139
+
140
+ @dataclass
141
+ class BatchItem:
142
+ target: str
143
+ status: str = "pending" # "pending", "in_progress", "completed", "failed"
144
+ error: Optional[str] = None
145
+ duration_seconds: float = 0.0
146
+ retries: int = 0
147
+
148
+ def to_dict(self) -> Dict[str, Any]:
149
+ return asdict(self)
150
+
151
+ @classmethod
152
+ def from_dict(cls, data: Dict[str, Any]) -> "BatchItem":
153
+ return cls(
154
+ target=data.get("target", ""),
155
+ status=data.get("status", "pending"),
156
+ error=data.get("error"),
157
+ duration_seconds=data.get("duration_seconds", 0.0),
158
+ retries=data.get("retries", 0),
159
+ )
160
+
161
+
162
+ class BatchQueue:
163
+ """
164
+ Manages queue execution for bulk targets with persistent state checkpointing,
165
+ exponential backoff retries, and randomized rate limiting (jitter).
166
+ """
167
+
168
+ def __init__(
169
+ self,
170
+ platform: str,
171
+ targets: Optional[List[str]] = None,
172
+ extra_args: Optional[List[str]] = None,
173
+ delay_range: Tuple[float, float] = (2.0, 5.0),
174
+ batch_id: Optional[str] = None,
175
+ max_retries: int = 3,
176
+ created_at: Optional[str] = None,
177
+ ):
178
+ self.platform = platform.lower()
179
+ self.plugin_folder = PLUGIN_CLI_MAP.get(self.platform, self.platform)
180
+ self.extra_args = extra_args or []
181
+ self.delay_range = delay_range
182
+ self.batch_id = batch_id or time.strftime("batch_%Y%m%d_%H%M%S")
183
+ self.max_retries = max_retries
184
+ self.created_at = created_at or time.strftime("%Y-%m-%d %H:%M:%S")
185
+ self.status = "in_progress"
186
+ self.items: List[BatchItem] = []
187
+ # Upgraded to JSONL for O(1) append-only hyper-scale persistence
188
+ self.state_file = BATCHES_DIR / f"{self.batch_id}.jsonl"
189
+
190
+ if targets:
191
+ for t in targets:
192
+ self.items.append(BatchItem(target=t))
193
+
194
+ def _append_event(self, event_type: str, payload: Dict[str, Any]) -> None:
195
+ """Appends a single event to the JSONL log in O(1) time."""
196
+ try:
197
+ BATCHES_DIR.mkdir(parents=True, exist_ok=True)
198
+ with open(self.state_file, "a", encoding="utf-8") as f:
199
+ event = {"event": event_type, "timestamp": time.time()}
200
+ event.update(payload)
201
+ f.write(json.dumps(event, ensure_ascii=False) + "\n")
202
+ except (IOError, OSError, PermissionError) as e:
203
+ console.print(f"[dim red]Warning: Could not save batch checkpoint event: {e}[/dim red]")
204
+
205
+ def init_checkpoint(self) -> None:
206
+ """Initializes the batch JSONL file with metadata and pending items."""
207
+ if self.state_file.exists():
208
+ return
209
+
210
+ self._append_event("batch_init", {
211
+ "batch_id": self.batch_id,
212
+ "platform": self.platform,
213
+ "plugin_folder": self.plugin_folder,
214
+ "extra_args": self.extra_args,
215
+ "created_at": self.created_at,
216
+ "total_items": len(self.items)
217
+ })
218
+ # Record initial pending states
219
+ for item in self.items:
220
+ self._append_event("item_update", item.to_dict())
221
+
222
+ def update_item_checkpoint(self, item: BatchItem) -> None:
223
+ """Appends a single item's status update to the JSONL log."""
224
+ self._append_event("item_update", item.to_dict())
225
+
226
+ def update_status_checkpoint(self) -> None:
227
+ """Appends a batch-level status change to the JSONL log."""
228
+ self._append_event("batch_status", {"status": self.status})
229
+
230
+ @classmethod
231
+ def from_file(
232
+ cls,
233
+ file_path: Path | str,
234
+ platform: str,
235
+ extra_args: Optional[List[str]] = None,
236
+ delay_range: Tuple[float, float] = (2.0, 5.0),
237
+ max_retries: int = 3,
238
+ ) -> "BatchQueue":
239
+ """Factory method to construct a BatchQueue directly from an input file."""
240
+ targets = load_targets_from_file(file_path)
241
+ queue = cls(
242
+ platform=platform,
243
+ targets=targets,
244
+ extra_args=extra_args,
245
+ delay_range=delay_range,
246
+ max_retries=max_retries,
247
+ )
248
+ queue.init_checkpoint()
249
+ return queue
250
+
251
+ @classmethod
252
+ def from_checkpoint(cls, checkpoint_file: Path | str) -> "BatchQueue":
253
+ """Reconstructs a BatchQueue from an existing JSONL checkpoint log."""
254
+ path = Path(checkpoint_file).resolve()
255
+ if not path.exists():
256
+ raise FileNotFoundError(f"Checkpoint file not found: {path}")
257
+
258
+ metadata = {}
259
+ items_map = {}
260
+ final_status = "in_progress"
261
+
262
+ with open(path, "r", encoding="utf-8") as f:
263
+ for line in f:
264
+ if not line.strip():
265
+ continue
266
+ try:
267
+ event = json.loads(line)
268
+ if event["event"] == "batch_init":
269
+ metadata = event
270
+ elif event["event"] == "item_update":
271
+ # Overwrite previous states with latest state
272
+ items_map[event["target"]] = event
273
+ elif event["event"] == "batch_status":
274
+ final_status = event["status"]
275
+ except json.JSONDecodeError:
276
+ continue
277
+
278
+ queue = cls(
279
+ platform=metadata.get("platform", "youtube"),
280
+ extra_args=metadata.get("extra_args", []),
281
+ batch_id=metadata.get("batch_id", path.stem),
282
+ created_at=metadata.get("created_at"),
283
+ )
284
+ queue.status = final_status
285
+
286
+ # Restore items while preserving order from initialization if possible
287
+ for item_data in items_map.values():
288
+ # Remove event metadata to cleanly map to BatchItem dataclass
289
+ clean_data = {k: v for k, v in item_data.items() if k in ["target", "status", "error", "duration_seconds", "retries"]}
290
+ queue.items.append(BatchItem.from_dict(clean_data))
291
+
292
+ return queue
293
+
294
+ def run(self) -> Dict[str, Any]:
295
+ """
296
+ Executes pending items in the queue with exponential backoff retries,
297
+ randomized rate limiting, and real-time checkpointing.
298
+ """
299
+ cli_script = PLUGINS_DIR / self.plugin_folder / "cli.py"
300
+ if not cli_script.exists():
301
+ render_action_card(f"[bold red][!] Error: Plugin CLI not found at '{cli_script}'[/bold red]")
302
+ self.status = "failed"
303
+ self.update_status_checkpoint()
304
+ return {"status": "error", "error": "Plugin CLI not found", "completed": 0, "total": len(self.items)}
305
+
306
+ total = len(self.items)
307
+ if total == 0:
308
+ render_action_card("[bold yellow]⚠️ No targets found in batch queue.[/bold yellow]")
309
+ return {"status": "empty", "completed": 0, "total": 0}
310
+
311
+ # Filter items that need execution (pending, in_progress, or previously failed)
312
+ pending_items = [it for it in self.items if it.status != "completed"]
313
+ already_completed = total - len(pending_items)
314
+
315
+ console.print()
316
+ header_text = Text()
317
+ header_text.append("🚀 Batch Extraction & Resilience Engine\n", style=f"bold {COLOR_PRIMARY}")
318
+ header_text.append(
319
+ f"Batch ID: [bold white]{self.batch_id}[/bold white] | "
320
+ f"Platform: [bold white]{self.plugin_folder}[/bold white] | "
321
+ f"Queue: [bold cyan]{len(pending_items)} pending[/bold cyan] ({already_completed} previously completed) | "
322
+ f"Max Retries: [bold yellow]{self.max_retries}[/bold yellow]\n",
323
+ style=f"{COLOR_MUTED}"
324
+ )
325
+ console.print(Panel(header_text, border_style=COLOR_BORDER, padding=(0, 2)))
326
+ console.print()
327
+
328
+ start_time = time.time()
329
+ interrupted = False
330
+
331
+ for idx, item in enumerate(self.items, 1):
332
+ if item.status == "completed":
333
+ continue
334
+
335
+ item.status = "in_progress"
336
+ self.update_item_checkpoint(item)
337
+
338
+ target_str = item.target
339
+ console.print(f"[{COLOR_BORDER}] ┌─ [bold {COLOR_PRIMARY}]Batch Item [{idx}/{total}][/{COLOR_PRIMARY}]: [bold {COLOR_TEXT}]{target_str}[/bold {COLOR_TEXT}][/{COLOR_BORDER}]")
340
+
341
+ cmd = [sys.executable, str(cli_script), target_str]
342
+ if self.extra_args:
343
+ cmd.extend(self.extra_args)
344
+
345
+ out_dir = get_outputs_dir(self.plugin_folder)
346
+ state_dir = get_state_dir()
347
+ out_dir.mkdir(parents=True, exist_ok=True)
348
+ state_dir.mkdir(parents=True, exist_ok=True)
349
+
350
+ child_env = os.environ.copy()
351
+ child_env["SOCIALSCRAPE_OUTPUT_DIR"] = str(out_dir)
352
+ child_env["SOCIALSCRAPE_STATE_DIR"] = str(state_dir)
353
+
354
+ success = False
355
+ for attempt in range(self.max_retries):
356
+ item_start = time.time()
357
+ try:
358
+ res = subprocess.run(cmd, cwd=ROOT_DIR, env=child_env, timeout=180)
359
+ item.duration_seconds += (time.time() - item_start)
360
+
361
+ if res.returncode == 0:
362
+ item.status = "completed"
363
+ item.error = None
364
+ success = True
365
+ console.print(f"[{COLOR_BORDER}] └─ [bold green]✓ Completed in {item.duration_seconds:.1f}s[/bold green][/{COLOR_BORDER}]")
366
+ break
367
+ else:
368
+ item.retries += 1
369
+ item.error = f"Exit code {res.returncode}"
370
+ if attempt < self.max_retries - 1:
371
+ backoff = (2 ** attempt) + random.uniform(0.5, 1.5)
372
+ console.print(f" [{COLOR_MUTED}]⚠️ Scraper exited ({res.returncode}). Retrying in {backoff:.1f}s (attempt {attempt + 2}/{self.max_retries})...[/{COLOR_MUTED}]")
373
+ time.sleep(backoff)
374
+ else:
375
+ console.print(f"[{COLOR_BORDER}] └─ [bold red]✗ Failed after {self.max_retries} attempts ({res.returncode})[/bold red][/{COLOR_BORDER}]")
376
+
377
+ except subprocess.TimeoutExpired:
378
+ item.duration_seconds += (time.time() - item_start)
379
+ item.retries += 1
380
+ item.error = "Process timed out (180s)"
381
+ if attempt < self.max_retries - 1:
382
+ backoff = (2 ** attempt) + random.uniform(1.0, 2.0)
383
+ console.print(f" [{COLOR_MUTED}]⚠️ Process timeout. Retrying in {backoff:.1f}s (attempt {attempt + 2}/{self.max_retries})...[/{COLOR_MUTED}]")
384
+ time.sleep(backoff)
385
+ else:
386
+ console.print(f"[{COLOR_BORDER}] └─ [bold red]✗ Failed after {self.max_retries} timeouts[/bold red][/{COLOR_BORDER}]")
387
+
388
+ except KeyboardInterrupt:
389
+ interrupted = True
390
+ console.print(f"\n[bold yellow]⚠️ Batch interrupted by user during item {idx}/{total}.[/bold yellow]")
391
+ item.status = "pending"
392
+ item.error = "Interrupted by user"
393
+ break
394
+
395
+ except Exception as e:
396
+ item.duration_seconds += (time.time() - item_start)
397
+ item.retries += 1
398
+ item.error = str(e)
399
+ if attempt < self.max_retries - 1:
400
+ backoff = (2 ** attempt) + random.uniform(0.5, 1.5)
401
+ console.print(f" [{COLOR_MUTED}]⚠️ Subprocess error ({e}). Retrying in {backoff:.1f}s...[/{COLOR_MUTED}]")
402
+ time.sleep(backoff)
403
+ else:
404
+ console.print(f"[{COLOR_BORDER}] └─ [bold red]✗ Exception: {e}[/bold red][/{COLOR_BORDER}]")
405
+
406
+ if interrupted:
407
+ self.status = "interrupted"
408
+ self.update_status_checkpoint()
409
+ break
410
+
411
+ if not success:
412
+ item.status = "failed"
413
+
414
+ # Checkpoint after each completed item
415
+ self.update_item_checkpoint(item)
416
+
417
+ # Apply human jitter pacing before next pending item
418
+ has_more = any(it.status != "completed" for it in self.items[idx:])
419
+ if has_more and not interrupted:
420
+ jitter = random.uniform(self.delay_range[0], self.delay_range[1])
421
+ console.print(f" [{COLOR_MUTED}]⏳ Pacing delay: sleeping for {jitter:.1f}s to prevent rate limits...[/{COLOR_MUTED}]")
422
+ time.sleep(jitter)
423
+ console.print()
424
+
425
+ if not interrupted:
426
+ all_done = all(it.status == "completed" for it in self.items)
427
+ self.status = "completed" if all_done else "finished_with_errors"
428
+ self.update_status_checkpoint()
429
+
430
+ total_elapsed = time.time() - start_time
431
+ completed_count = sum(1 for it in self.items if it.status == "completed")
432
+ failed_count = sum(1 for it in self.items if it.status == "failed")
433
+ pending_count = sum(1 for it in self.items if it.status in ("pending", "in_progress"))
434
+
435
+ # Final Batch Summary Table
436
+ summary_table = Table(
437
+ title=f"📊 Batch Checkpoint Summary ({self.batch_id})",
438
+ border_style=COLOR_BORDER,
439
+ show_header=True
440
+ )
441
+ summary_table.add_column("#", style="bold cyan", width=4)
442
+ summary_table.add_column("Target", style=f"bold {COLOR_TEXT}", width=38)
443
+ summary_table.add_column("Status", width=12)
444
+ summary_table.add_column("Retries", width=8)
445
+ summary_table.add_column("Duration", style=f"{COLOR_MUTED}", width=10)
446
+
447
+ for i, it in enumerate(self.items, 1):
448
+ if it.status == "completed":
449
+ status_str = "[bold green]✓ SUCCESS[/bold green]"
450
+ elif it.status == "failed":
451
+ status_str = "[bold red]✗ FAILED[/bold red]"
452
+ elif it.status == "in_progress":
453
+ status_str = "[bold yellow]● RUNNING[/bold yellow]"
454
+ else:
455
+ status_str = "[dim]PENDING[/dim]"
456
+
457
+ dur_str = f"{it.duration_seconds:.1f}s" if it.duration_seconds > 0 else "-"
458
+ summary_table.add_row(str(i), it.target[:36], status_str, str(it.retries), dur_str)
459
+
460
+ console.print()
461
+ console.print(summary_table)
462
+ console.print()
463
+ console.print(
464
+ f"[{COLOR_MUTED}]Total: [bold white]{total}[/bold white] | "
465
+ f"Completed: [bold green]{completed_count}[/bold green] | "
466
+ f"Failed: [bold red]{failed_count}[/bold red] | "
467
+ f"Pending: [bold yellow]{pending_count}[/bold yellow] | "
468
+ f"Elapsed: [bold cyan]{total_elapsed:.1f}s[/bold cyan][/{COLOR_MUTED}]\n"
469
+ )
470
+
471
+ if pending_count > 0:
472
+ console.print(f"[bold yellow]💡 Incomplete batch saved to {self.state_file}. Run [bold cyan]/resume-batch[/bold cyan] anytime to finish remaining items.[/bold yellow]\n")
473
+
474
+ return {
475
+ "batch_id": self.batch_id,
476
+ "platform": self.platform,
477
+ "status": self.status,
478
+ "total": total,
479
+ "completed": completed_count,
480
+ "failed": failed_count,
481
+ "pending": pending_count,
482
+ "elapsed_seconds": total_elapsed,
483
+ }
484
+
485
+
486
+ # ==============================================================================
487
+ # 2. CHECKPOINT DISCOVERY & RESUMPTION HELPERS
488
+ # ==============================================================================
489
+
490
+ def get_incomplete_batches() -> List[Dict[str, Any]]:
491
+ """Scans batches/ folder for any unfinished or interrupted batch state files (.jsonl)."""
492
+ BATCHES_DIR.mkdir(parents=True, exist_ok=True)
493
+ batch_files = sorted(BATCHES_DIR.glob("*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True)
494
+
495
+ incomplete = []
496
+ for f in batch_files:
497
+ try:
498
+ metadata = {}
499
+ items_map = {}
500
+ final_status = "in_progress"
501
+
502
+ with open(f, "r", encoding="utf-8") as fp:
503
+ for line in fp:
504
+ if not line.strip():
505
+ continue
506
+ try:
507
+ event = json.loads(line)
508
+ if event["event"] == "batch_init":
509
+ metadata = event
510
+ elif event["event"] == "item_update":
511
+ items_map[event["target"]] = event
512
+ elif event["event"] == "batch_status":
513
+ final_status = event["status"]
514
+ except json.JSONDecodeError:
515
+ continue
516
+
517
+ pending = sum(1 for it in items_map.values() if it.get("status") in ("pending", "in_progress"))
518
+ if final_status != "completed" or pending > 0:
519
+ metadata["status"] = final_status
520
+ metadata["pending_count"] = pending
521
+ metadata["completed_count"] = len(items_map) - pending
522
+ metadata["total_items"] = len(items_map)
523
+ # Keep file modification time as updated_at for sorting/display
524
+ metadata["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(f.stat().st_mtime))
525
+ incomplete.append(metadata)
526
+ except (IOError, OSError, PermissionError):
527
+ continue
528
+
529
+ return incomplete
530
+
531
+
532
+ def resume_batch(batch_id: Optional[str] = None) -> Dict[str, Any]:
533
+ """Resumes an incomplete batch from its checkpoint file."""
534
+ BATCHES_DIR.mkdir(parents=True, exist_ok=True)
535
+
536
+ if batch_id:
537
+ chk_file = BATCHES_DIR / f"{batch_id}.jsonl"
538
+ if not chk_file.exists():
539
+ render_action_card(f"[bold red][!] Checkpoint file not found: {chk_file}[/bold red]")
540
+ return {"status": "error", "error": "Checkpoint file not found"}
541
+ queue = BatchQueue.from_checkpoint(chk_file)
542
+ return queue.run()
543
+
544
+ incomplete = get_incomplete_batches()
545
+ if not incomplete:
546
+ render_action_card("[bold yellow]⚠️ No incomplete batch checkpoints found in batches/.[/bold yellow]")
547
+ return {"status": "empty", "message": "No incomplete batches"}
548
+
549
+ if len(incomplete) == 1:
550
+ chosen_id = incomplete[0]["batch_id"]
551
+ chk_file = BATCHES_DIR / f"{chosen_id}.jsonl"
552
+ queue = BatchQueue.from_checkpoint(chk_file)
553
+ return queue.run()
554
+
555
+ # If multiple incomplete batches, render picker table
556
+ table = Table(
557
+ title="📂 Incomplete Batch Checkpoints (Select to Resume)",
558
+ border_style=COLOR_BORDER,
559
+ show_header=True
560
+ )
561
+ table.add_column("#", style=f"bold {COLOR_PRIMARY}", width=4)
562
+ table.add_column("Batch ID", style=f"bold {COLOR_TEXT}", width=25)
563
+ table.add_column("Platform", style="cyan", width=12)
564
+ table.add_column("Pending", style="yellow", width=10)
565
+ table.add_column("Completed", style="green", width=10)
566
+ table.add_column("Last Active", style=f"{COLOR_MUTED}", width=19)
567
+
568
+ for idx, b in enumerate(incomplete, 1):
569
+ table.add_row(
570
+ str(idx),
571
+ b.get("batch_id", "-"),
572
+ b.get("platform", "-"),
573
+ str(b.get("pending_count", 0)),
574
+ str(b.get("completed_count", 0)),
575
+ b.get("updated_at", b.get("created_at", "-"))
576
+ )
577
+
578
+ console.print()
579
+ console.print(table)
580
+ console.print()
581
+
582
+ try:
583
+ choice = input(f"Select batch number [1-{len(incomplete)}] to resume (or Enter to cancel): ").strip()
584
+ if not choice:
585
+ return {"status": "cancelled"}
586
+
587
+ idx = int(choice) - 1
588
+ if 0 <= idx < len(incomplete):
589
+ chosen_id = incomplete[idx]["batch_id"]
590
+ chk_file = BATCHES_DIR / f"{chosen_id}.jsonl"
591
+ queue = BatchQueue.from_checkpoint(chk_file)
592
+ return queue.run()
593
+ else:
594
+ render_action_card("[bold yellow]Invalid selection.[/bold yellow]")
595
+ return {"status": "invalid_selection"}
596
+ except (ValueError, KeyboardInterrupt, EOFError):
597
+ return {"status": "cancelled"}
598
+
599
+
600
+ def run_batch_extraction(
601
+ platform: str,
602
+ input_file: Path | str,
603
+ extra_args: Optional[List[str]] = None,
604
+ delay_range: Tuple[float, float] = (2.0, 5.0),
605
+ max_retries: int = 3,
606
+ ) -> Dict[str, Any]:
607
+ """Convenience function to initialize and run a batch extraction from file."""
608
+ try:
609
+ queue = BatchQueue.from_file(
610
+ file_path=input_file,
611
+ platform=platform,
612
+ extra_args=extra_args,
613
+ delay_range=delay_range,
614
+ max_retries=max_retries,
615
+ )
616
+ return queue.run()
617
+ except FileNotFoundError as e:
618
+ render_action_card(f"[bold red][!] File error: {e}[/bold red]")
619
+ return {"status": "error", "error": str(e)}
620
+ except Exception as e:
621
+ render_action_card(f"[bold red][!] Batch error: {e}[/bold red]")
622
+ return {"status": "error", "error": str(e)}
package/engine/cli.py ADDED
@@ -0,0 +1,23 @@
1
+ """
2
+ SocialScrape Master Root CLI Runner (`cli.py`).
3
+ """
4
+
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ _PACKAGE_DIR = str(Path(__file__).parent.resolve())
9
+ if _PACKAGE_DIR in sys.path:
10
+ sys.path.remove(_PACKAGE_DIR)
11
+ sys.path.insert(0, _PACKAGE_DIR)
12
+
13
+ _EVICT_MODULES = ["storage", "ui", "handlers", "agent", "batch_manager", "plugins"]
14
+ for _mod in _EVICT_MODULES:
15
+ if _mod in sys.modules and getattr(sys.modules[_mod], "__file__", ""):
16
+ _mod_file = str(Path(sys.modules[_mod].__file__).resolve())
17
+ if not _mod_file.startswith(_PACKAGE_DIR):
18
+ del sys.modules[_mod]
19
+
20
+ from socialscrape_cli import main
21
+
22
+ if __name__ == "__main__":
23
+ main()