bear-utils


Namebear-utils JSON
Version 0.8.26 PyPI version JSON
download
home_pageNone
SummaryVarious utilities for Bear programmers, including a rich logging utility, a disk cache, and a SQLite database wrapper amongst other things.
upload_time2025-07-12 06:03:19
maintainerNone
docs_urlNone
authorNone
requires_python>=3.12
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Bear Utils v# Bear Utils v0.8.26

Personal set of tools and utilities for Python projects, focusing on modularity and ease of use. This library includes components for caching, database management, logging, time handling, file operations, CLI prompts, image processing, clipboard interaction, gradient utilities, event systems, and async helpers.

## Overview

Bear Utils is a collection of utility modules I've created for common tasks across my Python projects. The library is designed to be modular and easy to use, with each component focusing on a specific functionality.

## Installation

```bash
pip install bear-util.      # Core package (recommended for most users)
pip install bear-utils[gui] # With optional GUI functionality

# Using UV
uv add bear-utils                    # Core only
uv add bear-utils --group gui        # With GUI functionality
```

## Key Components

### Cache Management

The `cache` package provides disk cache functionality via `diskcache`:

```python
from bear_utils.cache import CacheWrapper, cache_factory

# Create a cache instance
cache = Cache(directory="~/.cache/my_app")

# Use the cache factory to create a decorated function
@cache_factory(directory="~/.cache/my_app")
def expensive_function(arg1, arg2):
    # Function will be cached based on arguments
    pass
```

### Database Management

The `database` package provides SQLAlchemy integration with helpful patterns:

```python
from bear_utils.database import DatabaseManager
from sqlalchemy import Column, Integer, String

# Get declarative base
Base = DatabaseManager.get_base()

# Define models
class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String)

# Create and use database
db = DatabaseManager("sqlite:///app.db")
with db.session() as session:
    session.add(User(name="test"))
    session.commit()
```

### Logging

The `logging` package provides an enhanced console logger using rich:

```python
from bear_utils.logger_manager import ConsoleLogger

logger = ConsoleLogger()
logger.info("Information message")
logger.error("Error message") 
logger.warning("Warning message")
```

### Time Management

The `time` package contains tools for time handling and measurement:

```python
from bear_utils.time import TimeTools, EpochTimestamp

# Get current timestamp
now = EpochTimestamp()

# Time function execution
from bear_utils.time.time_manager import timer

with timer(name="my_operation"):
    # Code to measure
    pass
```

### File Handling

The `files` package provides abstractions for working with different file types:

```python
from pathlib import Path
from bear_utils.files.file_handlers import FileHandlerFactory

factory = FileHandlerFactory()
handler = factory.get_handler(Path("config.json"))
data = handler.read_file()
```

### Prompt Helpers

Utilities for creating interactive command-line prompts:

```python
from bear_utils.cli.prompt_helpers import restricted_prompt

choice = restricted_prompt(
    message="Select an option:", 
    valid_options=["option1", "option2"]
)
```

### GUI Utilities (Optional)

**Note: GUI functionality requires the optional PyQt6 dependency. Install with `pip install bear-utils[gui]`**

The `gui` package provides PyQt6-based dialog utilities for desktop applications:

```python
# Color picker dialog
from bear_utils.gui import select_color

color_info = select_color(
    initial_color="#FF5733", 
    title="Choose a Color"
)
if color_info:
    print(f"Selected: {color_info.hex}")  # e.g., "#FF5733"
    print(f"RGB: {color_info.rgb}")       # ColorTriplet(255, 87, 51)
    print(f"RGBA: {color_info.rgba}")     # (255, 87, 51, 255)

# Text input dialog
from bear_utils.gui import get_text

user_input = get_text(
    title="Input Required",
    label="Enter your name:",
    default="Default text"
)

# Qt Application wrapper
from bear_utils.gui import QTApplication

app = QTApplication(
    app_name="My App",
    org_name="My Organization"
)
```

