๐Ÿ” Code Extractor

class RemarkablePDFUploader

Maturity: 47

A wrapper class that provides a simplified interface for uploading PDF documents to a reMarkable tablet using a temporary database session.

File:
/tf/active/vicechatdev/e-ink-llm/cloudtest/upload_pdf_new.py
Lines:
19 - 107
Complexity:
moderate

Purpose

RemarkablePDFUploader serves as a standalone utility for uploading PDF files to reMarkable tablets. It abstracts the complexity of the underlying RemarkableUploadManager by creating temporary database sessions and providing simple methods for listing folders and uploading PDFs. The class handles resource management including temporary directory creation and cleanup, making it suitable for one-off upload operations or scripts that need to upload PDFs without maintaining persistent state.

Source Code

class RemarkablePDFUploader:
    """Standalone PDF uploader using proven upload_manager logic"""
    
    def __init__(self):
        # Create a temporary database for this upload session
        self.temp_dir = tempfile.mkdtemp(prefix="remarkable_upload_")
        temp_db = os.path.join(self.temp_dir, "temp_upload.db")
        
        print(f"๐Ÿ”ง Initializing upload manager with temp DB: {temp_db}")
        
        # Initialize the proven upload manager
        self.upload_manager = RemarkableUploadManager(temp_db)
        
    def list_folders(self):
        """List available folders for upload target selection"""
        try:
            # Get the folder structure from the upload manager
            folders = {}
            replica = self.upload_manager.get_replica()
            
            for uuid, doc in replica.items():
                if doc.get('Type') == 'CollectionType':
                    name = doc.get('VissibleName', 'Unnamed Folder')
                    folders[uuid] = name
                    
            return folders
        except Exception as e:
            print(f"โš ๏ธ Error listing folders: {e}")
            return {}
    
    def upload_pdf(self, pdf_path, document_name, parent_uuid=None):
        """
        Upload a PDF using the proven upload_manager logic
        
        Args:
            pdf_path: Path to the PDF file
            document_name: Name for the document on reMarkable
            parent_uuid: UUID of parent folder (None for root)
            
        Returns:
            bool: True if upload successful, False otherwise
        """
        try:
            pdf_file = Path(pdf_path)
            if not pdf_file.exists():
                print(f"โŒ PDF file not found: {pdf_path}")
                return False
                
            if not pdf_file.suffix.lower() == '.pdf':
                print(f"โŒ File is not a PDF: {pdf_path}")
                return False
                
            print(f"๐Ÿ“„ Uploading: {pdf_file.name}")
            print(f"๐Ÿ“ Document name: {document_name}")
            if parent_uuid:
                print(f"๐Ÿ“ Target folder: {parent_uuid}")
            else:
                print("๐Ÿ“ Target: Root folder")
                
            # Use the proven upload manager to handle the upload
            print(f"\n๐Ÿ”ง Using proven upload_manager.py for upload...")
            
            # Call the working upload method
            success = self.upload_manager.upload_pdf_document(
                pdf_path=str(pdf_file),
                name=document_name,
                parent_uuid=parent_uuid
            )
            
            if success:
                print("โœ… Upload successful!")
                return True
            else:
                print("โŒ Upload failed!")
                return False
                
        except Exception as e:
            print(f"โŒ Upload error: {e}")
            return False
    
    def cleanup(self):
        """Clean up temporary resources"""
        try:
            import shutil
            if hasattr(self, 'temp_dir') and os.path.exists(self.temp_dir):
                shutil.rmtree(self.temp_dir)
                print(f"๐Ÿงน Cleaned up temp directory: {self.temp_dir}")
        except Exception as e:
            print(f"โš ๏ธ Cleanup warning: {e}")

Parameters

Name Type Default Kind
bases - -

Parameter Details

__init__: No parameters required. The constructor automatically creates a temporary directory and database for the upload session, then initializes an internal RemarkableUploadManager instance.

Return Value

Instantiation returns a RemarkablePDFUploader object. The upload_pdf method returns a boolean (True for successful upload, False for failure). The list_folders method returns a dictionary mapping folder UUIDs (strings) to folder names (strings). The cleanup method has no return value.

