semvec/pypi-packages huggingface dataset:
truenas-backup-tool 0.1.1
A simple tool to fetch backups from the TrueNAS via the JSON-RPC protocol
Requires Python: >=3.10

Usage
=====

**truenas-backup** is a simple tool to fetch configuration backups from
the TrueNAS installation using the JSON-RPC API.

Installation
------------

As the API client is not published as a package, you'll need to install
the dependency manually

.. code-block:: shell

   pip install git+https://github.com/truenas/api_client.git

Arguments
----------------

``-h``, ``--help``
   show the help message and exit.

``-c FILE``, ``--config FILE``
   the configuration file (default: ``~/.config/truenas-backup/config.yml``)

``-o FILE``, ``--output FILE``
   the output file. The file name can contain ``strftime`` directives. If the argument
   is specified, ``directory``, ``name`` and ``keep`` fields of the configuration
   are ignored.

Configuration file
==================

The ``truenas-backup`` needs a configuration file
(default ``~/.config/truenas-backup/config.yml``). As the file contains secrets,
take care to set reasonable permissions. The file is in
the `YAML <https://yaml.org/>`_ format.

Configuration file
------------------

.. code-block:: yaml

      truenas:
         host: truenas.local[:port]
         api_user: truenas_admin
         api_key: ...
         ssl_verify: false
         call_timeout: 20
         backup_password: ...
      output:
         directory: .
         name: "truenas-%Y%m%d-%H%M.backup"
         keep: 12

All fields except ``api_user`` and ``api_key`` are optional. The user
the API key was generated for needs to have the ``FULL_ADMIN`` role
(TrueNAS requirement).

``host`` is a hostname or an IP address, and an optional port.
Secure connection will be used.

The backup file is compressed using gzip first, then encrypted if ``backup_password``
is specified. It can be decrypted and unpacked manually using

``openssl aes-256-cbc -d -md sha512 -pbkdf2 -iter 100000 -in ... | tar tvfz -``

``name`` specifies the name of the output file. ``strftime`` directives
are allowed.

``keep`` removes all but the most recent ``*.backup`` files from the ``directory``,
that in this case has to be specified and has to be an absolute path.

``directory`` has to already exist. As the backup is not encrypted
and contains secrets the permissions should be set accordingly.


Observability
-------------

The backups done can be exported through prometheus text-file format and consumed
by the node exporter's textfile collector. If the ``metrics`` key exists, the file
is atomically populated after each backup run.

.. code-block:: yaml

    metrics:
        directory: "/var/local/lib/prom_metrics"
        suffix: "my-truenas"

``directory`` is mandatory and specifies the path of the directory passed as the
``--collector.textfile.directory`` for the ``node_exporter``. It has to already exist.
``suffix`` is optional and will be appended to the file name to distinguish metrics
files generated by different configurations. For the above configuration
the full file name will be ``/var/local/lib/prom_metrics/truenas-backup-my-truenas.prom``.
litellm-impacts 0.1.0
Environmental impact metrics callback for LiteLLM
Requires Python: >=3.10
Keywords: carbon, litellm, llm, metrics, prometheus, sustainability

# litellm-impacts

