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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
utils.background_factory
|
| 4 |
+
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 5 |
+
Generates professional backgrounds from presets **or** a user-supplied image.
|
| 6 |
+
|
| 7 |
+
Public API
|
| 8 |
+
----------
|
| 9 |
+
create_professional_background(cfg_or_key, width, height) β np.ndarray (BGR)
|
| 10 |
+
|
| 11 |
+
All lower-case helpers are considered private to this module.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Dict, Any, List, Tuple, Optional
|
| 17 |
+
import logging, os, cv2, numpy as np
|
| 18 |
+
|
| 19 |
+
from utils.background_presets import PROFESSIONAL_BACKGROUNDS
|
| 20 |
+
|
| 21 |
+
log = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
__all__ = ["create_professional_background"]
|
| 24 |
+
|
| 25 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
+
# Main entry
|
| 27 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
+
def create_professional_background(
|
| 29 |
+
bg_config: Dict[str, Any] | str,
|
| 30 |
+
width: int,
|
| 31 |
+
height: int,
|
| 32 |
+
) -> np.ndarray:
|
| 33 |
+
"""
|
| 34 |
+
Accepts either β¦
|
| 35 |
+
β’ a **key** into PROFESSIONAL_BACKGROUNDS (e.g. "office_modern"), or
|
| 36 |
+
β’ a **dict** (typically supplied by UI) that may include:
|
| 37 |
+
β background_choice: "office_modern"
|
| 38 |
+
β custom_path: "/path/to/image.png"
|
| 39 |
+
β OR directly contain {type:"gradient", colors:[β¦]}
|
| 40 |
+
Returns **BGR** uint8 image (OpenCV-ready).
|
| 41 |
+
"""
|
| 42 |
+
try:
|
| 43 |
+
# ββ Resolve input ---------------------------------------------------
|
| 44 |
+
choice : str = "minimalist"
|
| 45 |
+
custom_path : str | None = None
|
| 46 |
+
direct_style : Dict[str, Any] | None = None
|
| 47 |
+
|
| 48 |
+
if isinstance(bg_config, str):
|
| 49 |
+
choice = bg_config.lower()
|
| 50 |
+
|
| 51 |
+
elif isinstance(bg_config, dict):
|
| 52 |
+
choice = bg_config.get("background_choice", bg_config.get("name", "minimalist")).lower()
|
| 53 |
+
custom_path = bg_config.get("custom_path")
|
| 54 |
+
if "type" in bg_config and "colors" in bg_config:
|
| 55 |
+
direct_style = bg_config # full inline style
|
| 56 |
+
|
| 57 |
+
# ββ 1) Custom image? ----------------------------------------------
|
| 58 |
+
if custom_path and os.path.exists(custom_path):
|
| 59 |
+
img = cv2.imread(custom_path, cv2.IMREAD_COLOR)
|
| 60 |
+
if img is not None:
|
| 61 |
+
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 62 |
+
fitted = _fit_image_letterbox(img_rgb, width, height, fill=(32,32,32))
|
| 63 |
+
return cv2.cvtColor(fitted, cv2.COLOR_RGB2BGR)
|
| 64 |
+
log.warning(f"Custom-background read failed: {custom_path}")
|
| 65 |
+
|
| 66 |
+
# ββ 2) Inline dict style? -----------------------------------------
|
| 67 |
+
if direct_style:
|
| 68 |
+
if direct_style["type"] == "color":
|
| 69 |
+
bg = _create_solid_background(direct_style, width, height)
|
| 70 |
+
else: # gradient / image
|
| 71 |
+
bg = _create_gradient_background(direct_style, width, height)
|
| 72 |
+
return _apply_bg_adjustments(bg, direct_style)
|
| 73 |
+
|
| 74 |
+
# ββ 3) Preset dict lookup -----------------------------------------
|
| 75 |
+
preset = PROFESSIONAL_BACKGROUNDS.get(choice, PROFESSIONAL_BACKGROUNDS["minimalist"])
|
| 76 |
+
|
| 77 |
+
if preset["type"] == "color":
|
| 78 |
+
bg = _create_solid_background(preset, width, height)
|
| 79 |
+
elif preset["type"] == "image":
|
| 80 |
+
path = Path(preset["path"])
|
| 81 |
+
if path.exists():
|
| 82 |
+
img_bgr = cv2.imread(str(path), cv2.IMREAD_COLOR)
|
| 83 |
+
if img_bgr is not None:
|
| 84 |
+
return cv2.resize(img_bgr, (width, height), interpolation=cv2.INTER_LANCZOS4)
|
| 85 |
+
log.warning(f"Preset image not found: {path}; falling back to gradient")
|
| 86 |
+
bg = _create_gradient_background(
|
| 87 |
+
{**preset, "type": "gradient", "colors": ["#3a3a3a", "#2e2e2e"]}, width, height
|
| 88 |
+
)
|
| 89 |
+
else: # gradient
|
| 90 |
+
bg = _create_gradient_background(preset, width, height)
|
| 91 |
+
|
| 92 |
+
return _apply_bg_adjustments(bg, preset)
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
log.error(f"create_professional_background: {e}")
|
| 96 |
+
return np.full((height, width, 3), (128,128,128), np.uint8)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 100 |
+
# Letter-boxed fit for custom images
|
| 101 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββ
|
| 102 |
+
def _fit_image_letterbox(img_rgb: np.ndarray, dst_w: int, dst_h: int,
|
| 103 |
+
fill=(32,32,32)) -> np.ndarray:
|
| 104 |
+
h, w = img_rgb.shape[:2]
|
| 105 |
+
if h == 0 or w == 0:
|
| 106 |
+
return np.full((dst_h, dst_w, 3), fill, np.uint8)
|
| 107 |
+
|
| 108 |
+
src_a = w / h
|
| 109 |
+
dst_a = dst_w / dst_h
|
| 110 |
+
if src_a > dst_a:
|
| 111 |
+
new_w, new_h = dst_w, int(dst_w / src_a)
|
| 112 |
+
else:
|
| 113 |
+
new_h, new_w = dst_h, int(dst_h * src_a)
|
| 114 |
+
|
| 115 |
+
resized = cv2.resize(img_rgb, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 116 |
+
canvas = np.full((dst_h, dst_w, 3), fill, np.uint8)
|
| 117 |
+
y0 = (dst_h-new_h)//2; x0 = (dst_w-new_w)//2
|
| 118 |
+
canvas[y0:y0+new_h, x0:x0+new_w] = resized
|
| 119 |
+
return canvas
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 123 |
+
# Background builders
|
| 124 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 125 |
+
def _create_solid_background(style: Dict[str,Any], w: int, h: int) -> np.ndarray:
|
| 126 |
+
clr_hex = style["colors"][0].lstrip("#")
|
| 127 |
+
rgb = tuple(int(clr_hex[i:i+2],16) for i in (0,2,4))
|
| 128 |
+
return np.full((h,w,3), rgb[::-1], np.uint8) # BGR
|
| 129 |
+
|
| 130 |
+
def _create_gradient_background(style: Dict[str,Any], w:int, h:int) -> np.ndarray:
|
| 131 |
+
cols = [hex.lstrip("#") for hex in style["colors"]]
|
| 132 |
+
rgbs = [tuple(int(c[i:i+2],16) for i in (0,2,4)) for c in cols]
|
| 133 |
+
dirn = style.get("direction","vertical")
|
| 134 |
+
|
| 135 |
+
if dirn=="vertical": grad = _grad_vertical(rgbs, w, h)
|
| 136 |
+
elif dirn=="horizontal": grad = _grad_horizontal(rgbs, w, h)
|
| 137 |
+
elif dirn=="diagonal": grad = _grad_diagonal(rgbs, w, h)
|
| 138 |
+
else: grad = _grad_radial(rgbs, w, h,
|
| 139 |
+
soft=(dirn=="soft_radial"))
|
| 140 |
+
return cv2.cvtColor(grad, cv2.COLOR_RGB2BGR)
|
| 141 |
+
|
| 142 |
+
# --- gradient helpers -------------------------------------------------------
|
| 143 |
+
|
| 144 |
+
def _grad_vertical(colors, w, h):
|
| 145 |
+
g = np.zeros((h, w, 3), np.uint8)
|
| 146 |
+
for y in range(h):
|
| 147 |
+
g[y, :] = _interp_multi(colors, y/h)
|
| 148 |
+
return g
|
| 149 |
+
def _grad_horizontal(colors, w, h):
|
| 150 |
+
g = np.zeros((h, w, 3), np.uint8)
|
| 151 |
+
for x in range(w):
|
| 152 |
+
g[:, x] = _interp_multi(colors, x/w)
|
| 153 |
+
return g
|
| 154 |
+
def _grad_diagonal(colors, w, h):
|
| 155 |
+
y,x = np.mgrid[0:h, 0:w]
|
| 156 |
+
prog = np.clip((x+y)/(h+w), 0, 1)
|
| 157 |
+
g = np.zeros((h,w,3), np.uint8)
|
| 158 |
+
for c in range(3):
|
| 159 |
+
g[:,:,c] = _vector_interp(colors, prog, c)
|
| 160 |
+
return g
|
| 161 |
+
def _grad_radial(colors, w, h, soft=False):
|
| 162 |
+
cx, cy = w/2, h/2
|
| 163 |
+
maxd = np.hypot(cx, cy)
|
| 164 |
+
y,x = np.mgrid[0:h, 0:w]
|
| 165 |
+
prog = np.clip(np.hypot(x-cx, y-cy)/maxd, 0, 1)
|
| 166 |
+
if soft: prog = prog**0.7
|
| 167 |
+
g = np.zeros((h,w,3), np.uint8)
|
| 168 |
+
for c in range(3):
|
| 169 |
+
g[:,:,c] = _vector_interp(colors, prog, c)
|
| 170 |
+
return g
|
| 171 |
+
|
| 172 |
+
def _vector_interp(cols, prog, chan):
|
| 173 |
+
if len(cols)==1:
|
| 174 |
+
return np.full_like(prog, cols[0][chan], np.uint8)
|
| 175 |
+
segs = len(cols)-1
|
| 176 |
+
seg_prog = prog*segs
|
| 177 |
+
idx = np.clip(np.floor(seg_prog).astype(int), 0, segs-1)
|
| 178 |
+
local = seg_prog - idx
|
| 179 |
+
start = np.take([c[chan] for c in cols], idx)
|
| 180 |
+
end = np.take([c[chan] for c in cols[1:]+[cols[-1]]], idx)
|
| 181 |
+
return (start + (end-start)*local).astype(np.uint8)
|
| 182 |
+
|
| 183 |
+
def _interp_multi(cols, p):
|
| 184 |
+
# cols length 1..n p β[0,1]
|
| 185 |
+
if len(cols)==1: return cols[0]
|
| 186 |
+
seg = p*(len(cols)-1)
|
| 187 |
+
i = int(seg)
|
| 188 |
+
l = seg - i
|
| 189 |
+
c1, c2 = cols[i], cols[min(i+1, len(cols)-1)]
|
| 190 |
+
return tuple(int(c1[c]+(c2[c]-c1[c])*l) for c in range(3))
|
| 191 |
+
|
| 192 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 193 |
+
# Post-adjust
|
| 194 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 195 |
+
def _apply_bg_adjustments(bg: np.ndarray, cfg: Dict[str,Any]) -> np.ndarray:
|
| 196 |
+
bright = cfg.get("brightness",1.0)
|
| 197 |
+
contrast = cfg.get("contrast",1.0)
|
| 198 |
+
if bright==1.0 and contrast==1.0:
|
| 199 |
+
return bg
|
| 200 |
+
out = bg.astype(np.float32)*contrast*bright
|
| 201 |
+
return np.clip(out,0,255).astype(np.uint8)
|