Metadata-Version: 2.4
Name: blackbox-py-custom
Version: 0.1.1
Summary: Python scriptleri için sıfır-ayar olay yeri inceleme ve hata raporlama aracı.
Author: Ali İhsan Şahin
Keywords: debugging,crash,reporter,error,logging,blackbox
Requires-Python: >=3.6
Description-Content-Type: text/markdown
Dynamic: author
Dynamic: description
Dynamic: description-content-type
Dynamic: keywords
Dynamic: requires-python
Dynamic: summary

# Blackbox 🔲

*A zero-configuration, post-mortem state recorder and crash reporter for Python.*

##   Overview

When developing complex Python applications—especially long-running numerical simulations, data processing pipelines, or unattended scripts—a standard terminal traceback is rarely enough. Standard tracebacks tell you *where* your code crashed, but they completely fail to tell you *why*. 

You are often left wondering: What were the exact values of the local variables when the division by zero occurred? What was the state of the iteration index? **Blackbox** is designed to solve this exact problem.

Think of Blackbox as a flight recorder for your Python functions. By simply wrapping your core functions with a single decorator, Blackbox lies dormant with **zero performance overhead** during normal execution. However, the exact millisecond an unhandled exception occurs, Blackbox intercepts the crash, extracts the precise state of all local variables in the failing frame, and dumps this invaluable context into a clean, offline HTML report.

##   Core Mechanisms & Philosophy

Blackbox is built on the principle of maximum utility with minimum interference. 

1. **Zero-Overhead Execution:** Unlike traditional debuggers (like `pdb`) or profilers that continuously monitor state and slow down your code, Blackbox does not trace loops or evaluate variables during normal execution. Your heavy calculations and loops run at full native speed. Performance is absolutely unaffected until an actual exception is raised.
2. **Surgical State Capture:** Upon a crash, the system uses `sys.exc_info()` to traverse the traceback stack. It pinpoints the exact frame where the exception originated and extracts the local variables, arguments, and object states exactly as they were at the moment of failure.
3. **Safe Serialization (`safe_repr`):** Long-running scripts often deal with massive data structures, large arrays, or unreadable components (such as open serial ports, database connections, or unpicklable objects). Blackbox employs a custom sanitization module to safely truncate enormous objects. This guarantees that the crash reporter itself will never cause a secondary `MemoryError` or recursive loop while trying to save the state.
4. **Offline, Self-Contained Reporting:** There are no API keys, no cloud telemetry, and no external servers. A self-contained HTML file is generated locally in the `crash_reports` directory. The UI automatically highlights suspicious variable states (such as `0`, `None`, empty lists `[]`, or `False`) that typically cause systemic crashes.
5. **Standard Termination:** Blackbox does not swallow your errors. After the HTML report is successfully written to the disk, the original exception is faithfully re-raised. This ensures your program terminates natively or can be caught by upper-level exception handlers.

##   Installation

Install directly from PyPI:

```bash
pip install blackbox-py
```

##   Usage & Real-World Example

Wrap your function with the `@blackbox` decorator. No configuration, initialization, or setup functions are required.

### Basic Example

```python
from blackbox import blackbox

@blackbox
def run_heavy_simulation(battery_id, max_cycles):
    print(f"Starting simulation for {battery_id}")
    
    for cycle in range(max_cycles):
        # Complex calculations happening here...
        current = 10 - cycle
        voltage = 120.5
        
        # At cycle 10, current becomes 0. A standard traceback wouldn't 
        # tell you that 'cycle' was exactly 10 when this failed.
        # Blackbox will capture the exact state of 'current', 'voltage', and 'cycle'.
        resistance = voltage / current 

    return True

run_heavy_simulation("LFP-BATT-01", 15)
```

### What Happens When It Crashes?

1. The script will raise the `ZeroDivisionError` as it normally would.
2. A new directory called `crash_reports` will be instantly created in your working directory.
3. An HTML file named with the current timestamp (e.g., `crash_run_heavy_simulation_20260718_121825.html`) will be generated.
4. Opening this HTML file will reveal the exact line of code that failed, alongside a clean table showing:
* `battery_id`: `"LFP-BATT-01"`
* `max_cycles`: `15`
* `cycle`: `10`
* `current`: `0` *(Highlighted in red as a suspicious value)*
* `voltage`: `120.5`

