generates text from generators and provides as grid
Project description
ViewText
Declarative text grid layouts from structured data
ViewText is a lightweight Python library for building dynamic text-based grid layouts. It provides a simple, declarative way to map structured data to formatted text output through a flexible registry and layout system.
Features
- Field Registry: Register data getters that extract values from context objects
- Computed Fields: Perform calculations on data (unit conversions, arithmetic, aggregates)
- Formatter System: Built-in formatters for text, numbers, prices, dates, and relative times
- Layout Engine: TOML-based layout definitions that map fields to grid positions
- Extensible: Easy to add custom fields and formatters for domain-specific needs
Use Cases
- Terminal/CLI dashboards
- E-ink/LCD displays
- Text-based data visualization
- Any scenario requiring structured text layouts
Quick Example
from viewtext import LayoutEngine, LayoutLoader, FieldRegistry
# Define your field registry
registry = FieldRegistry()
registry.register("temperature", lambda ctx: ctx["temp"])
# Load layout from TOML
loader = LayoutLoader("layouts.toml")
layout = loader.get_layout("weather")
# Build grid output
engine = LayoutEngine()
lines = engine.build_line_str(layout, {"temp": 72})
Python Function Fields
Execute Python code to generate dynamic field values (timestamps, UUIDs, random numbers):
# Current timestamp
[fields.current_time]
python_module = "datetime"
python_function = "datetime.datetime.now().timestamp()"
transform = "int"
default = 0
# Generate UUID
[fields.request_id]
python_module = "uuid"
python_function = "str(uuid.uuid4())"
default = ""
# Random number
[fields.random_value]
python_module = "random"
python_function = "random.randint(1, 100)"
default = 0
See examples/time_diff_example.toml and examples/README_time_diff.md for more
details.
Computed Fields
Perform calculations on your data directly in TOML configuration:
[fields.temperature_f]
operation = "celsius_to_fahrenheit"
sources = ["temp_c"]
default = 0.0
[fields.total_price]
operation = "multiply"
sources = ["price", "quantity"]
default = 0.0
[fields.average_score]
operation = "average"
sources = ["score1", "score2", "score3"]
Available Operations
Temperature Conversions:
celsius_to_fahrenheit- Convert Celsius to Fahrenheitfahrenheit_to_celsius- Convert Fahrenheit to Celsius
Arithmetic Operations:
multiply- Multiply valuesdivide- Divide valuesadd- Add valuessubtract- Subtract valuesmodulo- Modulo operation
Aggregate Operations:
average- Calculate average of valuesmin- Find minimum valuemax- Find maximum value
Math Operations:
abs- Absolute valueround- Round to specified decimalsfloor- Round down to nearest integerceil- Round up to nearest integer
String Operations:
concat- Concatenate strings with separator, prefix, suffix, and skip_empty optionssplit- Split string by separator and get indexsubstring- Extract substring with start/end indices
Formatting Operations:
format_number- Format numbers with thousands/decimal separators
Transform Operations:
linear_transform- Apply linear transformation (multiply, divide, add)
Conditional Operations:
conditional- If/else logic with field references
See examples/computed_fields.toml and examples/README_computed_fields.md for more
details.
Installation
pip install viewtext
Command Line Interface
Viewtext includes a CLI for inspecting and testing layouts:
# Show all available layouts
viewtext list
# Show specific layout configuration
viewtext show weather
# Show field mappings from config
viewtext fields
# Render a layout with mock data
viewtext render weather
# Show all available formatters
viewtext formatters
# Show all template formatters in config
viewtext templates
# Show configuration info
viewtext info
# Use custom config file (global option)
viewtext -c my_layouts.toml list
viewtext --config examples/layouts.toml show weather
CLI Commands
- list: List all layouts in the configuration file
- show: Display detailed configuration for a specific layout
- fields: Display all field mappings from the configuration file
- render: Render a layout with mock data
- formatters: List all available formatters and their descriptions
- templates: List all template formatters used in layouts
- test: Test individual fields with custom context values and formatters
- info: Show configuration file information and global formatters
- generate-fields: Auto-generate field definitions from JSON data
Testing Fields
The test command allows you to test individual fields with custom values:
# Test a computed field
viewtext test total_price price=19.99 quantity=3
# Test with a formatter
viewtext test temp_f temp_c=25 --formatter temperature
# Test template formatters (requires --layout option)
viewtext test current_price \
'current_price={"fiat": "€1.234", "usd": 1.15, "sat_usd": 115000}' \
--formatter template --layout crypto_composite_price
JSON Pipeline Support
Pipe JSON data from external sources directly to ViewText:
# From API
curl -s https://api.example.com/data | viewtext render layout --json
# From Python
python3 -c "import json; print(json.dumps({'field': 'value'}))" | viewtext render layout --json
# From file with jq
cat data.json | jq '.users[0]' | viewtext render layout --json
# Live dashboard
watch -n 5 'curl -s API_URL | viewtext -c config.toml render layout --json'
See examples/json_pipeline_example.md for detailed examples and use cases.
Auto-Generating Field Definitions
ViewText can automatically generate field definitions from JSON data:
# Generate fields from API response
curl -s https://api.example.com/data | viewtext generate-fields
# Save to file
echo '{"name": "John", "age": 30}' | viewtext generate-fields -o fields.toml
# Add prefix to field names
curl -s https://api.example.com/user | viewtext generate-fields --prefix "api_"
# Nested JSON objects are flattened
echo '{"user": {"name": "Alice", "age": 25}}' | viewtext generate-fields
# Creates: user_name with context_key="user.name"
The command automatically infers types (str, int, float, bool, list, dict,
any) and creates properly formatted TOML field definitions.
Global Options
- --config, -c: Path to layouts.toml file (can be placed before any command)
Editor Support
ViewText provides a JSON Schema for TOML validation and autocomplete. Install the Even Better TOML extension in VS Code or use Taplo LSP in other editors for:
- Validation: Catch errors in field definitions, formatters, and layouts
- Autocomplete: Get intelligent suggestions for property names and values
- Hover Documentation: View descriptions of all configuration options
The schema is automatically configured in .taplo.toml for all layout files.
Documentation
Full documentation is available at Read the Docs:
- Quick Start Guide - Get started quickly
- User Guide - Core concepts and features
- Fields Reference - Complete field definition reference
- Validation Reference - Field validation and type checking
- Computed Fields Reference - Complete list of data transformation operations
- Formatters Reference - Complete list of display formatters with examples
- API Reference - Python API documentation
- Examples - Real-world examples and use cases
License
See LICENSE file in the root directory.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file viewtext-0.4.0.tar.gz.
File metadata
- Download URL: viewtext-0.4.0.tar.gz
- Upload date:
- Size: 105.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.24
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6f2b8fe3d6b906ee0882b952c7478e00af7ffcc5221e357d0cc796b416bd7d4c
|
|
| MD5 |
3c8afc526f9132574c9be83abc81392f
|
|
| BLAKE2b-256 |
8866497d0f836f32dc6cb79e748fc70b103fd8caa3592eb32b24a022deab8830
|
File details
Details for the file viewtext-0.4.0-py3-none-any.whl.
File metadata
- Download URL: viewtext-0.4.0-py3-none-any.whl
- Upload date:
- Size: 33.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.24
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a785b25f5aff3063e9deb6ec8da659d32c05dcaa3d13250dd70ac3756f5aba36
|
|
| MD5 |
878063417e64803800425f70f8815f69
|
|
| BLAKE2b-256 |
237771b7d401ca769cf1dd4f5f4db04ee13d23bc43b7878e55f9e3cd90a2e14a
|