**Error handling**: If PyQt6 is not installed, importing GUI components will raise a helpful error:
```
ImportError: PyQt6 is required for GUI functionality. Install it with: pip install bear-utils[gui]
```

### Image Helpers

Utilities for working with images are located in the `graphics` package:

```python
from pathlib import Path
from bear_utils.graphics import encode_image_to_jpeg, encode_image_to_png

# Encode image to base64 string
jpeg_data = encode_image_to_jpeg(Path("image.jpg"), max_size=800)
png_data = encode_image_to_png(Path("image.png"), max_size=800)
```

### Clipboard Helpers

`bear_utils.extras._tools` includes simple helpers for interacting with the system clipboard:

```python
from bear_utils.extras._tools import copy_to_clipboard, paste_from_clipboard

copy_to_clipboard("hello world")
text = paste_from_clipboard()
```

Supported platforms include macOS (`pbcopy/pbpaste`), Windows (`clip`/`powershell Get-Clipboard`),
and Linux with either Wayland (`wl-copy`/`wl-paste`) or X11 (`xclip`).

### Gradient Utilities

The `graphics.bear_gradient` module provides color gradient functionality for the purposes of visualizing data or creating color transitions:

```python
from bear_utils.graphics import ColorGradient, RichColor
from rich.console import Console
from rich.color_triplet import ColorTriplet

console = Console()

# Health meter goes from red (low health) to green (full health)
health_gradient = ColorGradient()

console.print("🏥 [bold]Health Meter Demonstration[/bold] 🏥\n")

# Normal health: Red (low) -> Green (high)
console.print("[bold green]Normal Health Levels (0% = Critical, 100% = Perfect):[/bold green]")
for health in range(0, 101, 10):
    color: ColorTriplet = health_gradient.map_to_color(0, 100, health)
    health_bar = "█" * (health // 5)
    console.print(f"HP: {health:3d}/100 {health_bar:<20}", style=color.rgb)

console.print("\n" + "="*50 + "\n")

# Reversed: Infection/Damage meter (Green = good, Red = bad)
console.print("[bold red]Infection Level (0% = Healthy, 100% = Critical):[/bold red]")
health_gradient.reverse = True
for infection in range(0, 101, 10):
    color: ColorTriplet = health_gradient.map_to_color(0, 100, infection)
    infection_bar = "█" * (infection // 5)
    status = "🦠" if infection > 70 else "⚠️" if infection > 30 else "✅"
    console.print(f"Infection: {infection:3d}% {infection_bar:<20} {status}", style=color.rgb)

health_scenarios = [
    (5, "💀 Nearly Dead"),
    (25, "🩸 Critical Condition"), 
    (50, "⚠️  Wounded"),
    (75, "😐 Recovering"),
    (95, "💪 Almost Full Health"),
    (100, "✨ Perfect Health")
]

console.print("[bold green]Health Status Examples:[/bold green]")
for hp, status in health_scenarios:
    color: ColorTriplet = health_gradient.map_to_color(0, 100, hp)
    console.print(f"{status}: {hp}/100 HP", style=color.rgb)
```

### Event System

The `events` module provides a pub/sub event system that supports both synchronous and asynchronous handlers:

```python
from bear_utils.events.events_module import subscribe, publish

# Subscribe to events
@subscribe("user_logged_in")
def handle_login(user_id):
    print(f"User {user_id} logged in")

# Publish events
publish("user_logged_in", 12345)

# Async support
@subscribe("data_processed")
async def handle_process(data):
    await process_async(data)

# Clear handlers
from bear_utils.events.events_module import clear_handlers_for_event
clear_handlers_for_event("user_logged_in")
```

### Async Helpers

The `extras/_async_helpers.py` module provides utility functions for working with async code:

