Deploy Project Halide Gradio Space
Browse filesFiles changed (35)
- LICENSEAdded+201
- README.md+8-8
- app.pyAdded+27
- config.pyAdded+154
- data/__init__.pyAdded+1
- data/augmentation.pyAdded+160
- data/datasets.pyAdded+130
- data/preprocessing.pyAdded+109
- data/schemas.pyAdded+268
- models/__init__.pyAdded+1
- models/reasoning/.gitkeepAdded
- models/reasoning/__init__.pyAdded+1
- models/reasoning/inference.pyAdded+7
- models/reasoning/nemotron_wrapper.pyAdded+166
- models/reasoning/prompts.pyAdded+307
- models/vision/.gitkeepAdded
- models/vision/__init__.pyAdded+1
- models/vision/inference.pyAdded+46
- models/vision/minicpm_wrapper.pyAdded+243
- pipeline/.gitkeepAdded
- pipeline/__init__.pyAdded+1
- pipeline/diagnoser.pyAdded+65
- pipeline/extractor.pyAdded+18
- pipeline/pipeline.pyAdded+62
- requirements.txtAdded+10
- storage/.gitkeepAdded
- storage/__init__.pyAdded+1
- storage/cache.pyAdded+94
- storage/database.pyAdded+190
- ui/.gitkeepAdded
- ui/__init__.pyAdded+1
- ui/app.pyAdded+251
- ui/components.pyAdded+106
- ui/server.pyAdded+39
- ui/theme.pyAdded+238
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.12345678910111213---title: Project Halideemoji: 🔥colorFrom: bluecolorTo: bluesdk: gradiosdk_version: 6.18.0python_version: '3.12'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213---title: Project Halidesdk: gradiosdk_version: 6.10.0app_file: app.pylicense: apache-2.0---# Project HalideEdge-native diagnostic engine for analog film scans. Runtime uses MiniCPM-V 4.6 for defect extraction and Nemotron-Mini-4B-Instruct for few-shot diagnostic reasoning.The Space runs without cloud inference APIs. Model execution is on the Space GPU runtime.
123456789101112131415161718192021222324252627"""Main entry point. Launches the Gradio app."""
from __future__ import annotations
import logging
from ui.app import build_app
def main() -> None: logging.basicConfig( level=logging.INFO, format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", ) from ui.theme import THEME_CSS, build_theme app = build_app() app.queue(max_size=8).launch( server_name="0.0.0.0", server_port=7860, show_error=True, theme=build_theme(), css=THEME_CSS, )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Runtime configuration for Project Halide.
This module intentionally contains no model imports. It is safe to import inlocal CPU-only tooling, tests, and dataset preparation scripts."""
from __future__ import annotations
import osfrom dataclasses import dataclassfrom pathlib import Path
REPO_ROOT = Path(__file__).resolve().parentDATA_DIR = REPO_ROOT / "data"STORAGE_DIR = REPO_ROOT / "storage"CHECKPOINT_DIR = REPO_ROOT / "checkpoints"
CANONICAL_VISION_MODEL_ID = "openbmb/MiniCPM-V-4.6"VISION_MODEL_ALIASES = { "openbmb/MiniCPM-V-4_6": CANONICAL_VISION_MODEL_ID,}DEFAULT_FINETUNED_MODEL_ID = "build-small-hackathon/halide-vision"DEFAULT_REASONING_MODEL_ID = "nvidia/Nemotron-Mini-4B-Instruct"
def env_bool(name: str, default: bool = False) -> bool: value = os.getenv(name) if value is None: return default return value.strip().lower() in {"1", "true", "yes", "on"}
def env_int(name: str, default: int) -> int: value = os.getenv(name) if value is None or value.strip() == "": return default return int(value)
def env_path(name: str, default: Path) -> Path: value = os.getenv(name) return Path(value) if value else default
def normalize_model_id(model_id: str) -> str: return VISION_MODEL_ALIASES.get(model_id, model_id)
@dataclass(frozen=True)class VisionConfig: base_model_id: str finetuned_model_id: str local_model_path: Path use_finetuned: bool downsample_mode: str max_slice_nums: int max_new_tokens: int
@dataclass(frozen=True)class ReasoningConfig: model_id: str max_new_tokens: int
@dataclass(frozen=True)class AppConfig: db_path: Path cache_size: int cache_ttl_seconds: int gpu_duration_seconds: int max_history_items: int
def get_vision_config() -> VisionConfig: return VisionConfig( base_model_id=normalize_model_id( os.getenv("HALIDE_VISION_BASE_MODEL_ID", CANONICAL_VISION_MODEL_ID) ), finetuned_model_id=os.getenv( "HALIDE_VISION_FINETUNED_MODEL_ID", DEFAULT_FINETUNED_MODEL_ID ), local_model_path=env_path( "HALIDE_VISION_LOCAL_MODEL_PATH", CHECKPOINT_DIR / "minicpm-v-4.6-merged-v3", ), use_finetuned=env_bool("HALIDE_USE_FINETUNED_VISION", False), downsample_mode=os.getenv("HALIDE_DOWNSAMPLE_MODE", "4x"), max_slice_nums=env_int("HALIDE_MAX_SLICE_NUMS", 36), max_new_tokens=env_int("HALIDE_MAX_NEW_TOKENS", 2048), )
def get_reasoning_config() -> ReasoningConfig: return ReasoningConfig( model_id=os.getenv("HALIDE_REASONING_MODEL_ID", DEFAULT_REASONING_MODEL_ID), max_new_tokens=env_int("HALIDE_NEMOTRON_MAX_TOKENS", 768), )
def get_app_config() -> AppConfig: return AppConfig( db_path=env_path("HALIDE_DB_PATH", STORAGE_DIR / "halide.db"), cache_size=env_int("HALIDE_CACHE_SIZE", 64), cache_ttl_seconds=env_int("HALIDE_CACHE_TTL_SECONDS", 3600), gpu_duration_seconds=env_int("HALIDE_GPU_DURATION_SECONDS", 300), max_history_items=env_int("HALIDE_HISTORY_LIMIT", 10), )
def running_on_hugging_face_space() -> bool: return bool(os.getenv("SPACE_ID") or os.getenv("SPACE_HOST"))
def require_gpu_for_inference(stage: str) -> None: """Refuse model inference unless a CUDA device is visible.
Local CPU use is allowed for file I/O, JSON parsing, image resizing, tests, and dataset preparation. It is not allowed for loading or running the vision or reasoning models. """ import torch
if torch.cuda.is_available(): return
raise RuntimeError( f"Halide refused to run {stage} model inference because no CUDA GPU " "is visible. Run inference on Modal, Hugging Face ZeroGPU, or another " "GPU runtime. Local CPU is reserved for editing, parsing, and tests." )
__all__ = [ "AppConfig", "CHECKPOINT_DIR", "CANONICAL_VISION_MODEL_ID", "DATA_DIR", "DEFAULT_FINETUNED_MODEL_ID", "DEFAULT_REASONING_MODEL_ID", "REPO_ROOT", "ReasoningConfig", "STORAGE_DIR", "VisionConfig", "env_bool", "env_int", "env_path", "get_app_config", "get_reasoning_config", "get_vision_config", "normalize_model_id", "require_gpu_for_inference", "running_on_hugging_face_space",]1"""Data package. Dataset loading, preprocessing, and schemas."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""Synthetic defect augmentation helpers."""
from __future__ import annotations
import randomfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Iterable
from PIL import Image, ImageEnhance, ImageOps
from data.preprocessing import load_image
SYNTHETIC_LABEL_MAP = { "dust": "dust", "dirt": "dirt", "dots": "dust", "hair": "long_hair", "hair-short": "short_hair", "lint": "short_hair", "scratches": "scratch", "scratch": "scratch", "smut": "dirt", "spots": "dirt", "sprinkles": "dust", "stain": "dirt",}
@dataclass(frozen=True)class OverlayDefect: path: Path label: str
def discover_overlays(root: str | Path) -> list[OverlayDefect]: """Find transparent PNG overlays and infer labels from folder names.""" root = Path(root) overlays: list[OverlayDefect] = [] if not root.exists(): return overlays for path in sorted(root.rglob("*.png")): label = SYNTHETIC_LABEL_MAP.get(path.parent.name.lower()) if label: overlays.append(OverlayDefect(path=path, label=label)) return overlays
def _visible_bbox(alpha: Image.Image) -> tuple[int, int, int, int] | None: bbox = alpha.getbbox() if bbox is None: return None x_min, y_min, x_max, y_max = bbox if x_max <= x_min or y_max <= y_min: return None return bbox
def _normalized_bbox( paste_x: int, paste_y: int, visible_bbox: tuple[int, int, int, int], width: int, height: int,) -> list[float]: x_min, y_min, x_max, y_max = visible_bbox return [ round((paste_x + x_min) / width, 6), round((paste_y + y_min) / height, 6), round((paste_x + x_max) / width, 6), round((paste_y + y_max) / height, 6), ]
def apply_overlay( base: Image.Image, overlay: OverlayDefect, *, rng: random.Random, scale_range: tuple[float, float] = (0.35, 1.4), opacity_range: tuple[float, float] = (0.55, 0.95),) -> tuple[Image.Image, dict] | None: """Paste one defect overlay onto a copy of base and return annotation.""" out = load_image(base).convert("RGBA") width, height = out.size
layer = Image.open(overlay.path).convert("RGBA") if rng.random() < 0.5: layer = ImageOps.mirror(layer) if rng.random() < 0.35: layer = layer.rotate(rng.uniform(-22, 22), expand=True, resample=Image.Resampling.BICUBIC)
scale = rng.uniform(*scale_range) new_size = ( max(2, int(layer.width * scale)), max(2, int(layer.height * scale)), ) layer = layer.resize(new_size, Image.Resampling.LANCZOS) if layer.width >= width or layer.height >= height: layer.thumbnail((width // 2, height // 2), Image.Resampling.LANCZOS)
alpha = layer.getchannel("A") alpha = ImageEnhance.Brightness(alpha).enhance(rng.uniform(*opacity_range)) layer.putalpha(alpha) visible = _visible_bbox(alpha) if visible is None: return None
max_x = max(0, width - layer.width) max_y = max(0, height - layer.height) paste_x = rng.randint(0, max_x) if max_x else 0 paste_y = rng.randint(0, max_y) if max_y else 0
out.alpha_composite(layer, (paste_x, paste_y)) annotation = { "label": overlay.label, "bbox": _normalized_bbox(paste_x, paste_y, visible, width, height), } return out.convert("RGB"), annotation
def augment_image( base: Image.Image, overlays: Iterable[OverlayDefect], *, seed: int, defects_per_image: tuple[int, int] = (3, 9),) -> tuple[Image.Image, list[dict]]: """Create one augmented image and its generated annotations.""" rng = random.Random(seed) overlay_list = list(overlays) if not overlay_list: return load_image(base), []
by_label: dict[str, list[OverlayDefect]] = {} for overlay in overlay_list: by_label.setdefault(overlay.label, []).append(overlay) labels = sorted(by_label)
out = load_image(base) annotations: list[dict] = [] target = rng.randint(*defects_per_image) for _ in range(target): label = rng.choice(labels) overlay = rng.choice(by_label[label]) result = apply_overlay(out, overlay, rng=rng) if result is None: continue out, annotation = result annotations.append(annotation) return out, annotations
__all__ = [ "OverlayDefect", "SYNTHETIC_LABEL_MAP", "apply_overlay", "augment_image", "discover_overlays",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Dataset loading and validation helpers."""
from __future__ import annotations
import jsonfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Iterable
from config import DATA_DIR, REPO_ROOTfrom data.schemas import ALLOWED_LABELS, clean_defects, label_counts
TRAINING_JSONL = DATA_DIR / "training_data.jsonl"FDS_SCANS_DIR = ( DATA_DIR / "raw" / "FilmDamageSimulator" / "FilmDamageSimulator" / "scans")
@dataclass(frozen=True)class DatasetIssue: image: str message: str
def load_jsonl(path: str | Path = TRAINING_JSONL) -> list[dict[str, Any]]: path = Path(path) rows: list[dict[str, Any]] = [] if not path.exists(): return rows with path.open("r", encoding="utf-8") as f: for line_no, line in enumerate(f, start=1): line = line.strip() if not line: continue try: rows.append(json.loads(line)) except json.JSONDecodeError as exc: raise ValueError(f"{path}:{line_no}: invalid JSONL row: {exc}") from exc return rows
def resolve_image_path(entry: dict[str, Any], scans_dir: Path = FDS_SCANS_DIR) -> Path: image = str(entry.get("image", "")) path = Path(image) if path.is_absolute(): return path candidate = scans_dir / image if candidate.exists(): return candidate return REPO_ROOT / image
def validate_entries( entries: Iterable[dict[str, Any]], *, require_images: bool = False, scans_dir: Path = FDS_SCANS_DIR,) -> list[DatasetIssue]: issues: list[DatasetIssue] = [] for entry in entries: image = str(entry.get("image", "")) if not image: issues.append(DatasetIssue(image="(missing)", message="missing image field")) if require_images and image and not resolve_image_path(entry, scans_dir).exists(): issues.append(DatasetIssue(image=image, message="image file does not exist"))
annotations = entry.get("annotations", []) cleaned, dropped = clean_defects(annotations) if dropped: issues.append( DatasetIssue( image=image or "(missing)", message=f"{dropped} invalid annotations", ) ) for defect in cleaned: if defect["label"] not in ALLOWED_LABELS: issues.append( DatasetIssue( image=image or "(missing)", message=f"unknown label {defect['label']}", ) ) return issues
def dataset_summary(entries: Iterable[dict[str, Any]]) -> dict[str, Any]: entries_list = list(entries) all_defects: list[dict[str, Any]] = [] dropped = 0 sources: dict[str, int] = {} for entry in entries_list: source = str(entry.get("source", "unknown")) sources[source] = sources.get(source, 0) + 1 cleaned, bad = clean_defects(entry.get("annotations", [])) all_defects.extend(cleaned) dropped += bad counts = label_counts(all_defects) return { "images": len(entries_list), "defects": len(all_defects), "dropped_annotations": dropped, "label_counts": counts, "sources": dict(sorted(sources.items())), }
def load_training_summary(path: str | Path = TRAINING_JSONL) -> dict[str, Any]: entries = load_jsonl(path) summary = dataset_summary(entries) summary["issues"] = [ issue.__dict__ for issue in validate_entries(entries, require_images=False) ] return summary
__all__ = [ "DatasetIssue", "FDS_SCANS_DIR", "TRAINING_JSONL", "dataset_summary", "load_jsonl", "load_training_summary", "resolve_image_path", "validate_entries",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Image preprocessing and visualization utilities."""
from __future__ import annotations
import hashlibimport iofrom pathlib import Pathfrom typing import Any, Iterable
from PIL import Image, ImageDraw, ImageFont, ImageOps
from data.schemas import LABEL_DISPLAY_NAMES, bbox_to_pixels
LABEL_STYLE = { "dust": ((245, 158, 11), 2), "dirt": ((217, 119, 6), 2), "scratch": ((220, 38, 38), 3), "long_hair": ((124, 58, 237), 2), "short_hair": ((8, 145, 178), 2),}DEFAULT_STYLE = ((255, 255, 255), 2)
def load_image(image: str | Path | Image.Image) -> Image.Image: """Load an image-like value and return RGB PIL Image.""" if isinstance(image, Image.Image): pil = image else: pil = Image.open(image) pil = ImageOps.exif_transpose(pil) if pil.mode == "RGBA": background = Image.new("RGB", pil.size, (24, 22, 20)) background.paste(pil, mask=pil.getchannel("A")) return background if pil.mode != "RGB": return pil.convert("RGB") return pil.copy()
def image_to_png_bytes(image: Image.Image) -> bytes: buf = io.BytesIO() load_image(image).save(buf, format="PNG", optimize=True) return buf.getvalue()
def image_sha256(image: Image.Image | bytes) -> str: if isinstance(image, bytes): payload = image else: payload = image_to_png_bytes(image) return hashlib.sha256(payload).hexdigest()
def resize_for_preview(image: Image.Image, max_side: int = 1400) -> Image.Image: pil = load_image(image) if max(pil.size) <= max_side: return pil out = pil.copy() out.thumbnail((max_side, max_side), Image.Resampling.LANCZOS) return out
def draw_defects( image: Image.Image, defects: Iterable[dict[str, Any]], *, title: str | None = None, max_boxes: int = 300,) -> Image.Image: """Draw normalized defect boxes onto an RGB copy of an image.""" out = load_image(image) draw = ImageDraw.Draw(out) width, height = out.size font = ImageFont.load_default()
if title: draw.rectangle((0, 0, min(width, 440), 24), fill=(12, 10, 9)) draw.text((8, 6), title, fill=(254, 243, 199), font=font)
drawn = 0 for defect in defects: if drawn >= max_boxes: break label = str(defect.get("label", "unknown")) pixels = bbox_to_pixels(defect.get("bbox"), width, height) if pixels is None: continue x_min, y_min, x_max, y_max = pixels color, line_width = LABEL_STYLE.get(label, DEFAULT_STYLE) draw.rectangle((x_min, y_min, x_max, y_max), outline=color, width=line_width)
label_text = LABEL_DISPLAY_NAMES.get(label, label) text_bbox = draw.textbbox((x_min, max(0, y_min - 16)), label_text, font=font) draw.rectangle(text_bbox, fill=(12, 10, 9)) draw.text((text_bbox[0] + 1, text_bbox[1]), label_text, fill=color, font=font) drawn += 1
return out
__all__ = [ "DEFAULT_STYLE", "LABEL_STYLE", "draw_defects", "image_sha256", "image_to_png_bytes", "load_image", "resize_for_preview",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268"""Defect schema and geometry helpers for Project Halide."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import Any, Iterable
ALLOWED_LABELS = frozenset( { "dust", "dirt", "scratch", "long_hair", "short_hair", })
LABEL_DISPLAY_NAMES = { "dust": "Dust", "dirt": "Dirt", "scratch": "Scratch", "long_hair": "Long hair", "short_hair": "Short hair",}
DEFECT_CLASSES_KNOWN = { "dust": 0, "dirt": 1, "scratch": 2, "long_hair": 3, "short_hair": 4, "light_leak": 5, "chemical_stain": 6, "emulsion_damage": 7,}
BBox = tuple[float, float, float, float]
@dataclass(frozen=True)class Defect: label: str bbox: BBox confidence: float | None = None
def to_json(self) -> dict[str, Any]: out: dict[str, Any] = { "label": self.label, "bbox": [round(v, 6) for v in self.bbox], } if self.confidence is not None: out["confidence"] = round(float(self.confidence), 4) return out
def _unwrap_bbox(bbox: Any) -> Any: """Accept a single nested bbox from imperfect model JSON.""" if ( isinstance(bbox, (list, tuple)) and len(bbox) == 1 and isinstance(bbox[0], (list, tuple)) ): return bbox[0] return bbox
def normalize_bbox(bbox: Any) -> BBox | None: """Normalize a bbox to float [0, 1].
Accepts either [0, 999] integer grid values or normalized [0, 1] floats. Returns None for malformed, reversed, or out-of-range boxes. """ bbox = _unwrap_bbox(bbox) if not isinstance(bbox, (list, tuple)) or len(bbox) != 4: return None
try: x_min, y_min, x_max, y_max = (float(v) for v in bbox) except (TypeError, ValueError): return None
if x_max <= x_min or y_max <= y_min: return None
max_val = max(x_min, y_min, x_max, y_max) all_whole = all( isinstance(v, int) or (isinstance(v, float) and v.is_integer()) for v in bbox ) scale = 999.0 if all_whole and max_val > 1.5 else 1.0 if scale == 999.0: x_min /= scale y_min /= scale x_max /= scale y_max /= scale
if not all(0.0 <= v <= 1.0 for v in (x_min, y_min, x_max, y_max)): return None if x_max <= x_min or y_max <= y_min: return None
return ( round(x_min, 6), round(y_min, 6), round(x_max, 6), round(y_max, 6), )
def validate_defect(raw: Any) -> Defect | None: if not isinstance(raw, dict): return None label = raw.get("label") if label not in ALLOWED_LABELS: return None bbox = normalize_bbox(raw.get("bbox")) if bbox is None: return None confidence = raw.get("confidence") if confidence is not None: try: confidence = float(confidence) except (TypeError, ValueError): confidence = None return Defect(label=label, bbox=bbox, confidence=confidence)
def clean_defects(raw_defects: Any) -> tuple[list[dict[str, Any]], int]: """Return valid defect dicts and number of dropped records.""" if not isinstance(raw_defects, list): return [], 1 if raw_defects else 0
cleaned: list[dict[str, Any]] = [] dropped = 0 for raw in raw_defects: defect = validate_defect(raw) if defect is None: dropped += 1 else: cleaned.append(defect.to_json()) return cleaned, dropped
def label_counts(defects: Iterable[dict[str, Any]]) -> dict[str, int]: counts: dict[str, int] = {} for defect in defects: label = defect.get("label") if label in ALLOWED_LABELS: counts[label] = counts.get(label, 0) + 1 return dict(sorted(counts.items()))
def dedupe_defects(defects: Iterable[dict[str, Any]]) -> tuple[list[dict[str, Any]], int]: """Drop exact duplicate label and bbox pairs from already-clean defects.""" unique: list[dict[str, Any]] = [] seen: set[tuple[str, tuple[float, float, float, float]]] = set() duplicate_count = 0
for defect in defects: label = str(defect.get("label", "")) bbox = normalize_bbox(defect.get("bbox")) if label not in ALLOWED_LABELS or bbox is None: continue key = (label, bbox) if key in seen: duplicate_count += 1 continue seen.add(key) unique.append({"label": label, "bbox": [round(v, 6) for v in bbox]})
return unique, duplicate_count
def bbox_area(bbox: Any) -> float: norm = normalize_bbox(bbox) if norm is None: return 0.0 x_min, y_min, x_max, y_max = norm return max(0.0, x_max - x_min) * max(0.0, y_max - y_min)
def bbox_iou(a: Any, b: Any) -> float: box_a = normalize_bbox(a) box_b = normalize_bbox(b) if box_a is None or box_b is None: return 0.0
ax1, ay1, ax2, ay2 = box_a bx1, by1, bx2, by2 = box_b ix1 = max(ax1, bx1) iy1 = max(ay1, by1) ix2 = min(ax2, bx2) iy2 = min(ay2, by2) if ix2 <= ix1 or iy2 <= iy1: return 0.0
inter = (ix2 - ix1) * (iy2 - iy1) union = bbox_area(box_a) + bbox_area(box_b) - inter if union <= 0: return 0.0 return round(inter / union, 6)
def bbox_to_pixels(bbox: Any, width: int, height: int) -> tuple[int, int, int, int] | None: norm = normalize_bbox(bbox) if norm is None: return None x_min, y_min, x_max, y_max = norm return ( int(round(x_min * width)), int(round(y_min * height)), int(round(x_max * width)), int(round(y_max * height)), )
def spatial_summary(defects: Iterable[dict[str, Any]]) -> dict[str, Any]: """Compute compact spatial cues for the reasoning model.""" defects_list = list(defects) if not defects_list: return { "edge_defects": 0, "center_defects": 0, "largest_labels": [], }
edge_count = 0 center_count = 0 largest: list[tuple[float, str]] = [] for defect in defects_list: bbox = normalize_bbox(defect.get("bbox")) if bbox is None: continue x_min, y_min, x_max, y_max = bbox cx = (x_min + x_max) / 2.0 cy = (y_min + y_max) / 2.0 if x_min < 0.08 or y_min < 0.08 or x_max > 0.92 or y_max > 0.92: edge_count += 1 if 0.35 <= cx <= 0.65 and 0.35 <= cy <= 0.65: center_count += 1 largest.append((bbox_area(bbox), str(defect.get("label", "unknown"))))
largest_labels = [ label for _, label in sorted(largest, reverse=True)[:5] ] return { "edge_defects": edge_count, "center_defects": center_count, "largest_labels": largest_labels, }
__all__ = [ "ALLOWED_LABELS", "BBox", "DEFECT_CLASSES_KNOWN", "Defect", "LABEL_DISPLAY_NAMES", "bbox_area", "bbox_iou", "bbox_to_pixels", "clean_defects", "dedupe_defects", "label_counts", "normalize_bbox", "spatial_summary", "validate_defect",]1"""Model package. Vision and reasoning model wrappers."""1"""Reasoning model package. Nemotron-Mini wrapper for diagnosis."""1234567"""Convenience entrypoints for diagnostic reasoning."""
from __future__ import annotations
from pipeline.diagnoser import diagnose
__all__ = ["diagnose"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Nemotron-Mini-4B wrapper. Loads the model and generates diagnoses.
Per AGENTS.md, this is the second stage of the dual-model pipeline.Receives defect JSON from the vision model plus user metadata, returnsroot cause diagnosis and physical remediation steps.
The `generate` method accepts a fully-formed `messages: list[dict]` array(system, user, assistant turns). It does NOT pre-process the messages; thecaller is responsible for assembling the full few-shot + system + currentrequest array. This is the only correct way to use a chat-tuned model with`tokenizer.apply_chat_template`."""
from __future__ import annotations
import loggingimport refrom typing import Any
from config import get_reasoning_config, require_gpu_for_inference
logger = logging.getLogger(__name__)
_ESCAPED_NEWLINE_PATTERN = re.compile( r"(```[\s\S]*?```|`[^`]+`)|(?<!\\)(?:\\r\\n|\\[nr])")
class NemotronReasoner: """Lazy-loading wrapper around Nemotron-Mini-4B-Instruct."""
def __init__(self, model_path: str | None = None) -> None: cfg = get_reasoning_config() self._model_path = model_path or cfg.model_id self._tokenizer: Any = None self._model: Any = None self._device: str = "cpu" self._dtype: Any = None
@property def model_path(self) -> str: return self._model_path
def load(self) -> None: if self._model is not None: return require_gpu_for_inference("reasoning") import torch from transformers import AutoModelForCausalLM, AutoTokenizer
logger.info("Loading Nemotron-Mini-4B from %s", self._model_path) self._tokenizer = AutoTokenizer.from_pretrained(self._model_path) self._dtype = _select_cuda_dtype(torch) self._model = AutoModelForCausalLM.from_pretrained( self._model_path, torch_dtype=self._dtype, device_map="auto", ) self._device = str(next(self._model.parameters()).device) logger.info("Nemotron loaded on %s with dtype %s", self._device, self._dtype)
def generate(self, messages: list[dict[str, str]]) -> str: """Run chat completion on a fully-formed messages array.
`messages` must be a list of dicts with `role` in {"system", "user", "assistant"} and `content` strings. The caller is responsible for assembling the full conversation including any few-shot examples. This wrapper just tokenizes and generates. """ if self._model is None: self.load()
if not messages: raise ValueError("messages must be a non-empty list of {role, content} dicts")
inputs, prompt_length = _build_chat_inputs( self._tokenizer, messages, self._device, )
import torch with torch.inference_mode(): output = self._model.generate( **inputs, max_new_tokens=get_reasoning_config().max_new_tokens, do_sample=False, pad_token_id=self._tokenizer.eos_token_id, )
response_ids = output[0][prompt_length:] text = self._tokenizer.decode( response_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False, ) return normalize_response_text(text).strip()
def close(self) -> None: if self._model is not None: del self._model self._model = None if self._tokenizer is not None: del self._tokenizer self._tokenizer = None
_default_reasoner: NemotronReasoner | None = None
def get_reasoner() -> NemotronReasoner: global _default_reasoner if _default_reasoner is None: _default_reasoner = NemotronReasoner() return _default_reasoner
def normalize_response_text(text: str) -> str: """Convert literal escaped newlines to display newlines outside code.""" if not isinstance(text, str) or "\\" not in text: return text return _ESCAPED_NEWLINE_PATTERN.sub(lambda m: m.group(1) or "\n", text)
def _build_chat_inputs( tokenizer: Any, messages: list[dict[str, str]], device: str,) -> tuple[dict[str, Any], int]: """Return generate kwargs across Transformers chat-template variants.""" try: encoded = tokenizer.apply_chat_template( messages, add_generation_prompt=True, return_tensors="pt", return_dict=True, ) except TypeError: encoded = tokenizer.apply_chat_template( messages, add_generation_prompt=True, return_tensors="pt", )
if hasattr(encoded, "to"): encoded = encoded.to(device)
if _has_input_ids(encoded): input_ids = encoded["input_ids"] return dict(encoded), input_ids.shape[-1]
return {"input_ids": encoded}, encoded.shape[-1]
def _has_input_ids(encoded: Any) -> bool: try: return "input_ids" in encoded except (TypeError, RuntimeError): return False
def _select_cuda_dtype(torch_module: Any) -> Any: major, _minor = torch_module.cuda.get_device_capability() if major >= 8: return torch_module.bfloat16 return torch_module.float16123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307"""Few-shot prompt templates for the Nemotron diagnostic reasoner."""
from __future__ import annotations
import jsonfrom typing import Any
SYSTEM_PROMPT = ( "You are a senior analog film lab technician with 30 years of experience " "in darkroom printing, negative inspection, and equipment repair. You are " "diagnosing the physical root cause of degradation in a film scan and " "prescribing specific, actionable physical fixes a lab can perform. " "Use the evidence you are given, do not invent unsupported camera or lab " "facts, and separate confirmed observations from likely causes. Do not " "carry film-stock-specific advice from examples into the current case " "unless the current film stock supports it. For scanners, recommend " "scanner-safe cleaning, manufacturer guidance, or professional service, " "not household cleaners or detergent. When uncertain, recommend inspection " "before high-risk physical cleaning. Treat static as a generic handling " "possibility unless the current metadata directly supports a stock-specific " "static claim. Return Markdown with these sections: Root cause, Evidence, " "Physical fixes, Confidence, Next inspection.")
FEW_SHOT_EXAMPLES: list[dict[str, str]] = [ { "role": "user", "content": ( "## Defect report\n" "{\n" ' "film_type": "Kodak Portra 400 (35mm)",\n' ' "film_age_years": 2,\n' ' "storage": "fridge, sealed",\n' ' "defects": [\n' ' {"label": "dust", "bbox_count": 240},\n' ' {"label": "dirt", "bbox_count": 80},\n' ' {"label": "short_hair", "bbox_count": 18},\n' ' {"label": "long_hair", "bbox_count": 4},\n' ' {"label": "scratch", "bbox_count": 1}\n' ' ],\n' ' "scan_resolution_dpi": 4000,\n' ' "total_defect_count": 343,\n' ' "spatial_evidence": {"edge_defects": 29, "center_defects": 96}\n' "}\n\n" "What is the root cause and what physical fixes do you recommend?" ), }, { "role": "assistant", "content": ( "## Root cause\n" "Scanner-side contamination is most likely, with a smaller chance " "of handling debris on the negative. The fridge-sealed storage " "argues against age or heat damage as the primary cause.\n\n" "## Evidence\n" "- Dust and dirt dominate the report, which points to particles on " "the scanner glass, holder, or negative surface.\n" "- Hair defects suggest lint in the film holder or transport path.\n" "- A single scratch should be inspected physically before blaming " "the roll or camera.\n\n" "## Physical fixes\n" "1. Clean scanner glass, holder, and feed path with scanner-safe " "swabs and reagent-grade isopropyl alcohol.\n" "2. Use a rocket blower and anti-static brush on the negative, " "then re-scan a small crop.\n" "3. Enable hardware dust removal only if it is supported for the " "film and scanner, then compare against a no-removal scan.\n" "4. Inspect the scratch under a 10x loupe. If it is physical, use " "wet-gate or wet-mount scanning rather than wiping the emulsion.\n" "5. If contamination returns after cleaning, service the holder " "or rollers before scanning more frames.\n\n" "## Confidence\n" "Medium-high. The storage metadata reduces the probability of " "storage deterioration, but the negative still needs inspection.\n\n" "## Next inspection\n" "Check whether particles move between scans. If they move, the " "problem is loose dust or scanner contamination." ), }, { "role": "user", "content": ( "## Defect report\n" "{\n" ' "film_type": "Ilford HP5 (35mm)",\n' ' "film_age_years": 0,\n' ' "storage": "fresh",\n' ' "defects": [\n' ' {"label": "dust", "bbox_count": 5},\n' ' {"label": "scratch", "bbox_count": 1}\n' ' ],\n' ' "scan_resolution_dpi": 3200,\n' ' "total_defect_count": 6,\n' ' "spatial_evidence": {"edge_defects": 0, "center_defects": 2}\n' "}\n\n" "What is the root cause and what physical fixes do you recommend?" ), }, { "role": "assistant", "content": ( "## Root cause\n" "A fresh HP5 roll with light dust and one scratch most likely " "reflects handling or scanner-side contamination plus one physical " "abrasion event. There is not enough evidence to claim HP5 has a " "special static problem.\n\n" "## Evidence\n" "- The film is fresh, so age and chemical deterioration are " "unlikely.\n" "- Five dust particles is a low count and can come from scanner " "glass, the holder, or brief handling.\n" "- The single scratch needs loupe inspection before assigning it " "to the camera, scanner, or handling.\n\n" "## Physical fixes\n" "1. Clean scanner glass and holder with scanner-safe swabs, then " "re-scan the same crop.\n" "2. Use a rocket blower on the negative. Avoid wiping the emulsion " "unless a lab confirms the defect is on the base side.\n" "3. Inspect the scratch under 10x magnification. If physical, use " "wet-gate or wet-mount scanning to reduce its appearance.\n" "4. Anti-static treatment may be tested as a generic dust-control " "step, but it should not be framed as HP5-specific.\n\n" "## Confidence\n" "Medium. The defect count is small, so the diagnosis should stay " "conservative.\n\n" "## Next inspection\n" "Re-scan after cleaning. If dust changes position, scanner or " "handling contamination is confirmed." ), }, { "role": "user", "content": ( "## Defect report\n" "{\n" ' "film_type": "Ilford HP5 (120 medium format)",\n' ' "film_age_years": 15,\n' ' "storage": "shoe box, attic",\n' ' "defects": [\n' ' {"label": "long_hair", "bbox_count": 4},\n' ' {"label": "scratch", "bbox_count": 1}\n' ' ],\n' ' "scan_resolution_dpi": 3200\n' "}\n\n" "What is the root cause and what physical fixes do you recommend?" ), }, { "role": "assistant", "content": ( "## Root cause\n" "Long hair and scratches on an aged, poorly stored roll indicate " "physical abrasion from dust and debris inside the storage " "container. Attic storage subjects film to temperature and " "humidity swings that can make the emulsion more vulnerable.\n\n" "## Evidence\n" "- The storage field explicitly says attic, so heat and humidity " "stress are supported for this case.\n" "- Hair plus a scratch indicates physical contact, not only scanner " "dust.\n\n" "## Physical fixes\n" "1. Inspect the negative under a 10x loupe to confirm hair is on " "the emulsion side (matte) vs. base side (glossy). Emulsion-side " "hair cannot be wet-wiped safely.\n" "2. If base-side only: gently wipe with a PEC*PAD soaked in " "Edwal Negative Cleaner, then PEC*PAD with distilled water, " "then dry.\n" "3. If emulsion-side: do not wipe. Use Print File archival " "sleeves and ship to a lab with wet-mount scanning (e.g., " "Northcoast Photographic).\n" "4. The single scratch is most likely from a dirty film " "transport. Have the scanner cleaned and the film path " "inspected; consider wet-gate scanning to mask the scratch.\n" "5. Long-term: transfer remaining unexposed rolls to a " "freezer at -18C in sealed bags with desiccant.\n\n" "## Confidence\n" "Medium. The metadata supports storage stress, but the side of the " "scratch and hair must be confirmed under magnification.\n\n" "## Next inspection\n" "Inspect both base and emulsion sides and note which defects stay " "fixed after a gentle air blow." ), }, { "role": "user", "content": ( "## Defect report\n" "{\n" ' "film_type": "CineStill 800T (35mm)",\n' ' "film_age_years": 0,\n' ' "storage": "fresh, refrigerated by manufacturer",\n' ' "defects": [\n' ' {"label": "dust", "bbox_count": 156},\n' ' {"label": "dirt", "bbox_count": 23},\n' ' {"label": "short_hair", "bbox_count": 8}\n' ' ],\n' ' "scan_resolution_dpi": 6000\n' "}\n\n" "What is the root cause and what physical fixes do you recommend?" ), }, { "role": "assistant", "content": ( "## Root cause\n" "Excessive dust and dirt on a brand-new refrigerated roll at 6000 " "dpi scan suggests a combination of static during handling and " "scanner-side contamination. The hair count points to the " "scanner's film transport path. Because the current film type is " "CineStill 800T, anti-static handling is especially worth testing " "on a re-scan.\n\n" "## Evidence\n" "- The film type is CineStill 800T, so static-prone handling is " "relevant for this case.\n" "- The film is fresh and refrigerated, which makes chemical age " "damage unlikely.\n" "- Short hairs point to the holder or transport path.\n\n" "## Physical fixes\n" "1. Test anti-static treatment: discharge " "the negative with a Zerostat gun on low setting 30 cm from the " "film before scanning.\n" "2. Clean the scanner glass, film holder, and feed rollers with " "PEC*PAD swabs and reagent-grade isopropyl alcohol.\n" "3. Use a static-discharge ionizing bar (e.g., Simco-Ion) at the " "scanner input if available.\n" "4. If the scanner and film workflow support hardware dust " "removal, test it on one crop at moderate strength before a full " "batch.\n" "5. For the short hairs, inspect the film path under magnification " "and remove any visible lint from the rollers with tweezers.\n\n" "## Confidence\n" "Medium-high because the metadata and defect mix are consistent.\n\n" "## Next inspection\n" "Re-scan after anti-static treatment. If the dust count drops, " "static and handling were major contributors." ), },]
def build_user_prompt( film_type: str, film_age_years: int, storage: str, scan_resolution_dpi: int, defect_summary: dict[str, int], total_defects: int, spatial_evidence: dict[str, Any] | None = None,) -> str: """Build the user message for the current diagnosis request.""" payload = { "film_type": film_type, "film_age_years": film_age_years, "storage": storage, "defects": [ {"label": label, "bbox_count": count} for label, count in sorted(defect_summary.items()) ], "scan_resolution_dpi": scan_resolution_dpi, "total_defect_count": total_defects, "spatial_evidence": spatial_evidence or {}, } return ( "## Defect report\n" f"{json.dumps(payload, indent=2)}\n\n" "What is the root cause and what physical fixes do you recommend?" )
def build_messages( film_type: str, film_age_years: int, storage: str, scan_resolution_dpi: int, defect_summary: dict[str, int], total_defects: int, spatial_evidence: dict[str, Any] | None = None,) -> list[dict[str, str]]: """Return full message list for the reasoner.
The list is structured for `tokenizer.apply_chat_template`: [system, user, assistant, user, assistant, user, assistant, user] The system prompt is index 0, the three few-shot examples follow as (user, assistant) pairs, and the final user message is the actual defect report. This preserves the role structure that `Nemotron-Mini-4B-Instruct` was trained on. """ messages: list[dict[str, str]] = [ {"role": "system", "content": SYSTEM_PROMPT}, ] messages.extend(FEW_SHOT_EXAMPLES) messages.append( { "role": "user", "content": build_user_prompt( film_type, film_age_years, storage, scan_resolution_dpi, defect_summary, total_defects, spatial_evidence=spatial_evidence, ), } ) return messages1"""Vision model package. MiniCPM-V 4.6 wrapper for film defect detection."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Vision inference pipeline. Takes a film scan and returns defect JSON."""from __future__ import annotations
import loggingimport timefrom pathlib import Pathfrom typing import Any
from data.schemas import clean_defects, dedupe_defects, label_countsfrom data.preprocessing import load_imagefrom models.vision.minicpm_wrapper import get_detector
logger = logging.getLogger(__name__)
def extract_defects(image: Any) -> dict: """Run defect extraction on a PIL image. Returns defect dict + metadata.""" started = time.perf_counter() detector = get_detector() raw = detector.detect(load_image(image)) elapsed = time.perf_counter() - started
if not isinstance(raw, dict): logger.warning("Model output is not a dict: %r", type(raw)) raw = {"defects": [], "_parse_error": "non_dict_output"}
cleaned, dropped = clean_defects(raw.get("defects", [])) cleaned, duplicate_count = dedupe_defects(cleaned) counts = label_counts(cleaned)
return { "defects": cleaned, "defect_count": len(cleaned), "label_counts": counts, "dropped_count": dropped, "duplicate_count": duplicate_count, "inference_seconds": round(elapsed, 3), "model_path": detector.model_path, "parse_error": raw.get("_parse_error"), }
def extract_defects_from_path(image_path: str | Path) -> dict: """Convenience: open image from path and run extraction.""" img = load_image(image_path) return extract_defects(img)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243"""MiniCPM-V 4.6 wrapper. Loads the model and runs inference on film scans."""
from __future__ import annotations
import jsonimport loggingimport osimport refrom typing import Any
from config import CHECKPOINT_DIR, get_vision_config, require_gpu_for_inference
logger = logging.getLogger(__name__)
DETECTION_PROMPT = ( "You are a film defect detection engine. Analyze the film scan and detect " "all visible defects. Output a JSON object with a 'defects' array. Each " "defect has: 'label' (dust, dirt, scratch, long_hair, short_hair), " "'bbox' as 4 integers in the [0, 999] grid " "[x_min, y_min, x_max, y_max] (multiply by image width/height to get pixels). " "Return at most 150 defects. Prefer the clearest defects. Do not repeat " "the same label and bbox. " "Output JSON only, no explanation.")
def _resolve_model_path() -> str: """Pick configured fine-tuned model or public base model.""" cfg = get_vision_config() explicit = os.getenv("HALIDE_VISION_MODEL_ID") if explicit: logger.info("Using explicit vision model %s", explicit) return explicit
if cfg.use_finetuned: local_candidates = [ cfg.local_model_path, CHECKPOINT_DIR / "minicpm-v-4.6-merged", ] seen: set[str] = set() for path in local_candidates: key = str(path.resolve()) if key in seen: continue seen.add(key) if path.exists() and (path / "config.json").exists(): logger.info("Using local fine-tuned vision model at %s", path) return str(path) logger.info("Using fine-tuned vision model repo %s", cfg.finetuned_model_id) return cfg.finetuned_model_id
logger.info("Using base vision model %s", cfg.base_model_id) return cfg.base_model_id
class MiniCPMVDetector: """Lazy-loading wrapper around MiniCPM-V 4.6 for film defect detection."""
def __init__(self, model_path: str | None = None) -> None: self._model_path = model_path or _resolve_model_path() self._model: Any = None self._processor: Any = None self._dtype: Any = None self._device: str = "cpu"
@property def model_path(self) -> str: return self._model_path
def load(self) -> None: if self._model is not None: return require_gpu_for_inference("vision") import torch from transformers import AutoModelForImageTextToText, AutoProcessor
logger.info("Loading MiniCPM-V 4.6 from %s", self._model_path) self._processor = AutoProcessor.from_pretrained( self._model_path, trust_remote_code=True ) self._dtype = _select_cuda_dtype(torch) self._model = AutoModelForImageTextToText.from_pretrained( self._model_path, torch_dtype=self._dtype, device_map="auto", trust_remote_code=True, ) self._device = str(next(self._model.parameters()).device) logger.info("Model loaded on %s with dtype %s", self._device, self._dtype)
def detect(self, image: Any) -> dict: """Run defect detection on a PIL image. Returns parsed JSON dict.""" import torch
if self._model is None: self.load()
cfg = get_vision_config() messages = [ { "role": "user", "content": [ {"type": "image", "image": image}, {"type": "text", "text": DETECTION_PROMPT}, ], } ]
inputs = _apply_chat_template( self._processor, messages, downsample_mode=cfg.downsample_mode, max_slice_nums=cfg.max_slice_nums, ).to(self._device)
with torch.inference_mode(): generated = self._model.generate( **inputs, downsample_mode=cfg.downsample_mode, max_new_tokens=cfg.max_new_tokens, do_sample=False, )
trimmed = [out[len(inp):] for inp, out in zip(inputs.input_ids, generated)] text = self._processor.batch_decode( trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False, )[0]
return _parse_defect_json(text)
def close(self) -> None: if self._model is not None: del self._model self._model = None if self._processor is not None: del self._processor self._processor = None
def _parse_defect_json(text: str) -> dict: """Extract and parse the first JSON object from model output.""" text = text.strip() if text.startswith("```"): text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.IGNORECASE) text = re.sub(r"\s*```$", "", text) try: parsed = json.loads(text) if isinstance(parsed, list): return {"defects": parsed} if isinstance(parsed, dict): return parsed return {"defects": [], "_raw": text, "_parse_error": "json_not_object"} except json.JSONDecodeError: pass
match = re.search(r"\{[\s\S]*\}", text) if not match: logger.warning("No JSON found in model output: %r", text[:200]) return {"defects": [], "_raw": text, "_parse_error": "no_json_object"} try: parsed = json.loads(match.group(0)) if isinstance(parsed, dict): return parsed return {"defects": [], "_raw": text, "_parse_error": "json_not_object"} except json.JSONDecodeError as exc: fragments = _parse_defect_fragments(text) if fragments: logger.warning( "Salvaged %s defect fragments from malformed JSON: %s", len(fragments), exc, ) return { "defects": fragments, "_parse_error": str(exc), "_parse_warning": "salvaged_defect_fragments", } logger.warning("JSON parse error: %s; raw: %r", exc, text[:200]) return {"defects": [], "_raw": text, "_parse_error": str(exc)}
def _parse_defect_fragments(text: str) -> list[dict[str, Any]]: """Recover complete defect objects from truncated JSON arrays.""" fragments: list[dict[str, Any]] = [] for match in re.finditer(r"\{[^{}]*\"label\"[^{}]*\"bbox\"\s*:\s*\[[^\]]+\][^{}]*\}", text): try: candidate = json.loads(match.group(0)) except json.JSONDecodeError: continue if isinstance(candidate, dict): fragments.append(candidate) return fragments
def _apply_chat_template( processor: Any, messages: list[dict], *, downsample_mode: str, max_slice_nums: int,) -> Any: """Call MiniCPM chat template across Transformers API variants.""" kwargs = { "tokenize": True, "add_generation_prompt": True, "return_dict": True, "return_tensors": "pt", } try: return processor.apply_chat_template( messages, **kwargs, downsample_mode=downsample_mode, max_slice_nums=max_slice_nums, ) except TypeError: return processor.apply_chat_template( messages, **kwargs, processor_kwargs={ "downsample_mode": downsample_mode, "max_slice_nums": max_slice_nums, }, )
def _select_cuda_dtype(torch_module: Any) -> Any: major, _minor = torch_module.cuda.get_device_capability() if major >= 8: return torch_module.bfloat16 return torch_module.float16
_default_detector: MiniCPMVDetector | None = None
def get_detector() -> MiniCPMVDetector: global _default_detector if _default_detector is None: _default_detector = MiniCPMVDetector() return _default_detector1"""Pipeline package. Orchestrates vision + reasoning stages."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Diagnoser. Takes defect JSON and user metadata, returns diagnosis and fixes."""
from __future__ import annotations
import loggingimport timefrom typing import Any
from data.schemas import spatial_summaryfrom models.reasoning.nemotron_wrapper import get_reasonerfrom models.reasoning.prompts import SYSTEM_PROMPT, build_messages
logger = logging.getLogger(__name__)
def diagnose( defect_result: dict, film_type: str, film_age_years: int, storage: str, scan_resolution_dpi: int,) -> dict: """Run Nemotron reasoning over a defect result + user metadata.
Returns a dict with the raw text response and timing metadata. """ started = time.perf_counter() reasoner = get_reasoner()
label_counts = defect_result.get("label_counts", {}) or {} defects = defect_result.get("defects", []) or [] total = defect_result.get("defect_count", 0) or sum(label_counts.values()) spatial = spatial_summary(defects)
messages = build_messages( film_type=film_type, film_age_years=film_age_years, storage=storage, scan_resolution_dpi=scan_resolution_dpi, defect_summary=label_counts, total_defects=total, spatial_evidence=spatial, )
logger.info( "Running Nemotron diagnosis (film=%s, age=%d, storage=%s, total_defects=%d)", film_type, film_age_years, storage, total, ) text = reasoner.generate(messages=messages) elapsed = time.perf_counter() - started
return { "diagnosis_text": text, "reasoning_seconds": round(elapsed, 3), "model_path": reasoner.model_path, "system_prompt": SYSTEM_PROMPT, "input_defect_summary": { "label_counts": label_counts, "total": total, "spatial_evidence": spatial, }, }
__all__ = ["diagnose"]123456789101112131415161718"""Defect extractor. Takes a film scan and returns structured defect JSON.
This is a thin wrapper that re-exports `extract_defects` from the visioninference module so the pipeline layer has a stable interface."""
from __future__ import annotations
from typing import Any
from models.vision.inference import extract_defects, extract_defects_from_path
__all__ = ["extract_defects", "extract_defects_from_path"]
def extract(image: Any) -> dict: """Top-level entry point used by the pipeline orchestrator.""" return extract_defects(image)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Main pipeline. Orchestrates vision extraction and diagnostic reasoning."""
from __future__ import annotations
import loggingimport timefrom typing import Any
from pipeline.diagnoser import diagnosefrom pipeline.extractor import extract
logger = logging.getLogger(__name__)
def run_diagnosis( image: Any, film_type: str = "Unknown 35mm", film_age_years: int = 1, storage: str = "unknown", scan_resolution_dpi: int = 4000,) -> dict: """End-to-end: image -> defect JSON -> diagnosis + fixes.
Returns a single dict with both stages' outputs and timing info. """ started = time.perf_counter()
logger.info("Stage 1: defect extraction") defect_result = extract(image)
logger.info( "Stage 1 complete: %d defects (%s) in %.2fs", defect_result.get("defect_count", 0), defect_result.get("label_counts", {}), defect_result.get("inference_seconds", 0.0), )
logger.info("Stage 2: Nemotron diagnosis") diagnosis_result = diagnose( defect_result, film_type=film_type, film_age_years=film_age_years, storage=storage, scan_resolution_dpi=scan_resolution_dpi, )
total_elapsed = time.perf_counter() - started
return { "film_metadata": { "film_type": film_type, "film_age_years": film_age_years, "storage": storage, "scan_resolution_dpi": scan_resolution_dpi, }, "defects": defect_result, "diagnosis": diagnosis_result, "total_seconds": round(total_elapsed, 3), }
__all__ = ["run_diagnosis"]12345678910gradio>=6.10.0spaces>=0.40.0torch>=2.4.0torchvision>=0.19.0transformers>=5.7.0accelerate>=1.8.0huggingface_hub>=0.20.0pillow>=10.0.0safetensors>=0.4.0numpy>=1.24.01"""Storage package. SQLite database and inference cache."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""Caching. In-process LRU cache for diagnosis results keyed by image hash.
For privacy, we hash the image bytes; the image itself is never persistedin the cache. Identical scans produce identical hashes, giving us a simplecontent-addressed cache."""
from __future__ import annotations
import hashlibimport loggingimport timefrom collections import OrderedDictfrom threading import Lockfrom typing import Any
from config import get_app_config
logger = logging.getLogger(__name__)
class DiagnosisCache: """Thread-safe LRU cache for diagnosis results."""
def __init__(self, max_size: int = 64, ttl_seconds: int = 3600) -> None: self._max_size = max_size self._ttl = ttl_seconds self._store: OrderedDict[str, tuple[float, dict]] = OrderedDict() self._lock = Lock() self._hits = 0 self._misses = 0
@staticmethod def hash_image(image_bytes: bytes) -> str: return hashlib.sha256(image_bytes).hexdigest()
def get(self, image_bytes: bytes) -> dict | None: key = self.hash_image(image_bytes) now = time.time() with self._lock: entry = self._store.get(key) if entry is None: self._misses += 1 return None ts, value = entry if now - ts > self._ttl: del self._store[key] self._misses += 1 return None self._store.move_to_end(key) self._hits += 1 logger.info("Cache hit for %s", key[:12]) return value
def put(self, image_bytes: bytes, value: dict) -> None: key = self.hash_image(image_bytes) now = time.time() with self._lock: self._store[key] = (now, value) self._store.move_to_end(key) while len(self._store) > self._max_size: self._store.popitem(last=False)
def stats(self) -> dict: with self._lock: return { "size": len(self._store), "max_size": self._max_size, "hits": self._hits, "misses": self._misses, }
def clear(self) -> None: with self._lock: self._store.clear() self._hits = 0 self._misses = 0
_default_cache: DiagnosisCache | None = None
def get_cache() -> DiagnosisCache: global _default_cache if _default_cache is None: cfg = get_app_config() _default_cache = DiagnosisCache( max_size=cfg.cache_size, ttl_seconds=cfg.cache_ttl_seconds, ) return _default_cache
__all__ = ["DiagnosisCache", "get_cache"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""SQLite database. Stores diagnostic history and user sessions.
Schema: sessions(id, started_at, film_type, film_age_years, storage, scan_dpi) diagnoses(id, session_id, created_at, defect_count, label_counts_json, diagnosis_text, vision_seconds, reasoning_seconds, total_seconds, vision_model, reasoning_model, raw_json)"""
from __future__ import annotations
import jsonimport loggingimport sqlite3import timeimport uuidfrom contextlib import contextmanagerfrom pathlib import Pathfrom typing import Any, Iterator
from config import get_app_config
logger = logging.getLogger(__name__)
REPO_ROOT = Path(__file__).resolve().parents[1]DEFAULT_DB_PATH = REPO_ROOT / "storage" / "halide.db"_INITIALIZED_DB_PATHS: set[Path] = set()
def get_db_path() -> Path: db_path = get_app_config().db_path db_path.parent.mkdir(parents=True, exist_ok=True) return db_path
SCHEMA = """CREATE TABLE IF NOT EXISTS sessions ( id TEXT PRIMARY KEY, started_at REAL NOT NULL, film_type TEXT NOT NULL, film_age_years INTEGER NOT NULL, storage TEXT NOT NULL, scan_dpi INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS diagnoses ( id TEXT PRIMARY KEY, session_id TEXT NOT NULL, created_at REAL NOT NULL, defect_count INTEGER NOT NULL, label_counts_json TEXT NOT NULL, diagnosis_text TEXT NOT NULL, vision_seconds REAL NOT NULL, reasoning_seconds REAL NOT NULL, total_seconds REAL NOT NULL, vision_model TEXT NOT NULL, reasoning_model TEXT NOT NULL, raw_json TEXT NOT NULL, FOREIGN KEY (session_id) REFERENCES sessions(id));
CREATE INDEX IF NOT EXISTS idx_diagnoses_session ON diagnoses(session_id);CREATE INDEX IF NOT EXISTS idx_diagnoses_created ON diagnoses(created_at);"""
@contextmanagerdef connect() -> Iterator[sqlite3.Connection]: db_path = get_db_path() conn = sqlite3.connect(str(db_path)) conn.row_factory = sqlite3.Row conn.execute("PRAGMA foreign_keys = ON") conn.execute("PRAGMA journal_mode = WAL") try: yield conn conn.commit() finally: conn.close()
def init_db() -> None: with connect() as conn: conn.executescript(SCHEMA) db_path = get_db_path() _INITIALIZED_DB_PATHS.add(db_path) logger.info("DB initialized at %s", db_path)
def _ensure_db_initialized() -> None: db_path = get_db_path() if db_path in _INITIALIZED_DB_PATHS and db_path.exists(): return init_db()
def record_diagnosis(result: dict) -> str: """Persist a full pipeline result. Returns the diagnosis id.""" _ensure_db_initialized() diagnosis_id = str(uuid.uuid4()) session_id = str(uuid.uuid4()) now = time.time()
meta = result.get("film_metadata", {}) or {} defects = result.get("defects", {}) or {} diagnosis = result.get("diagnosis", {}) or {}
with connect() as conn: conn.execute( """ INSERT INTO sessions (id, started_at, film_type, film_age_years, storage, scan_dpi) VALUES (?, ?, ?, ?, ?, ?) """, ( session_id, now, meta.get("film_type", "Unknown"), int(meta.get("film_age_years", 0) or 0), meta.get("storage", "unknown"), int(meta.get("scan_resolution_dpi", 0) or 0), ), ) conn.execute( """ INSERT INTO diagnoses (id, session_id, created_at, defect_count, label_counts_json, diagnosis_text, vision_seconds, reasoning_seconds, total_seconds, vision_model, reasoning_model, raw_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( diagnosis_id, session_id, now, int(defects.get("defect_count", 0) or 0), json.dumps(defects.get("label_counts", {}) or {}), diagnosis.get("diagnosis_text", ""), float(defects.get("inference_seconds", 0.0) or 0.0), float(diagnosis.get("reasoning_seconds", 0.0) or 0.0), float(result.get("total_seconds", 0.0) or 0.0), defects.get("model_path", ""), diagnosis.get("model_path", ""), json.dumps(result), ), ) logger.info("Recorded diagnosis %s (session %s)", diagnosis_id, session_id) return diagnosis_id
def list_recent(limit: int = 20) -> list[dict]: _ensure_db_initialized() with connect() as conn: rows = conn.execute( """ SELECT d.id, d.created_at, s.film_type, s.film_age_years, s.storage, s.scan_dpi, d.defect_count, d.label_counts_json, d.diagnosis_text, d.total_seconds FROM diagnoses d JOIN sessions s ON s.id = d.session_id ORDER BY d.created_at DESC LIMIT ? """, (limit,), ).fetchall() out: list[dict] = [] for r in rows: out.append( { "id": r["id"], "created_at": r["created_at"], "film_type": r["film_type"], "film_age_years": r["film_age_years"], "storage": r["storage"], "scan_dpi": r["scan_dpi"], "defect_count": r["defect_count"], "label_counts": json.loads(r["label_counts_json"]), "diagnosis_text": r["diagnosis_text"], "total_seconds": r["total_seconds"], } ) return out
__all__ = [ "init_db", "record_diagnosis", "list_recent", "get_db_path",]1"""UI package. Gradio app, theme, and components."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251"""Gradio app. Main UI definition and layout."""
from __future__ import annotations
import htmlimport jsonimport loggingfrom typing import Any
import gradio as gr
from config import get_app_configfrom data.preprocessing import draw_defects, image_to_png_bytes, load_imagefrom pipeline.pipeline import run_diagnosisfrom storage.cache import get_cachefrom storage.database import init_db, list_recent, record_diagnosisfrom ui.components import ( HEADER_HTML, defect_pills_html, diagnosis_html, render_history, stats_html,)from ui.theme import THEME_CSS, build_theme
logger = logging.getLogger(__name__)logging.basicConfig(level=logging.INFO)
def _gpu_decorator(): try: import spaces except ImportError: return lambda fn: fn return spaces.GPU(duration=get_app_config().gpu_duration_seconds)
DEFAULT_FILM_TYPES = [ "Kodak Portra 400 (35mm)", "Kodak Tri-X 400 (35mm)", "Kodak Ektar 100 (35mm)", "Ilford HP5 Plus (35mm)", "Ilford Delta 100 (35mm)", "Ilford FP4 Plus (120)", "CineStill 800T (35mm)", "Fujifilm Pro 400H (35mm)", "Fomapan 400 (35mm)", "Other / Unknown",]
STORAGE_OPTIONS = [ "fridge, sealed", "freezer, sealed", "room temp, sealed", "room temp, loose", "shoe box, attic", "shoe box, basement", "unknown",]
RESOLUTION_OPTIONS = [2000, 3000, 4000, 5000, 6000, 8000]
@_gpu_decorator()def run_pipeline( image: Any, film_type: str, film_age_years: int, storage: str, scan_dpi: int, progress: gr.Progress = gr.Progress(),) -> tuple[Any, str, str, str, str, str]: """Gradio handler for the diagnose button.""" if image is None: empty = '<p style="color: var(--halide-crimson);">No image provided.</p>' return None, empty, empty, empty, "{}", render_history(list_recent(limit=10))
try: progress(0.0, "Hashing image for cache lookup...") pil_image = load_image(image) cache = get_cache() image_bytes = image_to_png_bytes(pil_image) cached = cache.get(image_bytes) if cached is not None: logger.info("Returning cached diagnosis") result = cached else: progress(0.1, "Stage 1/2: running vision defect extraction...") result = run_diagnosis( image=pil_image, film_type=film_type or "Unknown 35mm", film_age_years=int(film_age_years or 0), storage=storage or "unknown", scan_resolution_dpi=int(scan_dpi or 4000), ) progress(0.85, "Stage 2/2: persisting diagnosis...") try: record_diagnosis(result) except Exception as exc: # pragma: no cover logger.warning("Failed to record diagnosis: %s", exc) cache.put(image_bytes, result)
progress(1.0, "Done.")
counts = result.get("defects", {}).get("label_counts", {}) or {} defects = result.get("defects", {}).get("defects", []) or [] annotated = draw_defects( pil_image, defects, title=f"Halide: {len(defects)} validated defects", ) stats = stats_html(result) pills = defect_pills_html(counts) diag = diagnosis_html(result.get("diagnosis", {}).get("diagnosis_text", "")) raw_json = json.dumps(result, indent=2, sort_keys=True) history = render_history(list_recent(limit=get_app_config().max_history_items)) return annotated, stats, pills, diag, raw_json, history except Exception as exc: # pragma: no cover logger.exception("Pipeline failed") err = ( '<div class="halide-panel" style="border-color: var(--halide-crimson);">' f'<div class="halide-section-title" style="color: var(--halide-red);">' f"Pipeline error</div>" f"<pre style=\"color: var(--halide-parchment); white-space: pre-wrap;\">" f"{html.escape(str(exc))}</pre></div>" ) return None, err, "", "", "{}", render_history(list_recent(limit=10))
def refresh_history() -> str: return render_history(list_recent(limit=get_app_config().max_history_items))
def build_app() -> gr.Blocks: init_db() theme = build_theme()
with gr.Blocks(title="Project Halide") as app: gr.HTML(HEADER_HTML)
with gr.Row(): with gr.Column(scale=1): with gr.Group(elem_classes="halide-panel"): gr.Markdown('<div class="halide-section-title">Scan upload</div>') image_input = gr.Image( label="Film scan", type="pil", height=380, sources=["upload", "clipboard"], )
with gr.Group(elem_classes="halide-panel"): gr.Markdown('<div class="halide-section-title">Film metadata</div>') film_type = gr.Dropdown( choices=DEFAULT_FILM_TYPES, value=DEFAULT_FILM_TYPES[0], label="Film stock", ) with gr.Row(): film_age = gr.Slider( minimum=0, maximum=80, step=1, value=2, label="Age (years)", ) scan_dpi = gr.Dropdown( choices=RESOLUTION_OPTIONS, value=4000, label="Scan resolution (dpi)", ) storage = gr.Radio( choices=STORAGE_OPTIONS, value=STORAGE_OPTIONS[0], label="Storage condition", )
run_btn = gr.Button("Diagnose scan", variant="primary", size="lg")
with gr.Column(scale=2): with gr.Group(elem_classes="halide-panel"): gr.Markdown('<div class="halide-section-title">Annotated scan</div>') annotated_output = gr.Image( label="Defect overlay", type="pil", height=430, interactive=False, )
with gr.Group(elem_classes="halide-panel"): gr.Markdown('<div class="halide-section-title">Defect summary</div>') defect_summary = gr.HTML( value='<p style="color: var(--halide-slate);">Awaiting scan.</p>' )
with gr.Group(elem_classes="halide-panel"): gr.Markdown('<div class="halide-section-title">Diagnosis & fixes</div>') diagnosis_output = gr.HTML( value='<p style="color: var(--halide-slate);">Awaiting scan.</p>' )
with gr.Group(elem_classes="halide-panel"): gr.Markdown('<div class="halide-section-title">Session stats</div>') stats_output = gr.HTML( value='<p style="color: var(--halide-slate);">Awaiting scan.</p>' )
with gr.Column(scale=1): with gr.Group(elem_classes="halide-panel"): gr.Markdown('<div class="halide-section-title">Recent diagnoses</div>') history_output = gr.HTML(value=refresh_history()) refresh_btn = gr.Button("Refresh history", size="sm")
with gr.Group(elem_classes="halide-panel"): gr.Markdown('<div class="halide-section-title">Structured result</div>') raw_output = gr.Code(value="{}", language="json", label="Pipeline JSON")
gr.HTML( "<footer>Project Halide. Edge-native, no cloud APIs. " "Vision: MiniCPM-V 4.6 (1.3B). Reasoning: Nemotron-Mini-4B-Instruct (few-shot).</footer>" )
run_btn.click( fn=run_pipeline, inputs=[image_input, film_type, film_age, storage, scan_dpi], outputs=[ annotated_output, stats_output, defect_summary, diagnosis_output, raw_output, history_output, ], ) refresh_btn.click(fn=refresh_history, outputs=[history_output])
return app
def main() -> None: app = build_app() app.queue(max_size=8).launch( server_name="0.0.0.0", server_port=7860, theme=build_theme(), css=THEME_CSS, )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""UI components. Defect list rendering and shared visual helpers."""
from __future__ import annotations
import htmlimport timefrom typing import Iterable
HEADER_HTML = """<div id="halide-header"> <h1>Project Halide</h1> <p>Edge-native diagnostic engine for analog film scans</p></div>"""
def defect_pills_html(label_counts: dict[str, int]) -> str: """Render defect counts as colored pills.""" if not label_counts: return '<p style="color: var(--halide-slate);">No defects detected.</p>' pills: list[str] = [] for label, count in sorted(label_counts.items(), key=lambda kv: -kv[1]): pills.append( f'<span class="halide-defect-pill {html.escape(label)}">' f"{html.escape(label)}: {int(count)}</span>" ) return '<div>' + "".join(pills) + "</div>"
def stats_html(result: dict) -> str: """Render a stats card with defect counts and timing.""" defects = result.get("defects", {}) or {} diagnosis = result.get("diagnosis", {}) or {} total = result.get("total_seconds", 0.0) or 0.0 vision_s = defects.get("inference_seconds", 0.0) or 0.0 reasoning_s = diagnosis.get("reasoning_seconds", 0.0) or 0.0
rows: list[str] = [] rows.append(_stat_row("Total defects", str(defects.get("defect_count", 0)))) rows.append(_stat_row("Dropped (invalid)", str(defects.get("dropped_count", 0)))) rows.append(_stat_row("Vision inference", f"{vision_s:.2f}s")) rows.append(_stat_row("Reasoning", f"{reasoning_s:.2f}s")) rows.append(_stat_row("Total", f"{total:.2f}s")) rows.append(_stat_row("Vision model", _truncate(defects.get("model_path", ""), 50))) rows.append(_stat_row("Reasoning model", _truncate(diagnosis.get("model_path", ""), 50))) return f'<div class="halide-stats">{"".join(rows)}</div>'
def _stat_row(label: str, value: str) -> str: return ( '<div class="halide-stat">' f'<span class="halide-stat-label">{html.escape(label)}</span>' f'<span>{html.escape(value)}</span>' "</div>" )
def _truncate(s: str, n: int) -> str: if len(s) <= n: return s return "..." + s[-(n - 3):]
def diagnosis_html(text: str) -> str: """Wrap diagnosis text in the styled card.""" safe = html.escape(text or "(no diagnosis produced)").replace("\n", "<br>") return f'<div class="halide-diagnosis">{safe}</div>'
def history_row_html(entry: dict) -> str: """Render a single row in the recent-diagnoses sidebar.""" counts = entry.get("label_counts", {}) or {} total = entry.get("defect_count", 0) or 0 film = entry.get("film_type", "Unknown") age = entry.get("film_age_years", "?") storage = entry.get("storage", "?") ts = entry.get("created_at", 0) seconds = entry.get("total_seconds", 0.0) or 0.0 stamp = time.strftime("%Y-%m-%d %H:%M", time.localtime(float(ts or 0))) return ( f'<div class="halide-history-item">' f'<div class="halide-section-title" style="font-size: 0.95rem;">' f"{html.escape(str(film))} (age {html.escape(str(age))}y, " f"{html.escape(str(storage))})</div>" f"{defect_pills_html(counts)}" f'<div style="color: var(--halide-slate); font-size: 0.8rem; margin-top: 0.4rem;">' f"defects: {int(total)} | {seconds:.2f}s | {html.escape(stamp)}" f"</div></div>" )
def render_history(entries: Iterable[dict]) -> str: items = "".join(history_row_html(e) for e in entries) if not items: return '<p style="color: var(--halide-slate);">No diagnoses yet.</p>' return items
__all__ = [ "HEADER_HTML", "defect_pills_html", "stats_html", "diagnosis_html", "render_history",]123456789101112131415161718192021222324252627282930313233343536373839"""Gradio Server wrapper for Project Halide."""
from __future__ import annotations
import gradio as gr
from config import CANONICAL_VISION_MODEL_ID, DEFAULT_REASONING_MODEL_IDfrom ui.app import build_appfrom ui.theme import THEME_CSS, build_theme
def build_server(blocks: gr.Blocks | None = None) -> gr.Server: """Build a gr.Server with the UI mounted at root and health metadata.""" server = gr.Server( title="Project Halide", version="0.1.0", description="Edge-native analog film diagnostic engine.", )
@server.get("/healthz") def healthz() -> dict[str, str]: return { "status": "ok", "vision_model": CANONICAL_VISION_MODEL_ID, "reasoning_model": DEFAULT_REASONING_MODEL_ID, }
gr.mount_gradio_app( server, blocks or build_app(), path="/", theme=build_theme(), css=THEME_CSS, show_error=True, ) return server
__all__ = ["build_server"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238"""Autumn theme. Colors derived from the project logo (orange-to-red on black)."""
from __future__ import annotations
import gradio as gr
AMBER = "#d97706"AMBER_DEEP = "#b45309"ORANGE = "#ea580c"RED = "#dc2626"CRIMSON = "#991b1b"EMBER = "#f59e0b"TEAL = "#0891b2"VIOLET = "#7c3aed"
INK = "#0c0a09"INK_SOFT = "#1c1917"GRAPHITE = "#292524"PARCHMENT = "#fef3c7"PARCHMENT_DEEP = "#fde68a"SLATE = "#44403c"
THEME_CSS = f""":root {{ --halide-amber: {AMBER}; --halide-amber-deep: {AMBER_DEEP}; --halide-orange: {ORANGE}; --halide-red: {RED}; --halide-crimson: {CRIMSON}; --halide-ember: {EMBER}; --halide-teal: {TEAL}; --halide-violet: {VIOLET}; --halide-ink: {INK}; --halide-ink-soft: {INK_SOFT}; --halide-graphite: {GRAPHITE}; --halide-parchment: {PARCHMENT}; --halide-parchment-deep: {PARCHMENT_DEEP}; --halide-slate: {SLATE};}}
body, .gradio-container {{ background: #0c0a09; color: var(--halide-parchment); font-family: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif;}}
#halide-header {{ background: linear-gradient(90deg, #1c1917 0%, #431407 50%, #78350f 100%); padding: 1rem 1.2rem; border-radius: 0 0 8px 8px; margin-bottom: 1rem; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35); border-bottom: 1px solid var(--halide-amber);}}
#halide-header h1 {{ color: var(--halide-parchment); font-size: 2rem; margin: 0; letter-spacing: 0; text-shadow: 0 2px 4px rgba(0,0,0,0.4);}}
#halide-header p {{ color: var(--halide-parchment-deep); margin: 0.4rem 0 0 0; font-size: 1.05rem; font-style: italic;}}
.halide-panel {{ background: rgba(28, 25, 23, 0.85); border: 1px solid var(--halide-amber-deep); border-radius: 8px; padding: 1rem; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);}}
.halide-history-item {{ background: rgba(41, 37, 36, 0.92); border: 1px solid rgba(180, 83, 9, 0.7); border-radius: 8px; margin-bottom: 0.6rem; padding: 0.85rem;}}
.halide-section-title {{ color: var(--halide-amber); font-size: 1.15rem; font-weight: 600; letter-spacing: 0; text-transform: uppercase; margin-bottom: 0.6rem; border-bottom: 1px solid var(--halide-amber-deep); padding-bottom: 0.3rem;}}
.halide-stat {{ display: flex; justify-content: space-between; padding: 0.4rem 0; border-bottom: 1px dotted var(--halide-slate); color: var(--halide-parchment);}}
.halide-stat-label {{ color: var(--halide-amber); font-weight: 600;}}
.halide-diagnosis {{ background: rgba(217, 119, 6, 0.08); border-left: 4px solid var(--halide-amber); padding: 1rem 1.2rem; border-radius: 6px; white-space: pre-wrap; font-size: 0.98rem; line-height: 1.6; color: var(--halide-parchment);}}
.halide-defect-pill {{ display: inline-block; background: var(--halide-amber); color: var(--halide-ink); padding: 0.2rem 0.7rem; border-radius: 999px; font-size: 0.85rem; font-weight: 600; margin: 0 0.3rem 0.3rem 0;}}
.halide-defect-pill.dust {{ background: var(--halide-amber); color: var(--halide-ink); }}.halide-defect-pill.dirt {{ background: var(--halide-orange); color: var(--halide-parchment); }}.halide-defect-pill.scratch {{ background: var(--halide-red); color: var(--halide-parchment); }}.halide-defect-pill.long_hair {{ background: var(--halide-crimson); color: var(--halide-parchment); }}.halide-defect-pill.short_hair {{ background: var(--halide-teal); color: var(--halide-parchment); }}
button.primary, .primary button {{ background: linear-gradient(135deg, var(--halide-orange), var(--halide-red)) !important; color: var(--halide-parchment) !important; border: 1px solid var(--halide-amber) !important; font-weight: 600 !important; letter-spacing: 0 !important; box-shadow: 0 2px 12px rgba(234, 88, 12, 0.4) !important;}}
button.primary:hover, .primary button:hover {{ background: linear-gradient(135deg, var(--halide-red), var(--halide-crimson)) !important;}}
input, textarea, select {{ background: var(--halide-ink-soft) !important; color: var(--halide-parchment) !important; border: 1px solid var(--halide-amber-deep) !important;}}
input:focus, textarea:focus, select:focus {{ border-color: var(--halide-amber) !important; box-shadow: 0 0 0 2px rgba(217, 119, 6, 0.3) !important;}}
label, .label, .gradio-radio label, .gradio-checkbox label {{ color: var(--halide-parchment-deep) !important; font-weight: 500 !important;}}
footer {{ color: var(--halide-slate) !important; text-align: center; padding: 1rem; font-size: 0.85rem;}}"""
def build_theme() -> gr.Theme: """Build the autumn-themed Gradio theme.""" return gr.themes.Base( primary_hue=gr.themes.Color( c50="#fef3c7", c100="#fde68a", c200="#fcd34d", c300="#fbbf24", c400="#f59e0b", c500=AMBER, c600=AMBER_DEEP, c700="#92400e", c800="#78350f", c900=CRIMSON, c950="#7c2d12", ), secondary_hue=gr.themes.Color( c50="#fef3c7", c100="#fde68a", c200="#fcd34d", c300="#fbbf24", c400=EMBER, c500=AMBER, c600=ORANGE, c700=RED, c800=CRIMSON, c900="#7c2d12", c950="#431407", ), neutral_hue=gr.themes.Color( c50="#fafaf9", c100="#f5f5f4", c200="#e7e5e4", c300="#d6d3d1", c400=SLATE, c500="#57534e", c600="#44403c", c700="#292524", c800=INK_SOFT, c900=INK, c950="#0c0a09", ), font=gr.themes.GoogleFont("Iowan Old Style"), font_mono=gr.themes.GoogleFont("JetBrains Mono"), ).set( body_background_fill=INK, body_background_fill_dark=INK, body_text_color=PARCHMENT, body_text_color_dark=PARCHMENT, button_primary_background_fill=ORANGE, button_primary_background_fill_dark=ORANGE, button_primary_text_color=PARCHMENT, button_primary_text_color_dark=PARCHMENT, block_background_fill=INK_SOFT, block_background_fill_dark=INK_SOFT, block_border_color=AMBER_DEEP, block_border_color_dark=AMBER_DEEP, input_background_fill=INK, input_background_fill_dark=INK, input_border_color=AMBER_DEEP, input_border_color_dark=AMBER_DEEP, )LICENSEAdded+201
README.md+8-8
app.pyAdded+27
config.pyAdded+154
data/__init__.pyAdded+1
data/augmentation.pyAdded+160
data/datasets.pyAdded+130
data/preprocessing.pyAdded+109
data/schemas.pyAdded+268
models/__init__.pyAdded+1
models/reasoning/.gitkeepAdded
models/reasoning/__init__.pyAdded+1
models/reasoning/inference.pyAdded+7
models/reasoning/nemotron_wrapper.pyAdded+166
models/reasoning/prompts.pyAdded+307
models/vision/.gitkeepAdded
models/vision/__init__.pyAdded+1
models/vision/inference.pyAdded+46
models/vision/minicpm_wrapper.pyAdded+243
pipeline/.gitkeepAdded
pipeline/__init__.pyAdded+1
pipeline/diagnoser.pyAdded+65
pipeline/extractor.pyAdded+18
pipeline/pipeline.pyAdded+62
requirements.txtAdded+10
storage/.gitkeepAdded
storage/__init__.pyAdded+1
storage/cache.pyAdded+94
storage/database.pyAdded+190
ui/.gitkeepAdded
ui/__init__.pyAdded+1
ui/app.pyAdded+251
ui/components.pyAdded+106
ui/server.pyAdded+39
ui/theme.pyAdded+238