Class Interface

Methods

__init__(self)

Purpose: Initialize the uploader by creating a temporary directory and database, then instantiating the underlying RemarkableUploadManager

Returns: None (constructor)

list_folders(self) -> dict

Purpose: Retrieve all available folders from the reMarkable device for use as upload targets

Returns: Dictionary mapping folder UUIDs (str) to folder names (str). Returns empty dict on error.

upload_pdf(self, pdf_path: str, document_name: str, parent_uuid: str = None) -> bool

Purpose: Upload a PDF file to the reMarkable device with specified name and optional parent folder

Parameters:

  • pdf_path: Path to the PDF file to upload (string or Path-like object)
  • document_name: Display name for the document on the reMarkable device
  • parent_uuid: UUID of the parent folder (None for root folder, must be valid folder UUID from list_folders())

Returns: Boolean: True if upload succeeded, False if upload failed or file validation failed

cleanup(self)

Purpose: Remove temporary directory and all associated resources created during initialization

Returns: None. Prints status messages but does not raise exceptions on cleanup failure.

Attributes

Name Type Description Scope
temp_dir str Path to the temporary directory created for this upload session, contains the temporary database file instance
upload_manager RemarkableUploadManager Instance of RemarkableUploadManager that handles the actual upload operations and cloud synchronization instance

Dependencies

  • tempfile
  • os
  • pathlib
  • shutil
  • cloudtest.upload_manager

Required Imports

import sys
import os
import tempfile
from pathlib import Path
from cloudtest.upload_manager import RemarkableUploadManager
import shutil

Conditional/Optional Imports

These imports are only needed under specific conditions:

import shutil

Condition: only needed when cleanup() method is called

Required (conditional)

Usage Example

# Create uploader instance
uploader = RemarkablePDFUploader()

try:
    # List available folders
    folders = uploader.list_folders()
    print(f"Available folders: {folders}")
    
    # Upload PDF to root folder
    success = uploader.upload_pdf(
        pdf_path='/path/to/document.pdf',
        document_name='My Document',
        parent_uuid=None
    )
    
    # Or upload to specific folder
    if folders:
        folder_uuid = list(folders.keys())[0]
        success = uploader.upload_pdf(
            pdf_path='/path/to/another.pdf',
            document_name='Another Document',
            parent_uuid=folder_uuid
        )
    
    if success:
        print('Upload completed successfully')
finally:
    # Always cleanup temporary resources
    uploader.cleanup()

Best Practices

  • Always call cleanup() method when done to remove temporary directories, preferably in a finally block or context manager
  • Check return value of upload_pdf() to verify successful upload before proceeding
  • Validate PDF file exists and has correct extension before calling upload_pdf()
  • Use list_folders() to get valid parent_uuid values before uploading to specific folders
  • The class creates a new temporary database for each instance, so create one instance per upload session
  • Do not reuse the instance after calling cleanup() as temporary resources will be deleted
  • Handle exceptions appropriately as network operations may fail
  • The temp_dir attribute contains the path to temporary resources if manual cleanup is needed

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class RemarkablePDFUploader_v1 94.1% similar

    A standalone PDF uploader class that manages uploading PDF documents to reMarkable cloud storage using authenticated sessions and temporary database storage.

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/upload_pdf.py
  • class SimplePDFUploadTest 71.2% similar

    A test class for validating PDF upload functionality to reMarkable cloud, including raw content upload and complete document creation with metadata.

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/test_simple_pdf_upload.py
  • class RemarkableUploadManager 70.9% similar

    Manages uploads to reMarkable cloud

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/upload_manager.py
  • class RemarkableUploadManager_v1 70.4% similar

    Manages uploads to reMarkable cloud

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/upload_manager_old.py
  • function test_quick_upload 67.5% similar

    A test function that performs a quick PDF upload to a reMarkable device without performing a full synchronization, used for testing the upload functionality in isolation.

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/quick_test.py
โ† Back to Browse