```python
from bear_utils.extras._async_helpers import is_async_function

def handle_function(func):
    if is_async_function(func):
        # Handle async function
        pass
    else:
        # Handle sync function
        pass
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "bear-utils",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": null,
    "keywords": null,
    "author": null,
    "author_email": "chaz <bright.lid5647@fastmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/b7/f3/3c50f6597391b4fbda7aea65f365c735d401c9a64c9cfb1b781243f422de/bear_utils-0.8.26.tar.gz",
    "platform": null,
    "description": "# Bear Utils v# Bear Utils v0.8.26\n\nPersonal set of tools and utilities for Python projects, focusing on modularity and ease of use. This library includes components for caching, database management, logging, time handling, file operations, CLI prompts, image processing, clipboard interaction, gradient utilities, event systems, and async helpers.\n\n## Overview\n\nBear Utils is a collection of utility modules I've created for common tasks across my Python projects. The library is designed to be modular and easy to use, with each component focusing on a specific functionality.\n\n## Installation\n\n```bash\npip install bear-util.      # Core package (recommended for most users)\npip install bear-utils[gui] # With optional GUI functionality\n\n# Using UV\nuv add bear-utils                    # Core only\nuv add bear-utils --group gui        # With GUI functionality\n```\n\n## Key Components\n\n### Cache Management\n\nThe `cache` package provides disk cache functionality via `diskcache`:\n\n```python\nfrom bear_utils.cache import CacheWrapper, cache_factory\n\n# Create a cache instance\ncache = Cache(directory=\"~/.cache/my_app\")\n\n# Use the cache factory to create a decorated function\n@cache_factory(directory=\"~/.cache/my_app\")\ndef expensive_function(arg1, arg2):\n    # Function will be cached based on arguments\n    pass\n```\n\n### Database Management\n\nThe `database` package provides SQLAlchemy integration with helpful patterns:\n\n```python\nfrom bear_utils.database import DatabaseManager\nfrom sqlalchemy import Column, Integer, String\n\n# Get declarative base\nBase = DatabaseManager.get_base()\n\n# Define models\nclass User(Base):\n    __tablename__ = \"users\"\n    id = Column(Integer, primary_key=True)\n    name = Column(String)\n\n# Create and use database\ndb = DatabaseManager(\"sqlite:///app.db\")\nwith db.session() as session:\n    session.add(User(name=\"test\"))\n    session.commit()\n```\n\n### Logging\n\nThe `logging` package provides an enhanced console logger using rich:\n\n```python\nfrom bear_utils.logger_manager import ConsoleLogger\n\nlogger = ConsoleLogger()\nlogger.info(\"Information message\")\nlogger.error(\"Error message\") \nlogger.warning(\"Warning message\")\n```\n\n### Time Management\n\nThe `time` package contains tools for time handling and measurement:\n\n```python\nfrom bear_utils.time import TimeTools, EpochTimestamp\n\n# Get current timestamp\nnow = EpochTimestamp()\n\n# Time function execution\nfrom bear_utils.time.time_manager import timer\n\nwith timer(name=\"my_operation\"):\n    # Code to measure\n    pass\n```\n\n### File Handling\n\nThe `files` package provides abstractions for working with different file types:\n\n```python\nfrom pathlib import Path\nfrom bear_utils.files.file_handlers import FileHandlerFactory\n\nfactory = FileHandlerFactory()\nhandler = factory.get_handler(Path(\"config.json\"))\ndata = handler.read_file()\n```\n\n### Prompt Helpers\n\nUtilities for creating interactive command-line prompts:\n\n```python\nfrom bear_utils.cli.prompt_helpers import restricted_prompt\n\nchoice = restricted_prompt(\n    message=\"Select an option:\", \n    valid_options=[\"option1\", \"option2\"]\n)\n```\n\n### GUI Utilities (Optional)\n\n**Note: GUI functionality requires the optional PyQt6 dependency. Install with `pip install bear-utils[gui]`**\n\nThe `gui` package provides PyQt6-based dialog utilities for desktop applications:\n\n```python\n# Color picker dialog\nfrom bear_utils.gui import select_color\n\ncolor_info = select_color(\n    initial_color=\"#FF5733\", \n    title=\"Choose a Color\"\n)\nif color_info:\n    print(f\"Selected: {color_info.hex}\")  # e.g., \"#FF5733\"\n    print(f\"RGB: {color_info.rgb}\")       # ColorTriplet(255, 87, 51)\n    print(f\"RGBA: {color_info.rgba}\")     # (255, 87, 51, 255)\n\n# Text input dialog\nfrom bear_utils.gui import get_text\n\nuser_input = get_text(\n    title=\"Input Required\",\n    label=\"Enter your name:\",\n    default=\"Default text\"\n)\n\n# Qt Application wrapper\nfrom bear_utils.gui import QTApplication\n\napp = QTApplication(\n    app_name=\"My App\",\n    org_name=\"My Organization\"\n)\n```\n\n**Error handling**: If PyQt6 is not installed, importing GUI components will raise a helpful error:\n```\nImportError: PyQt6 is required for GUI functionality. Install it with: pip install bear-utils[gui]\n```\n\n### Image Helpers\n\nUtilities for working with images are located in the `graphics` package:\n\n```python\nfrom pathlib import Path\nfrom bear_utils.graphics import encode_image_to_jpeg, encode_image_to_png\n\n# Encode image to base64 string\njpeg_data = encode_image_to_jpeg(Path(\"image.jpg\"), max_size=800)\npng_data = encode_image_to_png(Path(\"image.png\"), max_size=800)\n```\n\n### Clipboard Helpers\n\n`bear_utils.extras._tools` includes simple helpers for interacting with the system clipboard:\n\n```python\nfrom bear_utils.extras._tools import copy_to_clipboard, paste_from_clipboard\n\ncopy_to_clipboard(\"hello world\")\ntext = paste_from_clipboard()\n```\n\nSupported platforms include macOS (`pbcopy/pbpaste`), Windows (`clip`/`powershell Get-Clipboard`),\nand Linux with either Wayland (`wl-copy`/`wl-paste`) or X11 (`xclip`).\n\n### Gradient Utilities\n\nThe `graphics.bear_gradient` module provides color gradient functionality for the purposes of visualizing data or creating color transitions:\n\n```python\nfrom bear_utils.graphics import ColorGradient, RichColor\nfrom rich.console import Console\nfrom rich.color_triplet import ColorTriplet\n\nconsole = Console()\n\n# Health meter goes from red (low health) to green (full health)\nhealth_gradient = ColorGradient()\n\nconsole.print(\"\ud83c\udfe5 [bold]Health Meter Demonstration[/bold] \ud83c\udfe5\\n\")\n\n# Normal health: Red (low) -> Green (high)\nconsole.print(\"[bold green]Normal Health Levels (0% = Critical, 100% = Perfect):[/bold green]\")\nfor health in range(0, 101, 10):\n    color: ColorTriplet = health_gradient.map_to_color(0, 100, health)\n    health_bar = \"\u2588\" * (health // 5)\n    console.print(f\"HP: {health:3d}/100 {health_bar:<20}\", style=color.rgb)\n\nconsole.print(\"\\n\" + \"=\"*50 + \"\\n\")\n\n# Reversed: Infection/Damage meter (Green = good, Red = bad)\nconsole.print(\"[bold red]Infection Level (0% = Healthy, 100% = Critical):[/bold red]\")\nhealth_gradient.reverse = True\nfor infection in range(0, 101, 10):\n    color: ColorTriplet = health_gradient.map_to_color(0, 100, infection)\n    infection_bar = \"\u2588\" * (infection // 5)\n    status = \"\ud83e\udda0\" if infection > 70 else \"\u26a0\ufe0f\" if infection > 30 else \"\u2705\"\n    console.print(f\"Infection: {infection:3d}% {infection_bar:<20} {status}\", style=color.rgb)\n\nhealth_scenarios = [\n    (5, \"\ud83d\udc80 Nearly Dead\"),\n    (25, \"\ud83e\ude78 Critical Condition\"), \n    (50, \"\u26a0\ufe0f  Wounded\"),\n    (75, \"\ud83d\ude10 Recovering\"),\n    (95, \"\ud83d\udcaa Almost Full Health\"),\n    (100, \"\u2728 Perfect Health\")\n]\n\nconsole.print(\"[bold green]Health Status Examples:[/bold green]\")\nfor hp, status in health_scenarios:\n    color: ColorTriplet = health_gradient.map_to_color(0, 100, hp)\n    console.print(f\"{status}: {hp}/100 HP\", style=color.rgb)\n```\n\n### Event System\n\nThe `events` module provides a pub/sub event system that supports both synchronous and asynchronous handlers:\n\n```python\nfrom bear_utils.events.events_module import subscribe, publish\n\n# Subscribe to events\n@subscribe(\"user_logged_in\")\ndef handle_login(user_id):\n    print(f\"User {user_id} logged in\")\n\n# Publish events\npublish(\"user_logged_in\", 12345)\n\n# Async support\n@subscribe(\"data_processed\")\nasync def handle_process(data):\n    await process_async(data)\n\n# Clear handlers\nfrom bear_utils.events.events_module import clear_handlers_for_event\nclear_handlers_for_event(\"user_logged_in\")\n```\n\n### Async Helpers\n\nThe `extras/_async_helpers.py` module provides utility functions for working with async code:\n\n```python\nfrom bear_utils.extras._async_helpers import is_async_function\n\ndef handle_function(func):\n    if is_async_function(func):\n        # Handle async function\n        pass\n    else:\n        # Handle sync function\n        pass\n```\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Various utilities for Bear programmers, including a rich logging utility, a disk cache, and a SQLite database wrapper amongst other things.",
    "version": "0.8.26",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "9f77cf3f1f6b63d83f01b91f0e24806e5a44fdc4735023aa9f4c8cfc7cd64642",
                "md5": "506c7d2a8598226362f31bc3a8c9c080",
                "sha256": "982d147b057305cf31f2d7bd8328ca44aae514b63f82418012051cecbe8eaaf6"
            },
            "downloads": -1,
            "filename": "bear_utils-0.8.26-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "506c7d2a8598226362f31bc3a8c9c080",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 103070,
            "upload_time": "2025-07-12T06:03:18",
            "upload_time_iso_8601": "2025-07-12T06:03:18.420890Z",
            "url": "https://files.pythonhosted.org/packages/9f/77/cf3f1f6b63d83f01b91f0e24806e5a44fdc4735023aa9f4c8cfc7cd64642/bear_utils-0.8.26-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "b7f33c50f6597391b4fbda7aea65f365c735d401c9a64c9cfb1b781243f422de",
                "md5": "1b2e55837afd177c2821d653f7509823",
                "sha256": "fd1a4c43b84d2b4c57bf5fcdd2925aaadec29e5c85f547076cdad78efe9dfebd"
            },
            "downloads": -1,
            "filename": "bear_utils-0.8.26.tar.gz",
            "has_sig": false,
            "md5_digest": "1b2e55837afd177c2821d653f7509823",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 146535,
            "upload_time": "2025-07-12T06:03:19",
            "upload_time_iso_8601": "2025-07-12T06:03:19.762666Z",
            "url": "https://files.pythonhosted.org/packages/b7/f3/3c50f6597391b4fbda7aea65f365c735d401c9a64c9cfb1b781243f422de/bear_utils-0.8.26.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-12 06:03:19",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "bear-utils"
}
        
Elapsed time: 0.43799s