Environmental impact metrics callback for [LiteLLM](https://github.com/BerriAI/litellm). Calculates and exposes carbon footprint metrics (energy consumption, CO2 emissions, resource depletion) for LLM API calls using the [EcoLogits](https://github.com/genai-impact/ecologits) library.

## Installation

```bash
pip install litellm-impacts
```

Or with uv:

```bash
uv add litellm-impacts
```

## Usage

### With LiteLLM Proxy (config.yaml)

```yaml
litellm_settings:
  callbacks: custom_callbacks.impacts_callback

model_list:
  - model_name: gpt-4
    litellm_params:
      model: openai/gpt-4
```

Create `custom_callbacks.py` in the same directory:

```python
from litellm_impacts import ImpactsCallback

impacts_callback = ImpactsCallback()
```

### With LiteLLM Python SDK

```python
import litellm
from litellm_impacts import ImpactsCallback

litellm.callbacks = [ImpactsCallback()]

response = litellm.completion(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello!"}]
)
```

### Configuration Options

```python
from litellm_impacts import ImpactsCallback

callback = ImpactsCallback(
    prefix="litellm",        # Metric name prefix (default: "litellm")
    server_port=8000,        # Prometheus HTTP server port (default: 8000)
    start_server=True,       # Start built-in HTTP server (default: True)
    labels=["model", "key_alias"],  # Metric labels (default)
)
```

Set `start_server=False` if you're already running a Prometheus HTTP server or want to use a different metrics exposition method.

## Metrics

The callback exposes the following Prometheus metrics (all with min/max variants):

| Metric | Description |
|--------|-------------|
| `{prefix}_energy_kwh_min/max` | Energy consumption in kWh |
| `{prefix}_gwp_kgco2eq_min/max` | Global warming potential in kg CO2 equivalent |
| `{prefix}_adpe_kgsbeq_min/max` | Abiotic depletion potential in kg Sb equivalent |
| `{prefix}_pe_mj_min/max` | Primary energy in megajoules |

Labels:
- `model`: The LLM model name
- `key_alias`: The LiteLLM API key alias (if using proxy)

## Supported Providers

Models are automatically matched to EcoLogits providers:

- OpenAI (gpt-*, o1, o3, o4, chatgpt-*)
- Anthropic (claude-*)
- Google (gemini-*)
- Mistral AI (mistral-*, codestral-*, pixtral-*)
- Cohere (command-*)

Models can also be specified with explicit provider prefixes (e.g., `openai/gpt-4`, `anthropic/claude-3-sonnet`).

## License

MIT
browsefn 0.0.1
Comprehensive self-hosted web browsing and data extraction platform for developers
Requires Python: >=3.8
Keywords: crawling, geolocation, images, sdk, web-scraping

# BrowseFn Python SDK

> Comprehensive self-hosted web browsing and data extraction platform for developers.

The Python SDK for BrowseFn provides a unified interface for:

- Web scraping and crawling (HTML, Markdown, Text)
- Image search and download
- Geolocation services (Geocoding, Reverse Geocoding)
- Provider-agnostic interface (swap providers easily)

## Status

🚧 **Alpha**

## Features

- **Type-safe**: Built with Pydantic for robust data validation.
- **Async**: Fully asynchronous API using `httpx`.
- **Extensible**: Easy to add custom providers.
- **Batteries included**: Comes with basic providers (BeautifulSoup).

## Installation

```bash
pip install browsefn
```

## Usage

### Web Scraping

```python
import asyncio
from browsefn import browse_fn
from browsefn.web.providers.bs4 import BeautifulSoupProvider

async def main():
    # Initialize
    browse = browse_fn()
    
    # Register a provider (e.g., BeautifulSoup)
    bs4_provider = BeautifulSoupProvider()
    browse.web.register_provider("beautifulsoup", bs4_provider)
    browse.web.config.default_provider = "beautifulsoup"
    
    # Get a page
    page = await browse.web.get_page("https://example.com")
    
    print(f"Title: {page.metadata.title}")
    print(f"Content length: {len(page.content)}")

if __name__ == "__main__":
    asyncio.run(main())
```

### Configuration

You can configure BrowseFn using the `BrowseFnConfig` object.

```python
from browsefn import browse_fn, BrowseFnConfig, WebConfig

config = BrowseFnConfig(
    web=WebConfig(
        default_provider="firecrawl",
        # ...
    )
)
browse = browse_fn(config)
```

## Development

1.  **Install dependencies**:
    ```bash
    pip install -e ".[test]"
    ```

2.  **Run tests**:
    ```bash
    pytest
    ```
superfunctions-sqlalchemy 0.1.0
SQLAlchemy adapter for superfunctions.db
Requires Python: >=3.10
Keywords: adapter, database, orm, sqlalchemy, superfunctions

# superfunctions-sqlalchemy

SQLAlchemy adapter for `superfunctions.db`

**Location:** `packages/python-sqlalchemy/`  
**Package:** `superfunctions-sqlalchemy`  
**Import:** `from superfunctions_sqlalchemy import create_adapter`

## Installation

```bash
pip install superfunctions-sqlalchemy

# With PostgreSQL
pip install superfunctions-sqlalchemy[postgres]

# With MySQL
pip install superfunctions-sqlalchemy[mysql]

# With async support
pip install superfunctions-sqlalchemy[asyncpg]
```

## Usage

```python
from sqlalchemy import create_engine
from superfunctions_sqlalchemy import create_adapter

# Create SQLAlchemy engine
engine = create_engine("postgresql://user:password@localhost/dbname")

# Create adapter
adapter = create_adapter(engine)

# Use with superfunctions libraries
from authfn import create_authfn, AuthFnConfig

auth = create_authfn(
    AuthFnConfig(
        database=adapter,
        namespace="authfn",
    )
)
```

## Features

- ✅ Full CRUD operations
- ✅ Transaction support
- ✅ Batch operations
- ✅ Query builders (where, orderBy, limit, offset)
- ✅ All SQL operators
- ✅ Works with PostgreSQL, MySQL, SQLite
- ✅ Sync and async engines

## Example

```python
from sqlalchemy import create_engine
from superfunctions_sqlalchemy import create_adapter
from superfunctions.db import CreateParams, FindManyParams, WhereClause, Operator

engine = create_engine("postgresql://localhost/mydb")
adapter = create_adapter(engine)

# Create
user = await adapter.create(
    CreateParams(
        model="users",
        data={"name": "Alice", "email": "alice@example.com"},
    )
)

# Query
users = await adapter.find_many(
    FindManyParams(
        model="users",
        where=[
            WhereClause(field="email", operator=Operator.LIKE, value="%@example.com")
        ],
        limit=10,
    )
)
```

## License

MIT
superfunctions-flask 0.1.0
Flask adapter for superfunctions.http
Requires Python: >=3.10
Keywords: adapter, flask, http, superfunctions, web

# superfunctions-flask

Flask adapter for `superfunctions.http`

**Location:** `packages/python-flask/`  
**Package:** `superfunctions-flask`  
**Import:** `from superfunctions_flask import create_blueprint`

## Installation

```bash
pip install superfunctions-flask
```

## Usage

### Option 1: Create Blueprint from Routes

```python
from flask import Flask
from superfunctions.http import Route, HttpMethod, Response, NotFoundError
from superfunctions_flask import create_blueprint

app = Flask(__name__)

# Define handlers using superfunctions abstractions
async def get_user(request, context):
    user_id = context.params["id"]
    
    # Your logic here
    user = await db.find_one(...)
    if not user:
        raise NotFoundError(f"User {user_id} not found")
    
    return Response(status=200, body=user)

async def create_user(request, context):
    data = await request.json()
    user = await db.create(...)
    return Response(status=201, body=user)

# Create blueprint from routes
routes = [
    Route(method=HttpMethod.GET, path="/users/<id>", handler=get_user),
    Route(method=HttpMethod.POST, path="/users", handler=create_user),
]

blueprint = create_blueprint(routes, name="api", url_prefix="/api/v1")
app.register_blueprint(blueprint)
```

### Option 2: Convert Individual Handlers

```python
from flask import Flask
from superfunctions_flask import to_flask_handler
from superfunctions.http import Response

app = Flask(__name__)

async def get_user(request, context):
    return Response(status=200, body={"id": context.params["id"]})

@app.route("/users/<id>")
def route(id):
    handler = to_flask_handler(get_user)
    return handler(id=id)
```

## Features

- ✅ Automatic request/response conversion
- ✅ HTTP error handling
- ✅ Path parameters
- ✅ Query parameters
- ✅ Headers
- ✅ JSON body parsing
- ✅ Blueprint support

## Benefits

Write framework-agnostic handlers that work across:
- Flask
- FastAPI (with `superfunctions-fastapi`)
- Django (with `superfunctions-django`)

## Example with authfn

```python
from flask import Flask
from superfunctions_flask import create_blueprint
from superfunctions.http import Route, HttpMethod, Response, UnauthorizedError
from authfn import create_authfn, AuthFnConfig

app = Flask(__name__)
auth = create_authfn(AuthFnConfig(database=adapter))

async def get_protected_resource(request, context):
    # Authenticate using authfn
    auth_header = context.headers.get("authorization")
    if not auth_header:
        raise UnauthorizedError("Missing authorization header")
    
    session = await auth.provider.authenticate(request)
    if not session:
        raise UnauthorizedError("Invalid credentials")
    
    return Response(status=200, body={"message": "Protected resource", "user": session.keyId})

routes = [
    Route(method=HttpMethod.GET, path="/protected", handler=get_protected_resource),
]

blueprint = create_blueprint(routes)
app.register_blueprint(blueprint)
```

## License

MIT
superfunctions-fastapi 0.1.0
FastAPI adapter for superfunctions.http
Requires Python: >=3.10
Keywords: adapter, fastapi, http, superfunctions, web

# superfunctions-fastapi

FastAPI adapter for `superfunctions.http`

**Location:** `packages/python-fastapi/`  
**Package:** `superfunctions-fastapi`  
**Import:** `from superfunctions_fastapi import create_router`

## Installation

```bash
pip install superfunctions-fastapi
```

## Usage

### Option 1: Create Router from Routes

```python
from fastapi import FastAPI
from superfunctions.http import Route, HttpMethod, Response, NotFoundError
from superfunctions_fastapi import create_router

app = FastAPI()

# Define handlers using superfunctions abstractions
async def get_user(request, context):
    user_id = context.params["id"]
    
    # Your logic here
    user = await db.find_one(...)
    if not user:
        raise NotFoundError(f"User {user_id} not found")
    
    return Response(status=200, body=user)

async def create_user(request, context):
    data = await context.json()
    user = await db.create(...)
    return Response(status=201, body=user)

# Create router from routes
routes = [
    Route(method=HttpMethod.GET, path="/users/{id}", handler=get_user),
    Route(method=HttpMethod.POST, path="/users", handler=create_user),
]

router = create_router(routes, prefix="/api/v1", tags=["users"])
app.include_router(router)
```

### Option 2: Convert Individual Handlers

```python
from fastapi import FastAPI, Request
from superfunctions_fastapi import to_fastapi_handler
from superfunctions.http import Response

app = FastAPI()

async def get_user(request, context):
    return Response(status=200, body={"id": context.params["id"]})

@app.get("/users/{id}")
async def route(request: Request, id: str):
    handler = to_fastapi_handler(get_user)
    return await handler(request, id=id)
```

## Features

- ✅ Automatic request/response conversion
- ✅ HTTP error handling
- ✅ Path parameters
- ✅ Query parameters
- ✅ Headers
- ✅ JSON body parsing
- ✅ OpenAPI documentation support

## Benefits

Write framework-agnostic handlers that work across:
- FastAPI
- Flask (with `superfunctions-flask`)
- Django (with `superfunctions-django`)

## Example with authfn

```python
from fastapi import FastAPI, Depends
from superfunctions_fastapi import create_router
from superfunctions.http import Route, HttpMethod, Response, UnauthorizedError
from authfn import create_authfn, AuthFnConfig

app = FastAPI()
auth = create_authfn(AuthFnConfig(database=adapter))

async def get_protected_resource(request, context):
    # Authenticate using authfn
    auth_header = context.headers.get("authorization")
    if not auth_header:
        raise UnauthorizedError("Missing authorization header")
    
    session = await auth.provider.authenticate(request)
    if not session:
        raise UnauthorizedError("Invalid credentials")
    
    return Response(status=200, body={"message": "Protected resource", "user": session.keyId})

routes = [
    Route(method=HttpMethod.GET, path="/protected", handler=get_protected_resource),
]

router = create_router(routes)
app.include_router(router)
```

## License

MIT
sfns 0.1.0
Core abstractions for superfunctions ecosystem - database adapters and HTTP utilities
Requires Python: >=3.10
Keywords: adapter, database, http, sfns, superfunctions, web

# superfunctions

> Core abstractions for the superfunctions ecosystem - database adapters and HTTP utilities

**Location:** `packages/python-core/`  
**Package:** `sfns`  
**Import:** `from superfunctions.db import ...` or `from superfunctions.http import ...`

## Installation

```bash
pip install sfns
```

## Usage

### Database Adapters

```python
from superfunctions.db import (
    Adapter,
    CreateParams,
    FindManyParams,
    WhereClause,
    Operator,
)

# Use with any adapter implementation
user = await adapter.create(
    CreateParams(
        model="users",
        data={"name": "Alice", "email": "alice@example.com"},
    )
)

# Query with filters
users = await adapter.find_many(
    FindManyParams(
        model="users",
        where=[
            WhereClause(field="email", operator=Operator.LIKE, value="%@example.com")
        ],
        limit=10,
    )
)
```

### HTTP Abstractions

```python
from superfunctions.http import Request, Response, RouteContext, NotFoundError

async def get_user_handler(request: Request, context: RouteContext) -> Response:
    user_id = context.params.get("id")
    
    user = await db.find_one(...)
    if not user:
        raise NotFoundError(f"User {user_id} not found")
    
    return Response(status=200, body=user)
```

## Adapters

Install adapter packages separately based on your stack:

### Database Adapters

```bash
# SQLAlchemy (coming soon)
pip install superfunctions-sqlalchemy

# Django ORM (coming soon)
pip install superfunctions-django

# Tortoise ORM (coming soon)
pip install superfunctions-tortoise
```

### HTTP Framework Adapters

```bash
# FastAPI (coming soon)
pip install superfunctions-fastapi

# Flask (coming soon)
pip install superfunctions-flask

# Django (coming soon)
pip install superfunctions-django
```

## Documentation

- [Database Documentation](https://docs.superfunctions.dev/db)
- [HTTP Documentation](https://docs.superfunctions.dev/http)
- [API Reference](https://docs.superfunctions.dev/api)

## License

MIT
capl-formatter 0.1.0
Opinionated CAPL code formatter
Requires Python: >=3.10

# CAPL Formatter

AST-based code formatter for CAPL (CANoe/CANalyzer Programming Language).

## Overview

The `capl-formatter` package provides a robust, stable, and idempotent engine for formatting CAPL source code. Unlike regex-based formatters, it uses `tree-sitter-c` to understand the code's structure, ensuring that transformations are safe and accurate.

## Key Features

- **AST-Aware Transformation**: Applies changes based on code structure rather than text patterns.
- **Two-Pass Engine**: A structural pass for complex changes (splitting, spacing) followed by a final precision indentation pass.
- **Standardized Style**:
  - K&R Brace Style (opening brace on the same line).
  - Consistent spacing around binary operators (`+`, `-`, `*`, etc.).
  - Proper spacing for punctuation (commas, semicolons).
  - Intelligent line splitting for consecutive statements.
  - Quote normalization (consistent double quotes).
  - Include sorting and grouping.
- **Aggressive Cleanup**: Eliminates redundant blank lines and trailing whitespace.

## Usage

```python
from capl_formatter.engine import FormatterEngine
from capl_formatter.models import FormatterConfig
from capl_formatter.rules import SpacingRule, IndentationRule

config = FormatterConfig()
engine = FormatterEngine(config)

# Add rules in order
engine.add_rule(SpacingRule(config))
engine.add_rule(IndentationRule(config))

result = engine.format_string("void f(){int x=1;}")
print(result.source)
```

## Architecture

The formatter follows a **Neutral Fact** transformation model:
1.  **Analyze**: Each rule receives a `FormattingContext` (source + AST) and returns a list of `Transformation` objects (start/end offsets + new content).
2.  **Apply**: The `FormatterEngine` sorts and applies transformations bottom-up or iteratively to achieve stability.
3.  **Converge**: Multiple passes ensure that complex structural changes (like splitting lines) are correctly indented in subsequent passes.