Metadata-Version: 2.4
Name: edgemind-ai
Version: 0.1.1
Summary: High-performance, self-optimizing local AI image generation engine and Python SDK
Author: EdgeMind Contributors
License: MIT
Project-URL: Homepage, https://github.com/VikasPatel22/EdgeMind
Project-URL: Repository, https://github.com/VikasPatel22/EdgeMind.git
Project-URL: Issues, https://github.com/VikasPatel22/EdgeMind/issues
Keywords: ai,image-generation,stable-diffusion,diffusers,hyper-sd,cuda,mps,edge-ai
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Multimedia :: Graphics
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.1.0
Requires-Dist: diffusers>=0.27.0
Requires-Dist: transformers>=4.38.0
Requires-Dist: accelerate>=0.27.0
Requires-Dist: safetensors>=0.4.0
Requires-Dist: psutil>=5.9.0
Requires-Dist: Pillow>=10.0.0
Requires-Dist: huggingface_hub>=0.20.0
Requires-Dist: peft>=0.9.0
Requires-Dist: kornia>=0.7.1
Dynamic: license-file

# 🚀 EdgeMind

<div align="center">

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Python: 3.10+](https://img.shields.io/badge/Python-3.10%20%7C%203.11%20%7C%203.12-blue.svg)](https://www.python.org/)
[![PyTorch](https://img.shields.io/badge/PyTorch-2.1+-ee4c2c.svg)](https://pytorch.org/)
[![Diffusers](https://img.shields.io/badge/Diffusers-0.27+-orange.svg)](https://github.com/huggingface/diffusers)
[![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)](#-platform--hardware-support)
[![Hardware](https://img.shields.io/badge/Hardware-NVIDIA%20CUDA%20%7C%20Apple%20MPS%20%7C%20AMD%20ROCm%20%7C%20CPU-success.svg)](#-platform--hardware-support)

**A high-performance, self-optimizing local AI image generation engine and Python SDK.**  
Engineered to run seamlessly across any operating system, custom hardware configuration, or path setup without overflowing VRAM or system memory.

[Quickstart](#-quickstart) • [API Guide](#-python-sdk--api-guide) • [CLI Commands](#-cli-interface) • [Platform Support](#-platform--hardware-support) • [Model Setup](#-model-setup--scanning)

</div>

---

## ✨ Key Features

- **🐍 Pure Python Module**: Seamlessly embed local image generation into Python apps, Discord bots, agent workflows, and backend services with `import edgemind`.
- **⚡ 1-Step Hyper-SD Acceleration**: Generates photorealistic high-fidelity images in just **1 inference step** with zero quality loss using automatic Hyper-SD LoRA fusion.
- **🌐 Cross-Platform & Universal Paths**: Runs natively on **Windows**, **Linux**, and **macOS** (including Apple Silicon M-series). Automatically discovers models across custom directories, environment variables, Hugging Face caches, and local WebUI installations.
- **🧠 Hardware Telemetry & Dynamic Profiling**:
  - Live hardware probing for CPU cores, available system RAM, and GPU VRAM.
  - Automatic selection of optimization profiles:
    - 🟢 **Ultra VRAM** (>16GB VRAM): Full pipeline caching and native batch processing.
    - 🔵 **High VRAM** (8–16GB VRAM): FP16 / BF16 mixed-precision acceleration.
    - 🟡 **Medium VRAM** (4–8GB VRAM): Automated model CPU offloading and VAE tiling.
    - 🟠 **Low VRAM / CPU** (<4GB VRAM): Sequential sub-module CPU offloading, VAE slicing, and attention slicing.
- **🧹 Zero-Leak Memory Management**: Programmatic memory purging (`client.unload()`) releasing CUDA cache, IPC handles, and system garbage collector instantly.
- **🖼️ Rich Image Representation**: Output `EdgeMindImage` object provides direct `.save()`, `.show()`, raw `PIL.Image`, PNG byte stream, Base64 data URI, and embedded generation metadata.

---

## 💻 Platform & Hardware Support

EdgeMind automatically detects your hardware architecture and applies the most efficient backend:

| Hardware Tier | Platform | Acceleration Backend | Precision Supported |
| :--- | :--- | :--- | :--- |
| **NVIDIA GPU** | Windows / Linux | CUDA (11.8, 12.1, 12.4+) | FP16, BF16, FP32 |
| **Apple Silicon (M1/M2/M3/M4)** | macOS | Metal Performance Shaders (MPS) | FP16, FP32 |
| **AMD GPU** | Linux / Windows | ROCm / DirectML | FP16, FP32 |
| **CPU Only** | All Platforms | PyTorch CPU with CPU Offload & Slicing | FP32 |

---

## 🛠️ Installation & Setup

### 1. Install PyTorch Tailored to Your Hardware

#### NVIDIA GPU (CUDA 12.1 - Recommended):
```bash
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121
```

#### Apple Silicon (macOS MPS) or CPU-Only:
```bash
pip install torch torchvision
```

---

### 2. Install EdgeMind

#### From PyPI:
```bash
pip install edgemind-ai
```

#### From Source:
```bash
git clone https://github.com/VikasPatel22/EdgeMind.git
cd EdgeMind
pip install -e .
```

#### Via Requirements:
```bash
pip install -r requirements.txt
```

---

## 🚀 Quickstart

Generate an image in 3 lines of Python code:

```python
import edgemind

# Auto-detects local hardware, best checkpoint, and 1-step LoRA
image = edgemind.generate("Cyberpunk samurai cat in neon rain, cinematic lighting, 8k", save=True)

print(f"Generated in {image.elapsed_seconds}s (Seed: {image.seed})")
print(f"Saved to: {image.saved_path}")
image.show()
```

---

## 📖 Python SDK & API Guide

### 1. Initialize the Engine (`edgemind.init`)

Configure custom model checkpoints, optional 1-step Hyper-SD LoRA, and memory options:

```python
import edgemind

# Initialize client with custom paths and settings
ai = edgemind.init(
    model_path="models/dreamshaper_8.safetensors",               # Local checkpoint or Diffusers repo
    hyper_sd_path="models/Hyper-SD15-1step-lora.safetensors",   # Optional 1-step turbo LoRA
    output_dir="./outputs",                                      # Output save folder
    device="auto",                                               # "auto", "cuda", "mps", "cpu"
    precision="auto",                                            # "auto", "fp16", "bf16", "fp32"
    cpu_offload=True,                                            # Automated CPU offload
    vae_tiling=True,                                             # VAE tiling for lower VRAM
    attention_slicing=True                                       # Attention slicing
)
```

---

### 2. Configure Client Defaults (`client.configure`)

Set reusable generation defaults using the fluent builder API:

```python
ai.configure(
    negative_prompt="blurry, distorted, ugly, low quality, bad anatomy",
    steps=1,                 # 1 inference step for Hyper-SD LoRA
    cfg_scale=1.0,           # Recommended CFG for 1-step generation
    aspect_ratio="16:9",     # "1:1", "16:9", "9:16", "4:3", "3:4", "21:9"
    sampler="Euler",         # "Euler", "Euler A", "DPM++ 2M", "DDIM", "UniPC", "Heun"
    auto_enhance=True,       # Aesthetic prompt quality enhancer
    quality_preset="photorealistic" # "photorealistic", "cinematic", "anime", "cyberpunk", "3d"
)
```

---

### 3. Generate Single Images (`client.generate`)

```python
image = ai.generate(
    prompt="A celestial lion sculpted from galaxy nebulas, glowing starlight, 8k",
    seed=42,                 # Explicit seed or omit for random
    aspect_ratio="16:9",     # Overrides client default
    save=True                # Automatically saves to output_dir
)
```

---

### 4. Working With `EdgeMindImage`

The result returned by `generate()` provides rich native properties and export methods:

```python
# 1. Native PIL Image
pil_img = image.image       # Standard PIL.Image.Image instance

# 2. Save to custom location (with embedded generation metadata in PNG chunks)
image.save("custom_path.png")

# 3. View in OS default image viewer
image.show()

# 4. Binary PNG bytes (for file transfers, streaming, or Discord bots)
raw_bytes = image.bytes

# 5. Base64 Data URI (for web APIs or HTML rendering)
b64_uri = image.base64

# 6. NumPy array (for OpenCV or ML pipelines)
np_array = image.to_numpy()

# 7. Metadata inspection
print("Prompt:", image.prompt)
print("Seed:", image.seed)
print("Elapsed Time:", image.elapsed_seconds)
print("Model Used:", image.model)
print("Hyper-SD Active:", image.hyper_sd_active)
```

---

### 5. Batch Image Generation (`client.generate_batch`)

Generate multiple image variations sequentially:

```python
prompts = [
    "Ethereal crystal castle floating above storm clouds, golden hour",
    "Bioluminescent deep sea astronaut discovering ancient ruins",
    "Cyberpunk neon street market in Tokyo at midnight, ultra realistic"
]

results = ai.generate_batch(prompts, save=True, steps=1)

for img in results:
    print(f"Saved: {img.saved_path} (Seed: {img.seed})")
```

---

### 6. Memory Management (`client.unload`)

Explicitly flush GPU VRAM and release pipeline from system memory:

```python
ai.unload()
```

---

### 7. Inspect Hardware & Discovered Models

```python
# Hardware specs and auto-profile
specs = ai.hardware_info
print(f"Device: {specs['device_name']}, Profile: {specs['profile']}, VRAM: {specs['vram_total_gb']}GB")

# Discovered local model checkpoints across drives
models = ai.models
for m in models:
    print(f"- {m['name']} ({m['format']}) at {m['path']}")
```

---

## 💻 CLI Interface

EdgeMind provides a command-line interface directly from your terminal:

```bash
# Generate image from prompt
edgemind "A neon cyberpunk samurai cat, 8k resolution" --steps 1 --output cat.png --show

# Inspect hardware and execution tier
edgemind info

# List discovered local models
edgemind models
```

---

## 📁 Model Setup & Scanning

EdgeMind supports **`.safetensors`**, **`.ckpt`**, and **Diffusers format** folders (Stable Diffusion 1.5, SD 2.1, SDXL, SDXL Turbo, Flux, etc.).

### Option A: Local Models Folder
Place checkpoints into `./models/`:
```text
models/
├── dreamshaper_8.safetensors
└── Hyper-SD15-1step-lora.safetensors
```

### Option B: Automatic Cross-Platform Discovery
EdgeMind automatically detects models in common installation directories across Windows, macOS, and Linux without requiring duplicate downloads:
- `~/.cache/huggingface/hub/` (Hugging Face default hub cache)
- `~/stable-diffusion-webui/models/Stable-diffusion`
- `~/Fooocus/models/checkpoints`
- `~/ComfyUI/models/checkpoints`
- Common WebUI, Fooocus, and ComfyUI checkpoint folders across system drives (Windows / Linux / macOS)

### Option C: Custom Models Path via Environment Variable
```bash
# Windows (PowerShell)
$env:EDGEMIND_MODELS_DIR="D:\AI_Models\Checkpoints"

# Linux / macOS
export EDGEMIND_MODELS_DIR="/mnt/data/models"
```

---

## ⚡ 1-Step Hyper-SD LoRA Acceleration

For near-instant 1-step generation:
1. Download `Hyper-SD15-1step-lora.safetensors` from Hugging Face:
   ```bash
   curl -L -o models/Hyper-SD15-1step-lora.safetensors "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SD15-1step-lora.safetensors"
   ```
2. EdgeMind automatically detects and fuses the LoRA, configuring Euler scheduling with trailing timestep spacing for lightning inference.

---

## 📄 License

Distributed under the **MIT License**. See [LICENSE](LICENSE) for more details.
