remove-background-ai 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,28 @@
1
+ """Remove image backgrounds with OpenAI's GPT Image 2.5."""
2
+
3
+ from .core import remove_background
4
+ from .editor import ImageEditor, OpenAIImageEditor
5
+ from .errors import EditError, InvalidInputError, RemoveBackgroundError
6
+ from .models import (
7
+ Cutout,
8
+ EditRequest,
9
+ EditResponse,
10
+ ImageSize,
11
+ RemovalOptions,
12
+ Usage,
13
+ )
14
+
15
+ __all__ = [
16
+ "Cutout",
17
+ "EditError",
18
+ "EditRequest",
19
+ "EditResponse",
20
+ "ImageEditor",
21
+ "ImageSize",
22
+ "InvalidInputError",
23
+ "OpenAIImageEditor",
24
+ "RemovalOptions",
25
+ "RemoveBackgroundError",
26
+ "Usage",
27
+ "remove_background",
28
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import cli
2
+
3
+ cli(prog_name="remove-background-ai")
@@ -0,0 +1,245 @@
1
+ import json
2
+ import os
3
+ import secrets
4
+ from pathlib import Path
5
+ from typing import NoReturn, cast, get_args
6
+
7
+ import click
8
+ from pydantic import ValidationError
9
+
10
+ from .core import remove_background
11
+ from .editor import ImageEditor, OpenAIImageEditor
12
+ from .errors import EditError, InvalidInputError
13
+ from .models import Cutout, ModelName, OutputMode, Quality, RemovalOptions
14
+
15
+ EXIT_REFUSED = 3
16
+ EXIT_EDIT_FAILED = 4
17
+
18
+
19
+ @click.command(
20
+ name="remove-background-ai",
21
+ epilog=(
22
+ "Exit codes: 0 success; 1 general failure; 2 usage error; "
23
+ "3 input or output refused; 4 image edit failed."
24
+ ),
25
+ )
26
+ @click.option(
27
+ "-o",
28
+ "--output",
29
+ type=click.Path(path_type=Path),
30
+ metavar="FILE",
31
+ help="Write the PNG to FILE.",
32
+ )
33
+ @click.option(
34
+ "-d",
35
+ "--output-dir",
36
+ type=click.Path(path_type=Path),
37
+ metavar="DIRECTORY",
38
+ help="Write PNGs to DIRECTORY.",
39
+ )
40
+ @click.option("--force", is_flag=True, help="Replace output files that already exist.")
41
+ @click.option(
42
+ "--keep", help="What to keep, for example the red backpack and its straps."
43
+ )
44
+ @click.option("--remove", help="What to remove besides the background.")
45
+ @click.option(
46
+ "--mask",
47
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
48
+ help="Mask FILE: white keeps, black removes; same size as the image.",
49
+ )
50
+ @click.option(
51
+ "--mode",
52
+ type=click.Choice(get_args(OutputMode)),
53
+ default="original",
54
+ show_default=True,
55
+ help="Keep original pixels and size, or use the generated image.",
56
+ )
57
+ @click.option(
58
+ "--model",
59
+ type=click.Choice(get_args(ModelName)),
60
+ default="gpt-image-2.5-sunburst-2026-09-08",
61
+ show_default=True,
62
+ help="GPT Image model to use.",
63
+ )
64
+ @click.option(
65
+ "--quality",
66
+ type=click.Choice(get_args(Quality)),
67
+ default="high",
68
+ show_default=True,
69
+ help="Image edit quality.",
70
+ )
71
+ @click.option("--json", "as_json", is_flag=True, help="Write a JSON array to stdout.")
72
+ @click.version_option(
73
+ package_name="remove-background-ai", prog_name="remove-background-ai"
74
+ )
75
+ @click.argument(
76
+ "images",
77
+ nargs=-1,
78
+ required=True,
79
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
80
+ )
81
+ @click.pass_context
82
+ def cli(
83
+ ctx: click.Context,
84
+ images: tuple[Path, ...],
85
+ output: Path | None,
86
+ output_dir: Path | None,
87
+ force: bool,
88
+ keep: str | None,
89
+ remove: str | None,
90
+ mask: Path | None,
91
+ mode: str,
92
+ model: str,
93
+ quality: str,
94
+ as_json: bool,
95
+ ) -> None:
96
+ """Send each image to GPT Image 2.5 and write a transparent PNG. By default,
97
+ the result keeps the original pixels and size and takes only transparency
98
+ from the model. Set OPENAI_API_KEY before running this command.
99
+
100
+ Examples:
101
+
102
+ \b
103
+ remove-background-ai photo.jpg
104
+ remove-background-ai photo.jpg -o portrait.png
105
+ remove-background-ai photo.jpg other.png -d cutouts --json
106
+ remove-background-ai photo.jpg --keep "the red backpack, including both straps"
107
+ """
108
+ try:
109
+ options = RemovalOptions(
110
+ keep=keep,
111
+ remove=remove,
112
+ mode=cast("OutputMode", mode),
113
+ model=cast("ModelName", model),
114
+ quality=cast("Quality", quality),
115
+ )
116
+ except ValidationError as error:
117
+ first = error.errors()[0]
118
+ raise click.BadParameter(
119
+ first["msg"], param_hint=f"'--{first['loc'][0]}'"
120
+ ) from None
121
+ if output is not None and len(images) != 1:
122
+ raise click.UsageError("-o/--output requires exactly one image")
123
+ if mask is not None and len(images) != 1:
124
+ raise click.UsageError("--mask requires exactly one image")
125
+ if output is not None and output_dir is not None:
126
+ raise click.UsageError("-o/--output and -d/--output-dir cannot be combined")
127
+ destinations = tuple(
128
+ output or (output_dir or image.parent) / f"{image.stem}-no-bg.png"
129
+ for image in images
130
+ )
131
+ resolved = [destination.resolve() for destination in destinations]
132
+ if len(set(resolved)) != len(resolved):
133
+ raise click.UsageError("two images would write the same output")
134
+ inputs = {image.resolve() for image in images}
135
+ if mask is not None:
136
+ inputs.add(mask.resolve())
137
+ if any(destination in inputs for destination in resolved):
138
+ raise click.UsageError("an output path cannot be an input image or mask")
139
+ try:
140
+ editor: ImageEditor = (
141
+ ctx.obj["editor"]
142
+ if ctx.obj and "editor" in ctx.obj
143
+ else OpenAIImageEditor()
144
+ )
145
+ except EditError as error:
146
+ _fail_every_image(images, str(error), EXIT_EDIT_FAILED, as_json=as_json)
147
+ if output_dir is not None:
148
+ try:
149
+ output_dir.mkdir(parents=True, exist_ok=True)
150
+ except OSError as error:
151
+ message = f"cannot create {output_dir}: {error}"
152
+ _fail_every_image(images, message, EXIT_REFUSED, as_json=as_json)
153
+ results: list[dict[str, object]] = []
154
+ exit_code = 0
155
+ for image, destination in zip(images, destinations, strict=True):
156
+ click.echo(f"Removing the background from {image}", err=True)
157
+ try:
158
+ cutout = _process_one(
159
+ image,
160
+ destination,
161
+ options=options,
162
+ mask=mask,
163
+ editor=editor,
164
+ force=force,
165
+ )
166
+ except _ImageFailed as failure:
167
+ click.echo(f"{image}: {failure.message}", err=True)
168
+ results.append({"input": str(image), "error": failure.message})
169
+ exit_code = max(exit_code, failure.exit_code)
170
+ continue
171
+ results.append(
172
+ {
173
+ "input": str(image),
174
+ "output": str(destination),
175
+ **cutout.model_dump(mode="json"),
176
+ }
177
+ )
178
+ if not as_json:
179
+ click.echo(str(destination))
180
+ if as_json:
181
+ click.echo(json.dumps(results, indent=2))
182
+ if exit_code:
183
+ raise SystemExit(exit_code)
184
+
185
+
186
+ def _process_one(
187
+ image: Path,
188
+ output: Path,
189
+ *,
190
+ options: RemovalOptions,
191
+ mask: Path | None,
192
+ editor: ImageEditor,
193
+ force: bool,
194
+ ) -> Cutout:
195
+ already_exists = f"{output} already exists; use --force to replace it"
196
+ if output.exists() and not force:
197
+ raise _ImageFailed(already_exists, EXIT_REFUSED)
198
+ if not output.parent.is_dir():
199
+ raise _ImageFailed(
200
+ f"output directory {output.parent} does not exist", EXIT_REFUSED
201
+ )
202
+ try:
203
+ cutout = remove_background(image, options=options, mask=mask, editor=editor)
204
+ except InvalidInputError as error:
205
+ raise _ImageFailed(str(error), EXIT_REFUSED) from None
206
+ except EditError as error:
207
+ raise _ImageFailed(str(error), EXIT_EDIT_FAILED) from None
208
+ try:
209
+ _write_atomic(output, cutout.png, force=force)
210
+ except FileExistsError:
211
+ raise _ImageFailed(already_exists, EXIT_REFUSED) from None
212
+ except OSError as error:
213
+ raise _ImageFailed(f"cannot write {output}: {error}", EXIT_REFUSED) from None
214
+ return cutout
215
+
216
+
217
+ def _fail_every_image(
218
+ images: tuple[Path, ...], message: str, exit_code: int, *, as_json: bool
219
+ ) -> NoReturn:
220
+ click.echo(f"Error: {message}", err=True)
221
+ if as_json:
222
+ records = [{"input": str(image), "error": message} for image in images]
223
+ click.echo(json.dumps(records, indent=2))
224
+ raise SystemExit(exit_code)
225
+
226
+
227
+ class _ImageFailed(Exception):
228
+ def __init__(self, message: str, exit_code: int) -> None:
229
+ super().__init__(message)
230
+ self.message = message
231
+ self.exit_code = exit_code
232
+
233
+
234
+ def _write_atomic(output: Path, png: bytes, *, force: bool) -> None:
235
+ # A plain exclusive open, unlike tempfile, leaves the permissions to the umask.
236
+ temporary = output.with_name(f".{output.name}.{secrets.token_hex(8)}.tmp")
237
+ try:
238
+ with temporary.open("xb") as file:
239
+ file.write(png)
240
+ if force:
241
+ os.replace(temporary, output)
242
+ else:
243
+ os.link(temporary, output)
244
+ finally:
245
+ temporary.unlink(missing_ok=True)
@@ -0,0 +1,83 @@
1
+ from pathlib import Path
2
+
3
+ from pydantic import ConfigDict, InstanceOf, SkipValidation, validate_call
4
+
5
+ from . import imaging
6
+ from .editor import ImageEditor, OpenAIImageEditor
7
+ from .models import Cutout, EditRequest, ImageSize, RemovalOptions
8
+ from .sizing import model_size_for
9
+
10
+ DEFAULT_OPTIONS = RemovalOptions()
11
+ _PROMPT = """\
12
+ Edit the supplied image to remove its background.
13
+
14
+ KEEP: {keep}.
15
+ REMOVE: {remove}.
16
+
17
+ Leave what is kept in its existing position, scale, orientation and pose on the \
18
+ original canvas. Preserve its geometry, colours, lighting, texture, lettering, logos \
19
+ and fine detail such as hair, fur and thin parts. Do not retouch, restyle, recentre, \
20
+ crop, sharpen or reconstruct hidden parts.
21
+
22
+ Make every removed region fully transparent, including background seen through gaps \
23
+ and openings. Use partially transparent pixels where an edge is soft. Add no \
24
+ scenery, outline, replacement background, white fill, checkerboard or new shadow."""
25
+ _MASK_NOTE = """
26
+
27
+ The supplied mask marks the subject: keep its opaque area and remove the background \
28
+ in its transparent area."""
29
+
30
+
31
+ @validate_call(config=ConfigDict(strict=True, arbitrary_types_allowed=True))
32
+ def remove_background(
33
+ image: Path,
34
+ *,
35
+ editor: SkipValidation[ImageEditor | None] = None,
36
+ options: InstanceOf[RemovalOptions] = DEFAULT_OPTIONS,
37
+ mask: Path | None = None,
38
+ ) -> Cutout:
39
+ """Remove the background from an image file.
40
+
41
+ ``mask`` is an optional image the size of the upright source: white keeps,
42
+ black removes. ``editor`` defaults to the OpenAI API, authenticated by the
43
+ ``OPENAI_API_KEY`` environment variable.
44
+ """
45
+ source = imaging.load_source(image)
46
+ if editor is None:
47
+ editor = OpenAIImageEditor()
48
+ source_size = ImageSize(width=source.width, height=source.height)
49
+ size = model_size_for(source_size)
50
+ response = editor.edit(
51
+ EditRequest(
52
+ image=imaging.encode_request(source, size),
53
+ mask=None if mask is None else imaging.encode_mask(mask, source_size, size),
54
+ prompt=_prompt(options, masked=mask is not None),
55
+ model=options.model,
56
+ quality=options.quality,
57
+ size=size,
58
+ )
59
+ )
60
+ cutout = imaging.decode_cutout(response.image, size)
61
+ if options.mode == "generated":
62
+ png, output_size = response.image, size
63
+ else:
64
+ png, output_size = imaging.apply_alpha(source, cutout), source_size
65
+ return Cutout(
66
+ png=png,
67
+ mode=options.mode,
68
+ model=options.model,
69
+ quality=options.quality,
70
+ source_size=source_size,
71
+ model_size=size,
72
+ output_size=output_size,
73
+ request_id=response.request_id,
74
+ usage=response.usage,
75
+ )
76
+
77
+
78
+ def _prompt(options: RemovalOptions, *, masked: bool) -> str:
79
+ prompt = _PROMPT.format(
80
+ keep=(options.keep or "the main subject").rstrip("."),
81
+ remove=(options.remove or "everything else").rstrip("."),
82
+ )
83
+ return prompt + _MASK_NOTE if masked else prompt
@@ -0,0 +1,76 @@
1
+ import base64
2
+ from typing import Protocol
3
+
4
+ from openai import APIStatusError, OpenAI, OpenAIError, omit
5
+ from pydantic import ValidationError
6
+
7
+ from .errors import EditError
8
+ from .models import EditRequest, EditResponse, Usage
9
+
10
+
11
+ class ImageEditor(Protocol):
12
+ """Sends one edit to an image model and returns its result."""
13
+
14
+ def edit(self, request: EditRequest) -> EditResponse: ...
15
+
16
+
17
+ class OpenAIImageEditor:
18
+ """Send image edits through the OpenAI SDK."""
19
+
20
+ def __init__(self, client: OpenAI | None = None) -> None:
21
+ if client is None:
22
+ try:
23
+ client = OpenAI(timeout=300.0, max_retries=2)
24
+ except OpenAIError:
25
+ raise EditError("Set OPENAI_API_KEY to use the image editor") from None
26
+ self._client = client
27
+
28
+ def edit(self, request: EditRequest) -> EditResponse:
29
+ """Send one image edit and return the decoded result."""
30
+ try:
31
+ response = self._client.images.edit(
32
+ model=request.model,
33
+ image=("image.png", request.image, "image/png"),
34
+ mask=("mask.png", request.mask, "image/png")
35
+ if request.mask is not None
36
+ else omit,
37
+ prompt=request.prompt,
38
+ background="transparent",
39
+ output_format="png",
40
+ quality=request.quality,
41
+ size=str(request.size),
42
+ n=1,
43
+ )
44
+ except APIStatusError as error:
45
+ body = error.body
46
+ message = body.get("message") if isinstance(body, dict) else None
47
+ message = message if isinstance(message, str) else "no error message"
48
+ details = f"OpenAI image edit failed (HTTP {error.status_code}): {message}"
49
+ if error.request_id is not None:
50
+ details += f" (request ID: {error.request_id})"
51
+ raise EditError(
52
+ details.replace(self._client.api_key, "[redacted]")
53
+ ) from None
54
+ except OpenAIError as error:
55
+ raise EditError(f"OpenAI image edit request failed: {error}") from None
56
+ # The SDK does not validate responses against its own types.
57
+ data = response.data
58
+ first = data[0] if isinstance(data, list) and data else None
59
+ encoded = getattr(first, "b64_json", None)
60
+ if not isinstance(encoded, str):
61
+ raise EditError("OpenAI image edit response has no image data")
62
+ try:
63
+ image = base64.b64decode(encoded, validate=True)
64
+ except ValueError:
65
+ raise EditError("OpenAI image edit response has invalid base64") from None
66
+ return EditResponse(
67
+ image=image, request_id=response._request_id, usage=_usage(response.usage)
68
+ )
69
+
70
+
71
+ def _usage(reported: object) -> Usage | None:
72
+ """Return the reported token usage, or None if it is missing or unreadable."""
73
+ try:
74
+ return Usage.model_validate(reported, from_attributes=True)
75
+ except ValidationError:
76
+ return None
@@ -0,0 +1,10 @@
1
+ class RemoveBackgroundError(Exception):
2
+ """Base class for every error this package raises."""
3
+
4
+
5
+ class InvalidInputError(RemoveBackgroundError, ValueError):
6
+ """An input image, mask or setting cannot be sent to the model."""
7
+
8
+
9
+ class EditError(RemoveBackgroundError):
10
+ """The OpenAI request failed or returned an unusable image."""
@@ -0,0 +1,110 @@
1
+ import io
2
+ from pathlib import Path
3
+
4
+ from PIL import Image, ImageChops, ImageCms, ImageOps
5
+
6
+ from .errors import EditError, InvalidInputError
7
+ from .models import ImageSize
8
+
9
+
10
+ def load_source(path: Path) -> Image.Image:
11
+ """Decode a source image as upright 8-bit RGB or RGBA.
12
+
13
+ Its colour profile survives in ``info`` only when it describes RGB samples.
14
+ """
15
+ oriented = _open_upright(path)
16
+ has_alpha = "A" in oriented.getbands() or "transparency" in oriented.info
17
+ source = oriented.convert("RGBA" if has_alpha else "RGB")
18
+ profile = source.info.get("icc_profile")
19
+ source.info = {"icc_profile": profile} if _is_rgb_profile(profile) else {}
20
+ return source
21
+
22
+
23
+ def encode_request(image: Image.Image, size: ImageSize) -> bytes:
24
+ """Encode the image as the PNG to send to the model, at the model size."""
25
+ return _png(
26
+ image.resize((size.width, size.height), Image.Resampling.LANCZOS),
27
+ icc_profile=image.info.get("icc_profile"),
28
+ )
29
+
30
+
31
+ def encode_mask(path: Path, source_size: ImageSize, size: ImageSize) -> bytes:
32
+ """Encode a white-keeps, black-removes mask as the model's edit mask.
33
+
34
+ The mask must match the upright source. In the edit mask, kept pixels are
35
+ opaque and pixels the model may edit have alpha 0.
36
+ """
37
+ mask = _open_upright(path).convert("L")
38
+ mask_size = ImageSize(width=mask.width, height=mask.height)
39
+ if mask_size != source_size:
40
+ raise InvalidInputError(
41
+ f"the mask {path} is {mask_size} but the image is {source_size}"
42
+ )
43
+ keep = mask.point(lambda level: 255 if level >= 128 else 0)
44
+ edit_mask = Image.new("RGBA", (size.width, size.height), (255, 255, 255, 255))
45
+ edit_mask.putalpha(keep.resize((size.width, size.height), Image.Resampling.NEAREST))
46
+ return _png(edit_mask)
47
+
48
+
49
+ def decode_cutout(png: bytes, size: ImageSize) -> Image.Image:
50
+ """Decode the PNG the model returned and check it is a usable cutout."""
51
+ try:
52
+ with Image.open(io.BytesIO(png)) as image:
53
+ image.load()
54
+ image_format = image.format
55
+ cutout = image.convert("RGBA")
56
+ except (OSError, ValueError, Image.DecompressionBombError) as error:
57
+ raise EditError(f"the model's image could not be decoded: {error}") from None
58
+ if image_format != "PNG":
59
+ raise EditError(f"the model returned {image_format}, not PNG")
60
+ returned = ImageSize(width=cutout.width, height=cutout.height)
61
+ if returned != size:
62
+ raise EditError(f"the model returned {returned}, not the requested {size}")
63
+ lowest, highest = cutout.getchannel("A").getextrema()
64
+ if lowest == 255:
65
+ raise EditError("the model's image has no transparent pixels")
66
+ if highest == 0:
67
+ raise EditError("the model's image is entirely transparent")
68
+ return cutout
69
+
70
+
71
+ def apply_alpha(source: Image.Image, cutout: Image.Image) -> bytes:
72
+ """Return the source pixels with the cutout's alpha, as a PNG.
73
+
74
+ The cutout's alpha is total opacity, so it never raises the source's own alpha.
75
+ """
76
+ alpha = cutout.getchannel("A").resize(source.size, Image.Resampling.LANCZOS)
77
+ if source.mode == "RGBA":
78
+ alpha = ImageChops.darker(alpha, source.getchannel("A"))
79
+ result = source.convert("RGBA")
80
+ result.putalpha(alpha)
81
+ return _png(result, icc_profile=source.info.get("icc_profile"))
82
+
83
+
84
+ def _open_upright(path: Path) -> Image.Image:
85
+ try:
86
+ with Image.open(path) as image:
87
+ image.load()
88
+ frames = getattr(image, "n_frames", 1)
89
+ upright = ImageOps.exif_transpose(image)
90
+ except (OSError, ValueError, Image.DecompressionBombError) as error:
91
+ raise InvalidInputError(f"{path} cannot be read as an image: {error}") from None
92
+ if frames > 1:
93
+ raise InvalidInputError(f"{path} is animated; use a single-frame image")
94
+ return upright
95
+
96
+
97
+ def _is_rgb_profile(profile: object) -> bool:
98
+ if not isinstance(profile, bytes):
99
+ return False
100
+ try:
101
+ parsed = ImageCms.ImageCmsProfile(io.BytesIO(profile))
102
+ except ImageCms.PyCMSError, OSError:
103
+ return False
104
+ return parsed.profile.xcolor_space == "RGB "
105
+
106
+
107
+ def _png(image: Image.Image, *, icc_profile: bytes | None = None) -> bytes:
108
+ buffer = io.BytesIO()
109
+ image.save(buffer, format="PNG", icc_profile=icc_profile)
110
+ return buffer.getvalue()
@@ -0,0 +1,131 @@
1
+ from typing import Annotated, Literal
2
+
3
+ from pydantic import (
4
+ BaseModel,
5
+ ConfigDict,
6
+ Field,
7
+ PositiveInt,
8
+ StringConstraints,
9
+ model_serializer,
10
+ model_validator,
11
+ )
12
+
13
+ ModelName = Literal[
14
+ "gpt-image-2.5-sunburst-2026-09-08",
15
+ "gpt-image-2.5-sunburst",
16
+ "gpt-image-2.5-flare-2026-09-08",
17
+ "gpt-image-2.5-flare",
18
+ ]
19
+ Quality = Literal["low", "medium", "high", "xhigh", "max", "auto"]
20
+ OutputMode = Literal["original", "generated"]
21
+ Description = Annotated[
22
+ str, StringConstraints(strip_whitespace=True, min_length=1, max_length=10_000)
23
+ ]
24
+
25
+ _FROZEN = ConfigDict(frozen=True, extra="forbid")
26
+ # The API may add usage fields; a new one must not fail a request that was paid for.
27
+ _FROZEN_IGNORING_EXTRA = ConfigDict(frozen=True, extra="ignore")
28
+
29
+
30
+ class ImageSize(BaseModel):
31
+ """Width and height of an image in pixels."""
32
+
33
+ model_config = _FROZEN
34
+
35
+ width: PositiveInt
36
+ height: PositiveInt
37
+
38
+ @model_validator(mode="before")
39
+ @classmethod
40
+ def _parse_width_x_height(cls, value: object) -> object:
41
+ if isinstance(value, str):
42
+ width, _, height = value.partition("x")
43
+ return {"width": width, "height": height}
44
+ return value
45
+
46
+ @model_serializer(mode="plain", when_used="json")
47
+ def _serialise_as_width_x_height(self) -> str:
48
+ return str(self)
49
+
50
+ def __str__(self) -> str:
51
+ return f"{self.width}x{self.height}"
52
+
53
+
54
+ class RemovalOptions(BaseModel):
55
+ """How to remove a background."""
56
+
57
+ model_config = _FROZEN
58
+
59
+ model: ModelName = "gpt-image-2.5-sunburst-2026-09-08"
60
+ quality: Quality = "high"
61
+ mode: OutputMode = "original"
62
+ """``original`` puts the model's alpha on the source pixels at the source size;
63
+ ``generated`` returns the model's own PNG at the model size."""
64
+ keep: Description | None = None
65
+ """What to keep, e.g. "the red backpack, including both straps"."""
66
+ remove: Description | None = None
67
+ """What to remove besides the background, e.g. "the stand and its shadow"."""
68
+
69
+
70
+ class TokenDetails(BaseModel):
71
+ """Image and text token counts."""
72
+
73
+ model_config = _FROZEN_IGNORING_EXTRA
74
+
75
+ image_tokens: int
76
+ text_tokens: int
77
+
78
+
79
+ class Usage(BaseModel):
80
+ """Token usage the API reported for one edit."""
81
+
82
+ model_config = _FROZEN_IGNORING_EXTRA
83
+
84
+ input_tokens: int
85
+ output_tokens: int
86
+ total_tokens: int
87
+ input_tokens_details: TokenDetails | None = None
88
+ output_tokens_details: TokenDetails | None = None
89
+
90
+
91
+ class EditRequest(BaseModel):
92
+ """One image edit to send to the model."""
93
+
94
+ model_config = _FROZEN
95
+
96
+ image: bytes
97
+ mask: bytes | None = None
98
+ prompt: str
99
+ model: ModelName
100
+ quality: Quality
101
+ size: ImageSize
102
+
103
+
104
+ class EditResponse(BaseModel):
105
+ """The image the model returned, with its request metadata."""
106
+
107
+ model_config = _FROZEN
108
+
109
+ image: bytes
110
+ request_id: str | None
111
+ usage: Usage | None
112
+
113
+
114
+ class Cutout(BaseModel):
115
+ """A transparent PNG with the background removed, and how it was made.
116
+
117
+ ``png`` is left out of ``model_dump()`` so the metadata can be logged or
118
+ written as JSON.
119
+ """
120
+
121
+ model_config = _FROZEN
122
+
123
+ png: bytes = Field(exclude=True, repr=False)
124
+ mode: OutputMode
125
+ model: ModelName
126
+ quality: Quality
127
+ source_size: ImageSize
128
+ model_size: ImageSize
129
+ output_size: ImageSize
130
+ request_id: str | None
131
+ usage: Usage | None
File without changes
@@ -0,0 +1,56 @@
1
+ import math
2
+
3
+ from .errors import InvalidInputError
4
+ from .models import ImageSize
5
+
6
+ GRID = 16
7
+ MIN_PIXELS = 655_360
8
+ # Larger outputs, up to 8,294,400 pixels, are experimental; never request them.
9
+ MAX_PIXELS = 3_686_400
10
+ MAX_ASPECT = 3
11
+
12
+
13
+ def model_size_for(source: ImageSize) -> ImageSize:
14
+ """Return the size to request from GPT Image 2.5 for a source image."""
15
+ if not _within_aspect_limit(source):
16
+ raise InvalidInputError(
17
+ f"{source} has an aspect ratio beyond {MAX_ASPECT}:1, "
18
+ "which GPT Image 2.5 cannot produce"
19
+ )
20
+ if is_supported(source):
21
+ return source
22
+ ratio = source.width / source.height
23
+ area = source.width * source.height
24
+ scale = math.sqrt(min(max(area, MIN_PIXELS), MAX_PIXELS) / area)
25
+ candidates = [
26
+ ImageSize(width=width, height=height)
27
+ for width in _nearest_multiples(source.width * scale)
28
+ for height in _nearest_multiples(source.height * scale)
29
+ ]
30
+ supported = [size for size in candidates if is_supported(size)]
31
+ return min(
32
+ supported,
33
+ key=lambda size: (
34
+ abs(math.log(size.width / size.height / ratio)),
35
+ -size.width * size.height,
36
+ ),
37
+ )
38
+
39
+
40
+ def is_supported(size: ImageSize) -> bool:
41
+ """Return whether GPT Image 2.5 can produce an image of this size."""
42
+ return (
43
+ size.width % GRID == 0
44
+ and size.height % GRID == 0
45
+ and MIN_PIXELS <= size.width * size.height <= MAX_PIXELS
46
+ and _within_aspect_limit(size)
47
+ )
48
+
49
+
50
+ def _within_aspect_limit(size: ImageSize) -> bool:
51
+ return max(size.width, size.height) <= MAX_ASPECT * min(size.width, size.height)
52
+
53
+
54
+ def _nearest_multiples(length: float) -> set[int]:
55
+ steps = length / GRID
56
+ return {max(1, math.floor(steps)) * GRID, max(1, math.ceil(steps)) * GRID}
@@ -0,0 +1,293 @@
1
+ Metadata-Version: 2.4
2
+ Name: remove-background-ai
3
+ Version: 0.1.0
4
+ Summary: Remove image backgrounds with OpenAI's GPT Image 2.5 and get a transparent PNG
5
+ Author-email: Nick Powell <hey+remove-background-ai@nickmp.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/nmpowell/remove-background-ai
8
+ Project-URL: Issues, https://github.com/nmpowell/remove-background-ai/issues
9
+ Project-URL: Changelog, https://github.com/nmpowell/remove-background-ai/releases
10
+ Keywords: background-removal,openai,gpt-image,transparent-png,cli
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Multimedia :: Graphics
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.14
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: click<9,>=8.5
22
+ Requires-Dist: openai<4,>=3.19.2
23
+ Requires-Dist: pillow<13,>=12.3
24
+ Requires-Dist: pydantic<3,>=2.13
25
+ Dynamic: license-file
26
+
27
+ # remove-background-ai
28
+
29
+ Remove the background from a photo with OpenAI's GPT Image 2.5 and get a transparent PNG, from the command line or from Python.
30
+
31
+ ```bash
32
+ export OPENAI_API_KEY=sk-...
33
+ uvx remove-background-ai photo.jpg
34
+ ```
35
+
36
+ That writes `photo-no-bg.png` next to `photo.jpg`: your original pixels, at their original size, with the background made transparent.
37
+
38
+ > ⚠️ Much of this is AI-generated, and not formally reviewed by hand or eye. It's published chiefly for myself: for my own reference, use, and for experimentation with the whole open-source publishing process. I also *use* this code: I dogfood it. It works, for me. I also write tests, and run them to check that it works, and does what it says.
39
+
40
+ ## Installation
41
+
42
+ Run it without installing, with [uv](https://docs.astral.sh/uv/):
43
+
44
+ ```bash
45
+ uvx remove-background-ai photo.jpg
46
+ ```
47
+
48
+ Or install it:
49
+
50
+ ```bash
51
+ pip install remove-background-ai
52
+ ```
53
+
54
+ It needs Python 3.14 or later and an OpenAI API key with access to the GPT Image 2.5 models. Set the key in the `OPENAI_API_KEY` environment variable; the command has no option for it. The OpenAI SDK's other variables, such as `OPENAI_BASE_URL`, `OPENAI_ORG_ID` and `OPENAI_PROJECT_ID`, work too.
55
+
56
+ Every image is a paid API call, billed by tokens. See [OpenAI's pricing](https://developers.openai.com/api/docs/pricing). The free tier cannot use GPT Image 2.5. A paid tier can, and OpenAI may ask you to verify your organisation first.
57
+
58
+ ## Usage
59
+
60
+ Remove the background from one image:
61
+
62
+ ```bash
63
+ remove-background-ai photo.jpg
64
+ ```
65
+
66
+ Say what to keep when the photo has more than one candidate subject, and what else to remove:
67
+
68
+ ```bash
69
+ remove-background-ai shelf.jpg --keep "the red backpack, including both straps" \
70
+ --remove "the stand and its shadow on the floor"
71
+ ```
72
+
73
+ Process several images into a directory, and get the results as JSON:
74
+
75
+ ```bash
76
+ remove-background-ai *.jpg --output-dir cutouts --json
77
+ ```
78
+
79
+ Choose where one image goes, or replace an existing output:
80
+
81
+ ```bash
82
+ remove-background-ai photo.jpg -o cutout.png --force
83
+ ```
84
+
85
+ Keep the model's own image instead of your original pixels (see [How it works](#how-it-works)):
86
+
87
+ ```bash
88
+ remove-background-ai photo.jpg --mode generated
89
+ ```
90
+
91
+ Use the faster model at a lower quality:
92
+
93
+ ```bash
94
+ remove-background-ai photo.jpg --model gpt-image-2.5-flare-2026-09-08 --quality medium
95
+ ```
96
+
97
+ The command prints each output path on standard output, one per line, and its progress and errors on standard error. It never overwrites a file unless you pass `--force`, and it checks for an existing output before it spends money on an API call.
98
+
99
+ ## How it works
100
+
101
+ The command sends your image to the [image edit endpoint](https://developers.openai.com/api/reference/python/resources/images/methods/edit) with a prompt that says what to keep and what to remove, and asks for a PNG with a transparent background. There is no dedicated background-removal endpoint: GPT Image 2.5 redraws the image with the background removed.
102
+
103
+ The model redraws the whole image, so it can soften a label, move an edge or change a texture. By default the command keeps only the model's transparency and puts it on your original pixels. You choose between two output modes:
104
+
105
+ | Mode | What you get | Size |
106
+ | --- | --- | --- |
107
+ | `original` (default) | Your pixels, with the model's alpha channel | Your image's size |
108
+ | `generated` | The PNG the model returned, byte for byte | The size sent to the model |
109
+
110
+ In `original` mode the transparency is still the model's work. An edge can land a few pixels off, and a thin band of the old background can survive along the subject's outline: in testing, a strip of brick wall stayed along the top of a backpack. `generated` mode gives cleaner edges, because the model redraws them. Look at the result on a dark and a light backdrop before you rely on it. `generated` mode keeps the provenance metadata (C2PA) that OpenAI embeds in the PNG. `original` mode writes a new file, so that metadata is lost.
111
+
112
+ ### Image sizes
113
+
114
+ GPT Image 2.5 only produces images whose width and height are multiples of 16, with an aspect ratio no wider than 3:1 and an area of 655,360 to 8,294,400 pixels. Anything over 3,686,400 pixels (2560×1440) is experimental. The command sends your image at the nearest size the model can produce, never an experimental one, and scales the returned transparency back to your image's size.
115
+
116
+ | Your image | Sent to the model | Why |
117
+ | --- | --- | --- |
118
+ | 1024×1024 | 1024×1024 | Already a size the model produces |
119
+ | 1920×1080 | 1920×1088 | 1080 is not a multiple of 16 |
120
+ | 512×512 | 816×816 | Below the minimum area |
121
+ | 6000×4000 | 2336×1552 | Above the largest standard area |
122
+ | 3000×900 | refused | Wider than 3:1 |
123
+
124
+ Sending 1920×1080 as 1920×1088 changes the aspect ratio slightly. Scaling the transparency back to 1920×1080 undoes that change, so the cutout does not shift.
125
+
126
+ The command first turns the image upright using its EXIF orientation. It accepts any format Pillow can open (JPEG, PNG, WebP, TIFF and others) in any colour mode, and always writes an 8-bit RGBA PNG. If your image already has transparency, the output never makes it more opaque. An embedded RGB colour profile goes to the model with the image and stays in the `original` output. Other profiles would describe the wrong colours after conversion, so they are dropped. CMYK images are converted to RGB without colour management, so their colours can shift; convert them to RGB yourself first if colour matters. EXIF data is not copied. Animated images are refused.
127
+
128
+ ### Masks
129
+
130
+ If the model keeps the wrong thing, give it a mask: an image the same size as the photo (after EXIF rotation), white where the subject is and black elsewhere.
131
+
132
+ ```bash
133
+ remove-background-ai photo.jpg --mask subject.png
134
+ ```
135
+
136
+ Grey at half intensity or brighter counts as white. The mask guides the model, which can still stray over its edges.
137
+
138
+ ## JSON output
139
+
140
+ `--json` replaces the list of paths with one JSON array. Each image gets an object, in the order given, whether it succeeded or failed:
141
+
142
+ ```json
143
+ [
144
+ {
145
+ "input": "mug.jpg",
146
+ "output": "mug-no-bg.png",
147
+ "mode": "original",
148
+ "model": "gpt-image-2.5-sunburst-2026-09-08",
149
+ "quality": "medium",
150
+ "source_size": "1300x1132",
151
+ "model_size": "1312x1136",
152
+ "output_size": "1300x1132",
153
+ "request_id": "req_e4351b4660894c96ad6f08a86fc013aa",
154
+ "usage": {
155
+ "input_tokens": 1618,
156
+ "output_tokens": 440,
157
+ "total_tokens": 2058,
158
+ "input_tokens_details": {"image_tokens": 1476, "text_tokens": 142},
159
+ "output_tokens_details": {"image_tokens": 440, "text_tokens": 0}
160
+ }
161
+ },
162
+ {
163
+ "input": "broken.png",
164
+ "error": "broken.png cannot be read as an image: cannot identify image file 'broken.png'"
165
+ }
166
+ ]
167
+ ```
168
+
169
+ `usage` is whatever token counts the API reported, or `null`. Errors also go to standard error, so keep the two streams apart when you parse the JSON.
170
+
171
+ ## Exit codes
172
+
173
+ | Code | Meaning |
174
+ | --- | --- |
175
+ | 0 | Every image succeeded |
176
+ | 1 | Interrupted (Ctrl-C), or a broken pipe |
177
+ | 2 | The command line was wrong: an unknown option, a missing file, `-o` or `--mask` with several images, `-o` with `--output-dir`, an output that is also an input or the mask, or two images that would write the same output |
178
+ | 3 | The tool refused an image or an output before or after the API call: it cannot be read, is animated, is wider than 3:1, its mask does not match, or the output exists or cannot be written |
179
+ | 4 | The OpenAI call failed or returned an unusable image, or `OPENAI_API_KEY` is not set |
180
+
181
+ With several images the command carries on after a failure. If any image failed, it exits with 4 when at least one failure was an API failure, and 3 otherwise.
182
+
183
+ ## Timeouts and retries
184
+
185
+ The OpenAI client waits up to 300 seconds on each network operation and retries twice after a rate limit, a server error, a dropped connection or a timeout, pausing between attempts as the server asks. There is no overall deadline, so a slow image can take many minutes. A retried request can be billed more than once, because the server may have finished the first attempt.
186
+
187
+ ## Python library
188
+
189
+ ```python
190
+ from pathlib import Path
191
+
192
+ from remove_background_ai import RemovalOptions, remove_background
193
+
194
+ cutout = remove_background(
195
+ Path("photo.jpg"),
196
+ options=RemovalOptions(keep="the red backpack", quality="medium"),
197
+ )
198
+ Path("photo-no-bg.png").write_bytes(cutout.png)
199
+ print(cutout.model_size, cutout.request_id)
200
+ ```
201
+
202
+ `remove_background` validates its arguments with Pydantic and raises `pydantic.ValidationError` for the wrong types. It takes a `Path` (not a `str`) as its only positional argument; `options`, `mask` and `editor` are keyword-only. `RemovalOptions` takes `model` (default `gpt-image-2.5-sunburst-2026-09-08`), `quality` (`low`, `medium`, `high`, `xhigh`, `max` or `auto`; default `high`), `mode` (`original` or `generated`), `keep` and `remove`.
203
+
204
+ It returns a `Cutout` holding the PNG bytes and their metadata; `cutout.model_dump(mode="json")` gives the metadata shown under [JSON output](#json-output), without the image. It raises `InvalidInputError` when it refuses an image and `EditError` when the API call fails; both are `RemoveBackgroundError`s.
205
+
206
+ To change the timeout or retries, pass your own client:
207
+
208
+ ```python
209
+ from pathlib import Path
210
+
211
+ from openai import OpenAI
212
+
213
+ from remove_background_ai import OpenAIImageEditor, remove_background
214
+
215
+ editor = OpenAIImageEditor(OpenAI(timeout=600, max_retries=0))
216
+ cutout = remove_background(Path("photo.jpg"), editor=editor)
217
+ ```
218
+
219
+ Any object with an `edit(EditRequest) -> EditResponse` method can stand in for `OpenAIImageEditor`, which is how the tests run without the API.
220
+
221
+ ## CLI reference
222
+
223
+ <!-- [[[cog
224
+ import cog
225
+ from click.testing import CliRunner
226
+ from remove_background_ai.cli import cli
227
+
228
+ result = CliRunner().invoke(cli, ["--help"], terminal_width=88)
229
+ assert result.exit_code == 0, result.output
230
+ cog.out("```\n" + result.stdout.replace("Usage: cli", "Usage: remove-background-ai") + "```\n")
231
+ ]]] -->
232
+ ```
233
+ Usage: remove-background-ai [OPTIONS] IMAGES...
234
+
235
+ Send each image to GPT Image 2.5 and write a transparent PNG. By default, the result
236
+ keeps the original pixels and size and takes only transparency from the model. Set
237
+ OPENAI_API_KEY before running this command.
238
+
239
+ Examples:
240
+
241
+ remove-background-ai photo.jpg
242
+ remove-background-ai photo.jpg -o portrait.png
243
+ remove-background-ai photo.jpg other.png -d cutouts --json
244
+ remove-background-ai photo.jpg --keep "the red backpack, including both straps"
245
+
246
+ Options:
247
+ -o, --output FILE Write the PNG to FILE.
248
+ -d, --output-dir DIRECTORY Write PNGs to DIRECTORY.
249
+ --force Replace output files that already exist.
250
+ --keep TEXT What to keep, for example the red backpack and its
251
+ straps.
252
+ --remove TEXT What to remove besides the background.
253
+ --mask FILE Mask FILE: white keeps, black removes; same size as
254
+ the image.
255
+ --mode [original|generated] Keep original pixels and size, or use the generated
256
+ image. [default: original]
257
+ --model [gpt-image-2.5-sunburst-2026-09-08|gpt-image-2.5-sunburst|gpt-image-2.5-flare-2026-09-08|gpt-image-2.5-flare]
258
+ GPT Image model to use. [default: gpt-
259
+ image-2.5-sunburst-2026-09-08]
260
+ --quality [low|medium|high|xhigh|max|auto]
261
+ Image edit quality. [default: high]
262
+ --json Write a JSON array to stdout.
263
+ --version Show the version and exit.
264
+ --help Show this message and exit.
265
+
266
+ Exit codes: 0 success; 1 general failure; 2 usage error; 3 input or output refused; 4
267
+ image edit failed.
268
+ ```
269
+ <!-- [[[end]]] -->
270
+
271
+ ## Development
272
+
273
+ ```bash
274
+ git clone https://github.com/nmpowell/remove-background-ai
275
+ cd remove-background-ai
276
+ uv sync --locked
277
+ uv run pytest
278
+ uv run mypy
279
+ uv run ruff check .
280
+ uv run ruff format --check .
281
+ ```
282
+
283
+ The tests run without the API, except one live test that makes a real call and costs one image. It is skipped unless you ask for it:
284
+
285
+ ```bash
286
+ RUN_LIVE_OPENAI_TESTS=1 OPENAI_API_KEY=sk-... uv run pytest -m live
287
+ ```
288
+
289
+ After changing the command's options, regenerate the CLI reference above with `uv run cog -r README.md`. The test suite fails while the reference is out of date.
290
+
291
+ ## Licence
292
+
293
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,16 @@
1
+ remove_background_ai/__init__.py,sha256=2up7pbtNtWBN0xYuoeKCqJmxFPymqQdj7JEhnXmvfpY,597
2
+ remove_background_ai/__main__.py,sha256=1IHeqkGgystQbr1fprJ0TfMYx33vItpsOkH6xHTiU2E,60
3
+ remove_background_ai/cli.py,sha256=GonlmQi3-R3oeHpRO8ADIDOHo8MIC07t7kVoVgI8eC0,8065
4
+ remove_background_ai/core.py,sha256=ptXpX0C8fko4M7ZdIcZl1OEdllYt7aV47h_-yHz24zs,3012
5
+ remove_background_ai/editor.py,sha256=ihBCJORUES9aHf7GBqbF4u8q112xGnn2JYT8VLxtUG8,3011
6
+ remove_background_ai/errors.py,sha256=WFbQeONppbuI9xzqnwQisc--odAKO8LMFpsy2L6FEls,340
7
+ remove_background_ai/imaging.py,sha256=iGa37Hf9MdOpNnA8qBrpO0zTkVW8vJGqy5QdpQGmLfU,4333
8
+ remove_background_ai/models.py,sha256=kIwX6wcajCSxszNApvZIhuLT_ohJUHsO4_kOssp6UKg,3385
9
+ remove_background_ai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ remove_background_ai/sizing.py,sha256=KE8F_6msLRkkn5PQwN2fnidUQ75lusLZpXprseDoQI0,1812
11
+ remove_background_ai-0.1.0.dist-info/licenses/LICENSE,sha256=w9inRfPBTkhJMIpRdFn2WW8A7yEIT2aCSJmRmwc1HIE,11341
12
+ remove_background_ai-0.1.0.dist-info/METADATA,sha256=zBEfaKuPPlBI54GNSS1Wmdvr9iKq_LogmkP2RNJTu40,13609
13
+ remove_background_ai-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
14
+ remove_background_ai-0.1.0.dist-info/entry_points.txt,sha256=2w5k4LVIHCihS5hz37PU32iR4rg07e0J3cSgFZCrkdI,70
15
+ remove_background_ai-0.1.0.dist-info/top_level.txt,sha256=mOdLZ_mnuKTOFc9DBlk1uCOUj7zELsq6_j4AeHQTwpk,21
16
+ remove_background_ai-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ remove-background-ai = remove_background_ai.cli:cli
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Nick Powell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ remove_background_ai