moonlabel 0.1.0__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.
moonlabel/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from .dataset import create_dataset
2
+
3
+ __all__ = ["create_dataset"]
4
+ __version__ = "0.1.0"
5
+
6
+
moonlabel/dataset.py ADDED
@@ -0,0 +1,141 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ from typing import Iterable, List, Literal, Optional, Sequence, Tuple
6
+
7
+ from PIL import Image
8
+
9
+ from .infer import MoonDreamInference
10
+
11
+
12
+ @dataclass
13
+ class Detection:
14
+ label: str
15
+ x_min: float
16
+ y_min: float
17
+ x_max: float
18
+ y_max: float
19
+
20
+ def to_yolo(self, image_width: int, image_height: int) -> Tuple[float, float, float, float]:
21
+ x_center = (self.x_min + self.x_max) / 2 / image_width
22
+ y_center = (self.y_min + self.y_max) / 2 / image_height
23
+ width = (self.x_max - self.x_min) / image_width
24
+ height = (self.y_max - self.y_min) / image_height
25
+ return x_center, y_center, width, height
26
+
27
+
28
+ ExportFormat = Literal["yolo"]
29
+
30
+
31
+ def _iter_image_files(root: Path) -> Iterable[Path]:
32
+ exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
33
+ for p in sorted(root.rglob("*")):
34
+ if p.suffix.lower() in exts and p.is_file():
35
+ yield p
36
+
37
+
38
+ try: # optional progress bar dependency
39
+ from tqdm.auto import tqdm as _tqdm
40
+ except Exception: # noqa: S110 - optional
41
+ _tqdm = None
42
+
43
+
44
+ def _progress_iter(iterable: Iterable[Path], total: Optional[int], desc: str, enabled: bool) -> Iterable[Path]:
45
+ if enabled and _tqdm is not None:
46
+ return _tqdm(iterable, total=total, desc=desc, dynamic_ncols=True)
47
+ return iterable
48
+
49
+
50
+ def _write_yolo_labels(
51
+ txt_path: Path,
52
+ detections: List[Detection],
53
+ image_size: Tuple[int, int],
54
+ class_to_id: dict[str, int],
55
+ ) -> None:
56
+ width, height = image_size
57
+ with txt_path.open("w", encoding="utf-8") as f:
58
+ for det in detections:
59
+ x_c, y_c, w, h = det.to_yolo(width, height)
60
+ class_id = class_to_id.get(det.label, 0)
61
+ f.write(f"{class_id} {x_c:.6f} {y_c:.6f} {w:.6f} {h:.6f}\n")
62
+
63
+
64
+ def create_dataset(
65
+ images_dir: str | Path,
66
+ export_format: ExportFormat = "yolo",
67
+ output_dir: Optional[str | Path] = "moonlabel_out_dataset",
68
+ objects: Sequence[str] = (),
69
+ api_key: Optional[str] = None,
70
+ station_endpoint: Optional[str] = None,
71
+ show_progress: bool = True,
72
+ ) -> Path:
73
+ images_root = Path(images_dir).resolve()
74
+ if not images_root.exists() or not images_root.is_dir():
75
+ raise FileNotFoundError(f"Images directory not found: {images_root}")
76
+
77
+ if output_dir is None:
78
+ output_root = images_root / "moonlabel_out"
79
+ else:
80
+ output_root = Path(output_dir).resolve()
81
+ output_root.mkdir(parents=True, exist_ok=True)
82
+
83
+ if export_format != "yolo":
84
+ raise ValueError("Only 'yolo' export_format is supported at the moment")
85
+
86
+ images_out = output_root / "images"
87
+ labels_out = output_root / "labels"
88
+ images_out.mkdir(exist_ok=True)
89
+ labels_out.mkdir(exist_ok=True)
90
+
91
+ prompt_objects = ",".join(objects) if objects else "object"
92
+
93
+ infer = MoonDreamInference(api_key=api_key, station_endpoint=station_endpoint)
94
+
95
+ processed = 0
96
+ labels_list: List[str] = list(objects) if objects else ["object"]
97
+ class_to_id: dict[str, int] = {label: idx for idx, label in enumerate(labels_list)}
98
+ image_paths = list(_iter_image_files(images_root))
99
+ for img_path in _progress_iter(image_paths, total=len(image_paths), desc="Creating dataset", enabled=show_progress):
100
+ image = Image.open(img_path)
101
+ width, height = image.width, image.height
102
+
103
+ _, dets_raw = infer.detect(str(img_path), prompt_objects)
104
+
105
+ detections: List[Detection] = []
106
+ for d in dets_raw:
107
+ label = d.get("label") or prompt_objects
108
+ x_min = float(d["x_min"]) * width
109
+ y_min = float(d["y_min"]) * height
110
+ x_max = float(d["x_max"]) * width
111
+ y_max = float(d["y_max"]) * height
112
+ detections.append(Detection(label, x_min, y_min, x_max, y_max))
113
+ if label not in class_to_id:
114
+ class_to_id[label] = len(labels_list)
115
+ labels_list.append(label)
116
+
117
+ txt_name = img_path.with_suffix(".txt").name
118
+ _write_yolo_labels(labels_out / txt_name, detections, (width, height), class_to_id)
119
+
120
+ target_img = images_out / img_path.name
121
+ if not target_img.exists():
122
+ try:
123
+ import os
124
+ os.link(img_path, target_img)
125
+ except Exception:
126
+ from shutil import copy2
127
+ copy2(img_path, target_img)
128
+
129
+ processed += 1
130
+
131
+ if processed == 0:
132
+ raise RuntimeError(f"No images found under {images_root}")
133
+
134
+ classes_file = output_root / "classes.txt"
135
+ with classes_file.open("w", encoding="utf-8") as f:
136
+ for label in labels_list:
137
+ f.write(label + "\n")
138
+
139
+ return output_root
140
+
141
+
moonlabel/infer.py ADDED
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import List, Tuple, Optional
4
+
5
+ import moondream as md
6
+ from PIL import Image
7
+
8
+ _HF_MODEL = None
9
+
10
+
11
+ class MoonDreamInference:
12
+ def __init__(self, api_key: Optional[str] = None, station_endpoint: Optional[str] = None):
13
+ if api_key and api_key.strip():
14
+ self.model = md.vl(api_key=api_key)
15
+ self.source = "cloud"
16
+ elif station_endpoint and station_endpoint.strip():
17
+ self.model = md.vl(endpoint=station_endpoint)
18
+ self.source = "station"
19
+ else:
20
+ global _HF_MODEL
21
+ if _HF_MODEL is None:
22
+ try:
23
+ from transformers import AutoModelForCausalLM
24
+ import torch
25
+ import os
26
+ except Exception as exc: # ImportError or others
27
+ raise RuntimeError(
28
+ "Local inference requires optional dependencies. Install with 'pip install \"moonlabel[local]\"' or provide api_key/station_endpoint."
29
+ ) from exc
30
+
31
+ env_device = os.getenv("MOONDREAM_DEVICE", "").lower()
32
+ if env_device:
33
+ device_target = env_device
34
+ else:
35
+ if torch.cuda.is_available():
36
+ device_target = "cuda"
37
+ elif torch.backends.mps.is_available():
38
+ device_target = "mps"
39
+ else:
40
+ device_target = "cpu"
41
+
42
+ device_map_arg = {"": device_target} if device_target != "cpu" else None
43
+
44
+ _HF_MODEL = AutoModelForCausalLM.from_pretrained(
45
+ "vikhyatk/moondream2",
46
+ revision="2025-06-21",
47
+ trust_remote_code=True,
48
+ device_map=device_map_arg,
49
+ )
50
+ self.model = _HF_MODEL
51
+ self.source = "local"
52
+
53
+ def detect(self, image_path: str, objects: str) -> Tuple[Image.Image, List[dict]]:
54
+ image = Image.open(image_path)
55
+ result = self.model.detect(image, objects)
56
+ detections = result.get("objects", [])
57
+ return image, detections
58
+
59
+
@@ -0,0 +1,3 @@
1
+ __all__ = []
2
+
3
+
@@ -0,0 +1,101 @@
1
+ from pathlib import Path
2
+ import os
3
+ from importlib.resources import files as resource_files
4
+ from tempfile import NamedTemporaryFile
5
+ from typing import List, Optional
6
+
7
+ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
8
+ from fastapi.staticfiles import StaticFiles
9
+ from fastapi.responses import FileResponse
10
+
11
+ from ..infer import MoonDreamInference
12
+
13
+
14
+ app = FastAPI()
15
+
16
+
17
+ @app.post("/api/detect")
18
+ async def detect(
19
+ image: UploadFile = File(...),
20
+ objects: List[str] = Form(...),
21
+ api_key: Optional[str] = Form(None),
22
+ station_endpoint: Optional[str] = Form(None),
23
+ ):
24
+ try:
25
+ suffix = Path(image.filename).suffix or ".jpg"
26
+ with NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
27
+ tmp.write(await image.read())
28
+ tmp_path = Path(tmp.name)
29
+ except Exception as exc:
30
+ raise HTTPException(status_code=400, detail=f"Failed to read image file: {exc}")
31
+
32
+ try:
33
+ detector = MoonDreamInference(api_key=api_key, station_endpoint=station_endpoint)
34
+ image_pil, detections = detector.detect(str(tmp_path), ",".join(objects))
35
+ finally:
36
+ try:
37
+ tmp_path.unlink(missing_ok=True)
38
+ except Exception:
39
+ pass
40
+
41
+ yolo = []
42
+ for det in detections:
43
+ x_min = det["x_min"]
44
+ y_min = det["y_min"]
45
+ x_max = det["x_max"]
46
+ y_max = det["y_max"]
47
+ x_c = (x_min + x_max) / 2.0
48
+ y_c = (y_min + y_max) / 2.0
49
+ bw = x_max - x_min
50
+ bh = y_max - y_min
51
+ label = det.get("label") or (objects[0] if len(objects) == 1 else "object")
52
+ yolo.append({
53
+ "label": label,
54
+ "x_center": x_c,
55
+ "y_center": y_c,
56
+ "width": bw,
57
+ "height": bh,
58
+ })
59
+
60
+ return {"detections": yolo}
61
+
62
+
63
+ _pkg_static = resource_files("moonlabel.server").joinpath("static")
64
+ _fallback_dist = (Path(__file__).resolve().parents[3] / "ui" / "dist").resolve()
65
+
66
+ def _select_static_root() -> Path | None:
67
+ # Prefer packaged static if it contains an index.html
68
+ if _pkg_static.is_dir():
69
+ pkg_index = Path(os.fspath(_pkg_static)) / "index.html"
70
+ if pkg_index.exists():
71
+ return Path(os.fspath(_pkg_static))
72
+ # Fallback to local ui/dist for development
73
+ if _fallback_dist.is_dir() and (_fallback_dist / "index.html").exists():
74
+ return _fallback_dist
75
+ return None
76
+
77
+ _static_root = _select_static_root()
78
+
79
+ if _static_root and _static_root.exists():
80
+ app.mount(
81
+ "/assets",
82
+ StaticFiles(directory=str(_static_root / "assets")),
83
+ name="assets",
84
+ )
85
+ app.mount(
86
+ "/favicon.ico",
87
+ StaticFiles(directory=str(_static_root)),
88
+ name="fav",
89
+ )
90
+
91
+
92
+ @app.get("/{full_path:path}")
93
+ async def spa_fallback(full_path: str):
94
+ if not (_static_root and _static_root.exists()):
95
+ raise HTTPException(status_code=404, detail="Not Found")
96
+ index_file = _static_root / "index.html"
97
+ if index_file.exists():
98
+ return FileResponse(index_file)
99
+ raise HTTPException(status_code=404, detail="Not Found")
100
+
101
+
@@ -0,0 +1,32 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import webbrowser
5
+
6
+ import uvicorn
7
+
8
+
9
+ DEFAULT_HOST = "localhost"
10
+ DEFAULT_PORT = 8342 # fixed, uncommon port
11
+
12
+
13
+ def main() -> None:
14
+ parser = argparse.ArgumentParser(
15
+ prog="moonlabel-ui",
16
+ description="Start the MoonLabel UI (FastAPI + built UI)",
17
+ )
18
+ parser.add_argument("--host", default=DEFAULT_HOST, help=f"Bind address (default: {DEFAULT_HOST})")
19
+ parser.add_argument("--reload", action="store_true", help="Enable auto reload (dev mode)")
20
+ parser.add_argument("--no-open", action="store_true", help="Do not open the browser automatically")
21
+ args = parser.parse_args()
22
+
23
+ url = f"http://{args.host}:{DEFAULT_PORT}"
24
+ if not args.no_open:
25
+ try:
26
+ webbrowser.open_new_tab(url)
27
+ except Exception:
28
+ pass
29
+
30
+ uvicorn.run("moonlabel.server.api:app", host=args.host, port=DEFAULT_PORT, reload=args.reload)
31
+
32
+