🔍 Code Extractor

function process_single_remarkable_file

Maturity: 62

Asynchronously processes a single document from reMarkable Cloud by downloading it, processing it through an e-ink LLM processor, and returning the path to the generated response PDF.

File:
/tf/active/vicechatdev/e-ink-llm/remarkable_processor.py
Lines:
222 - 267
Complexity:
moderate

Purpose

This function serves as a high-level interface for processing individual reMarkable Cloud documents. It handles authentication with reMarkable Cloud, downloads a specific document by ID to a temporary location, processes it using the RemarkableEInkProcessor (which likely involves LLM-based analysis or transformation), and returns the path to the resulting PDF. This is useful for automated workflows that need to process handwritten notes or documents from reMarkable tablets through an AI pipeline.

Source Code

async def process_single_remarkable_file(remarkable_document_id: str, api_key: Optional[str] = None, 
                                       remarkable_config: Optional[Dict[str, Any]] = None) -> Optional[str]:
    """
    Process a single file from reMarkable Cloud
    
    Args:
        remarkable_document_id: ID of the document in reMarkable Cloud
        api_key: OpenAI API key
        remarkable_config: reMarkable configuration
        
    Returns:
        Path to generated response PDF or None if failed
    """
    # Enable remarkable integration for this operation
    config = remarkable_config or {}
    config['enabled'] = True
    
    processor = RemarkableEInkProcessor(api_key=api_key, remarkable_config=config)
    
    # Authenticate
    auth_success = await processor.authenticate_remarkable()
    if not auth_success:
        print("❌ Failed to authenticate with reMarkable Cloud")
        return None
    
    try:
        # Get the document
        from rmcl import Item
        document = Item.get_by_id_s(remarkable_document_id)
        
        # Download to temporary location
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_path = Path(temp_dir)
            local_file = await processor.cloud_manager.download_document(document, temp_path)
            
            if local_file:
                # Process the file
                result = await processor.process_file(local_file)
                return str(result) if result else None
            else:
                print("❌ Failed to download document")
                return None
                
    except Exception as e:
        print(f"❌ Error processing reMarkable document: {e}")
        return None

Parameters

Name Type Default Kind
remarkable_document_id str - positional_or_keyword
api_key Optional[str] None positional_or_keyword
remarkable_config Optional[Dict[str, Any]] None positional_or_keyword

Parameter Details

remarkable_document_id: The unique identifier string for a document stored in reMarkable Cloud. This ID is used to retrieve the specific document to be processed. Must be a valid document ID that exists in the authenticated user's reMarkable Cloud account.

api_key: Optional OpenAI API key string used for LLM processing operations. If not provided, the processor may attempt to use an API key from environment variables or configuration. Required for any OpenAI-based processing functionality.

remarkable_config: Optional dictionary containing reMarkable Cloud configuration settings such as authentication tokens, device tokens, or other service-specific parameters. The function automatically sets 'enabled': True in this config. If None, an empty dictionary is used as the base configuration.

Return Value

Type: Optional[str]

Returns an Optional[str] representing the file path to the generated response PDF if processing succeeds, or None if any step fails (authentication, download, or processing). The path is converted to a string from a Path object if successful.

Dependencies

  • asyncio
  • tempfile
  • pathlib
  • typing
  • logging
  • rmcl

Required Imports

import asyncio
import tempfile
from pathlib import Path
from typing import Optional, Dict, Any

Conditional/Optional Imports

These imports are only needed under specific conditions:

from rmcl import Item

Condition: Required when executing the document retrieval logic inside the try block

Required (conditional)
from processor import EInkLLMProcessor

Condition: Required as base class or related functionality for RemarkableEInkProcessor

Required (conditional)
from remarkable_cloud import RemarkableCloudManager, RemarkableFileWatcher

Condition: Required for RemarkableEInkProcessor initialization and cloud operations

Required (conditional)

Usage Example

import asyncio
from pathlib import Path
from typing import Optional, Dict, Any

# Assuming the function and required classes are imported
# from your_module import process_single_remarkable_file

async def main():
    # Configuration for reMarkable Cloud
    remarkable_config = {
        'device_token': 'your_device_token',
        'user_token': 'your_user_token'
    }
    
    # OpenAI API key
    api_key = 'sk-your-openai-api-key'
    
    # Document ID from reMarkable Cloud
    document_id = 'abc123-def456-ghi789'
    
    # Process the document
    result_path = await process_single_remarkable_file(
        remarkable_document_id=document_id,
        api_key=api_key,
        remarkable_config=remarkable_config
    )
    
    if result_path:
        print(f"✅ Processing successful! Result saved to: {result_path}")
    else:
        print("❌ Processing failed")

# Run the async function
if __name__ == '__main__':
    asyncio.run(main())

Best Practices

  • Always handle the None return value to check if processing succeeded before using the result path
  • Ensure proper authentication credentials are provided in remarkable_config before calling this function
  • The function uses temporary directories that are automatically cleaned up, so copy the result file if you need to persist it
  • Use proper async/await syntax when calling this function since it's an async coroutine
  • Implement proper error logging in production environments as the function only prints errors to console
  • Verify that the remarkable_document_id exists and is accessible before calling to avoid unnecessary API calls
  • Consider implementing retry logic for network-related failures when downloading from reMarkable Cloud
  • Be aware that the temporary directory is deleted after processing, so the returned path should be used or copied immediately

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function main_v21 65.7% similar

    Asynchronous main function that runs a reMarkable tablet file watcher as a separate process, monitoring a specified folder for new documents, processing them, and uploading responses back to the reMarkable Cloud.

    From: /tf/active/vicechatdev/e-ink-llm/run_remarkable_bridge.py
  • class RemarkableEInkProcessor 65.7% similar

    Enhanced E-Ink LLM Processor that extends EInkLLMProcessor with reMarkable Cloud integration, enabling file processing from both local directories and reMarkable Cloud storage.

    From: /tf/active/vicechatdev/e-ink-llm/remarkable_processor.py
  • class RemarkableCloudWatcher 62.8% similar

    Monitors the reMarkable Cloud 'gpt_out' folder for new documents, automatically downloads them, and converts .rm (reMarkable native) files to PDF format.

    From: /tf/active/vicechatdev/e-ink-llm/mixed_cloud_processor.py
  • function main_v104 62.7% similar

    A test function that uploads a PDF document to a reMarkable tablet folder using the folder's hash value as the parent identifier instead of its UUID, then verifies the upload through replica synchronization.

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/test_hash_parent_upload.py
  • function main_v15 62.6% similar

    A test function that uploads a PDF document to reMarkable cloud, syncs the local replica, and validates the upload with detailed logging and metrics.

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/test_raw_upload.py
← Back to Browse