Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python

name: Python package

on:
push:
branches: ["main"]
pull_request:
branches: ["main"]

jobs:
build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.9", "3.10", "3.11", "3.12"]

steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
- name: Lint with ruff
run: |
# Run Ruff for linting
ruff check .
160 changes: 160 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
19 changes: 6 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,26 @@

Python wrapper for the BEN API that removes backgrounds from images.

## Installation

## Installation
```bash
git clone https://github.com/PramaLLC/ben-api-python-integration
cd ben-api-python-integration
pip install -r requirements.txt
pip install git+https://github.com/PramaLLC/ben-api-python-integration.git
```

## Generate api token
You must have a business subscription that can be found at https://backgrounderase.net/pricing. To generate the token navigate to
https://backgrounderase.net/account and scroll to the bottom of the page.

## Example
create example.py
```python
from prama import predict_image
from PIL import Image
from main import predict_image # import predict image function from repo

image = Image.open("image.jpg") # your image file path or pil image object

image = Image.open("image.jpg")

mask, foregorund = predict_image(image,"your_ben_api_token")

mask, foreground = predict_image(image,"your_ben_api_token")

mask.save("mask.png")
foregorund.save("foreground.png")

foreground.save("foreground.png")
```


Expand Down
38 changes: 12 additions & 26 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,29 @@
import requests
import base64
from PIL import Image,ImageOps
from PIL import Image, ImageOps
import io
import numpy as np

def predict_image(image, api_key, api_url="https://api.backgrounderase.net/v2"):


def predict_image(image, api_key, api_url="https://api.backgrounderase.net/v2"):
image = ImageOps.exif_transpose(image)

buffer = io.BytesIO()
image_resized = image.resize((1024, 1024), Image.BILINEAR)
image_resized.save(buffer, format='JPEG', quality=85, optimize=True)
image_resized.save(buffer, format="JPEG", quality=85, optimize=True)
image_bytes = buffer.getvalue()
image_base64 = base64.b64encode(image_bytes).decode('utf-8')

headers = {
'x-api-key': api_key,
'Content-Type': 'application/json'
}
payload = {
"image": image_base64
}
response = requests.post(
api_url,
headers=headers,
json=payload
)
image_base64 = base64.b64encode(image_bytes).decode("utf-8")

headers = {"x-api-key": api_key, "Content-Type": "application/json"}
payload = {"image": image_base64}
response = requests.post(api_url, headers=headers, json=payload)
if response.status_code == 200:
try:
result = response.json()
mask_bytes = base64.b64decode(result['mask'])
mask_bytes = base64.b64decode(result["mask"])

mask_img = Image.open(io.BytesIO(mask_bytes))

mask_array = np.array(mask_img)

mask = Image.fromarray(mask_array)
Expand All @@ -43,15 +33,11 @@ def predict_image(image, api_key, api_url="https://api.backgrounderase.net/v2"):

image.putalpha(mask)

return mask, image
return mask, image
except Exception as e:
print(f"Error processing response: {e}")
return None
else:
print(f"Error: {response.status_code}")
print("Response:", response.content)
return None




7 changes: 7 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[build-system]
requires = [
"setuptools>=42",
"wheel",
"tqdm"
]
build-backend = "setuptools.build_meta"
32 changes: 32 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import pathlib
from setuptools import find_packages, setup


def get_version() -> str:
rel_path = "src/prama/__init__.py"
with open(rel_path, "r") as fp:
for line in fp.read().splitlines():
if line.startswith("__version__"):
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
raise RuntimeError("Unable to find version string.")


setup(
name="prama",
version=get_version(),
description="client for prama APIs",
long_description=pathlib.Path("README.md").read_text(encoding="utf-8"),
long_description_content_type="text/markdown",
Homepage="https://github.com/PramaLLC/ben-api-python-integration",
url="https://github.com/PramaLLC/ben-api-python-integration",
Issues="https://github.com/PramaLLC/ben-api-python-integration/issues",
authors=[{"name": "Prama", "email": "pramadevelopment@gmail.com"}],
author_email="pramadevelopment@gmail.com",
license="Apache 2.0 License",
package_dir={"": "src"},
packages=find_packages("src"),
include_package_data=True,
classifiers=["Topic :: Utilities", "Programming Language :: Python :: 3.9"],
requires=["setuptools", "wheel", "typing", "pillow", "numpy", "requests", "tqdm"],
)
3 changes: 3 additions & 0 deletions src/prama/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .client import predict_image # noqa: F401

__version__ = "0.1.0" # Update this version as needed
38 changes: 38 additions & 0 deletions src/prama/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import requests
import base64
from PIL import Image, ImageOps
import io


def predict_image(image, api_key, api_url="https://api.backgrounderase.net/v2"):
image = ImageOps.exif_transpose(image)

buffer = io.BytesIO()
image_resized = image.resize((1024, 1024), Image.BILINEAR)
image_resized.save(buffer, format="JPEG", quality=85, optimize=True)
image_bytes = buffer.getvalue()
image_base64 = base64.b64encode(image_bytes).decode("utf-8")

headers = {"x-api-key": api_key, "Content-Type": "application/json"}
payload = {"image": image_base64}
response = requests.post(api_url, headers=headers, json=payload)
if response.status_code == 200:
try:
result = response.json()
mask_bytes = base64.b64decode(result["mask"])

mask = Image.open(io.BytesIO(mask_bytes))

image = image.convert("RGB")
mask = mask.resize(image.size)

image.putalpha(mask)

return mask, image
except Exception as e:
print(f"Error processing response: {e}")
return None
else:
print(f"Error: {response.status_code}")
print("Response:", response.content)
return None