GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — r1tool/r1tool.py at main · nesdeq/r1tool Expand file tree/ Copy pathr1tool.pyMore file actions executable file ·814 lines (642 loc) · 25.3 KB / Copy pathr1tool.pyFile metadata and controlsexecutable file ·814 lines (642 loc) · 25.3 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 #!/usr/bin/env python3 """ r1tool, batch stuff on hole.rabbit.tech via cli - download all images (original + magic cam) - export journal as json - delete entries (all or by month) usage: python r1tool.py """ import json import random import sys import time import re from collections import defaultdict from datetime import datetime from pathlib import Path from urllib.parse import urljoin, urlparse try: import requests except ImportError: print("error: requests library not installed. run: pip install -r requirements.txt") sys.exit(1) try: from rich.console import Console from rich.panel import Panel from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn from rich.table import Table except ImportError: print("error: rich library not installed. run: pip install -r requirements.txt") sys.exit(1) try: import questionary from questionary import Style except ImportError: print("error: questionary library not installed. run: pip install -r requirements.txt") sys.exit(1) console = Console() # Custom style for questionary custom_style = Style([ ('qmark', 'fg:cyan bold'), ('question', 'fg:white bold'), ('answer', 'fg:green bold'), ('pointer', 'fg:cyan bold'), ('highlighted', 'fg:cyan bold'), ('selected', 'fg:green'), ]) # Optional: playwright for browser-based login HAS_PLAYWRIGHT = False try: from playwright.sync_api import sync_playwright HAS_PLAYWRIGHT = True except ImportError: pass # Token storage TOKEN_FILE = Path.home() / ".r1tool_token" class RabbitHoleAPI: """API client for Rabbit R1's Rabbithole""" BASE_URL = "https://hole.rabbit.tech/apis/" HEADERS = { "Accept": "application/json, text/plain, */*", "Accept-Encoding": "gzip, deflate, br, zstd", "Accept-Language": "en-US,en;q=0.9", "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", "Origin": "https://hole.rabbit.tech", "Referer": "https://hole.rabbit.tech/journal/details", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", } def __init__(self, access_token: str): self.access_token = access_token self.session = requests.Session() self.session.headers.update(self.HEADERS) def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None) -> dict: """Make API request with access token""" url = urljoin(self.BASE_URL, endpoint) params = params or {} data = data or {} try: if method.upper() == "GET": params["accessToken"] = self.access_token resp = self.session.get(url, params=params, timeout=30) elif method.upper() == "POST": data["accessToken"] = self.access_token resp = self.session.post(url, json=data, timeout=30) else: raise ValueError(f"Unknown method: {method}") if resp.status_code == 401: raise Exception("Access token expired or invalid") if resp.status_code == 403: raise Exception("Access forbidden - token may be invalid") resp.raise_for_status() return resp.json() if resp.text else {} except requests.exceptions.RequestException as e: raise Exception(f"Request failed: {e}") def fetch_journal(self, limit: int = 1000, offset: int = 0) -> dict: """Fetch journal entries""" return self._request("POST", "fetchUserJournal", data={"limit": limit, "offset": offset}) def fetch_all_journal_entries(self, progress_callback=None) -> list: """Fetch all journal entries with pagination""" all_entries = [] seen_ids = set() offset = 0 limit = 100 while True: try: result = self.fetch_journal(limit=limit, offset=offset) entries = [] if isinstance(result, list): entries = result elif isinstance(result, dict): if "journal" in result and isinstance(result["journal"], dict): entries = result["journal"].get("entries", []) else: entries = result.get("entries", result.get("data", [])) if not entries: break new_entries = [] for entry in entries: eid = entry.get("_id", entry.get("id", entry.get("entryId"))) if eid and eid not in seen_ids: seen_ids.add(eid) new_entries.append(entry) if not new_entries: break all_entries.extend(new_entries) if progress_callback: progress_callback(len(all_entries)) if len(new_entries) < limit: break offset += limit time.sleep(0.3) except Exception: break return all_entries def get_signed_urls(self, urls: list) -> dict: """Get signed URLs for S3 assets""" try: return self._request("GET", "fetchJournalEntryResources", params={ "urls": json.dumps(urls, separators=(',', ':')), }) except Exception: return {} def delete_entry(self, entry_id: str) -> bool: """Delete a single journal entry""" try: self._request("POST", "updateJournalEntry", data={ "entryId": entry_id, "deleteEntry": True }) return True except Exception: return False def get_entry_id(entry: dict) -> str: """Get entry ID""" return entry.get("_id", entry.get("id", entry.get("entryId", "unknown"))) def extract_images_from_entry(entry: dict) -> list: """Extract all image URLs from a journal entry""" images = [] entry_id = get_entry_id(entry) entry_type = entry.get("type", "unknown") dt = get_entry_date(entry) date_str = dt.strftime("%Y%m%d_%H%M%S") if dt else "unknown_date" def add_image(url: str, variant: str = "original"): if url and isinstance(url, str) and (url.startswith("http") or url.startswith("s3://")): images.append({ "url": url, "entry_id": entry_id, "type": entry_type, "variant": variant, "date": date_str, }) if "data" in entry and isinstance(entry["data"], dict): data = entry["data"] if "magicCameraData" in data: mcd = data["magicCameraData"] if isinstance(mcd, dict): if "originalImage" in mcd and isinstance(mcd["originalImage"], dict): add_image(mcd["originalImage"].get("url"), "original") if "aiGeneratedImages" in mcd and isinstance(mcd["aiGeneratedImages"], list): for i, img in enumerate(mcd["aiGeneratedImages"]): if isinstance(img, dict): add_image(img.get("url"), f"magic_{i}" if i > 0 else "magic") if "visionData" in data: vd = data["visionData"] if isinstance(vd, dict): if "image" in vd and isinstance(vd["image"], dict): add_image(vd["image"].get("url"), "vision") add_image(vd.get("imageUrl"), "vision") if "recordingData" in data: rd = data["recordingData"] if isinstance(rd, dict): if "image" in rd and isinstance(rd["image"], dict): add_image(rd["image"].get("url"), "recording") for field in ["imageUrl", "image_url", "image", "originalUrl", "processedUrl"]: if field in data: val = data[field] if isinstance(val, str): add_image(val, "original") elif isinstance(val, dict): add_image(val.get("url"), "original") for field in ["imageUrl", "image_url", "image", "url", "photoUrl", "photo_url"]: if field in entry: val = entry[field] if isinstance(val, str): add_image(val) elif isinstance(val, dict): add_image(val.get("url")) if "images" in entry: imgs = entry["images"] if isinstance(imgs, list): for i, img in enumerate(imgs): if isinstance(img, str): add_image(img, f"image_{i}") elif isinstance(img, dict): add_image(img.get("url", img.get("imageUrl")), img.get("type", f"image_{i}")) return images def download_image(url: str, filepath: Path, session: requests.Session) -> bool: """Download a single image""" try: resp = session.get(url, timeout=60, stream=True) resp.raise_for_status() filepath.parent.mkdir(parents=True, exist_ok=True) with open(filepath, "wb") as f: for chunk in resp.iter_content(chunk_size=8192): f.write(chunk) return True except Exception: return False def sanitize_filename(name: str) -> str: """Remove invalid characters from filename""" return re.sub(r'[<>:"/\\|?*]', '_', name) def get_entry_date(entry: dict) -> datetime | None: """Get datetime from entry""" timestamp = entry.get("createdOn", entry.get("createdAt", entry.get("timestamp", ""))) try: if timestamp: if isinstance(timestamp, (int, float)): return datetime.fromtimestamp(timestamp / 1000 if timestamp > 1e10 else timestamp) else: return datetime.fromisoformat(timestamp.replace("Z", "+00:00")).replace(tzinfo=None) except Exception: pass return None def get_entry_month(entry: dict) -> str | None: """Get month string (YYYY-MM) from entry""" dt = get_entry_date(entry) if dt: return dt.strftime("%Y-%m") return None def load_token() -> str | None: """Load saved token""" if TOKEN_FILE.exists(): try: data = json.loads(TOKEN_FILE.read_text()) return data.get("token") except Exception: pass return None def save_token(token: str): """Save token""" TOKEN_FILE.write_text(json.dumps({"token": token})) def test_token(token: str) -> bool: """Test if token is valid by making a small API request""" try: api = RabbitHoleAPI(token) api.fetch_journal(limit=1, offset=0) return True except Exception: return False def login_with_browser() -> str | None: """Open browser, let user log in manually, capture the access token""" token = None with sync_playwright() as p: browser = p.chromium.launch( headless=False, args=["--disable-blink-features=AutomationControlled"], ) page = browser.new_page() page.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})") def on_request(request): nonlocal token if token or "rabbit.tech/apis/" not in request.url: return if request.method == "POST": try: body = request.post_data_json if body and body.get("accessToken"): token = body["accessToken"] except Exception: pass elif request.method == "GET": from urllib.parse import parse_qs params = parse_qs(urlparse(request.url).query) if "accessToken" in params: token = params["accessToken"][0] page.on("request", on_request) page.goto("https://hole.rabbit.tech") # wait until we capture a token from an API call while not token: try: page.wait_for_timeout(1000) except Exception: break browser.close() return token def prompt_for_token() -> str: """Show instructions and prompt user for token""" console.print() console.print(Panel( "[bold]how to get your access token:[/bold]\n\n" "1. go to [cyan]https://hole.rabbit.tech[/cyan] and log in\n" "2. open browser devtools ([cyan]F12[/cyan]) -> [cyan]network[/cyan] tab\n" "3. reload the page\n" "4. find the [cyan]fetchUserJournal[/cyan] request\n" "5. in the [cyan]payload[/cyan] tab, copy the [cyan]accessToken[/cyan] value", title="token instructions", border_style="cyan" )) console.print() token = questionary.text( "paste your access token:", style=custom_style ).ask() if not token: console.print("[red]no token provided. exiting.[/red]") sys.exit(1) return token def get_token() -> str: """Get token from saved file or prompt user""" token = load_token() if token: console.print("[cyan]testing saved token...[/cyan]") if test_token(token): console.print("[green]saved token is valid[/green]") return token else: console.print("[yellow]saved token is invalid or expired[/yellow]") if HAS_PLAYWRIGHT: method = questionary.select( "how would you like to log in?", choices=["open browser (log in normally)", "paste token (manual)"], style=custom_style ).ask() if method and "browser" in method: console.print("[cyan]opening browser — log in and the token will be captured automatically...[/cyan]") token = login_with_browser() if token and test_token(token): save_token(token) console.print("[green]logged in successfully![/green]") return token else: console.print("[red]could not capture token. try manual paste.[/red]") token = prompt_for_token() if not test_token(token): console.print("[red]token is invalid. exiting.[/red]") sys.exit(1) save_token(token) console.print("[green]token saved![/green]") return token def analyze_entries(entries: list) -> dict: """Analyze entries and return stats""" stats = { "total": len(entries), "types": defaultdict(int), "months": defaultdict(int), "images_count": 0, "date_range": {"start": None, "end": None} } dates = [] for entry in entries: entry_type = entry.get("type", "unknown") stats["types"][entry_type] += 1 month = get_entry_month(entry) if month: stats["months"][month] += 1 images = extract_images_from_entry(entry) stats["images_count"] += len(images) dt = get_entry_date(entry) if dt: dates.append(dt) if dates: stats["date_range"]["start"] = min(dates) stats["date_range"]["end"] = max(dates) return stats def display_stats(stats: dict): """Display journal statistics""" console.print() # Main stats table table = Table(title="journal statistics", border_style="cyan") table.add_column("metric", style="cyan") table.add_column("value", style="green") table.add_row("total entries", str(stats["total"])) table.add_row("total images", str(stats["images_count"])) if stats["date_range"]["start"] and stats["date_range"]["end"]: start = stats["date_range"]["start"].strftime("%Y-%m-%d") end = stats["date_range"]["end"].strftime("%Y-%m-%d") table.add_row("date range", f"{start} to {end}") console.print(table) # Entry types table if stats["types"]: console.print() type_table = Table(title="entry types", border_style="cyan") type_table.add_column("type", style="cyan") type_table.add_column("count", style="green") for entry_type, count in sorted(stats["types"].items(), key=lambda x: -x[1]): type_table.add_row(entry_type, str(count)) console.print(type_table) def filter_entries_by_month(entries: list, month: str) -> list: """Filter entries by month (YYYY-MM format)""" return [e for e in entries if get_entry_month(e) == month] def prompt_month_selection(stats: dict, prompt: str = "select month:") -> str | None: """Prompt user to select a month, return YYYY-MM string or None""" sorted_months = sorted(stats["months"].keys(), reverse=True) if not sorted_months: console.print("[yellow]no entries with dates found.[/yellow]") return None month_choices = [f"{m} ({stats['months'][m]} entries)" for m in sorted_months] selected = questionary.select(prompt, choices=month_choices, style=custom_style).ask() return selected.split(" ")[0] if selected else None def do_export_json(entries: list): """Export journal to JSON""" output = questionary.text( "output filename:", default="journal.json", style=custom_style ).ask() if not output: return output_file = Path(output) export_data = { "exported_at": datetime.now().isoformat(), "total_entries": len(entries), "entries": entries, } with open(output_file, "w") as f: json.dump(export_data, f, indent=2) console.print(f"[green]exported {len(entries)} entries to {output_file.absolute()}[/green]") def do_download_images(api: RabbitHoleAPI, entries: list, label: str = "all"): """Download images from entries""" output = questionary.text( "output directory:", default="./r1_images", style=custom_style ).ask() if not output: return output_dir = Path(output) output_dir.mkdir(parents=True, exist_ok=True) # Collect entries with images entries_with_images = [(e, extract_images_from_entry(e)) for e in entries] entries_with_images = [(e, imgs) for e, imgs in entries_with_images if imgs] total_images = sum(len(imgs) for _, imgs in entries_with_images) if not entries_with_images: console.print("[yellow]no images found in selected entries.[/yellow]") return console.print(f"[cyan]found {total_images} images in {len(entries_with_images)} entries[/cyan]") session = requests.Session() session.headers.update(RabbitHoleAPI.HEADERS) downloaded = 0 failed = 0 skipped = 0 with Progress( SpinnerColumn(), TextColumn("[progress.description]{task.description}"), BarColumn(), TaskProgressColumn(), console=console ) as progress: task = progress.add_task(f"[cyan]downloading {label} images...", total=total_images) for entry, images in entries_with_images: # Get signed URLs s3_urls = [img["url"] for img in images if img["url"].startswith("s3://")] url_map = {} if s3_urls: try: result = api.get_signed_urls(s3_urls) if result and "resources" in result: for s3_url, signed_url in zip(s3_urls, result["resources"]): url_map[s3_url] = signed_url except Exception: pass # Download images for img in images: url = url_map.get(img["url"], img["url"]) if url.startswith("s3://"): failed += 1 progress.advance(task) continue ext = Path(urlparse(url).path).suffix or ".jpg" if not ext or len(ext) > 5: ext = ".jpg" filename = sanitize_filename(f"{img['date']}_{img['entry_id'][:8]}_{img['variant']}{ext}") filepath = output_dir / filename if filepath.exists(): skipped += 1 progress.advance(task) continue if download_image(url, filepath, session): downloaded += 1 else: failed += 1 progress.advance(task) time.sleep(random.uniform(0.1, 0.3)) time.sleep(random.uniform(0.3, 0.8)) console.print() console.print(Panel( f"[green]downloaded:[/green] {downloaded}\n" f"[yellow]skipped (exist):[/yellow] {skipped}\n" f"[red]failed:[/red] {failed}\n" f"[cyan]total:[/cyan] {downloaded + skipped + failed}\n\n" f"saved to: [cyan]{output_dir.absolute()}[/cyan]", title="download complete", border_style="green" )) def do_delete_entries(api: RabbitHoleAPI, entries: list, label: str = "all"): """Delete entries""" if not entries: console.print("[yellow]no entries to delete.[/yellow]") return console.print(f"[red bold]warning: this will permanently delete {len(entries)} entries![/red bold]") confirm = questionary.text( "type 'DELETE' to confirm:", style=custom_style ).ask() if confirm != "DELETE": console.print("[yellow]aborted.[/yellow]") return entry_ids = [get_entry_id(e) for e in entries if get_entry_id(e) != "unknown"] if not entry_ids: console.print("[red]could not extract entry IDs.[/red]") return deleted = 0 failed = 0 with Progress( SpinnerColumn(), TextColumn("[progress.description]{task.description}"), BarColumn(), TaskProgressColumn(), console=console ) as progress: task = progress.add_task(f"[red]deleting {label} entries...", total=len(entry_ids)) for eid in entry_ids: if api.delete_entry(eid): deleted += 1 else: failed += 1 progress.advance(task) time.sleep(random.uniform(0.3, 0.8)) console.print() console.print(Panel( f"[green]deleted:[/green] {deleted}\n" f"[red]failed:[/red] {failed}", title="delete complete", border_style="green" if failed == 0 else "yellow" )) def main(): console.print() console.print(Panel( "[bold cyan]r1tool[/bold cyan], batch stuff on hole.rabbit.tech via cli\n" "download images, export journal, delete entries", border_style="cyan" )) console.print() # Get token token = get_token() api = RabbitHoleAPI(token) # Fetch entries console.print() entries = [] with Progress( SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console ) as progress: task = progress.add_task("[cyan]fetching journal entries...", total=None) def update_progress(count): progress.update(task, description=f"[cyan]fetching journal entries... ({count} found)") entries = api.fetch_all_journal_entries(progress_callback=update_progress) if not entries: console.print("[yellow]no journal entries found.[/yellow]") console.print("[cyan]your journal is empty. nothing to do.[/cyan]") sys.exit(0) # Analyze and display stats stats = analyze_entries(entries) display_stats(stats) # Main menu loop while True: console.print() action = questionary.select( "what would you like to do?", choices=[ "download all images", "download images by month", "export journal as json", "delete all entries", "delete entries by month", "refresh stats", "exit" ], style=custom_style ).ask() if action == "exit" or action is None: console.print("[cyan]goodbye![/cyan]") break elif action == "download all images": do_download_images(api, entries, "all") elif action == "download images by month": month = prompt_month_selection(stats) if month: do_download_images(api, filter_entries_by_month(entries, month), month) elif action == "export journal as json": do_export_json(entries) elif action == "delete all entries": do_delete_entries(api, entries, "all") # Refresh after delete entries = api.fetch_all_journal_entries() stats = analyze_entries(entries) elif action == "delete entries by month": month = prompt_month_selection(stats, "select month to delete:") if month: do_delete_entries(api, filter_entries_by_month(entries, month), month) entries = api.fetch_all_journal_entries() stats = analyze_entries(entries) elif action == "refresh stats": with Progress( SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console ) as progress: task = progress.add_task("[cyan]refreshing...", total=None) entries = api.fetch_all_journal_entries() stats = analyze_entries(entries) display_stats(stats) if __name__ == "__main__": try: main() except KeyboardInterrupt: console.print("\n[yellow]interrupted.[/yellow]") sys.exit(0) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |