class RemarkablePDFUploader
A wrapper class that provides a simplified interface for uploading PDF documents to a reMarkable tablet using a temporary database session.
/tf/active/vicechatdev/e-ink-llm/cloudtest/upload_pdf_new.py
19 - 107
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 deviceparent_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
tempfileospathlibshutilcloudtest.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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class RemarkablePDFUploader_v1 94.1% similar
-
class SimplePDFUploadTest 71.2% similar
-
class RemarkableUploadManager 70.9% similar
-
class RemarkableUploadManager_v1 70.4% similar
-
function test_quick_upload 67.5% similar