##   API Reference & Usage Guide

The Blackbox library is designed to be completely plug-and-play. You do not need to write custom error handlers or modify your core logic.

### `@blackbox`

**What does it do?**

This is the core decorator of the library. It acts as a wrapper around any function. During normal operation, it does nothing and has zero impact on performance. If (and only if) an unhandled exception occurs inside the wrapped function, it intercepts the crash, reads the state of all local variables at that exact moment, generates the HTML report, and then re-raises the error.

**How to use it:**

Simply import it and place it directly above the function you want to monitor. It requires no arguments.

```python
from blackbox import blackbox

@blackbox
def process_sensor_data(sensor_id, readings):
    # If anything in this function fails, Blackbox will generate a report.
    multiplier = 0
    result = readings[0] / multiplier # Crash happens here
    return result
```

### What do you need to write to catch an error?

Nothing. You do not need to write `try-except` blocks. Blackbox automatically catches native Python errors (like `ZeroDivisionError`, `IndexError`, `TypeError`, etc.).

It also catches manual errors raised by the developer. If your script logic dictates a failure, simply use Python's standard `raise` statement:

```python
from blackbox import blackbox

@blackbox
def connect_to_database(retries):
    connection_status = False
    
    if retries == 0:
        # Manually triggering a crash. Blackbox will catch this, 
        # save the state showing 'retries = 0' and 'connection_status = False', 
        # and generate the HTML report.
        raise ConnectionError("Failed to connect after all retries.")
```

##   Security & Privacy Warning

Blackbox captures the exact values of all local variables at the time of a crash. This means if you have hardcoded passwords, API keys, or sensitive database URIs present in the failing function, they will be written in plain text to the HTML report.

* Always add `crash_reports/` to your `.gitignore` file.
* Never share these HTML reports on public forums without reviewing them for sensitive data first.

##   Under the Hood (Developer Documentation)

Blackbox is modular by design. If you want to contribute or just understand how the magic happens, here is a breakdown of the internal architecture:

### 1. `core.py` (The Interceptor)

This is the heart of the library. It contains the `@blackbox` decorator. 

* **Mechanism:** It wraps the target function inside a barebones `try-except` block. During normal execution, it simply returns the function's original output. 
* **Crash Handling:** If an exception is caught, it uses Python's built-in `sys.exc_info()` to grab the active traceback object. It navigates to the exact frame where the error originated (`tb.tb_next`) and extracts the local variable dictionary (`frame.f_locals`). It then passes this raw data to the reporter before finally re-raising the original exception.

### 2. `utils.py` (The Sanitizer)

Dumping raw memory into a string is dangerous. If your local variables contain a 10,000-element list, a raw database connection pool, or deeply nested dictionaries, a naive string conversion will cause a secondary `MemoryError` or recursion limit crash.

* **Mechanism:** The `safe_repr(obj)` function inspects every extracted variable. It safely truncates large iterables (e.g., showing only the first and last few elements of a list), limits string lengths, and handles unpicklable or complex objects gracefully. This guarantees Blackbox will never crash your system while trying to report a crash.

### 3. `reporter.py` (The Visualizer)

This module is responsible for turning the sanitized variables and traceback data into a human-readable format.

* **Mechanism:** It dynamically generates an offline HTML file. The reporter iterates through the sanitized local variables and applies a simple heuristic check: if a variable's value is `0`, `None`, `[]`, or `False`, it flags it visually in the HTML report. This helps developers instantly spot the "empty" or "null" states that typically lead to `ZeroDivisionError` or `TypeError` crashes.

##   Project Structure

For developers looking to contribute or understand the source code:

* `core.py`: Contains the main `@blackbox` decorator and exception interception logic.
* `reporter.py`: Handles the generation and formatting of the HTML output.
* `utils.py`: Contains the `safe_repr` function and data sanitization algorithms.

##   License

This project is licensed under the MIT License. See the LICENSE file for details.
