diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml new file mode 100644 index 0000000..95b6b40 --- /dev/null +++ b/.github/workflows/python-package.yml @@ -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 . diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..68bc17f --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/README.md b/README.md index bcbccbb..e0a79f3 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,9 @@ 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 @@ -15,20 +12,16 @@ You must have a business subscription that can be found at https://backgroundera 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") ``` diff --git a/main.py b/main.py index 5498b86..70d63f2 100644 --- a/main.py +++ b/main.py @@ -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) @@ -43,7 +33,7 @@ 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 @@ -51,7 +41,3 @@ def predict_image(image, api_key, api_url="https://api.backgrounderase.net/v2"): print(f"Error: {response.status_code}") print("Response:", response.content) return None - - - - diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..32aa480 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,7 @@ +[build-system] +requires = [ + "setuptools>=42", + "wheel", + "tqdm" +] +build-backend = "setuptools.build_meta" \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..cb8399a --- /dev/null +++ b/setup.py @@ -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"], +) diff --git a/src/prama/__init__.py b/src/prama/__init__.py new file mode 100644 index 0000000..6736fcc --- /dev/null +++ b/src/prama/__init__.py @@ -0,0 +1,3 @@ +from .client import predict_image # noqa: F401 + +__version__ = "0.1.0" # Update this version as needed diff --git a/src/prama/client.py b/src/prama/client.py new file mode 100644 index 0000000..36fd75a --- /dev/null +++ b/src/prama/client.py @@ -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