caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

284 lines
12 KiB
Python

"""Import product images into the owner's media library (R2 ``uploads/``).
Each remote image is fetched through the SSRF guard, decoded with Pillow (which
also rejects non-images and decompression bombs), normalized to an RGB JPEG
capped at 2048px on the long edge, content-hashed for de-duplication, uploaded
privately, and recorded as an owned ``Asset`` (``kind='image'``). Owned
``uploads/`` keys are what the rest of the platform accepts as inputs — the
B-roll i2v generator, the editor, and the reel pipeline — so imported product
images are immediately reusable outside Ad Studio.
**Product-cutout refinement (optional, gated).** Plain Pillow flattening treats
the whole frame as the subject, so a product shot with background clutter
produces a noisy canvas. When ``MODEL_API_KEY``/``SAM_API_KEY`` is configured,
:func:`normalize_image` asks SAM 3.1 (``routing/providers/sam_segment.py``, a
real Meta Model API adapter) to locate the product and crops to its bounding
box before flattening — a real subject isolation step, not a mocked toggle.
``MODEL_API_KEY`` is live in production as of 2026-10-26 (owner's Meta Global
AI Developer Hackathon credit) and this path is verified end-to-end against the
real API (2026-10-28, see ``sam_segment.py``'s module docstring) — unconfigured
deployments still fall back to the byte-for-byte pre-adapter behavior, never a
blocked import.
"""
from __future__ import annotations
import concurrent.futures
import hashlib
import io
import re
import uuid
from typing import Any, Callable
from loguru import logger
from app.domains.adstudio.fetch import IMAGE_MAX_BYTES, FetchError, FetchResult, safe_get
MAX_IMPORTED_IMAGES = 8
MAX_EDGE = 2048
MIN_EDGE = 200
MAX_PIXELS = 60_000_000
#: Fallback object phrase when no usable product title is available at all.
PRODUCT_PHRASE = "the product"
# Cut a title at its first trailing variant/color/size separator (" - Brown",
# ", RFID Blocking", " (White)", " | Men's", " : Size 9", " · Anka") so the
# derived phrase below only ever looks at the part of the title that actually
# names the product, never a color/size/variant-name suffix. "·" is included
# because it's a real storefront convention (confirmed live 2026-11-02 against
# Oxhan Atelier's "Very Turkish Time Sweatshirt · Anka" — without it the old
# regex kept the trailing variant name and SAM 3.1 correctly failed to ground
# on it, same failure mode as every other non-category-noun case already
# documented above).
_TITLE_SEPARATOR_RE = re.compile(r"\s*[\(\[|,:;·]\s*|\s[-–—]\s")
_WORD_RE = re.compile(r"[A-Za-z]+")
#: Below this length a "noun" is almost always an initial/unit, not a real
#: object category (e.g. a stray "a"/"in" that slipped past word-splitting).
_MIN_NOUN_LEN = 3
def phrase_from_title(title: str) -> str:
"""Derive a short, concrete noun phrase SAM 3.1 can actually ground on.
Verified live against the real Meta Model API (2026-10-26, see
``plans/menivor.md``): SAM 3.1's grounding reliably matches a bare
category noun — "shoe", "shoes", "the wallet", "a sneaker" — but **never**
an abstract placeholder like "the product"/"the item"/"the object", and
**never** a multi-word phrase that still carries a leading
adjective/qualifier or brand/model name ("Running shoes", "Nike Air Zoom
Pegasus 40 Running Shoes", even a heuristic trim like "Running Shoes"
all returned zero matches). This was previously untestable — no real key
existed before that date — so the module shipped with the generic
``PRODUCT_PHRASE`` default, which turned out to essentially never match.
E-commerce product titles conventionally put the actual category noun as
the LAST word before any trailing color/size/variant suffix, so: cut the
title at its first such separator, then take the last alphabetic word of
what remains. Falls back to :data:`PRODUCT_PHRASE` (itself a documented
no-op below) when there's no usable title — segmentation is always a
refinement, never a requirement.
"""
head = _TITLE_SEPARATOR_RE.split(title or "", maxsplit=1)[0]
words = _WORD_RE.findall(head)
if not words:
return PRODUCT_PHRASE
noun = words[-1].lower()
if len(noun) < _MIN_NOUN_LEN:
return PRODUCT_PHRASE
return f"the {noun}"
def _default_cutout_box(data: bytes, *, phrase: str = PRODUCT_PHRASE) -> Any:
"""Real SAM 3.1 cutout lookup, no-op unless a Meta Model API key is set.
Returns the best (largest-area) detected box, or ``None`` when
unconfigured, no match, or the call fails — segmentation refines a cutout,
it never blocks product-photo import.
"""
from app.domains.routing.providers import sam_segment
if not sam_segment.sam_api_key():
return None
try:
import base64
data_url = f"data:image/jpeg;base64,{base64.b64encode(data).decode('ascii')}"
result = sam_segment.sam_segment_image(data_url, phrase)
except Exception as exc: # noqa: BLE001 - segmentation is a refinement, never fatal
logger.info(f"adstudio SAM 3.1 cutout skipped: {exc}")
return None
return result.best_box
def normalize_image(
data: bytes,
*,
cutout: Callable[[bytes], Any] | None = _default_cutout_box,
) -> tuple[bytes, int, int] | None:
"""Decode arbitrary image bytes into a bounded RGB JPEG (None if unusable).
``cutout`` optionally returns a :class:`~app.domains.routing.providers.sam_segment.SamBox`
for the detected product; when one comes back, the frame is cropped to that
box (clamped to the real image bounds) before the existing flatten/resize
pipeline runs. Pass ``cutout=None`` to disable (or in tests, to keep the
exact pre-SAM behavior).
"""
try:
from PIL import Image
with Image.open(io.BytesIO(data)) as probe:
width, height = probe.size
if width * height > MAX_PIXELS:
return None
box = cutout(data) if cutout is not None else None
with Image.open(io.BytesIO(data)) as img:
img.load()
if min(img.size) < MIN_EDGE:
return None
if box is not None:
img = _cropped_to_box(img, box)
if min(img.size) < MIN_EDGE:
# A degenerate/too-tight detection must never make an
# otherwise-usable photo unusable: fall back to the
# original, uncropped frame.
img = Image.open(io.BytesIO(data))
img.load()
if img.mode in ("RGBA", "LA", "P"):
rgba = img.convert("RGBA")
canvas = Image.new("RGB", rgba.size, (255, 255, 255))
canvas.paste(rgba, mask=rgba.split()[-1])
img_rgb = canvas
else:
img_rgb = img.convert("RGB")
img_rgb.thumbnail((MAX_EDGE, MAX_EDGE))
out = io.BytesIO()
img_rgb.save(out, "JPEG", quality=90, optimize=True)
return out.getvalue(), img_rgb.size[0], img_rgb.size[1]
except Exception: # noqa: BLE001 - any decode failure means "skip this image"
return None
def _cropped_to_box(img: Any, box: Any) -> Any:
"""Crop ``img`` to a SAM box, padded 8% and clamped to the frame bounds.
SAM 3.1's box coordinates are relative to the ``w``/``h`` it reports
alongside the box (its own working frame size, per the documented grammar
example — not necessarily our source image's actual pixel dimensions), so
coordinates are rescaled onto ``img``'s real size before cropping.
"""
width, height = img.size
sx = (width / box.frame_width) if box.frame_width > 0 else 1.0
sy = (height / box.frame_height) if box.frame_height > 0 else 1.0
x1, y1 = box.x1 * sx, box.y1 * sy
x2, y2 = box.x2 * sx, box.y2 * sy
pad_x = max(1.0, (x2 - x1) * 0.08)
pad_y = max(1.0, (y2 - y1) * 0.08)
left = max(0, int(x1 - pad_x))
top = max(0, int(y1 - pad_y))
right = min(width, int(x2 + pad_x))
bottom = min(height, int(y2 + pad_y))
if right <= left or bottom <= top:
return img
return img.crop((left, top, right, bottom))
def store_remote_images(
urls: list[str],
*,
title: str = "",
fetcher: Callable[..., FetchResult] | None = None,
uploader: Callable[[str, bytes], None] | None = None,
) -> list[dict[str, Any]]:
"""Fetch, normalize, de-duplicate and upload up to 8 product images.
``title`` is the scraped/typed product title (Ad Studio requires one —
see ``scrape.py``), used to derive a concrete SAM 3.1 grounding phrase
(:func:`phrase_from_title`) instead of the generic, SAM-does-not-match
``PRODUCT_PHRASE`` default. Network-only (no DB session is held while
remote stores respond); the returned entries are recorded as owned
assets by :func:`register_images`.
"""
fetch = fetcher or safe_get
upload = uploader or _upload
phrase = phrase_from_title(title)
def _download(url: str) -> tuple[bytes, int, int] | None:
try:
result = fetch(url, max_bytes=IMAGE_MAX_BYTES, accept="image/jpeg,image/png,image/webp,image/*;q=0.8")
except FetchError as exc:
logger.info(f"adstudio image skipped ({exc.status_code}): {exc.message}")
return None
return normalize_image(result.body, cutout=lambda d: _default_cutout_box(d, phrase=phrase))
candidates = list(dict.fromkeys(u for u in urls if u))[: MAX_IMPORTED_IMAGES + 4]
if not candidates:
return []
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
downloaded = list(pool.map(_download, candidates))
stored: list[dict[str, Any]] = []
seen: set[str] = set()
for url, normalized in zip(candidates, downloaded):
if len(stored) >= MAX_IMPORTED_IMAGES:
break
if normalized is None:
continue
data, width, height = normalized
digest = hashlib.sha256(data).hexdigest()
if digest in seen:
continue
seen.add(digest)
key = f"uploads/{uuid.uuid4().hex}.jpg"
try:
upload(key, data)
except Exception as exc: # noqa: BLE001 - storage outage for one image
logger.warning(f"adstudio image upload failed: {exc}")
continue
stored.append({"key": key, "origin_url": url, "width": width, "height": height, "size": len(data)})
return stored
def register_images(session: Any, *, user_id: str, project_id: str, stored: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Record stored images as owned ``image`` assets; returns project entries."""
from app.models.db.repositories import AssetRepository
repo = AssetRepository(session)
entries: list[dict[str, Any]] = []
for index, item in enumerate(stored):
repo.create(
user_id=user_id,
kind="image",
r2_key=item["key"],
content_type="image/jpeg",
size_bytes=int(item.get("size") or 0),
meta={
"filename": f"product-{index + 1}.jpg",
"source": "adstudio",
"project_id": project_id,
"origin_url": str(item.get("origin_url") or "")[:1000],
"upload_state": "registered",
},
)
entries.append({k: item[k] for k in ("key", "origin_url", "width", "height")})
return entries
def _upload(key: str, data: bytes) -> None:
from app.platform.storage.r2 import get_r2_client
get_r2_client().upload_bytes(key, data, content_type="image/jpeg")
def owned_image_entries(session: Any, *, user_id: str, keys: list[str]) -> list[dict[str, Any]]:
"""Validate caller-supplied upload keys (already in their library)."""
from app.domains.media.service import require_owned_asset
entries: list[dict[str, Any]] = []
for key in dict.fromkeys(k.strip() for k in keys if k and k.strip()):
require_owned_asset(session, user_id=user_id, key=key)
entries.append({"key": key, "origin_url": "", "width": 0, "height": 0})
return entries[:MAX_IMPORTED_IMAGES]
__all__ = ["MAX_IMPORTED_IMAGES", "normalize_image", "owned_image_entries", "register_images", "store_remote_images"]