Metadata-Version: 2.5
Name: naveeeen
Version: 0.0.9
Summary: See the difference, with/out naveeeen modv8. Benchmark threading vs sequential execution.
Project-URL: Homepage, https://github.com/navpypi/naveeeen-pypi
Project-URL: Bug Tracker, https://github.com/navpypi/naveeeen-pypi
Author-email: naveen v <navpypi@gmail.com>
License-File: LICENCE
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.5
Description-Content-Type: text/markdown

# naveeeen

> **See the difference, with/out naveeeen modv8.**
> Benchmark threading vs sequential execution in one line of code.

---

## What Is naveeeen?

`naveeeen` is a Python library that lets you:

1. **Run any function over a list of items** using threads or sequentially
2. **Measure and compare the speed** of both approaches
3. **Understand when threading actually helps** (and when it doesn't)
4. **Collect return values** from your function calls
5. **Add retry logic** for flaky operations
6. **Auto-detect** the best execution strategy for your workload

---

## Install

```bash
pip install naveeeen
```

---

## Quick Start — One Line

```python
from naveeeen import e
import time

def fetch(url):
    time.sleep(0.1)   # simulates a network request

urls = [f"https://example.com/{i}" for i in range(20)]

# Run with threading (default)
print(e(fetch, urls))

# Run sequential
print(e(fetch, urls, whizz=False))

# Compare both side by side
print(e(fetch, urls, whizz='both'))
```

**Output:**
```
Completed in 0.112s using naveeeen modv8 (threaded).
  Total   : 20
  Success : 20
  Failed  : 0
  Speed   : 178.57 items/sec

Completed in 2.003s using sequential (no naveeeen modv8).
  Total   : 20
  Success : 20
  Failed  : 0
  Speed   : 9.98 items/sec

  ⚡ Winner     : threaded
  ⏱  Difference : 1.891s
  📈 Speedup    : 17.883x
  ✅ Threading was 94.4% faster.
```

---

## The `e()` Function — Simplest API

```python
from naveeeen import e

result_string = e(
    func,           # your function — must accept one argument
    items,          # any iterable: list, range, generator, tuple
    whizz=True,     # execution mode (see table below)
    max_workers=None,   # number of threads/processes (None = auto)
    retry_policy=None,  # RetryPolicy object (see Retry section)
    strict=False,       # True = stop on first failure
    ordered=True,       # True = results in same order as input
    chunk_size=None,    # split large lists into chunks
)
# Always returns a string — simple to print
```

### `whizz=` Options

```
whizz value          What happens
───────────────────  ─────────────────────────────────────────────
True                 ThreadPoolExecutor — concurrent (default)
False                Plain for-loop — sequential
"threaded"           Same as True
"thread"             Same as True
"sequential"         Same as False
"seq"                Same as False
"process"            ProcessPoolExecutor — for CPU-heavy tasks
"proc"               Same as "process"
"auto"               Library picks the best mode for your function
"both"               Runs threaded + sequential, shows comparison
```

> **Case insensitive** — `"Both"`, `"BOTH"`, `"both"` all work.

---

## Full API — `NaveeeenExecutor`

Use this when you need the actual result data, not just a string.

```python
from naveeeen import NaveeeenExecutor, RetryPolicy

executor = NaveeeenExecutor(
    max_workers=16,        # how many threads/processes
    retry_policy=None,     # RetryPolicy or None
    strict=False,          # raise on first failure?
    ordered=True,          # preserve input order in results?
    chunk_size=None,       # process in batches?
    strategy=None,         # inject custom strategy (advanced)
)

result = executor.run(func, items, whizz=True)
```

### `ExecutionResult` — What You Get Back

```python
result = executor.run(my_func, my_items)

# ── timing ────────────────────────────────────────────────
result.duration      # float — total seconds taken
result.throughput    # float — items per second

# ── counts ────────────────────────────────────────────────
result.total         # int — how many items were processed
result.succeeded     # int — how many succeeded
result.failed        # int — how many failed
result.success       # bool — True only if ALL items succeeded

# ── data ──────────────────────────────────────────────────
result.outputs       # list — return values from func(item)
result.item_results  # tuple of ItemResult objects (one per item)
result.failed_items  # list of ItemResult where success=False

# ── display ───────────────────────────────────────────────
str(result)          # human-readable summary string
result.summary()     # dict — for JSON / logging / APIs
```

### `BothResult` — When `whizz='both'`

```python
result = executor.run(func, items, whizz='both')
# Returns BothResult, not ExecutionResult

result.threaded       # ExecutionResult for threaded run
result.sequential     # ExecutionResult for sequential run
result.faster         # whichever ExecutionResult was faster
result.slower         # whichever was slower
result.difference     # float — time difference in seconds
result.speedup        # float — how many times faster (e.g. 18.2x)

str(result)           # full comparison string
result.summary()      # dict with both results + winner + speedup

# BothResult is iterable — unpack like a tuple
threaded_r, seq_r = result    # ✅ works
for r in result:              # ✅ works
    print(r.summary())
```

---

## Collecting Return Values

The original simple `e()` ignores return values.
Use `NaveeeenExecutor` to collect them:

```python
from naveeeen import NaveeeenExecutor

def double(n):
    return n * 2

executor = NaveeeenExecutor()
result   = executor.run(double, range(10))

print(result.outputs)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
```

---

## Retry Logic

For flaky operations like network requests:

```python
from naveeeen import NaveeeenExecutor, RetryPolicy

# Retry up to 3 times, wait 1s between attempts,
# double the wait each time (1s → 2s → 4s)
policy = RetryPolicy(
    max_attempts = 3,
    delay        = 1.0,    # seconds between retries
    backoff      = 2.0,    # multiply delay after each failure
    exceptions   = (ConnectionError, TimeoutError),  # which errors to retry
)

executor = NaveeeenExecutor(retry_policy=policy)
result   = executor.run(flaky_request, urls)

# See which items needed retries
for item_result in result.item_results:
    if item_result.attempt > 1:
        print(f"{item_result.item} succeeded on attempt {item_result.attempt}")
```

---

## Strict Mode — Stop On First Failure

```python
from naveeeen import NaveeeenExecutor, ExecutionError

def risky(x):
    if x == 5:
        raise ValueError("don't like 5")
    return x * 2

executor = NaveeeenExecutor(strict=True)

try:
    result = executor.run(risky, range(10))
except ExecutionError as e:
    print(f"Stopped: {e}")
```

Without `strict=True`, failures are logged and execution continues.

---

## CPU-Bound Tasks — Multiprocessing

```python
from naveeeen import NaveeeenExecutor

def heavy(n):
    # CPU-intensive work
    return sum(i * i for i in range(n))

# MUST have this guard on Windows/macOS
if __name__ == '__main__':
    executor = NaveeeenExecutor(max_workers=4)
    result   = executor.run(heavy, range(100), whizz='process')
    print(result)
```

> **Why the `if __name__ == '__main__'` guard?**
> On Windows and macOS, Python uses "spawn" to create new processes.
> This re-imports your script in each worker.
> Without the guard, workers spawn more workers → infinite loop → crash.
> On Linux this is not needed (uses "fork").
> If you forget it, naveeeen automatically falls back to threading.

---

## Auto Mode — Let naveeeen Decide

```python
from naveeeen import NaveeeenExecutor

executor = NaveeeenExecutor()

# naveeeen inspects your function's source code
# and picks threading, multiprocessing, or sequential
result = executor.run(my_func, my_items, whizz='auto')
```

---

## Chunked Processing — Large Lists

```python
from naveeeen import NaveeeenExecutor

# Process 1 million items in batches of 10,000
# Prevents RAM spike from submitting all items at once
executor = NaveeeenExecutor(chunk_size=10_000)
result   = executor.run(process, range(1_000_000))
```

---

## Profile Your Function

```python
from naveeeen.detector import WorkloadDetector

def my_func(x):
    import time
    time.sleep(0.1)
    return x

profile = WorkloadDetector.profile(my_func, items_count=50)
print(profile)
# 📊 Task Profile for 'my_func'
#   Items       : 50
#   IO score    : 4
#   CPU score   : 0
#   Local score : 0
#   Recommended : THREADED
#   Threading benefit: HIGH — task has network/wait I/O.
```

---

## Inspecting Failures

```python
from naveeeen import NaveeeenExecutor

def sometimes_fails(x):
    if x % 3 == 0:
        raise ValueError(f"{x} is divisible by 3")
    return x

executor = NaveeeenExecutor()
result   = executor.run(sometimes_fails, range(20))

print(f"Succeeded: {result.succeeded}")
print(f"Failed:    {result.failed}")

for failure in result.failed_items:
    print(f"  Item {failure.item}: {failure.error}")

# Get successful outputs only
print(result.outputs)
```

---

## When Does Threading Help?

```
✅ USE THREADING (whizz=True) FOR:          ❌ DO NOT USE THREADING FOR:
─────────────────────────────────────────   ──────────────────────────────────
HTTP / API requests                         Simple math (x * 2)
Database queries                            Local file create/delete
File downloads/uploads                      In-memory list operations
time.sleep() / waiting                      CPU-heavy computation
SSH / FTP operations                        Tiny lists (< 4 items)
Any task that "waits" for something         Tasks that finish < 1ms each

✅ USE MULTIPROCESSING (whizz='process') FOR:
────────────────────────────────────────────
Heavy math / scientific computing
Image / video processing
Machine learning inference
Any task that maxes out one CPU core
```

> **Rule of thumb:** If your function takes more than 1ms per item
> AND it spends that time waiting (not computing), threading will help.

---

## All Exceptions

```python
from naveeeen import (
    NaveeeenError,         # base — catch all naveeeen errors
    InvalidStrategyError,  # bad whizz= value
    ExecutionError,        # infrastructure failure
    ItemExecutionError,    # single item failed (strict mode)
    RetryExhaustedError,   # all retries used up
)

try:
    result = executor.run(func, items, whizz='bad_value')
except InvalidStrategyError as e:
    print(e)   # Unknown strategy 'bad_value'. Valid options: ...

try:
    result = executor.run(risky_func, items)
except NaveeeenError as e:
    print(e)   # catches ANY naveeeen exception
```

---

## Complete Example

```python
import time
import os
from naveeeen import NaveeeenExecutor, RetryPolicy, BothResult

# ── 1. Define your function ───────────────────────────────────────────────
def download_page(url):
    """Simulate downloading a web page."""
    time.sleep(0.05)   # 50ms network wait
    return f"content of {url}"

# ── 2. Build executor with full config ───────────────────────────────────
executor = NaveeeenExecutor(
    max_workers  = 10,
    retry_policy = RetryPolicy(max_attempts=2, delay=0.5),
    strict       = False,
    ordered      = True,
    chunk_size   = None,
)

# ── 3. Run and compare ────────────────────────────────────────────────────
urls   = [f"https://example.com/page/{i}" for i in range(30)]
result = executor.run(download_page, urls, whizz='both')

# ── 4. Print comparison ───────────────────────────────────────────────────
print(result)

# ── 5. Access data ────────────────────────────────────────────────────────
print(f"\nFaster mode  : {result.faster.mode.name}")
print(f"Speedup      : {result.speedup:.2f}x")
print(f"All outputs  : {result.threaded.outputs[:3]}...")

# ── 6. Machine-readable summary ───────────────────────────────────────────
import json
print(json.dumps(result.summary(), indent=2))
```

---

## License

MIT License. See `LICENSE` file.