🔍 Code Extractor

function print_node_tree

Maturity: 56

Recursively prints a hierarchical tree visualization of nodes with icons, names, file counts, and modification dates to the console.

File:
/tf/active/vicechatdev/e-ink-llm/cloudtest/analyze_replica.py
Lines:
82 - 129
Complexity:
moderate

Purpose

This function provides a visual representation of a node hierarchy (like a file system or document structure) by recursively traversing parent-child relationships and displaying them in a tree format with appropriate indentation, icons based on node type, and metadata such as file counts and last modified dates. It's useful for debugging, visualizing data structures, or providing user-friendly output of hierarchical data.

Source Code

def print_node_tree(nodes: Dict[str, Any], hierarchy: Dict[str, List[str]], 
                   uuid: str, depth: int = 0, max_depth: int = 3, prefix: str = ""):
    """Print a tree view of nodes"""
    if depth > max_depth:
        return
    
    node = nodes.get(uuid)
    if not node:
        return
    
    # Format node info
    name = node.get('name', 'unnamed')
    node_type = node.get('node_type', 'unknown')
    extracted_files = node.get('extracted_files', [])
    
    # Icon based on type
    if node_type == 'folder':
        icon = "📁"
    elif extracted_files and any(f.endswith('.pdf') for f in extracted_files):
        icon = "📄"
    elif extracted_files:
        icon = "📝"
    else:
        icon = "📄"
    
    # Additional info
    info_parts = []
    if extracted_files:
        info_parts.append(f"{len(extracted_files)} files")
    
    if node.get('last_modified'):
        try:
            mod_time = datetime.fromtimestamp(int(node['last_modified']) / 1000)
            info_parts.append(f"modified {mod_time.strftime('%Y-%m-%d')}")
        except:
            pass
    
    info_str = f" ({', '.join(info_parts)})" if info_parts else ""
    
    print(f"{prefix}{icon} {name}{info_str}")
    
    # Show children
    children = hierarchy.get(uuid, [])
    if children and depth < max_depth:
        for i, child_uuid in enumerate(sorted(children, key=lambda x: nodes.get(x, {}).get('name', ''))):
            is_last = i == len(children) - 1
            child_prefix = prefix + ("    " if is_last else "│   ")
            print_node_tree(nodes, hierarchy, child_uuid, depth + 1, max_depth, child_prefix)

Parameters

Name Type Default Kind
nodes Dict[str, Any] - positional_or_keyword
hierarchy Dict[str, List[str]] - positional_or_keyword
uuid str - positional_or_keyword
depth int 0 positional_or_keyword
max_depth int 3 positional_or_keyword
prefix str '' positional_or_keyword

Parameter Details

nodes: Dictionary mapping node UUIDs (strings) to node data dictionaries. Each node dictionary should contain keys like 'name', 'node_type', 'extracted_files' (list), and 'last_modified' (timestamp in milliseconds). This is the complete collection of all nodes in the hierarchy.

hierarchy: Dictionary mapping parent node UUIDs (strings) to lists of child node UUIDs (strings). Defines the parent-child relationships between nodes. Keys are parent UUIDs, values are lists of their children's UUIDs.

uuid: String identifier of the current node to print. This is the starting point for the tree traversal and should be a valid key in the 'nodes' dictionary.

depth: Integer representing the current depth level in the tree traversal. Starts at 0 for the root node and increments with each recursive call. Used to control indentation and enforce max_depth limits.

max_depth: Integer specifying the maximum depth to traverse in the tree. Prevents infinite recursion and limits output size. Default is 3 levels deep.

prefix: String used for indentation and tree structure visualization. Contains characters like spaces, '│', and '└' to create the tree lines. Builds up with each recursive level.

Return Value

This function returns None (no explicit return value). It produces side effects by printing the tree structure directly to stdout using the print() function.

Dependencies

  • datetime
  • typing

Required Imports

from datetime import datetime
from typing import Dict, Any, List

Usage Example

from datetime import datetime
from typing import Dict, Any, List

def print_node_tree(nodes: Dict[str, Any], hierarchy: Dict[str, List[str]], 
                   uuid: str, depth: int = 0, max_depth: int = 3, prefix: str = ""):
    # ... function code ...
    pass

# Example data structure
nodes = {
    'root-123': {
        'name': 'Documents',
        'node_type': 'folder',
        'extracted_files': [],
        'last_modified': 1704067200000
    },
    'child-456': {
        'name': 'Report.pdf',
        'node_type': 'file',
        'extracted_files': ['report.pdf'],
        'last_modified': 1704153600000
    },
    'child-789': {
        'name': 'Notes.txt',
        'node_type': 'file',
        'extracted_files': ['notes.txt'],
        'last_modified': 1704240000000
    }
}

hierarchy = {
    'root-123': ['child-456', 'child-789']
}

# Print the tree starting from root
print_node_tree(nodes, hierarchy, 'root-123', max_depth=2)

Best Practices

  • Ensure the 'uuid' parameter corresponds to a valid key in the 'nodes' dictionary to avoid returning early without output
  • Set an appropriate 'max_depth' value to prevent excessive output or stack overflow with deeply nested hierarchies
  • The 'last_modified' field in nodes should be a timestamp in milliseconds (Unix epoch * 1000) for proper date formatting
  • The function silently handles missing nodes and invalid timestamps using try-except blocks, so validate your data beforehand for debugging
  • Children are sorted alphabetically by name for consistent output; ensure node names are present to avoid sorting issues
  • The function uses Unicode characters (📁, 📄, 📝, │) which may not display correctly in all terminal environments
  • This function has side effects (prints to stdout); consider redirecting output or capturing it if you need to process the tree structure programmatically

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function show_directory_tree 72.2% similar

    Recursively displays a visual tree structure of a directory and its contents, showing files with sizes and subdirectories up to a specified depth.

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/test_complete_suite.py
  • function build_document_tree_recursive 57.6% similar

    Recursively builds a complete hierarchical tree structure of documents and folders from a target directory path, filtering for supported file types and skipping hidden/cache directories.

    From: /tf/active/vicechatdev/docchat/app.py
  • function analyze_hierarchy 56.1% similar

    Analyzes a hierarchical database structure to extract statistics about nodes, their relationships, depths, and types.

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/analyze_replica.py
  • function print_database_analysis 55.6% similar

    Prints a comprehensive, formatted analysis of a reMarkable tablet replica database, including statistics, hierarchy information, file types, and a content tree visualization.

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/analyze_replica.py
  • function create_folder_hierarchy_v2 52.1% similar

    Creates a hierarchical structure of Subfolder nodes in a Neo4j graph database based on a file path, establishing parent-child relationships between folders.

    From: /tf/active/vicechatdev/offline_parser_docstore.py
← Back to Browse