edgemind-ai 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
edgemind/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ """
2
+ EdgeMind — High-Performance Local AI Image Generation Engine & SDK
3
+ """
4
+
5
+ from edgemind.client import EdgeMind, EdgeMindImage, init, generate, unload
6
+ from edgemind.telemetry import get_hardware_specs
7
+ from edgemind.model_manager import scan_models, find_hyper_sd_lora
8
+
9
+ __version__ = "0.1.1"
10
+ __license__ = "MIT"
11
+
12
+ __all__ = [
13
+ "EdgeMind",
14
+ "EdgeMindImage",
15
+ "init",
16
+ "generate",
17
+ "unload",
18
+ "get_hardware_specs",
19
+ "scan_models",
20
+ "find_hyper_sd_lora",
21
+ "__version__",
22
+ ]
edgemind/cli.py ADDED
@@ -0,0 +1,91 @@
1
+ """
2
+ EdgeMind CLI — Command-line interface for the edgemind package.
3
+ """
4
+
5
+ import sys
6
+ import argparse
7
+ from edgemind.client import init, generate
8
+ from edgemind.telemetry import get_hardware_specs
9
+ from edgemind.model_manager import scan_models
10
+
11
+ def main():
12
+ parser = argparse.ArgumentParser(
13
+ prog="edgemind",
14
+ description="EdgeMind — High-Performance Local AI Image Generation Engine"
15
+ )
16
+ subparsers = parser.add_subparsers(dest="command", help="Sub-commands")
17
+
18
+ # Command: generate
19
+ gen_parser = subparsers.add_parser("generate", help="Generate an image from prompt")
20
+ gen_parser.add_argument("prompt", type=str, help="Text description of image to generate")
21
+ gen_parser.add_argument("--negative", "-n", type=str, default=None, help="Negative prompt")
22
+ gen_parser.add_argument("--model", "-m", type=str, default=None, help="Path to model checkpoint")
23
+ gen_parser.add_argument("--hyper-sd", type=str, default=None, help="Path to Hyper-SD 1-step LoRA")
24
+ gen_parser.add_argument("--steps", "-s", type=int, default=None, help="Number of inference steps")
25
+ gen_parser.add_argument("--cfg", type=float, default=None, help="Guidance scale")
26
+ gen_parser.add_argument("--aspect-ratio", "-ar", type=str, default="1:1", help="Aspect ratio (1:1, 16:9, etc.)")
27
+ gen_parser.add_argument("--output", "-o", type=str, default=None, help="Output image file path")
28
+ gen_parser.add_argument("--seed", type=int, default=None, help="Random seed (-1 for random)")
29
+ gen_parser.add_argument("--show", action="store_true", help="Open generated image immediately")
30
+
31
+ # Command: info
32
+ subparsers.add_parser("info", help="Display hardware specs and optimal execution profile")
33
+
34
+ # Command: models
35
+ subparsers.add_parser("models", help="List discovered models on local machine")
36
+
37
+ # Default to generate if first argument is a prompt string
38
+ args_list = sys.argv[1:]
39
+ if args_list and args_list[0] not in ["generate", "info", "models", "-h", "--help"]:
40
+ args_list = ["generate"] + args_list
41
+
42
+ args = parser.parse_args(args_list)
43
+
44
+ if args.command == "info":
45
+ specs = get_hardware_specs()
46
+ print("=" * 55)
47
+ print(" EDGEMIND HARDWARE & TELEMETRY PROFILE")
48
+ print("=" * 55)
49
+ print(f" Device Engine : {specs['device_name']} ({specs['device'].upper()})")
50
+ print(f" Profile Tier : {specs['profile']}")
51
+ print(f" System RAM : {specs['ram_used_gb']} GB / {specs['ram_total_gb']} GB ({specs['ram_percent']}%)")
52
+ print(f" GPU VRAM : {specs['vram_used_gb']} GB / {specs['vram_total_gb']} GB")
53
+ print(f" CPU Cores : {specs['cpu_count']}")
54
+ print(f" Precision : {specs['rec_precision'].upper()}")
55
+ print(f" CPU Offload : {specs['rec_cpu_offload']}")
56
+ print(f" VAE Tiling : {specs['rec_vae_tiling']}")
57
+ print("=" * 55)
58
+ return
59
+
60
+ if args.command == "models":
61
+ models = scan_models()
62
+ print(f"Discovered {len(models)} local model(s):")
63
+ for idx, m in enumerate(models, 1):
64
+ print(f" [{idx}] {m['name']} ({m['type']})")
65
+ print(f" Path: {m['path']}")
66
+ return
67
+
68
+ if args.command == "generate":
69
+ print(f"[*] EdgeMind generating: '{args.prompt}'")
70
+ res = generate(
71
+ prompt=args.prompt,
72
+ negative_prompt=args.negative,
73
+ model_path=args.model,
74
+ hyper_sd_path=args.hyper_sd,
75
+ steps=args.steps,
76
+ cfg_scale=args.cfg,
77
+ aspect_ratio=args.aspect_ratio,
78
+ seed=args.seed,
79
+ save=True,
80
+ output_path=args.output
81
+ )
82
+ print(f"[+] Done in {res.elapsed_seconds}s (Seed: {res.seed})")
83
+ print(f"[+] Saved to: {res.saved_path}")
84
+ if args.show:
85
+ res.show()
86
+ return
87
+
88
+ parser.print_help()
89
+
90
+ if __name__ == "__main__":
91
+ main()
edgemind/client.py ADDED
@@ -0,0 +1,402 @@
1
+ """
2
+ EdgeMind Client & Image Representation
3
+ High-level programmatic API for edge AI image generation.
4
+ """
5
+
6
+ import os
7
+ import io
8
+ import time
9
+ import base64
10
+ from typing import Optional, List, Dict, Any, Union
11
+
12
+ try:
13
+ from PIL import Image
14
+ from PIL.PngImagePlugin import PngInfo
15
+ except ImportError:
16
+ Image = None
17
+ PngInfo = None
18
+
19
+ from edgemind.generator import synthesize_image, resolve_dimensions
20
+ from edgemind.model_manager import (
21
+ current_model_info,
22
+ load_diffusers_pipeline,
23
+ unload_model,
24
+ scan_models,
25
+ find_hyper_sd_lora
26
+ )
27
+ from edgemind.telemetry import get_hardware_specs
28
+
29
+
30
+ class EdgeMindImage:
31
+ """
32
+ Rich image result returned by EdgeMind generation.
33
+ Wraps the synthesized PIL Image with native metadata, save helpers, and binary formats.
34
+ """
35
+ def __init__(self, image: Any, metadata: Dict[str, Any], default_output_dir: Optional[str] = None):
36
+ self._image = image
37
+ self.metadata = metadata
38
+ self._default_output_dir = default_output_dir or os.path.join(os.getcwd(), "outputs")
39
+ self.saved_path: Optional[str] = None
40
+
41
+ # Expose primary metadata fields as top-level attributes
42
+ self.prompt: str = metadata.get("prompt", "")
43
+ self.original_prompt: str = metadata.get("original_prompt", "")
44
+ self.negative_prompt: str = metadata.get("negative_prompt", "")
45
+ self.model: Optional[str] = metadata.get("model")
46
+ self.seed: Optional[int] = metadata.get("seed")
47
+ self.steps: int = metadata.get("steps", 1)
48
+ self.cfg_scale: float = metadata.get("cfg_scale", 1.0)
49
+ self.sampler: str = metadata.get("sampler", "Euler")
50
+ self.width: int = metadata.get("width", getattr(image, "width", 512))
51
+ self.height: int = metadata.get("height", getattr(image, "height", 512))
52
+ self.elapsed_seconds: float = metadata.get("elapsed_seconds", 0.0)
53
+ self.hyper_sd_active: bool = metadata.get("hyper_sd_active", False)
54
+
55
+ @property
56
+ def image(self) -> Any:
57
+ """Returns the native PIL Image object."""
58
+ return self._image
59
+
60
+ @property
61
+ def size(self) -> tuple:
62
+ """Returns (width, height) tuple."""
63
+ return (self.width, self.height)
64
+
65
+ def save(self, filepath: Optional[str] = None) -> str:
66
+ """
67
+ Saves the synthesized image to disk with generation metadata embedded in PNG chunks.
68
+ If filepath is omitted, auto-generates a filename in the configured output directory.
69
+ """
70
+ if filepath:
71
+ target_path = os.path.abspath(filepath)
72
+ os.makedirs(os.path.dirname(target_path), exist_ok=True)
73
+ else:
74
+ os.makedirs(self._default_output_dir, exist_ok=True)
75
+ slug = "".join(c if c.isalnum() else "_" for c in self.original_prompt[:24]).strip("_") or "image"
76
+ timestamp = int(time.time())
77
+ filename = f"edgemind_{timestamp}_{self.seed}_{slug}.png"
78
+ target_path = os.path.join(self._default_output_dir, filename)
79
+
80
+ if hasattr(self._image, "info"):
81
+ png_info = self._image.info.get("png_info")
82
+ if png_info:
83
+ self._image.save(target_path, "PNG", pnginfo=png_info)
84
+ else:
85
+ self._image.save(target_path, "PNG")
86
+ elif hasattr(self._image, "save"):
87
+ self._image.save(target_path)
88
+
89
+ self.saved_path = target_path
90
+ return target_path
91
+
92
+ def show(self) -> None:
93
+ """Opens the image immediately in the default OS image viewer."""
94
+ if hasattr(self._image, "show"):
95
+ self._image.show()
96
+
97
+ @property
98
+ def bytes(self) -> bytes:
99
+ """Returns the image as raw PNG binary bytes."""
100
+ buffer = io.BytesIO()
101
+ if hasattr(self._image, "info"):
102
+ png_info = self._image.info.get("png_info")
103
+ if png_info:
104
+ self._image.save(buffer, format="PNG", pnginfo=png_info)
105
+ else:
106
+ self._image.save(buffer, format="PNG")
107
+ elif hasattr(self._image, "save"):
108
+ self._image.save(buffer, format="PNG")
109
+ return buffer.getvalue()
110
+
111
+ @property
112
+ def base64(self) -> str:
113
+ """Returns data URI Base64 string for direct web/API embedding."""
114
+ raw_b64 = base64.b64encode(self.bytes).decode("utf-8")
115
+ return f"data:image/png;base64,{raw_b64}"
116
+
117
+ def to_numpy(self):
118
+ """Converts image to a NumPy array (compatible with OpenCV, PyTorch, Matplotlib)."""
119
+ import numpy as np
120
+ return np.array(self._image)
121
+
122
+ def __repr__(self) -> str:
123
+ return (f"<EdgeMindImage prompt='{self.prompt[:30]}...' "
124
+ f"size={self.width}x{self.height} steps={self.steps} seed={self.seed}>")
125
+
126
+
127
+ class EdgeMind:
128
+ """
129
+ EdgeMind Inference Engine Client.
130
+ Manages model loading, LoRA acceleration, settings, and generation tasks.
131
+ """
132
+ def __init__(
133
+ self,
134
+ model_path: Optional[str] = None,
135
+ hyper_sd_path: Optional[str] = None,
136
+ output_dir: Optional[str] = None,
137
+ device: str = "auto",
138
+ precision: str = "auto",
139
+ cpu_offload: bool = True,
140
+ vae_tiling: bool = True,
141
+ attention_slicing: bool = True,
142
+ preload: bool = False
143
+ ):
144
+ specs = get_hardware_specs()
145
+
146
+ # Resolve device
147
+ if device == "auto":
148
+ self.device = specs["device"]
149
+ else:
150
+ self.device = device.lower()
151
+
152
+ # Resolve precision
153
+ if precision == "auto":
154
+ self.precision = specs["rec_precision"]
155
+ else:
156
+ self.precision = precision.lower()
157
+
158
+ self.cpu_offload = cpu_offload
159
+ self.vae_tiling = vae_tiling
160
+ self.attention_slicing = attention_slicing
161
+
162
+ # Model and LoRA resolution
163
+ self.model_path = model_path or self._auto_discover_model()
164
+ self.hyper_sd_path = hyper_sd_path or find_hyper_sd_lora(self.model_path or "")
165
+ self.output_dir = os.path.abspath(output_dir or os.path.join(os.getcwd(), "outputs"))
166
+
167
+ # Default generation parameters
168
+ self.default_negative_prompt: str = ""
169
+ self.default_steps: Optional[int] = None
170
+ self.default_cfg_scale: Optional[float] = None
171
+ self.default_width: Optional[int] = None
172
+ self.default_height: Optional[int] = None
173
+ self.default_aspect_ratio: str = "1:1"
174
+ self.default_sampler: str = "Euler"
175
+ self.default_auto_enhance: bool = True
176
+ self.default_quality_preset: str = "photorealistic"
177
+
178
+ if preload and self.model_path:
179
+ self.preload()
180
+
181
+ def _auto_discover_model(self) -> Optional[str]:
182
+ """Automatically discovers an available model checkpoint on the system."""
183
+ models = scan_models()
184
+ if models:
185
+ return models[0]["path"]
186
+ return None
187
+
188
+ def configure(
189
+ self,
190
+ model_path: Optional[str] = None,
191
+ hyper_sd_path: Optional[str] = None,
192
+ output_dir: Optional[str] = None,
193
+ negative_prompt: Optional[str] = None,
194
+ steps: Optional[int] = None,
195
+ cfg_scale: Optional[float] = None,
196
+ aspect_ratio: Optional[str] = None,
197
+ width: Optional[int] = None,
198
+ height: Optional[int] = None,
199
+ sampler: Optional[str] = None,
200
+ quality_preset: Optional[str] = None,
201
+ auto_enhance: Optional[bool] = None,
202
+ precision: Optional[str] = None,
203
+ cpu_offload: Optional[bool] = None,
204
+ vae_tiling: Optional[bool] = None,
205
+ attention_slicing: Optional[bool] = None
206
+ ) -> "EdgeMind":
207
+ """Fluent configuration method to update client defaults."""
208
+ if model_path is not None:
209
+ self.model_path = model_path
210
+ if hyper_sd_path is not None:
211
+ self.hyper_sd_path = hyper_sd_path
212
+ if output_dir is not None:
213
+ self.output_dir = os.path.abspath(output_dir)
214
+ if negative_prompt is not None:
215
+ self.default_negative_prompt = negative_prompt
216
+ if steps is not None:
217
+ self.default_steps = steps
218
+ if cfg_scale is not None:
219
+ self.default_cfg_scale = cfg_scale
220
+ if aspect_ratio is not None:
221
+ self.default_aspect_ratio = aspect_ratio
222
+ if width is not None:
223
+ self.default_width = width
224
+ if height is not None:
225
+ self.default_height = height
226
+ if sampler is not None:
227
+ self.default_sampler = sampler
228
+ if quality_preset is not None:
229
+ self.default_quality_preset = quality_preset
230
+ if auto_enhance is not None:
231
+ self.default_auto_enhance = auto_enhance
232
+ if precision is not None:
233
+ self.precision = precision
234
+ if cpu_offload is not None:
235
+ self.cpu_offload = cpu_offload
236
+ if vae_tiling is not None:
237
+ self.vae_tiling = vae_tiling
238
+ if attention_slicing is not None:
239
+ self.attention_slicing = attention_slicing
240
+
241
+ return self
242
+
243
+ def preload(self) -> bool:
244
+ """Explicitly preloads the configured model into memory."""
245
+ if not self.model_path:
246
+ raise ValueError("No model_path configured to preload.")
247
+ success, msg = load_diffusers_pipeline(
248
+ model_path=self.model_path,
249
+ hyper_sd_path=self.hyper_sd_path,
250
+ precision=self.precision,
251
+ device=self.device,
252
+ cpu_offload=self.cpu_offload,
253
+ vae_tiling=self.vae_tiling,
254
+ attention_slicing=self.attention_slicing
255
+ )
256
+ if not success:
257
+ raise RuntimeError(f"Preload failed: {msg}")
258
+ return True
259
+
260
+ def unload(self) -> None:
261
+ """Explicitly unloads the loaded pipeline from memory and purges VRAM cache."""
262
+ unload_model()
263
+
264
+ def generate(
265
+ self,
266
+ prompt: str,
267
+ negative_prompt: Optional[str] = None,
268
+ steps: Optional[int] = None,
269
+ cfg_scale: Optional[float] = None,
270
+ aspect_ratio: Optional[str] = None,
271
+ width: Optional[int] = None,
272
+ height: Optional[int] = None,
273
+ sampler: Optional[str] = None,
274
+ seed: Optional[int] = None,
275
+ auto_enhance: Optional[bool] = None,
276
+ quality_preset: Optional[str] = None,
277
+ save: bool = False,
278
+ output_path: Optional[str] = None
279
+ ) -> EdgeMindImage:
280
+ """
281
+ Synthesizes an image from a text prompt using configured or overridden parameters.
282
+ """
283
+ final_negative = negative_prompt if negative_prompt is not None else self.default_negative_prompt
284
+ final_steps = steps if steps is not None else self.default_steps
285
+ final_cfg = cfg_scale if cfg_scale is not None else self.default_cfg_scale
286
+ final_ar = aspect_ratio if aspect_ratio is not None else self.default_aspect_ratio
287
+ final_w = width if width is not None else self.default_width
288
+ final_h = height if height is not None else self.default_height
289
+ final_sampler = sampler if sampler is not None else self.default_sampler
290
+ final_enhance = auto_enhance if auto_enhance is not None else self.default_auto_enhance
291
+ final_preset = quality_preset if quality_preset is not None else self.default_quality_preset
292
+
293
+ image, metadata = synthesize_image(
294
+ prompt=prompt,
295
+ negative_prompt=final_negative,
296
+ model_path=self.model_path,
297
+ hyper_sd_path=self.hyper_sd_path,
298
+ steps=final_steps,
299
+ cfg_scale=final_cfg,
300
+ width=final_w,
301
+ height=final_h,
302
+ aspect_ratio=final_ar,
303
+ sampler=final_sampler,
304
+ seed=seed,
305
+ auto_enhance=final_enhance,
306
+ quality_preset=final_preset,
307
+ precision=self.precision,
308
+ device=self.device,
309
+ cpu_offload=self.cpu_offload,
310
+ vae_tiling=self.vae_tiling,
311
+ attention_slicing=self.attention_slicing
312
+ )
313
+
314
+ res = EdgeMindImage(image, metadata, default_output_dir=self.output_dir)
315
+ if save or output_path:
316
+ res.save(output_path)
317
+
318
+ return res
319
+
320
+ def generate_batch(
321
+ self,
322
+ prompts: List[str],
323
+ save: bool = False,
324
+ **kwargs
325
+ ) -> List[EdgeMindImage]:
326
+ """Generates multiple images sequentially."""
327
+ results = []
328
+ for p in prompts:
329
+ results.append(self.generate(p, save=save, **kwargs))
330
+ return results
331
+
332
+ @property
333
+ def models(self) -> List[Dict[str, Any]]:
334
+ """Returns list of discovered models across local machine paths."""
335
+ return scan_models()
336
+
337
+ @property
338
+ def hardware_info(self) -> Dict[str, Any]:
339
+ """Returns live hardware telemetry and memory profiles."""
340
+ return get_hardware_specs()
341
+
342
+ @property
343
+ def is_loaded(self) -> bool:
344
+ """Returns True if a model pipeline is currently loaded in memory."""
345
+ return current_model_info.get("loaded", False)
346
+
347
+ def __repr__(self) -> str:
348
+ loaded_str = "Loaded" if self.is_loaded else "Idle"
349
+ model_name = os.path.basename(self.model_path) if self.model_path else "None"
350
+ return f"<EdgeMind model='{model_name}' device='{self.device}' state='{loaded_str}'>"
351
+
352
+
353
+ # Module-level single instance cache
354
+ _default_client: Optional[EdgeMind] = None
355
+
356
+ def init(
357
+ model_path: Optional[str] = None,
358
+ hyper_sd_path: Optional[str] = None,
359
+ output_dir: Optional[str] = None,
360
+ device: str = "auto",
361
+ precision: str = "auto",
362
+ cpu_offload: bool = True,
363
+ vae_tiling: bool = True,
364
+ attention_slicing: bool = True,
365
+ preload: bool = False
366
+ ) -> EdgeMind:
367
+ """
368
+ Initializes and returns an EdgeMind inference client.
369
+ Sets the default client for module-level edgemind.generate(...) calls.
370
+ """
371
+ global _default_client
372
+ client = EdgeMind(
373
+ model_path=model_path,
374
+ hyper_sd_path=hyper_sd_path,
375
+ output_dir=output_dir,
376
+ device=device,
377
+ precision=precision,
378
+ cpu_offload=cpu_offload,
379
+ vae_tiling=vae_tiling,
380
+ attention_slicing=attention_slicing,
381
+ preload=preload
382
+ )
383
+ _default_client = client
384
+ return client
385
+
386
+ def generate(prompt: str, **kwargs) -> EdgeMindImage:
387
+ """
388
+ One-liner module-level image generation function.
389
+ Automatically initializes default EdgeMind client if not already initialized.
390
+ """
391
+ global _default_client
392
+ if _default_client is None:
393
+ _default_client = init()
394
+ return _default_client.generate(prompt, **kwargs)
395
+
396
+ def unload() -> None:
397
+ """Frees loaded pipeline from memory and purges VRAM cache."""
398
+ global _default_client
399
+ if _default_client:
400
+ _default_client.unload()
401
+ else:
402
+ unload_model()