Repository: imgly/background-removal-js Branch: main Commit: 12f56cc4f2a9 Files: 124 Total size: 268.9 KB Directory structure: gitextract_zf76w0ij/ ├── .gitattributes ├── .github/ │ └── workflows/ │ └── pnpm-pr-check.yml ├── .gitignore ├── .husky/ │ └── pre-commit ├── .npmrc ├── .nvmrc ├── .prettierignore ├── .prettierrc.js ├── LICENSE.md ├── README.md ├── TODOS.md ├── bundle/ │ └── models/ │ ├── isnet │ ├── isnet_fp16 │ └── isnet_quint8 ├── package.json ├── packages/ │ ├── node/ │ │ ├── .resources.mjs │ │ ├── CHANGELOG.md │ │ ├── LICENSE.md │ │ ├── README.md │ │ ├── ThirdPartyLicenses.json │ │ ├── changelog/ │ │ │ ├── 1.2.0/ │ │ │ │ └── 20230811184244-export_type_and_formats.yml │ │ │ ├── 1.2.1/ │ │ │ │ └── 20230811184244-Changelog_item.yml │ │ │ ├── 1.3.0/ │ │ │ │ ├── 20230612112304-progress_return_type.yaml │ │ │ │ ├── 20231512181521-resource_data_chunking.yaml │ │ │ │ └── 20231512193816-upscale_mask_to_original_image.yaml │ │ │ ├── 1.4.0/ │ │ │ │ ├── 20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml │ │ │ │ ├── 20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml │ │ │ │ ├── 20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml │ │ │ │ └── 20242301155647-Typescript_bindings_are_generated_with_tsc.yaml │ │ │ ├── 1.4.5/ │ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml │ │ │ ├── Unreleased/ │ │ │ │ └── .keep │ │ │ └── info.yml │ │ ├── package.json │ │ ├── scripts/ │ │ │ ├── build.mjs │ │ │ └── watch.mjs │ │ ├── src/ │ │ │ ├── codecs.ts │ │ │ ├── index.ts │ │ │ ├── inference.ts │ │ │ ├── onnx.ts │ │ │ ├── resource.ts │ │ │ ├── schema.ts │ │ │ ├── url.ts │ │ │ └── utils.ts │ │ └── tsconfig.json │ ├── node-e2e/ │ │ ├── fixtures/ │ │ │ └── images/ │ │ │ └── img2img.sh │ │ ├── package.json │ │ └── src/ │ │ └── example.test.js │ ├── node-examples/ │ │ ├── package.json │ │ └── src/ │ │ └── example_001.cjs │ ├── web/ │ │ ├── CHANGELOG.md │ │ ├── LICENSE.md │ │ ├── README.md │ │ ├── ThirdPartyLicenses.json │ │ ├── changelog/ │ │ │ ├── 1.2.0/ │ │ │ │ └── 20230811184244-export_type_and_formats.yml │ │ │ ├── 1.2.1/ │ │ │ │ └── 20230811184244-Changelog_item.yml │ │ │ ├── 1.3.0/ │ │ │ │ ├── 20230612112148-progress_return_type.yaml │ │ │ │ ├── 20231512181521-resource_data_chunking.yaml │ │ │ │ └── 20231512193816-upscale_mask_to_original_image.yaml │ │ │ ├── 1.4.0/ │ │ │ │ ├── 20233012103509-Moved.yaml │ │ │ │ ├── 20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml │ │ │ │ ├── 20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml │ │ │ │ ├── 20241601144157-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml │ │ │ │ ├── 20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml │ │ │ │ ├── 20241601175908-Fallback_to_Canvas_if_OffscreenCanvas_is_not_available.yaml │ │ │ │ └── 20242301155639-Typescript_bindings_are_generated_with_tsc.yaml │ │ │ ├── 1.4.5/ │ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml │ │ │ ├── 1.5.0/ │ │ │ │ ├── 20242403201534-Added_option_to_execute_on_gpu_webgpu_and_cpu_Added.yaml │ │ │ │ └── 20242503170808-Added_isnet_model_for_webgpu_Added.yaml │ │ │ ├── 1.5.6/ │ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml │ │ │ ├── Unreleased/ │ │ │ │ └── .keep │ │ │ └── info.yml │ │ ├── package.json │ │ ├── scripts/ │ │ │ ├── build.mjs │ │ │ └── watch.mjs │ │ ├── src/ │ │ │ ├── MimeType.ts │ │ │ ├── api/ │ │ │ │ └── v1.ts │ │ │ ├── capabilities.js │ │ │ ├── codecs.ts │ │ │ ├── index.ts │ │ │ ├── inference.ts │ │ │ ├── onnx.ts │ │ │ ├── resource.ts │ │ │ ├── schema.ts │ │ │ ├── types.d.ts │ │ │ ├── url.ts │ │ │ └── utils.ts │ │ └── tsconfig.json │ ├── web-data/ │ │ ├── .resources.mjs │ │ ├── LICENSE.md │ │ ├── ThirdPartyLicenses.json │ │ ├── changelog/ │ │ │ ├── 1.4.5/ │ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml │ │ │ └── 1.5.6/ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml │ │ └── package.json │ └── web-examples/ │ ├── next-example/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── eslint.config.mjs │ │ ├── next.config.ts │ │ ├── package.json │ │ ├── src/ │ │ │ └── app/ │ │ │ ├── BackgroundRemoval.tsx │ │ │ ├── BackgroundRemovalNoSSR.tsx │ │ │ ├── globals.css │ │ │ ├── layout.tsx │ │ │ └── page.tsx │ │ └── tsconfig.json │ └── vite-project/ │ ├── .gitignore │ ├── .vercel/ │ │ ├── README.txt │ │ └── project.json │ ├── README.md │ ├── index.html │ ├── package.json │ ├── src/ │ │ ├── App.vue │ │ ├── main.ts │ │ ├── style.css │ │ └── vite-env.d.ts │ ├── tsconfig.json │ ├── tsconfig.node.json │ └── vite.config.ts ├── pnpm-workspace.yaml └── scripts/ ├── changelog/ │ ├── changelog-create.mjs │ ├── changelog-generate.mjs │ └── template.yml.ejs ├── deploy-assets.mjs ├── package-resources.mjs └── package-version.mjs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ bundle/**/* filter=lfs diff=lfs merge=binary **/*.onnx filter=lfs diff=lfs merge=binary **/*.ort filter=lfs diff=lfs merge=binary **/*.{jpeg,jpg} filter=lfs diff=lfs merge=binary **/*.png filter=lfs diff=lfs merge=binary **/*.webp filter=lfs diff=lfs merge=binary **/*.avif filter=lfs diff=lfs merge=binary **/*.heic filter=lfs diff=lfs merge=binary **/*.heif filter=lfs diff=lfs merge=binary **/*.pdf filter=lfs diff=lfs merge=binary **/*.psd filter=lfs diff=lfs merge=binary **/*.mp4 filter=lfs diff=lfs merge=binary **/*.mov filter=lfs diff=lfs merge=binary **/*.m4v filter=lfs diff=lfs merge=binary **/*.mp3 filter=lfs diff=lfs merge=binary **/*.wav filter=lfs diff=lfs merge=binary **/*.aif filter=lfs diff=lfs merge=binary **/*.aiff filter=lfs diff=lfs merge=binary ================================================ FILE: .github/workflows/pnpm-pr-check.yml ================================================ name: Build and test pnpm workspace on: push: branches: [main] pull_request: branches: [main] jobs: build-and-test: name: Build and test uses: imgly/github-workflows/.github/workflows/pnpm-pr-check.yml@v1 secrets: inherit ================================================ FILE: .gitignore ================================================ node_modules releases dist tmp .DS_Store .vscode .parcel-cache .env ================================================ FILE: .husky/pre-commit ================================================ ================================================ FILE: .npmrc ================================================ ; Allow transitive dependency type access shamefully-hoist = true ; Hard error on unsatisfied peer dependency requirements strict-peer-dependencies = true ; Prevent accidents when running actions with outdated node_modules verify-deps-before-run = error ; Fix sync-dependencies-meta-injected crashing due to some dependencies not respecting the injected flag as an optimization dedupe-injected-deps = false ================================================ FILE: .nvmrc ================================================ v20.17.0 ================================================ FILE: .prettierignore ================================================ **/node_modules **/dist **/tmp build **/package-lock.json .vscode/ **/public/** CHANGELOG.md ================================================ FILE: .prettierrc.js ================================================ module.exports = { singleQuote: true, arrowParens: 'always', trailingComma: 'none' }; ================================================ FILE: LICENSE.md ================================================ # GNU Affero General Public License _Version 3, 19 November 2007_ _Copyright © 2007 Free Software Foundation, Inc. <>_ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. ## Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: **(1)** assert copyright on the software, and **(2)** offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. ## TERMS AND CONDITIONS ### 0. Definitions “This License” refers to version 3 of the GNU Affero General Public License. “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. A “covered work” means either the unmodified Program or a work based on the Program. To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that **(1)** displays an appropriate copyright notice, and **(2)** tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. ### 1. Source Code The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The “System Libraries” of an executable work include anything, other than the work as a whole, that **(a)** is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and **(b)** serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. ### 2. Basic Permissions All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. ### 4. Conveying Verbatim Copies You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. ### 5. Conveying Modified Source Versions You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: - **a)** The work must carry prominent notices stating that you modified it, and giving a relevant date. - **b)** The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. - **c)** You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. - **d)** If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. ### 6. Conveying Non-Source Forms You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - **a)** Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. - **b)** Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either **(1)** a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or **(2)** access to copy the Corresponding Source from a network server at no charge. - **c)** Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. - **d)** Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. - **e)** Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A “User Product” is either **(1)** a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or **(2)** anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. ### 7. Additional Terms “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - **a)** Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or - **b)** Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or - **c)** Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or - **d)** Limiting the use for publicity purposes of names of licensors or authors of the material; or - **e)** Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or - **f)** Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. ### 8. Termination You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated **(a)** provisionally, unless and until the copyright holder explicitly and finally terminates your license, and **(b)** permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. ### 9. Acceptance Not Required for Having Copies You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. ### 10. Automatic Licensing of Downstream Recipients Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. ### 11. Patents A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either **(1)** cause the Corresponding Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the patent license for this particular work, or **(3)** arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license **(a)** in connection with copies of the covered work conveyed by you (or copies made from those copies), or **(b)** primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. ### 12. No Surrender of Others' Freedom If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. ### 13. Remote Network Interaction; Use with the GNU General Public License Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. ### 14. Revised Versions of this License The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. ### 15. Disclaimer of Warranty THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. ### 16. Limitation of Liability IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. ### 17. Interpretation of Sections 15 and 16 If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. _END OF TERMS AND CONDITIONS_ ## How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a “Source” link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <>. ================================================ FILE: README.md ================================================ # Background Removal in the Browser & Node.js ### 🚨 We are hiring 🚨 We are always looking for great people at IMG.LY. If you are working with our background removal library you might be a perfect fit! **Apply now at [IMG.LY Careers](https://img.ly/company/careers/?utm_source=github&utm_medium=readme&utm_campaign=background-removal-js)**

background removal js showcase

Remove backgrounds from images directly in the browser or Node.js environment with ease and no additional costs or privacy concerns. Explore an [interactive demo](https://img.ly/showcases/cesdk/web/background-removal/web?utm_source=github&utm_medium=project&utm_campaign=background-removal-js). ## Overview `@imgly/background-removal` is a powerful npm package that allows developers to seamlessly remove the background from images directly in the browser. `@imgly/background-removal-node` is a powerful npm package that allows developers to remove the background from images in Node.js. With its unique features and capabilities, this package offers an innovative and cost-effective solution for background removal tasks without compromising data privacy. ## Who is it for? `@imgly/background-removal` is ideal for developers and projects that require efficient and cost-effective background removal directly in the browser or Node.js. It caters to a wide range of use cases, including but not limited to: - _E-commerce applications_ that need to remove backgrounds from product images in real time. - _Image editing applications_ that require background removal capabilities for enhancing user experience. - _Web-based graphic design tools_ that aim to simplify the creative process with in-browser background removal. Whether you are a professional developer or a hobbyist, `@imgly/background-removal` empowers you to deliver impressive applications and services with ease. ## License The software is free for use under the AGPL License. Please contact [support@img.ly](mailto:support@img.ly?subject=Background-Removal%20License) for questions about other licensing options. ## Authors & Contributors This library is made by IMG.LY shipping the world's premier SDKs for building creative applications. Start your trial of the [CreativeEditor SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), [PhotoEditor SDK](https://img.ly/products/photo-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js) & [VideoEditor SDK](https://img.ly/products/video-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js). ================================================ FILE: TODOS.md ================================================ # Todos ## Todo 2.0 - [ ] use logger/telemetry callback instead of custom debug output - [ ] use resolver callback instead of publicPath as such we can allow various ``` resolve: (path: string) => Response ``` - [ ] default to `gpu` - [ ] remove image encode and decode - [ ] removebg should get `ImageData` and return raw `ImageData` ================================================ FILE: bundle/models/isnet ================================================ version https://git-lfs.github.com/spec/v1 oid sha256:cc2c9f5c1751b9737cb81e708ff0c5e9542c2205daed22418a4fd2ab5d4c481a size 176149806 ================================================ FILE: bundle/models/isnet_fp16 ================================================ version https://git-lfs.github.com/spec/v1 oid sha256:2eb4b5dda7ec41c617e59706e5aafa1f978c9a5f983d2518d9f0ae4d6eb04f20 size 88152708 ================================================ FILE: bundle/models/isnet_quint8 ================================================ version https://git-lfs.github.com/spec/v1 oid sha256:d1ca3535c21b53d08fa3b640e5949389f82e764f6376a0502d44982c35cae482 size 44348940 ================================================ FILE: package.json ================================================ { "version": "1.7.0", "name": "workspace", "private": true, "bin": { "changelog-create": "./scripts/changelog/changelog-create.mjs", "changelog-generate": "./scripts/changelog/changelog-generate.mjs" }, "files": [], "scripts": { "start": "pnpm run watch", "watch": "concurrently \"pnpm run watch --prefix packages/web\" \"pnpm run watch --prefix packages/node\"", "build": "pnpm recursive run build", "lint:fix": "npx prettier -c -w --ignore-unknown .", "lint:check": "npx prettier -c --ignore-unknown .", "publish:latest": "pnpm run publish:latest --workspaces --if-present && pnpm run deploy-assets", "publish:next": "pnpm run publish:next --workspaces --if-present && pnpm run deploy-assets", "package:version": "node ./scripts/package-version.mjs", "deploy-assets": "node -r dotenv/config ./scripts/deploy-assets.mjs", "tag": "git tag $npm_package_version & git push origin $npm_package_version", "package:pack": "pnpm run package:pack --workspaces --if-present", "prepare": "husky" }, "devDependencies": { "chalk": "~5.3.0", "concurrently": "~8.2.2", "dotenv": "~16.3.1", "ejs": "~3.1.9", "es-main": "~1.3.0", "esbuild": "^0.21.1", "glob": "~10.3.3", "husky": "^9.0.11", "lint-staged": "^15.2.2", "meow": "~13.0.0", "moment": "~2.29.4", "onchange": "~7.1.0", "prettier": "^3.5.3", "rimraf": "^6.0.1", "yaml": "~2.3.4" }, "packageManager": "pnpm@10.6.5+sha512.cdf928fca20832cd59ec53826492b7dc25dc524d4370b6b4adbf65803d32efaa6c1c88147c0ae4e8d579a6c9eec715757b50d4fa35eea179d868eada4ed043af" } ================================================ FILE: packages/node/.resources.mjs ================================================ export default [ { path: '/models/', source: '../../bundle/models/*', mime: 'application/octet-steam' } ]; ================================================ FILE: packages/node/CHANGELOG.md ================================================ # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.4.5] ### Added - Added ThirdPartyLicenses.json ## [1.4.0] ### Added - Bumped onnx runtime to 1.17 Changed - Changed license from GPL to AGPL Changed - Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets. ### Changed - Typescript bindings are generated with tsc ## [1.3.0] ### Added - Resources are now chunked to 4MB for better caching performance and download restart. - Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only. - Config option to export 'x-alpha8' format to get receive single channel alpha mask. ### Removed - Configuration options to specify if background, foreground or mask is exported. ### Changed - Changed the return value type of the progress callback from undefined to void - Output is now in the original image size. Mask is upscaled and applied to the original image. ## [1.2.1] ### Added - `CHANGELOG.md` for an better overview of the changes. - support for raw `rgba8` export formats. ## [1.2.0] ### Added - Support `foreground`, `background` and `mask` export type. - Added support for `webp` and `jpeg` export formats. ================================================ FILE: packages/node/LICENSE.md ================================================ # GNU Affero General Public License _Version 3, 19 November 2007_ _Copyright © 2007 Free Software Foundation, Inc. <>_ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. ## Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: **(1)** assert copyright on the software, and **(2)** offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. ## TERMS AND CONDITIONS ### 0. Definitions “This License” refers to version 3 of the GNU Affero General Public License. “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. A “covered work” means either the unmodified Program or a work based on the Program. To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that **(1)** displays an appropriate copyright notice, and **(2)** tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. ### 1. Source Code The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The “System Libraries” of an executable work include anything, other than the work as a whole, that **(a)** is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and **(b)** serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. ### 2. Basic Permissions All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. ### 4. Conveying Verbatim Copies You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. ### 5. Conveying Modified Source Versions You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: - **a)** The work must carry prominent notices stating that you modified it, and giving a relevant date. - **b)** The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. - **c)** You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. - **d)** If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. ### 6. Conveying Non-Source Forms You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - **a)** Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. - **b)** Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either **(1)** a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or **(2)** access to copy the Corresponding Source from a network server at no charge. - **c)** Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. - **d)** Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. - **e)** Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A “User Product” is either **(1)** a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or **(2)** anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. ### 7. Additional Terms “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - **a)** Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or - **b)** Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or - **c)** Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or - **d)** Limiting the use for publicity purposes of names of licensors or authors of the material; or - **e)** Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or - **f)** Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. ### 8. Termination You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated **(a)** provisionally, unless and until the copyright holder explicitly and finally terminates your license, and **(b)** permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. ### 9. Acceptance Not Required for Having Copies You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. ### 10. Automatic Licensing of Downstream Recipients Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. ### 11. Patents A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either **(1)** cause the Corresponding Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the patent license for this particular work, or **(3)** arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license **(a)** in connection with copies of the covered work conveyed by you (or copies made from those copies), or **(b)** primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. ### 12. No Surrender of Others' Freedom If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. ### 13. Remote Network Interaction; Use with the GNU General Public License Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. ### 14. Revised Versions of this License The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. ### 15. Disclaimer of Warranty THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. ### 16. Limitation of Liability IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. ### 17. Interpretation of Sections 15 and 16 If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. _END OF TERMS AND CONDITIONS_ ## How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a “Source” link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <>. ================================================ FILE: packages/node/README.md ================================================ # Background Removal in NodeJs ### 🚨 We are hiring 🚨 We are always looking for great people at IMG.LY. If you are working with our background removal library you might be a perfect fit! **Apply now at [IMG.LY Careers](https://img.ly/company/careers/?utm_source=github&utm_medium=readme&utm_campaign=background-removal-js)**

background removal js showcase

Remove backgrounds from images in NodeJs environment with ease and no additional costs or privacy concerns. Explore an [interactive demo](https://img.ly/showcases/cesdk/web/background-removal/web?utm_source=github&utm_medium=project&utm_campaign=background-removal-js). ## News - **`July 18th, 2025`:** Updated to use stable ONNX runtime version 1.21.0 instead of dev version. - **`November 8th, 2023`:** Added support for raw `rgba8` export formats. - **`November 6th, 2023`:** Added support `foreground`, `background` and `mask` export type - **`November 6th, 2023`:** Added support for `webp` and `jpeg` export formats. - **`September 12th, 2023`:** We released the code of Background Removal NodeJS. For more detail information please refer to the [CHANGELOG](./CHANGELOG.md). ## Overview `@imgly/background-removal-node` is a powerful npm package that allows developers to seamlessly remove the background from images in NodeJs. With its unique features and capabilities, this package offers an innovative and cost-effective solution for background removal tasks without compromising data privacy. The key features of `@imgly/background-removal-node` are: - **Seamless Integration with IMG.LY's CE.SDK**: `@imgly/background-removal-node` provides seamless integration with [IMG.LY's CE.SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), allowing developers to easily incorporate powerful NodeJS image matting and background removal capabilities into their projects. The Neural Network model files ([ONNX model](https://onnx.ai/)) are hosted by [IMG.LY](https://img.ly/), making it readily available for download to all users of the library. See the section Custom Asset Serving if you want to host data on your own servers. ## Installation You can install `@imgly/background-removal-node` via npm or yarn. Use the following commands to install the package: ### NPM ```shell npm install @imgly/background-removal-node ``` ## Usage ```typescript import {removeBackground} from "@imgly/background-removal-node"; // const {removeBackground} = require("@imgly/background-removal-node"); let image_src: ImageData | ArrayBuffer | Uint8Array | Blob | URL | string = ...; removeBackground(image_src).then((blob: Blob) => { // The result is a blob encoded as PNG. It can be converted to an URL to be used as HTMLImage.src }) ``` Note: On the first run the wasm and onnx model files are fetched. This might, depending on the bandwidth, take time. Therefore, the first run takes proportionally longer than each consecutive run. Also, all files are cached by the browser and an additional model cache. ## Advanced Configuration The library does not need any configuration to get started. However, there are optional parameters that influence the behaviour and give more control over the library. ```typescript type Config = { publicPath: string; // The public path used for model and wasm files. Default: '`file://${path.resolve(`node_modules/${pkg.name}/dist/`)}/`. debug: bool; // enable or disable useful console.log outputs model: 'small' | 'medium'; // The model to use. (Default "medium") output: { format: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/x-rgba8'; // The output format. (Default "image/png") quality: number; // The quality. (Default: 0.8) type: 'foreground' | 'background' | 'mask'; // The output type. (Default "foreground") }; }; ``` ### Download Size vs Quality The onnx model is shipped in various sizes and needs. - small (~40 MB) is the smallest model and is in most cases working fine but sometimes shows some artifacts. It's a quantized model. - medium (~80MB) is the default model. ### Download Progress Monitoring On the first run, the necessary data will be fetched and stored in the browser cache. Since the download might take some time, you have the option to tap into the download progress. ```typescript let config: Config = { progress: (key, current, total) => { console.log(`Downloading ${key}: ${current} of ${total}`); } }; ``` ### Custom Asset Serving The wasm and onnx neural networks are hosted by IMG.LY by default. For production use, we advise you to host them yourself. Therefore, copy all .wasm and .onnx files to your public path `$PUBLIC_PATH` and reconfigure the library. ```shell cp node_modules/@imgly/background-removal-node/dist/*.* $PUBLIC_PATH ``` ```typescript import { removeBackground, Config} from "@imgly/background-removal-node" const public_path = "file://${ASSET_PATH}" ; // the path on the local file system //const public_path = "https://example.com/assets/" ; // the path assets are served from let config: Config = { publicPath: public_path, // path to the wasm files }; let image_src: Buffer | ArrayBuffer | Uint8Array | Blob | URL | string = ...; removeBackground(image_src, config).then((blob: Blob) => { // result is a blob encoded as PNG. // It can be converted to an URL to be used as HTMLImage.src const url = URL.createObjectURL(blob); }) ``` ### Debug Outputs Enable debug outputs and logging to the console ```typescript let config: Config = { debug: true }; ``` ### Cross-Origin Resource Sharing (CORS) If you are running into CORS issues you might want to pass additional parameters to the fetch function via ```typescript let config: Config = { fetchArgs: { mode: 'no-cors' } }; ``` `fetchArgs` are passed as second parameters to the fetch function as described in [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). ## Who is it for? `@imgly/background-removal-node` is ideal for developers and projects that require efficient and cost-effective background removal directly in the browser. It caters to a wide range of use cases, including but not limited to: - _E-commerce applications_ that need to remove backgrounds from product images in real time. - _Image editing applications_ that require background removal capabilities for enhancing user experience. - _Web-based graphic design tools_ that aim to simplify the creative process with in-browser background removal. Whether you are a professional developer or a hobbyist, `@imgly/background-removal-node` empowers you to deliver impressive applications and services with ease. ## License The software is free for use under the AGPL License. Please contact [support@img.ly](mailto:support@img.ly?subject=Background-Removal-Node%20License) for questions about other licensing options. ## Authors & Contributors This library is made by IMG.LY shipping the world's premier SDKs for building creative applications. Start your trial of the [CreativeEditor SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js-node), [PhotoEditor SDK](https://img.ly/products/photo-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js-node) & [VideoEditor SDK](https://img.ly/products/video-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js-node). ================================================ FILE: packages/node/ThirdPartyLicenses.json ================================================ { "onnxruntime-web": { "source": "https://www.npmjs.com/package/onnxruntime-node", "type": "code", "license": "MIT" }, "ISNET": { "source": "https://github.com/xuebinqin/DIS", "type": "model", "license": "MIT" } } ================================================ FILE: packages/node/changelog/1.2.0/20230811184244-export_type_and_formats.yml ================================================ --- type: Added description: Support `foreground`, `background` and `mask` export type. --- type: Added description: Added support for `webp` and `jpeg` export formats. ================================================ FILE: packages/node/changelog/1.2.1/20230811184244-Changelog_item.yml ================================================ --- type: Added description: | `CHANGELOG.md` for an better overview of the changes. --- type: Added description: | support for raw `rgba8` export formats. ================================================ FILE: packages/node/changelog/1.3.0/20230612112304-progress_return_type.yaml ================================================ --- type: Changed # type: Changed # type: Removed # type: Security # private: true description: | Changed the return value type of the progress callback from undefined to void ================================================ FILE: packages/node/changelog/1.3.0/20231512181521-resource_data_chunking.yaml ================================================ --- type: Added # type: Changed # type: Removed # type: Security # private: true description: | Resources are now chunked to 4MB for better caching performance and download restart. ================================================ FILE: packages/node/changelog/1.3.0/20231512193816-upscale_mask_to_original_image.yaml ================================================ --- type: Changed # type: Removed # type: Security # private: true description: | Output is now in the original image size. Mask is upscaled and applied to the original image. --- type: Added # type: Removed # type: Security # private: true description: | Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only. --- type: Removed # type: Removed # type: Security # private: true description: | Configuration options to specify if background, foreground or mask is exported. --- type: Added # type: Removed # type: Security # private: true description: | Config option to export 'x-alpha8' format to get receive single channel alpha mask. ================================================ FILE: packages/node/changelog/1.4.0/20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Bumped onnx runtime to 1.17 Changed ================================================ FILE: packages/node/changelog/1.4.0/20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Changed license from GPL to AGPL Changed ================================================ FILE: packages/node/changelog/1.4.0/20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets. ================================================ FILE: packages/node/changelog/1.4.0/20242301155647-Typescript_bindings_are_generated_with_tsc.yaml ================================================ --- type: Changed # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Typescript bindings are generated with tsc ================================================ FILE: packages/node/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Added ThirdPartyLicenses.json ================================================ FILE: packages/node/changelog/Unreleased/.keep ================================================ ================================================ FILE: packages/node/changelog/info.yml ================================================ --- description: | All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ================================================ FILE: packages/node/package.json ================================================ { "name": "@imgly/background-removal-node", "version": "1.7.0", "description": "Background Removal in NodeJS", "resources": "@imgly/background-removal-node", "keywords": [ "background-removal", "nodejs", "image-segmentation", "image-matting", "onnx" ], "repository": { "type": "git", "url": "git+https://github.com/imgly/background-removal-js.git" }, "license": "SEE LICENSE IN LICENSE.md", "author": { "name": "IMG.LY GmbH", "email": "support@img.ly", "url": "https://img.ly" }, "bugs": { "email": "support@img.ly" }, "homepage": "https://img.ly/showcases/cesdk/web/background-removal", "source": "./src/index.ts", "main": "./dist/index.cjs", "module": "./dist/index.mjs", "types": "./dist/index.d.ts", "exports": { ".": { "require": "./dist/index.cjs", "import": "./dist/index.mjs", "types": "./dist/index.d.ts" } }, "files": [ "LICENSE.md", "README.md", "CHANGELOG.md", "ThirdPartyLicenses.json", "dist/", "bin/" ], "scripts": { "start": "pnpm run watch", "clean": "npx rimraf dist", "test": "true", "resources": "node ../../scripts/package-resources.mjs", "changelog:create": "node ../../scripts/changelog/changelog-create.mjs", "changelog:generate": "node ../../scripts/changelog/changelog-generate.mjs", "build": "pnpm run clean && pnpm run resources && pnpm run types && pnpm run changelog:generate && node scripts/build.mjs", "types": "tsc --declaration --emitDeclarationOnly --declarationDir dist --declarationMap", "watch": "pnpm run clean && pnpm run resources && pnpm run changelog:generate && node scripts/watch.mjs", "check:all": "pnpm run check:pretty", "check:pretty": "prettier --list-different './src/**/*.{ts,tsx}'", "pretty": "prettier --write './src/**/*.{ts,tsx}'", "publish:latest": "pnpm publish --tag latest --access public", "publish:next": "pnpm publish --tag next --access public", "package:pack": "pnpm pack . --pack-destination ../../releases" }, "dependencies": { "@types/lodash": "~4.14.195", "@types/ndarray": "~1.0.14", "@types/node": "~20.3.1", "lodash": "~4.17.21", "ndarray": "~1.0.19", "onnxruntime-node": "1.21.0", "sharp": "~0.32.4", "zod": "^3.23.8" }, "devDependencies": { "assert": "~2.0.0", "esbuild": "~0.18.18", "npm-dts": "~1.3.12", "os-browserify": "~0.3.0", "path-browserify": "~1.0.1", "process": "~0.11.10", "stream-browserify": "~3.0.0", "ts-loader": "~9.4.3", "tslib": "~2.5.3", "typescript": "~5.1.6", "util": "~0.12.5", "webpack": "~5.85.1", "webpack-cli": "~5.1.4" } } ================================================ FILE: packages/node/scripts/build.mjs ================================================ export { configs }; import * as esbuild from 'esbuild'; import { readFileSync } from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const pkg = JSON.parse( readFileSync(path.resolve(__dirname, '../package.json')) ); const dependencies = Object.keys(pkg.dependencies); const configs = [ { entryPoints: ['src/index.ts'], bundle: true, sourcemap: true, platform: 'node', format: 'cjs', external: dependencies, outfile: 'dist/index.cjs' }, { entryPoints: ['src/index.ts'], bundle: true, sourcemap: true, external: dependencies, platform: 'node', format: 'esm', outfile: 'dist/index.mjs' } ]; await configs.map(async (config) => await esbuild.build(config)); ================================================ FILE: packages/node/scripts/watch.mjs ================================================ import * as esbuild from 'esbuild'; import { configs } from './build.mjs'; import dts from 'npm-dts'; new dts.Generator({ entry: 'src/index.ts', output: 'dist/index.d.ts' }).generate(); const contexts = await Promise.all( configs.map((config) => esbuild.context(config)) ); await Promise.any(contexts.map((ctx) => ctx.watch())); console.log('watching...'); ================================================ FILE: packages/node/src/codecs.ts ================================================ export { imageEncode, imageDecode, MimeType }; import sharp, { FormatEnum } from 'sharp'; import ndarray, { NdArray } from 'ndarray'; async function imageDecode(blob: Blob): Promise> { const buffer = await blob.arrayBuffer(); const mime = MimeType.fromString(blob.type); switch (mime.type) { case 'image/x-alpha8': { const width = parseInt(mime.params['width']); const height = parseInt(mime.params['height']); return ndarray(new Uint8Array(await blob.arrayBuffer()), [ height, width, 1 ]); } case 'image/x-rgba8': { const width = parseInt(mime.params['width']); const height = parseInt(mime.params['height']); return ndarray(new Uint8Array(await blob.arrayBuffer()), [ height, width, 4 ]); } case 'application/octet-stream': case `image/png`: case `image/jpeg`: case `image/jpg`: case `image/webp`: { const decoded = sharp(buffer); let { width, height, channels } = await decoded.metadata(); if (channels === 3) { decoded.ensureAlpha(); channels = 4; } const outBuffer = await decoded.raw().toBuffer(); const array = ndarray(outBuffer, [height!, width!, channels!]); await sharp(array.data, { raw: { width: width!, height: height!, channels: channels! } }); return array; } default: throw new Error(`Unsupported format: ${mime.type}`); } } async function imageEncode( imageTensor: NdArray, quality: number = 0.8, type: string = 'image/png' ): Promise { const [height, width, channels] = imageTensor.shape; if (channels !== 4) throw new Error('Only 4-channel images are supported'); const image = sharp(imageTensor.data, { raw: { height, width, channels } }); type Keys = keyof FormatEnum; switch (type) { case 'image/x-alpha8': case 'image/x-rgba8': { const mime = MimeType.create(type, { width: width.toString(), height: height.toString() }); return new Blob([imageTensor.data], { type: mime.toString() }); } case `image/png`: case `image/jpeg`: case `image/webp`: const format = type.split('/').pop()! as Keys; const buffer = await image .toFormat(format, { quality: quality * 100 }) .toBuffer(); return new Blob([buffer], { type: type }); default: throw new Error(`Invalid format: ${format}`); } } class MimeType { type: string = 'application/octet-stream'; params: Record = {}; private constructor(type: string, params: Record) { this.type = type; this.params = params; } toString(): string { const paramsStr = []; for (const key in this.params) { const value = this.params[key]; paramsStr.push(`${key}=${value}`); } return [this.type, ...paramsStr].join(';'); } static create(type, params: Record): MimeType { return new MimeType(type, params); } isIdentical(other: MimeType): Boolean { return this.type === other.type && this.params === other.params; } isEqual(other: MimeType): Boolean { return this.type === other.type; } static fromString(mimeType: string): MimeType { const [type, ...paramsArr] = mimeType.split(';'); const params: Record = {}; for (const param of paramsArr) { const [key, value] = param.split('='); params[key.trim()] = value.trim(); } return new MimeType(type, params); } } ================================================ FILE: packages/node/src/index.ts ================================================ export default removeBackground; export { removeBackground, removeForeground, segmentForeground, applySegmentationMask }; export type { Config, ImageSource }; import lodash from 'lodash'; import ndarray from 'ndarray'; import { initInference, runInference } from './inference'; import { Config, validateConfig } from './schema'; import * as utils from './utils'; import { ImageSource } from './utils'; const { memoize } = lodash; const init = memoize(initInference, (config) => JSON.stringify(config)); /** * Removes the background from an image. * * @param image - The image to remove the background from. * @param configuration - Optional configuration for the background removal process. * @returns A Promise that resolves to the resulting image with the background removed. */ async function removeBackground( image: ImageSource, configuration?: Config ): Promise { const { config, session } = await init(configuration); const imageTensor = await utils.imageSourceToImageData(image, config); const [width, height, channels] = imageTensor.shape; const alphamask = await runInference(imageTensor, config, session); const stride = width * height; const outImageTensor = imageTensor; for (let i = 0; i < stride; i += 1) { outImageTensor.data[4 * i + 3] = alphamask.data[i]; } const outImage = await utils.imageEncode( outImageTensor, config.output.quality, config.output.format ); return outImage; } /** * Removes the foreground from an image. * * @param image - The image to remove the foreground from. * @param configuration - Optional configuration for the foreground removal process. * @returns A Promise that resolves to the resulting image with the foreground removed. */ async function removeForeground( image: ImageSource, configuration?: Config ): Promise { const { config, session } = await init(configuration); const imageTensor = await utils.imageSourceToImageData(image, config); const [width, height, channels] = imageTensor.shape; const alphamask = await runInference(imageTensor, config, session); const stride = width * height; const outImageTensor = imageTensor; for (let i = 0; i < stride; i += 1) { outImageTensor.data[4 * i + 3] = 255 - alphamask.data[i]; } const outImage = await utils.imageEncode( outImageTensor, config.output.quality, config.output.format ); return outImage; } /** * Segments the foreground of an image using a given configuration. * * @param image - The image source to segment. * @param configuration - The optional configuration for the segmentation. * @returns A Promise that resolves to the segmented foreground as a Blob. */ async function segmentForeground( image: ImageSource, configuration?: Config ): Promise { const { config, session } = await init(configuration); const imageTensor = await utils.imageSourceToImageData(image, config); const [height, width, channels] = imageTensor.shape; const alphamask = await runInference(imageTensor, config, session); const stride = width * height; if (config.output.format === 'image/x-alpha8') { const outImage = await utils.imageEncode( alphamask, config.output.quality, config.output.format ); return outImage; } else { const outImageTensor = ndarray(new Uint8Array(channels * stride), [ height, width, channels ]); for (let i = 0; i < stride; i += 1) { const index = 4 * i + 3; outImageTensor.data[index] = alphamask.data[i]; //Red outImageTensor.data[index + 1] = alphamask.data[i]; //Green outImageTensor.data[index + 2] = alphamask.data[i]; // Blue outImageTensor.data[index + 3] = 255; } const outImage = await utils.imageEncode( outImageTensor, config.output.quality, config.output.format ); return outImage; } } async function applySegmentationMask( image, mask, config?: Config ): Promise { config = validateConfig(config); const imageTensor = await utils.imageSourceToImageData(image, config); const [imageHeight, imageWidth, imageChannels] = imageTensor.shape; const maskTensor = await utils.imageSourceToImageData(mask, config); const [maskHeight, maskWidth, maskChannels] = maskTensor.shape; const alphaMask = maskHeight !== imageHeight || maskWidth !== imageWidth ? utils.tensorResizeBilinear(maskTensor, imageWidth, imageHeight) : maskTensor; const stride = imageWidth * imageHeight; for (let i = 0; i < stride; i += 1) { const idxImage = imageChannels * i; const idxMask = maskChannels * i; imageTensor.data[idxImage + 3] = alphaMask.data[idxMask]; // alpha information it always in the first (sometimes also in the others) } const outImage = await utils.imageEncode( imageTensor, config.output.quality, config.output.format ); return outImage; } ================================================ FILE: packages/node/src/inference.ts ================================================ export { initInference, runInference }; import { tensorResizeBilinear, tensorHWCtoBCHW } from './utils'; import { createOnnxSession, runOnnxSession } from './onnx'; import { Config, validateConfig } from './schema'; import { loadAsBlob } from './resource'; import ndarray, { NdArray } from 'ndarray'; import { convertFloat32ToUint8 } from './utils'; async function initInference(config?: Config) { config = validateConfig(config); if (config.debug) console.debug('Loading model...'); const model = config.model; const blob = await loadAsBlob(`/models/${model}`, config); const arrayBuffer = await blob.arrayBuffer(); const session = await createOnnxSession(arrayBuffer, config); return { config, session }; } async function runInference( imageTensor: NdArray, config: Config, session: any ): Promise> { if (config.progress) config.progress('compute:inference', 0, 1); const resolution = 1024; const [srcHeight, srcWidth, srcChannels] = imageTensor.shape; let tensorImage = tensorResizeBilinear(imageTensor, resolution, resolution); const inputTensor = tensorHWCtoBCHW(tensorImage); // this converts also from float to rgba // run const predictionsDict = await runOnnxSession( session, [['input', inputTensor]], ['output'] ); let alphamask = ndarray(predictionsDict[0].data, [resolution, resolution, 1]); let alphamaskU8 = convertFloat32ToUint8(alphamask); alphamaskU8 = tensorResizeBilinear(alphamaskU8, srcWidth, srcHeight); if (config.progress) config.progress('compute:inference', 1, 1); return alphamaskU8; } ================================================ FILE: packages/node/src/onnx.ts ================================================ export { createOnnxSession, runOnnxSession }; import ndarray, { NdArray } from 'ndarray'; import * as ort from 'onnxruntime-node'; // import * as ort from 'onnxruntime-node-gpu'; import { Config } from './schema'; async function createOnnxSession(model: any, config: Config) { if (config.debug) { ort.env.debug = true; ort.env.logLevel = 'verbose'; console.debug('ort.env.wasm:', ort.env.wasm); } const ort_config: ort.InferenceSession.SessionOptions = { graphOptimizationLevel: 'all', executionMode: 'parallel' }; const session = await ort.InferenceSession.create(model, ort_config).catch( (e: any) => { throw new Error( `Failed to create session: ${e}. Please check if the publicPath is set correctly.` ); } ); return session; } async function runOnnxSession( session: any, inputs: [string, NdArray][], outputs: [string] ) { const feeds: Record = {}; for (const [key, tensor] of inputs) { feeds[key] = new ort.Tensor( 'float32', new Float32Array(tensor.data), tensor.shape ); } const outputData = await session.run(feeds, {}); const outputKVPairs: NdArray[] = []; for (const key of outputs) { const output: ort.Tensor = outputData[key]; const shape: number[] = output.dims as number[]; const data: Float32Array = output.data as Float32Array; const tensor = ndarray(data, shape); outputKVPairs.push(tensor); } return outputKVPairs; } ================================================ FILE: packages/node/src/resource.ts ================================================ export { loadAsBlob, loadAsUrl, loadFromURI }; import { Config } from './schema'; import { ensureAbsoluteURI } from './url'; import { readFile } from 'fs/promises'; import { fileURLToPath } from 'url'; async function loadAsUrl(url: string, config: Config) { return URL.createObjectURL(await loadAsBlob(url, config)); } async function loadFromURI( uri: URL, config = { headers: { 'Content-Type': 'application/octet-stream' } } ) { switch (uri.protocol) { case 'http:': return await fetch(uri); case 'https:': return await fetch(uri); case 'file:': { const buffer = await readFile(fileURLToPath(uri)); return new Response(buffer, { status: 200, headers: config.headers }); } default: throw new Error(`Unsupported protocol: ${uri.protocol}`); } } async function loadAsBlob(key: string, config: Config) { // load resource metadata const resourceUri = ensureAbsoluteURI('./resources.json', config.publicPath); const resourceResponse = await loadFromURI(resourceUri); if (!resourceResponse.ok) { throw new Error( `Resource metadata not found. Ensure that the config.publicPath is configured correctly.` ); } const resourceMap = await resourceResponse.json(); const entry = resourceMap[key]; if (!entry) { throw new Error( `Resource ${key} not found. Ensure that the config.publicPath is configured correctly.` ); } const chunks = entry.chunks; // list of entries let downloadedSize = 0; const responses = chunks.map(async (chunk) => { const url = ensureAbsoluteURI(chunk.hash, config.publicPath); const chunkSize = chunk.offsets[1] - chunk.offsets[0]; const response = await loadFromURI(url, { headers: { 'Content-Type': entry.mime } }); const blob = await response.blob(); if (chunkSize !== blob.size) { throw new Error( `Failed to fetch ${key} with size ${chunkSize} but got ${blob.size}` ); } if (config.progress) { downloadedSize += chunkSize; config.progress(`fetch:${key}`, downloadedSize, entry.size); } return blob; }); // we could create a new buffer here and use the chunk entries and combine the file instead const allChunkData = await Promise.all(responses); const data = new Blob(allChunkData, { type: entry.mime }); if (data.size !== entry.size) { throw new Error( `Failed to fetch ${key} with size ${entry.size} but got ${data.size}` ); } return data; } ================================================ FILE: packages/node/src/schema.ts ================================================ export { ConfigSchema, Config, validateConfig }; import { z } from 'zod'; import path from 'node:path'; import pkg from '../package.json'; function isURI(s: string) { try { new URL(s); return true; } catch (err) { return false; } } const ConfigSchema = z .object({ publicPath: z .string() .optional() .describe('The public path to the wasm files and the onnx model.') .default(`file://${path.resolve(`node_modules/${pkg.name}/dist/`)}/`) .transform((val) => { return val .replace('${PACKAGE_NAME}', pkg.name) .replace('${PACKAGE_VERSION}', pkg.version); }) .refine((val) => isURI(val), { message: 'String must be a valid uri' }), debug: z .boolean() .default(false) .describe('Whether to enable debug logging.'), proxyToWorker: z .boolean() .default(true) .describe('Whether to proxy inference to a web worker.'), fetchArgs: z .any({}) .default({}) .describe('Arguments to pass to fetch when loading the model.'), progress: z .function() .args(z.string(), z.number(), z.number()) .returns(z.void()) .describe('Progress callback.') .optional(), model: z .preprocess( (val) => { switch (val) { case 'large': return 'isnet'; case 'small': return 'isnet_quint8'; case 'medium': return 'isnet_fp16'; default: return val; } }, z.enum(['isnet', 'isnet_fp16', 'isnet_quint8']) ) .default('medium'), output: z .object({ format: z .enum([ 'image/png', 'image/jpeg', 'image/webp', 'image/x-rgba8', 'image/x-alpha8' ]) .default('image/png'), quality: z.number().default(0.8) }) .default({}) }) .default({}) .transform((config) => { if (config.debug) console.log('Config:', config); if (config.debug && !config.progress) { config.progress = config.progress ?? ((key, current, total) => { console.debug(`Downloading ${key}: ${current} of ${total}`); }); } return config; }); type Config = z.infer; function validateConfig(configuration?: Config): Config { return ConfigSchema.parse(configuration ?? {}); } ================================================ FILE: packages/node/src/url.ts ================================================ export { ensureAbsoluteURI }; function isAbsoluteURI(url: string): boolean { const regExp = new RegExp('^(?:[a-z+]+:)?//', 'i'); return regExp.test(url); // true - regular http absolute URL } function ensureAbsoluteURI(url: string, baseUrl: string): URL { if (isAbsoluteURI(url)) { return new URL(url); } else { return new URL(url, baseUrl); } } ================================================ FILE: packages/node/src/utils.ts ================================================ export { imageDecode, imageEncode, tensorResizeBilinear, tensorHWCtoBCHW, calculateProportionalSize, imageSourceToImageData, ImageSource, convertFloat32ToUint8 }; import { Config } from './schema'; import * as codecs from './codecs'; import { ensureAbsoluteURI } from './url'; import { loadFromURI } from './resource'; import ndarray, { NdArray } from 'ndarray'; import { imageDecode, imageEncode } from './codecs'; type ImageSource = | ArrayBuffer | Uint8Array | Blob | URL | string | NdArray; function tensorResizeBilinear( imageTensor: NdArray, newWidth: number, newHeight: number ): NdArray { const [srcHeight, srcWidth, srcChannels] = imageTensor.shape; // Calculate the scaling factors const scaleX = srcWidth / newWidth; const scaleY = srcHeight / newHeight; // Create a new NdArray to store the resized image const resizedImageData = ndarray( new Uint8Array(srcChannels * newWidth * newHeight), [newHeight, newWidth, srcChannels] ); // Perform interpolation to fill the resized NdArray for (let y = 0; y < newHeight; y++) { for (let x = 0; x < newWidth; x++) { const srcX = x * scaleX; const srcY = y * scaleY; const x1 = Math.max(Math.floor(srcX), 0); const x2 = Math.min(Math.ceil(srcX), srcWidth - 1); const y1 = Math.max(Math.floor(srcY), 0); const y2 = Math.min(Math.ceil(srcY), srcHeight - 1); const dx = srcX - x1; const dy = srcY - y1; for (let c = 0; c < srcChannels; c++) { const p1 = imageTensor.get(y1, x1, c); const p2 = imageTensor.get(y1, x2, c); const p3 = imageTensor.get(y2, x1, c); const p4 = imageTensor.get(y2, x2, c); // Perform bilinear interpolation const interpolatedValue = (1 - dx) * (1 - dy) * p1 + dx * (1 - dy) * p2 + (1 - dx) * dy * p3 + dx * dy * p4; resizedImageData.set(y, x, c, Math.round(interpolatedValue)); } } } return resizedImageData; } function tensorHWCtoBCHW( imageTensor: NdArray, mean: number[] = [128, 128, 128], std: number[] = [256, 256, 256] ): NdArray { var imageBufferData = imageTensor.data; const [srcHeight, srcWidth, srcChannels] = imageTensor.shape; const stride = srcHeight * srcWidth; const float32Data = new Float32Array(3 * stride); // r_0, r_1, .... g_0,g_1, .... b_0 for (let i = 0, j = 0; i < imageBufferData.length; i += 4, j += 1) { float32Data[j] = (imageBufferData[i] - mean[0]) / std[0]; float32Data[j + stride] = (imageBufferData[i + 1] - mean[1]) / std[1]; float32Data[j + stride + stride] = (imageBufferData[i + 2] - mean[2]) / std[2]; } return ndarray(float32Data, [1, 3, srcHeight, srcWidth]); } function calculateProportionalSize( originalWidth: number, originalHeight: number, maxWidth: number, maxHeight: number ): [number, number] { const widthRatio = maxWidth / originalWidth; const heightRatio = maxHeight / originalHeight; const scalingFactor = Math.min(widthRatio, heightRatio); const newWidth = Math.floor(originalWidth * scalingFactor); const newHeight = Math.floor(originalHeight * scalingFactor); return [newWidth, newHeight]; } async function imageSourceToImageData( image: ImageSource, _: Config ): Promise> { if (typeof image === 'string') { image = ensureAbsoluteURI(image, `file://${process.cwd()}/`); } if (image instanceof URL) { image = await (await loadFromURI(image)).blob(); } if (image instanceof ArrayBuffer || ArrayBuffer.isView(image)) { image = new Blob([image]); } if (image instanceof Blob) { image = await codecs.imageDecode(image); } return image as NdArray; } function convertFloat32ToUint8( float32Array: NdArray ): NdArray { const uint8Array = new Uint8Array(float32Array.data.length); for (let i = 0; i < float32Array.data.length; i++) { uint8Array[i] = float32Array.data[i] * 255; } return ndarray(uint8Array, float32Array.shape); } ================================================ FILE: packages/node/tsconfig.json ================================================ { "compilerOptions": { "lib": ["DOM", "ES2015"], "resolveJsonModule": true, "esModuleInterop": true, "emitDeclarationOnly": true, "declaration": true, "target": "ES6", "moduleResolution": "Node16" } } ================================================ FILE: packages/node-e2e/fixtures/images/img2img.sh ================================================ filename="photo-1686002359940-6a51b0d64f68.jpeg" basename="${filename%.*}" cp "$filename" "$filename".orig magick "$filename" "$basename".png magick "$filename" "$basename".webp magick "$filename" "$basename".jpg magick "$filename" "$basename".avif magick "$filename" "$basename".heif # Raw RGB magick "$filename" -depth 8 "$basename".rgb magick "$filename" -depth 8 "$basename".cmyk # rgb to tensor magick "$filename" "$basename".pdf magick "$filename" "$basename".psd ================================================ FILE: packages/node-e2e/package.json ================================================ { "name": "e2e", "private": true, "scripts": {}, "devDependencies": { "@imgly/background-removal-node": "workspace:*", "jest": "^29.6.2" }, "version": "1.7.0" } ================================================ FILE: packages/node-e2e/src/example.test.js ================================================ // const pkg = require('@imgly/background-removal-node'); // const removeBackground = pkg.default; // Test case to ensure the system doesn't crash with valid inputs // test('removeBackground should not crash with valid inputs', async () => { // const image = 'https://images.unsplash.com/photo-1686002359940-6a51b0d64f68?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1024&q=80'; // const result = await removeBackground(image, { debug: true }) // await expect(result).resolves.toBeInstanceOf(Blob); // }); ================================================ FILE: packages/node-examples/package.json ================================================ { "name": "examples-node-cli", "private": true, "main": "index.mjs", "scripts": { "start": "node src/example_001.cjs" }, "dependencies": { "@imgly/background-removal-node": "workspace:*", "uuidv4": "^6.2.13" }, "version": "1.7.0" } ================================================ FILE: packages/node-examples/src/example_001.cjs ================================================ const { removeBackground, segmentForeground, applySegmentationMask } = require('@imgly/background-removal-node'); const fs = require('fs'); const uuidv4 = require('uuid').v4; const images = [ // 'files/photo-1686002359940-6a51b0d64f68.jpeg', 'files/photo-1686002359940-hires.webp' // 'files/photo-1590523278191-hires.webp' // 'https://images.unsplash.com/photo-1686002359940-6a51b0d64f68?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&q=80' // 'https://images.unsplash.com/photo-1590523278191-995cbcda646b?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9' ]; async function run() { const randomImage = images[Math.floor(Math.random() * images.length)]; console.log('Random image: ' + randomImage); const config = { debug: false, // publicPath: ... progress: (key, current, total) => { const [type, subtype] = key.split(':'); console.log( `${type} ${subtype} ${((current / total) * 100).toFixed(0)}%` ); }, // model: 'small', model: 'isnet', output: { quality: 0.8, format: 'image/webp' //image/jpeg, image/webp } }; console.time(); const blob = await removeBackground(randomImage, config); // const mask = await segmentForeground(randomImage, config); // const blob = await applySegmentationMask(randomImage, mask, config); console.timeEnd(); const buffer = await blob.arrayBuffer(); try { const format = config.output.format.split('/').pop(); const outFile = `tmp/${uuidv4()}.${format}`; await fs.promises.mkdir('tmp', { recursive: true }); await fs.promises.writeFile(outFile, Buffer.from(buffer)); console.log(`Image saved to ${outFile}`); } catch (error) { console.error(error); } } run(); ================================================ FILE: packages/web/CHANGELOG.md ================================================ # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.5.6] ### Changed - Upgrade onnx-runtime ## [1.5.0] ### Added - Added option to execute on gpu (webgpu) and cpu. Enable by setting `device: "gpu"` - Added isnet model for webgpu ## [1.4.5] ### Added - Added ThirdPartyLicenses.json ## [1.4.0] ### Added - Moved all data into it's own package. Therefore, reducing the main package size for the general case. - Bumped onnx runtime to 1.17 Changed - Changed license from GPL to AGPL Changed - Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets. - Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets. ### Changed - Fallback to Canvas if OffscreenCanvas is not available - Typescript bindings are generated with tsc ## [1.3.0] ### Added - Resources are now chunked to 4MB for better caching performance and download restart. - Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only. - Config option to export 'x-alpha8' format to get receive single channel alpha mask. ### Removed - Configuration options to specify if background, foreground or mask is exported. ### Changed - Changed the return value type of the progress callback from undefined to void - Output is now in the original image size. Mask is upscaled and applied to the original image. ## [1.2.1] ### Added - `CHANGELOG.md` for an better overview of the changes. - support for raw `rgba8` export formats. ## [1.2.0] ### Added - Support `foreground`, `background` and `mask` export type. - Added support for `webp` and `jpeg` export formats. ================================================ FILE: packages/web/LICENSE.md ================================================ # GNU Affero General Public License _Version 3, 19 November 2007_ _Copyright © 2007 Free Software Foundation, Inc. <>_ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. ## Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: **(1)** assert copyright on the software, and **(2)** offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. ## TERMS AND CONDITIONS ### 0. Definitions “This License” refers to version 3 of the GNU Affero General Public License. “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. A “covered work” means either the unmodified Program or a work based on the Program. To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that **(1)** displays an appropriate copyright notice, and **(2)** tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. ### 1. Source Code The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The “System Libraries” of an executable work include anything, other than the work as a whole, that **(a)** is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and **(b)** serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. ### 2. Basic Permissions All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. ### 4. Conveying Verbatim Copies You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. ### 5. Conveying Modified Source Versions You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: - **a)** The work must carry prominent notices stating that you modified it, and giving a relevant date. - **b)** The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. - **c)** You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. - **d)** If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. ### 6. Conveying Non-Source Forms You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - **a)** Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. - **b)** Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either **(1)** a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or **(2)** access to copy the Corresponding Source from a network server at no charge. - **c)** Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. - **d)** Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. - **e)** Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A “User Product” is either **(1)** a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or **(2)** anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. ### 7. Additional Terms “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - **a)** Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or - **b)** Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or - **c)** Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or - **d)** Limiting the use for publicity purposes of names of licensors or authors of the material; or - **e)** Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or - **f)** Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. ### 8. Termination You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated **(a)** provisionally, unless and until the copyright holder explicitly and finally terminates your license, and **(b)** permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. ### 9. Acceptance Not Required for Having Copies You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. ### 10. Automatic Licensing of Downstream Recipients Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. ### 11. Patents A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either **(1)** cause the Corresponding Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the patent license for this particular work, or **(3)** arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license **(a)** in connection with copies of the covered work conveyed by you (or copies made from those copies), or **(b)** primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. ### 12. No Surrender of Others' Freedom If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. ### 13. Remote Network Interaction; Use with the GNU General Public License Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. ### 14. Revised Versions of this License The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. ### 15. Disclaimer of Warranty THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. ### 16. Limitation of Liability IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. ### 17. Interpretation of Sections 15 and 16 If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. _END OF TERMS AND CONDITIONS_ ## How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a “Source” link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <>. ================================================ FILE: packages/web/README.md ================================================ # Background Removal in the Browser We are always looking for great people at IMG.LY. If you are working with our background removal library you might be a perfect fit! **Apply now at [IMG.LY Careers](https://img.ly/company/careers/?utm_source=github&utm_medium=readme&utm_campaign=background-removal-js)** <p align="center"> <img src="https://img.ly/showcases/cesdk/web/s/case-thumbnail/background-removal/background-removal-0.png?utm_source=github&utm_medium=project&utm_campaign=background-removal-js" alt="background removal js showcase" /> </p> Remove backgrounds from images directly in the browser environment with ease and no additional costs or privacy concerns. Explore an [interactive demo](https://img.ly/showcases/cesdk/web/background-removal/web?utm_source=github&utm_medium=project&utm_campaign=background-removal-js). ## News For more detail information please refer to the [CHANGELOG](./CHANGELOG.md). ## Overview `@imgly/background-removal` is a powerful npm package that allows developers to seamlessly remove the background from images directly in the browser. With its unique features and capabilities, this package offers an innovative and cost-effective solution for background removal tasks without compromising data privacy. The key features of `@imgly/background-removal` are: - **In-Browser Background Removal**: Our one-of-a-kind solution performs the entire background removal process directly in the user's browser, eliminating the need for additional server costs. By leveraging the computing power of the local device, users can enjoy a fast and efficient background removal process. - **Data Protection**: As `@imgly/background-removal` runs entirely in the browser, users can have peace of mind knowing that their images and sensitive information remain secure within their own devices. With no data transfers to external servers, data privacy concerns are effectively mitigated. - **Seamless Integration with IMG.LY's CE.SDK**: `@imgly/background-removal` provides seamless integration with [IMG.LY's CE.SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), allowing developers to easily incorporate powerful in-browser image matting and background removal capabilities into their projects. The Neural Network ([ONNX model](https://onnx.ai/)) and WASM files used by `@imgly/background-removal` are hosted by [IMG.LY](https://img.ly/) by default. See the section Custom Asset Serving if you want to host them on your own servers. ## Installation You can install `@imgly/background-removal` via npm or yarn. You also need to install the onnxruntime-web peer dependency. Use the following commands to install the packages: ### NPM ```shell npm install @imgly/background-removal onnxruntime-web@1.21.0-dev.20250206-d981b153d3 ``` ## Usage ```typescript import imglyRemoveBackground from "@imgly/background-removal" let image_src: ImageData | ArrayBuffer | Uint8Array | Blob | URL | string = ...; imglyRemoveBackground(image_src).then((blob: Blob) => { // The result is a blob encoded as PNG. It can be converted to an URL to be used as HTMLImage.src const url = URL.createObjectURL(blob); }) ``` Note: On the first run the wasm and onnx model files are fetched. This might, depending on the bandwidth, take time. Therefore, the first run takes proportionally longer than each consecutive run. Also, all files are cached by the browser and an additional model cache. ## Advanced Configuration The library does not need any configuration to get started. However, there are optional parameters that influence the behaviour and give more control over the library. ```typescript type Config = { publicPath: string; // The public path used for model and wasm files. Default: 'https://staticimgly.com/${PACKAGE_NAME}-data/${PACKAGE_VERSION}/dist/' debug: bool; // enable or disable useful console.log outputs device: 'cpu' | 'gpu'; // choose the execution device. gpu will use webgpu if available model: 'isnet' | 'isnet_fp16' | 'isnet_quint8'; // The model to use. (Default "isnet_fp16") output: { format: 'image/png' | 'image/jpeg' | 'image/webp'; // The output format. (Default "image/png") quality: number; // The quality. (Default: 0.8) type: 'foreground' | 'background' | 'mask'; // The output type. (Default "foreground") }; }; ``` ### NextJS Note that currently only NextJS 15 is supported. ### Download Size vs Quality The onnx model is shipped in various sizes and needs. - small (\~40 MB) is the smallest model and is in most cases working fine but sometimes shows some artifacts. It's a quantized model. - medium (\~80MB) is the default model. ### Preloading Assets Per default, assets are downloaded on demand. You might enforce downloading all assets at once at any time by preloading them: ```typescript import removeBackground, { preload, Config } from '@imgly/background-removal'; const config: Configuration = ...; preload(config).then(() => { console.log("Asset preloading succeeded") }) ``` ### Download Progress Monitoring On the first run, the necessary data will be fetched and stored in the browser cache. Since the download might take some time, you have the option to tap into the download progress. ```typescript let config: Config = { progress: (key, current, total) => { console.log(`Downloading ${key}: ${current} of ${total}`); } }; ``` ### Performance The performance is largely dependent on the feature set available. Most prominently, ensure that `SharedArrayBuffer` is available [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer). Due to the security requirements of `SharedArrayBuffer` two headers need to be set to cross-origin isolate your site: ```typescript 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp' ``` ### Custom Asset Serving The wasm and onnx neural networks are hosted by IMG.LY by default. For production use, we advise you to host them yourself: - Download the following package with the package version that matches your `@imgly/background-removal` version from the IMG.LY CDN and decompress it. Note that you need to replace `YOUR_PACKAGE_VERSION` with the actual version of the package you are using. The URL is `https://staticimgly.com/@imgly/background-removal-data/YOUR_PACKAGE_VERSION/package.tgz`. - Move the content of the `package/dist` folder to be served by your web server. This often is the `/public` folder. ```typescript import imglyRemoveBackground, {Config} from "@imgly/background-removal" const public_path = "https://example.com/assets/" ; // the path assets are served from let config: Config = { publicPath: public_path, // path to the wasm files }; let image_src: ImageData | ArrayBuffer | Uint8Array | Blob | URL | string = ...; imglyRemoveBackground(image_src, config).then((blob: Blob) => { // result is a blob encoded as PNG. // It can be converted to an URL to be used as HTMLImage.src const url = URL.createObjectURL(blob); }) ``` ### Debug Outputs Enable debug outputs and logging to the console ```typescript let config: Config = { debug: true }; ``` ### Cross-Origin Resource Sharing (CORS) If you are running into CORS issues you might want to pass additional parameters to the fetch function via ```typescript let config: Config = { fetchArgs: { mode: 'no-cors' } }; ``` ### Fetch Args `fetchArgs` are passed as second parameters to the fetch function as described in [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). ## Who is it for? `@imgly/background-removal` is ideal for developers and projects that require efficient and cost-effective background removal directly in the browser. It caters to a wide range of use cases, including but not limited to: - _E-commerce applications_ that need to remove backgrounds from product images in real time. - _Image editing applications_ that require background removal capabilities for enhancing user experience. - _Web-based graphic design tools_ that aim to simplify the creative process with in-browser background removal. Whether you are a professional developer or a hobbyist, `@imgly/background-removal` empowers you to deliver impressive applications and services with ease. ## License The software is free for use under the AGPL License. Please contact [support@img.ly](mailto:support@img.ly?subject=Background-Removal%20License) for questions about other licensing options. ## Authors & Contributors This library is made by IMG.LY shipping the world's premier SDKs for building creative applications. Start your trial of the [CreativeEditor SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), [PhotoEditor SDK](https://img.ly/products/photo-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js) & [VideoEditor SDK](https://img.ly/products/video-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js). ================================================ FILE: packages/web/ThirdPartyLicenses.json ================================================ { "onnxruntime-web": { "source": "https://www.npmjs.com/package/onnxruntime-web", "type": "code", "license": "MIT" }, "ISNET": { "source": "https://github.com/xuebinqin/DIS", "type": "model", "license": "MIT" }, "lodash-es": { "source": "https://lodash.com/", "type": "code", "license": "MIT" }, "ndarray": { "source": "https://www.npmjs.com/package/ndarray", "type": "code", "license": "MIT" }, "zod": { "source": "https://www.npmjs.com/package/zod", "type": "code", "license": "MIT" } } ================================================ FILE: packages/web/changelog/1.2.0/20230811184244-export_type_and_formats.yml ================================================ --- type: Added description: Support `foreground`, `background` and `mask` export type. --- type: Added description: Added support for `webp` and `jpeg` export formats. ================================================ FILE: packages/web/changelog/1.2.1/20230811184244-Changelog_item.yml ================================================ --- type: Added description: | `CHANGELOG.md` for an better overview of the changes. --- type: Added description: | support for raw `rgba8` export formats. ================================================ FILE: packages/web/changelog/1.3.0/20230612112148-progress_return_type.yaml ================================================ --- type: Changed # type: Changed # type: Removed # type: Security # private: true description: | Changed the return value type of the progress callback from undefined to void ================================================ FILE: packages/web/changelog/1.3.0/20231512181521-resource_data_chunking.yaml ================================================ --- type: Added # type: Changed # type: Removed # type: Security # private: true description: | Resources are now chunked to 4MB for better caching performance and download restart. ================================================ FILE: packages/web/changelog/1.3.0/20231512193816-upscale_mask_to_original_image.yaml ================================================ --- type: Changed # type: Removed # type: Security # private: true description: | Output is now in the original image size. Mask is upscaled and applied to the original image. --- type: Added # type: Removed # type: Security # private: true description: | Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only. --- type: Removed # type: Removed # type: Security # private: true description: | Configuration options to specify if background, foreground or mask is exported. --- type: Added # type: Removed # type: Security # private: true description: | Config option to export 'x-alpha8' format to get receive single channel alpha mask. ================================================ FILE: packages/web/changelog/1.4.0/20233012103509-Moved.yaml ================================================ --- type: Added # type: Changed # type: Removed # type: Security # private: true description: | Moved all data into it's own package. Therefore, reducing the main package size for the general case. ================================================ FILE: packages/web/changelog/1.4.0/20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Bumped onnx runtime to 1.17 Changed ================================================ FILE: packages/web/changelog/1.4.0/20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Changed license from GPL to AGPL Changed ================================================ FILE: packages/web/changelog/1.4.0/20241601144157-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets. ================================================ FILE: packages/web/changelog/1.4.0/20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets. ================================================ FILE: packages/web/changelog/1.4.0/20241601175908-Fallback_to_Canvas_if_OffscreenCanvas_is_not_available.yaml ================================================ --- type: Changed # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Fallback to Canvas if OffscreenCanvas is not available ================================================ FILE: packages/web/changelog/1.4.0/20242301155639-Typescript_bindings_are_generated_with_tsc.yaml ================================================ --- type: Changed # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Typescript bindings are generated with tsc ================================================ FILE: packages/web/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Added ThirdPartyLicenses.json ================================================ FILE: packages/web/changelog/1.5.0/20242403201534-Added_option_to_execute_on_gpu_webgpu_and_cpu_Added.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Added option to execute on gpu (webgpu) and cpu. Enable by setting `device: "gpu"` ================================================ FILE: packages/web/changelog/1.5.0/20242503170808-Added_isnet_model_for_webgpu_Added.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Added isnet model for webgpu ================================================ FILE: packages/web/changelog/1.5.6/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml ================================================ --- type: Changed # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Upgrade onnx-runtime ================================================ FILE: packages/web/changelog/Unreleased/.keep ================================================ ================================================ FILE: packages/web/changelog/info.yml ================================================ --- description: | All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ================================================ FILE: packages/web/package.json ================================================ { "name": "@imgly/background-removal", "version": "1.7.0", "description": "Background Removal in the Browser", "keywords": [ "background-removal", "client-side", "data-privacy", "image-segmentation", "image-matting", "onnx" ], "repository": { "type": "git", "url": "git+https://github.com/imgly/background-removal-js.git" }, "license": "SEE LICENSE IN LICENSE.md", "author": { "name": "IMG.LY GmbH", "email": "support@img.ly", "url": "https://img.ly" }, "bugs": { "email": "support@img.ly" }, "source": "./src/index.ts", "main": "./dist/index.cjs", "module": "./dist/index.mjs", "types": "./dist/src/index.d.ts", "exports": { ".": { "require": "./dist/index.cjs", "import": "./dist/index.mjs", "types": "./dist/src/index.d.ts" } }, "homepage": "https://img.ly/showcases/cesdk/web/background-removal", "files": [ "LICENSE.md", "README.md", "CHANGELOG.md", "ThirdPartyLicenses.json", "dist/", "bin/" ], "scripts": { "start": "pnpm run watch", "clean": "npx rimraf dist", "test": "true", "resources": "node ../../scripts/package-resources.mjs", "changelog:create": "node ../../scripts/changelog/changelog-create.mjs", "changelog:generate": "node ../../scripts/changelog/changelog-generate.mjs", "build": "pnpm run clean && pnpm run types && pnpm run resources && pnpm run changelog:generate && node scripts/build.mjs", "types": " npx tsc --declaration --emitDeclarationOnly --declarationDir dist --declarationMap", "watch": "pnpm run clean && pnpm run resources && pnpm run changelog:generate && node scripts/watch.mjs", "publish:latest": "pnpm publish --tag latest --access public", "publish:next": "pnpm publish --tag next --access public", "package:pack": "pnpm pack . --pack-destination ../../releases", "check:all": "pnpm run check:pretty", "check:pretty": "prettier --list-different './src/**/*.{ts,tsx}'", "pretty": "prettier --write './src/**/*.{ts,tsx}'" }, "dependencies": { "lodash-es": "^4.17.21", "ndarray": "~1.0.0", "zod": "^3.23.8" }, "peerDependencies": { "onnxruntime-web": "1.21.0" }, "devDependencies": { "@types/lodash-es": "^4.17.12", "@types/ndarray": "~1.0.14", "@types/node": "~20.3.0", "assert": "~2.0.0", "esbuild": "~0.18.0", "glob": "~10.3.0", "npm-dts": "~1.3.0", "process": "~0.11.0", "ts-loader": "~9.4.0", "tslib": "~2.5.0", "typescript": "~5.1.0", "util": "~0.12.0", "webpack": "~5.85.0", "webpack-cli": "~5.1.0" } } ================================================ FILE: packages/web/scripts/build.mjs ================================================ export { configs }; import * as esbuild from 'esbuild'; import { readFileSync } from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const pkg = JSON.parse( readFileSync(path.resolve(__dirname, '../package.json')) ); const dependencies = [Object.keys(pkg.peerDependencies)].flat(); const configs = [ { entryPoints: ['src/index.ts'], bundle: true, sourcemap: true, platform: 'browser', external: dependencies, format: 'cjs', outfile: 'dist/index.cjs' }, { entryPoints: ['src/index.ts'], bundle: true, sourcemap: true, external: dependencies, platform: 'browser', format: 'esm', outfile: 'dist/index.mjs' } ]; await configs.map(async (config) => await esbuild.build(config)); ================================================ FILE: packages/web/scripts/watch.mjs ================================================ import * as esbuild from 'esbuild'; import { configs } from './build.mjs'; import dts from 'npm-dts'; new dts.Generator({ entry: 'src/index.ts', output: 'dist/index.d.ts' }).generate(); const contexts = await Promise.all( configs.map((config) => esbuild.context(config)) ); await Promise.any(contexts.map((ctx) => ctx.watch())); console.log('watching...'); ================================================ FILE: packages/web/src/MimeType.ts ================================================ export class MimeType { type: string = 'application/octet-stream'; params: Record = {}; private constructor(type: string, params: Record) { this.type = type; this.params = params; } toString(): string { const paramsStr = []; for (const key in this.params) { const value = this.params[key]; paramsStr.push(`${key}=${value}`); } return [this.type, ...paramsStr].join(';'); } static create(type, params: Record): MimeType { return new MimeType(type, params); } isIdentical(other: MimeType): Boolean { return this.type === other.type && this.params === other.params; } isEqual(other: MimeType): Boolean { return this.type === other.type; } static fromString(mimeType: string): MimeType { const [type, ...paramsArr] = mimeType.split(';'); const params: Record = {}; for (const param of paramsArr) { const [key, value] = param.split('='); params[key.trim()] = value.trim(); } return new MimeType(type, params); } } ================================================ FILE: packages/web/src/api/v1.ts ================================================ export default removeBackground; export { preload, removeBackground, removeForeground, alphamask, segmentForeground, applySegmentationMask }; export type { Config, ImageSource }; import memoize from 'lodash-es/memoize'; import { initInference, runInference } from '../inference'; import { Config, validateConfig } from '../schema'; import * as utils from '../utils'; import { ImageSource } from '../utils'; const init = memoize(initInference, (config) => JSON.stringify(config)); async function preload(configuration?: Config): Promise { await init(configuration); return; } /** * Removes the background from an image. * * @param image - The image to remove the background from. * @param configuration - Optional configuration for the background removal process. * @returns A Promise that resolves to the resulting image with the background removed. */ async function removeBackground( image: ImageSource, configuration?: Config ): Promise { const { config, session } = await init(configuration); if (config.progress) config.progress('compute:decode', 0, 4); const inputImageTensor = await utils.imageSourceToImageData(image, config); config.progress?.('compute:inference', 1, 4); const [alphamask, imageTensor] = await runInference( inputImageTensor, config, session ); config.progress?.('compute:mask', 2, 4); const outImageTensor = imageTensor; const [width, height] = outImageTensor.shape; const stride = width * height; for (let i = 0; i < stride; i += 1) { outImageTensor.data[4 * i + 3] = alphamask.data[i]; } config.progress?.('compute:encode', 3, 4); const outImage = await utils.imageEncode( outImageTensor, config.output.quality, config.output.format ); config.progress?.('compute:encode', 4, 4); return outImage; } /** * Removes the foreground from an image. * * @param image - The image to remove the foreground from. * @param configuration - Optional configuration for the foreground removal process. * @returns A Promise that resolves to the resulting image with the foreground removed. */ async function removeForeground( image: ImageSource, configuration?: Config ): Promise { const { config, session } = await init(configuration); const imageTensor = await utils.imageSourceToImageData(image, config); const [alphamask, imageInput] = await runInference( imageTensor, config, session ); const outImageTensor = imageInput; const [width, height, channels] = outImageTensor.shape; const stride = width * height; for (let i = 0; i < stride; i += 1) { outImageTensor.data[4 * i + 3] = 255 - alphamask.data[i]; } const outImage = await utils.imageEncode( outImageTensor, config.output.quality, config.output.format ); return outImage; } /** * Segments the foreground of an image using a given configuration. * * @param image - The image source to segment. * @param configuration - The optional configuration for the segmentation. * @returns A Promise that resolves to the segmented foreground as a Blob. */ const alphamask = segmentForeground; async function segmentForeground( image: ImageSource, configuration?: Config ): Promise { const { config, session } = await init(configuration); const imageTensor = await utils.imageSourceToImageData(image, config); let [height, width, channels] = imageTensor.shape; const [alphamask, imageInput] = await runInference( imageTensor, config, session ); const stride = width * height; const outImageTensor = imageTensor; for (let i = 0; i < stride; i += 1) { const index = 4 * i; let alpha = alphamask.data[i]; outImageTensor.data[index] = 255; outImageTensor.data[index + 1] = 255; outImageTensor.data[index + 2] = 255; outImageTensor.data[index + 3] = alpha; } const outImage = await utils.imageEncode( outImageTensor, config.output.quality, config.output.format ); return outImage; } async function applySegmentationMask( image, mask, config?: Config ): Promise { config = validateConfig(config); const imageTensor = await utils.imageSourceToImageData(image, config); const [imageHeight, imageWidth, imageChannels] = imageTensor.shape; const maskTensor = await utils.imageSourceToImageData(mask, config); const [maskHeight, maskWidth, maskChannels] = maskTensor.shape; const alphaMask = maskHeight !== imageHeight || maskWidth !== imageWidth ? utils.tensorResizeBilinear(maskTensor, imageWidth, imageHeight) : maskTensor; const stride = imageWidth * imageHeight; for (let i = 0; i < stride; i += 1) { const idxImage = imageChannels * i; const idxMask = maskChannels * i; imageTensor.data[idxImage + 3] = alphaMask.data[idxMask + 3]; } const outImage = await utils.imageEncode( imageTensor, config.output.quality, config.output.format ); return outImage; } ================================================ FILE: packages/web/src/capabilities.js ================================================ export const bigInt = () => (async (e) => { try { return ( (await WebAssembly.instantiate(e)).instance.exports.b(BigInt(0)) === BigInt(0) ); } catch (e) { return !1; } })( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 1, 126, 1, 126, 3, 2, 1, 0, 7, 5, 1, 1, 98, 0, 0, 10, 6, 1, 4, 0, 32, 0, 11 ]) ), bulkMemory = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 3, 1, 0, 1, 10, 14, 1, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11 ]) ), exceptions = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 8, 1, 6, 0, 6, 64, 25, 11, 11 ]) ), extendedConst = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 5, 3, 1, 0, 1, 11, 9, 1, 0, 65, 1, 65, 2, 106, 11, 0 ]) ), gc = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 10, 2, 95, 1, 125, 0, 96, 0, 1, 107, 0, 3, 2, 1, 1, 10, 12, 1, 10, 0, 67, 0, 0, 0, 0, 251, 7, 0, 11 ]) ), memory64 = () => WebAssembly.validate( new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 5, 3, 1, 4, 1]) ), multiValue = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 0, 2, 127, 127, 3, 2, 1, 0, 10, 8, 1, 6, 0, 65, 0, 65, 0, 11 ]) ), mutableGlobals = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 2, 8, 1, 1, 97, 1, 98, 3, 127, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 5, 1, 1, 97, 3, 1 ]) ), referenceTypes = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 7, 1, 5, 0, 208, 112, 26, 11 ]) ), relaxedSimd = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 15, 1, 13, 0, 65, 1, 253, 15, 65, 2, 253, 15, 253, 128, 2, 11 ]) ), saturatedFloatToInt = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 12, 1, 10, 0, 67, 0, 0, 0, 0, 252, 0, 26, 11 ]) ), signExtensions = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 8, 1, 6, 0, 65, 0, 192, 26, 11 ]) ), simd = () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11 ]) ), streamingCompilation = () => (async () => 'compileStreaming' in WebAssembly)(), tailCall = async () => WebAssembly.validate( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 6, 1, 4, 0, 18, 0, 11 ]) ), threads = () => (async (e) => { try { return ( 'undefined' != typeof MessageChannel && new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(e) ); } catch (e) { return !1; } })( new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11 ]) ); export const webgpu = async () => { if (navigator.gpu === undefined) return false; const adapter = await navigator.gpu.requestAdapter(); return adapter !== null; }; export const maxNumThreads = () => navigator.hardwareConcurrency ?? 4; ================================================ FILE: packages/web/src/codecs.ts ================================================ export { imageEncode, imageDecode, MimeType }; import { MimeType } from './MimeType'; import { imageBitmapToImageData, createCanvas } from './utils'; import ndarray, { NdArray } from 'ndarray'; async function imageDecode(blob: Blob): Promise> { const mime = MimeType.fromString(blob.type); switch (mime.type) { case 'image/x-alpha8': { const width = parseInt(mime.params['width']); const height = parseInt(mime.params['height']); return ndarray(new Uint8Array(await blob.arrayBuffer()), [ height, width, 1 ]); } case 'image/x-rgba8': { const width = parseInt(mime.params['width']); const height = parseInt(mime.params['height']); return ndarray(new Uint8Array(await blob.arrayBuffer()), [ height, width, 4 ]); } case 'application/octet-stream': // this is an unknwon type case `image/png`: case `image/jpeg`: case `image/jpg`: case `image/webp`: { const imageBitmap = await createImageBitmap(blob); const imageData = imageBitmapToImageData(imageBitmap); return ndarray(new Uint8Array(imageData.data), [ imageData.height, imageData.width, 4 ]); } default: throw new Error( `Invalid format: ${mime.type} with params: ${mime.params}` ); } } async function imageEncode( imageTensor: NdArray, quality: number = 0.8, format: string = 'image/png' ): Promise { const [height, width, channels] = imageTensor.shape; switch (format) { case 'image/x-alpha8': case 'image/x-rgba8': { const mime = MimeType.create(format, { width: width.toString(), height: height.toString() }); return new Blob([imageTensor.data], { type: mime.toString() }); } case `image/png`: case `image/jpeg`: case `image/webp`: { const imageData = new ImageData( new Uint8ClampedArray(imageTensor.data), width, height ); var canvas = createCanvas(imageData.width, imageData.height); var ctx = canvas.getContext('2d')!; ctx.putImageData(imageData, 0, 0); return canvas.convertToBlob({ quality, type: format }); } default: throw new Error(`Invalid format: ${format}`); } } ================================================ FILE: packages/web/src/index.ts ================================================ export * from './api/v1'; // export * as next from './api/v2'; ================================================ FILE: packages/web/src/inference.ts ================================================ export { initInference, runInference }; import { tensorResizeBilinear, tensorHWCtoBCHW } from './utils'; import { createOnnxSession, runOnnxSession } from './onnx'; import { Config, validateConfig } from './schema'; import { loadAsBlob } from './resource'; import ndarray, { NdArray } from 'ndarray'; import { convertFloat32ToUint8 } from './utils'; async function initBase(config: Config): Promise { if (config.debug) console.debug('Loading model...', config.model); const model = config.model; const blob = await loadAsBlob(`/models/${model}`, config); const arrayBuffer = await blob.arrayBuffer(); const session = await createOnnxSession(arrayBuffer, config); return session; } async function initInference( config?: Config ): Promise<{ config: Config; session: { base: unknown } }> { config = validateConfig(config); const base = await initBase(config); return { config, session: { base } }; } async function runInference( imageTensor: NdArray, config: Config, session: { base: unknown } ): Promise<[NdArray, NdArray]> { const resolution = 1024; const [srcHeight, srcWidth, srcChannels] = imageTensor.shape; const keepAspect = false; let resizedImageTensor = tensorResizeBilinear( imageTensor, resolution, resolution, keepAspect ); const inputTensor = tensorHWCtoBCHW(resizedImageTensor); // this converts also from float to rgba let predictionsDict = await runOnnxSession( session.base, [['input', inputTensor]], ['output'], config ); let alphamask = ndarray(predictionsDict[0].data, [resolution, resolution, 1]); let alphamaskU8 = convertFloat32ToUint8(alphamask); if (config.rescale) { alphamaskU8 = tensorResizeBilinear( alphamaskU8, srcWidth, srcHeight, keepAspect ); return [alphamaskU8, imageTensor]; } else { return [alphamaskU8, resizedImageTensor]; } } ================================================ FILE: packages/web/src/onnx.ts ================================================ export { createOnnxSession, runOnnxSession }; import ndarray, { NdArray } from 'ndarray'; import { InferenceSession, Tensor } from 'onnxruntime-web'; import * as caps from './capabilities'; import { loadAsUrl } from './resource'; import { Config } from './schema'; type ORT = typeof import('onnxruntime-web'); // use a dynamic import to avoid bundling the entire onnxruntime-web package let ort: ORT | null = null; const getOrt = async (useWebGPU: boolean): Promise => { if (ort !== null) { return ort; } if (useWebGPU) { ort = (await import('onnxruntime-web/webgpu')).default; } else { ort = (await import('onnxruntime-web')).default; } return ort; }; async function createOnnxSession(model: any, config: Config) { const useWebGPU = config.device === 'gpu' && (await caps.webgpu()); // BUG: proxyToWorker is not working for WASM/CPU Backend for now const proxyToWorker = useWebGPU && config.proxyToWorker; const executionProviders = [useWebGPU ? 'webgpu' : 'wasm']; const ort = await getOrt(useWebGPU); if (config.debug) { console.debug('\tUsing WebGPU:', useWebGPU); console.debug('\tProxy to Worker:', proxyToWorker); ort.env.debug = true; ort.env.logLevel = 'verbose'; } ort.env.wasm.numThreads = caps.maxNumThreads(); ort.env.wasm.proxy = proxyToWorker; // The path inside the resource bundle const baseFilePath = useWebGPU ? '/onnxruntime-web/ort-wasm-simd-threaded.jsep' : '/onnxruntime-web/ort-wasm-simd-threaded'; const wasmPath = await loadAsUrl(`${baseFilePath}.wasm`, config); const mjsPath = await loadAsUrl(`${baseFilePath}.mjs`, config); ort.env.wasm.wasmPaths = { mjs: mjsPath, wasm: wasmPath }; if (config.debug) { console.debug('ort.env.wasm:', ort.env.wasm); } const ortConfig: InferenceSession.SessionOptions = { executionProviders: executionProviders, graphOptimizationLevel: 'all', executionMode: 'parallel', enableCpuMemArena: true }; const session = await ort.InferenceSession.create(model, ortConfig).catch( (e: any) => { throw new Error( `Failed to create session: "${e}". Please check if the publicPath is set correctly.` ); } ); return session; } async function runOnnxSession( session: any, inputs: [string, NdArray][], outputs: [string], config: Config ) { const useWebGPU = config.device === 'gpu' && (await caps.webgpu()); const ort = await getOrt(useWebGPU); const feeds: Record = {}; for (const [key, tensor] of inputs) { feeds[key] = new ort.Tensor( 'float32', new Float32Array(tensor.data), tensor.shape ); } const outputData = await session.run(feeds, {}); const outputKVPairs: NdArray[] = []; for (const key of outputs) { const output: Tensor = outputData[key]; const shape: number[] = output.dims as number[]; const data: Float32Array = output.data as Float32Array; const tensor = ndarray(data, shape); outputKVPairs.push(tensor); } return outputKVPairs; } ================================================ FILE: packages/web/src/resource.ts ================================================ export { loadAsBlob, loadAsUrl, loadAsArrayBuffer, preload, resolveChunkUrls }; import { Config } from './schema'; async function preload(config: Config): Promise { // load resource metadata const resourceUrl = new URL('resources.json', config.publicPath); const resourceResponse = await fetch(resourceUrl); if (!resourceResponse.ok) { throw new Error( `Resource metadata not found. Ensure that the config.publicPath is configured correctly: ${config.publicPath}` ); } const resourceMap = await resourceResponse.json(); const keys = Object.keys(resourceMap); await Promise.all( keys.map(async (key) => { return loadAsBlob(key, config); }) ); } async function loadAsUrl(url: string, config: Config): Promise { return URL.createObjectURL(await loadAsBlob(url, config)); } async function loadAsArrayBuffer( url: string, config: Config ): Promise { return await (await loadAsBlob(url, config)).arrayBuffer(); } async function loadAsBlob(key: string, config: Config) { // load resource metadata const resourceUrl = new URL('resources.json', config.publicPath); const resourceResponse = await fetch(resourceUrl); if (!resourceResponse.ok) { throw new Error( `Resource metadata not found. Ensure that the config.publicPath is configured correctly.` ); } const resourceMap = await resourceResponse.json(); const entry = resourceMap[key]; if (!entry) { throw new Error( `Resource ${key} not found. Ensure that the config.publicPath is configured correctly.` ); } const chunks = entry.chunks; // list of entries let downloadedSize = 0; const responses = chunks.map(async (chunk) => { const chunkSize = chunk.offsets[1] - chunk.offsets[0]; const url = config.publicPath ? new URL(chunk.name, config.publicPath).toString() : chunk.name; const response = await fetch(url, config.fetchArgs); const blob = await response.blob(); if (chunkSize !== blob.size) { throw new Error( `Failed to fetch ${key} with size ${chunkSize} but got ${blob.size}` ); } if (config.progress) { downloadedSize += chunkSize; config.progress(`fetch:${key}`, downloadedSize, entry.size); } return blob; }); // we could create a new buffer here and use the chunk entries and combine the file instead const allChunkData = await Promise.all(responses); const data = new Blob(allChunkData, { type: entry.mime }); if (data.size !== entry.size) { throw new Error( `Failed to fetch ${key} with size ${entry.size} but got ${data.size}` ); } return data; } async function resolveChunkUrls(key: string, config: Config) { // load resource metadata const resourceUrl = new URL('resources.json', config.publicPath); const resourceResponse = await fetch(resourceUrl); if (!resourceResponse.ok) { throw new Error( `Resource metadata not found. Ensure that the config.publicPath is configured correctly.` ); } const resourceMap = await resourceResponse.json(); const entry = resourceMap[key]; if (!entry) { throw new Error( `Resource ${key} not found. Ensure that the config.publicPath is configured correctly.` ); } const chunks = entry.chunks; // list of entries const responses = chunks.map(async (chunk) => { const url = config.publicPath ? new URL(chunk.name, config.publicPath).toString() : chunk.name; return url; }); // we could create a new buffer here and use the chunk entries and combine the file instead const allUrls = await Promise.all(responses); return allUrls; } ================================================ FILE: packages/web/src/schema.ts ================================================ export { Config, ConfigSchema, validateConfig }; import { z } from 'zod'; import pkg from '../package.json'; const ConfigSchema = z .object({ publicPath: z .string() .optional() .describe('The public path to the wasm files and the onnx model.') .default( 'https://staticimgly.com/@imgly/background-removal-data/${PACKAGE_VERSION}/dist/' ) .transform((val) => { return val .replace('${PACKAGE_NAME}', pkg.name) .replace('${PACKAGE_VERSION}', pkg.version); }), debug: z .boolean() .default(false) .describe('Whether to enable debug logging.'), rescale: z .boolean() .default(true) .describe('Whether to rescale the image.'), device: z .enum(['cpu', 'gpu']) .default('cpu') .describe('The device to run the model on.'), proxyToWorker: z .boolean() .default(false) .describe('Whether to proxy inference to a web worker.'), fetchArgs: z .any() .default({}) .describe('Arguments to pass to fetch when loading the model.'), progress: z .function() .args(z.string(), z.number(), z.number()) .returns(z.void()) .describe('Progress callback.') .optional(), model: z .preprocess( (val) => { switch (val) { case 'large': return 'isnet'; case 'small': return 'isnet_quint8'; case 'medium': return 'isnet_fp16'; default: return val; } }, z.enum(['isnet', 'isnet_fp16', 'isnet_quint8']) ) .default('medium'), output: z .object({ format: z .enum([ 'image/png', 'image/jpeg', 'image/webp', 'image/x-rgba8', 'image/x-alpha8' ]) .default('image/png'), quality: z.number().default(0.8) }) .default({}) }) .default({}) .transform((config) => { if (config.debug) console.log('Config:', config); if (config.debug && !config.progress) { config.progress = config.progress ?? ((key, current, total) => { console.debug(`Downloading ${key}: ${current} of ${total}`); }); if (!crossOriginIsolated) { if (config.debug) console.debug( 'Cross-Origin-Isolated is not enabled. Performance will be degraded. Please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer.' ); } } return config; }); type Config = z.infer; function validateConfig(configuration?: Config): Config { return ConfigSchema.parse(configuration ?? {}); } ================================================ FILE: packages/web/src/types.d.ts ================================================ interface Navigator { gpu: any; } ================================================ FILE: packages/web/src/url.ts ================================================ export { isAbsoluteURI, ensureAbsoluteURI }; function isAbsoluteURI(url: string): boolean { const regExp = new RegExp('^(?:[a-z+]+:)?//', 'i'); return regExp.test(url); // true - regular http absolute URL } const isNode = typeof window === 'undefined'; const isBrowser = typeof window !== 'undefined'; function ensureAbsoluteURI(url: string, baseUrl: string): string { if (isAbsoluteURI(url)) { return url; } else { return new URL(url, baseUrl).href; } } ================================================ FILE: packages/web/src/utils.ts ================================================ export { imageDecode, imageEncode, tensorResizeBilinear, tensorHWCtoBCHW, imageBitmapToImageData, imageSourceToImageData, type ImageSource, createCanvas }; import ndarray, { NdArray, TypedArray } from 'ndarray'; import { imageDecode, imageEncode } from './codecs'; import { ensureAbsoluteURI } from './url'; import { Config } from './schema'; type ImageSource = | ImageData | ArrayBuffer | Uint8Array | Blob | URL | string | NdArray; function imageBitmapToImageData(imageBitmap: ImageBitmap): ImageData { var canvas = createCanvas(imageBitmap.width, imageBitmap.height); var ctx = canvas.getContext('2d')!; ctx.drawImage(imageBitmap, 0, 0); return ctx.getImageData(0, 0, canvas.width, canvas.height); } function createTypeArray(length: number) { if (typeof Uint8Array !== 'undefined') { return new Uint8Array(length) as T; } else if (typeof Uint8ClampedArray !== 'undefined') { return new Uint8ClampedArray(length) as T; } else if (typeof Uint16Array !== 'undefined') { return new Uint16Array(length) as T; } else if (typeof Uint32Array !== 'undefined') { return new Uint32Array(length) as T; } else if (typeof Float32Array !== 'undefined') { return new Float32Array(length) as T; } else if (typeof Float64Array !== 'undefined') { return new Float64Array(length) as T; } else { throw new Error('TypedArray not supported'); } } function tensorResizeBilinear( imageTensor: NdArray, newWidth: number, newHeight: number, proportional: boolean = false ): NdArray { const [srcHeight, srcWidth, srcChannels] = imageTensor.shape; let scaleX = srcWidth / newWidth; let scaleY = srcHeight / newHeight; if (proportional) { const downscaling = Math.max(scaleX, scaleY) > 1.0; scaleX = scaleY = downscaling ? Math.max(scaleX, scaleY) : Math.min(scaleX, scaleY); } // Create a new NdArray to store the resized image const resizedImageData = ndarray( createTypeArray(srcChannels * newWidth * newHeight), [newHeight, newWidth, srcChannels] ); // Perform interpolation to fill the resized NdArray for (let y = 0; y < newHeight; y++) { for (let x = 0; x < newWidth; x++) { const srcX = x * scaleX; const srcY = y * scaleY; const x1 = Math.max(Math.floor(srcX), 0); const x2 = Math.min(Math.ceil(srcX), srcWidth - 1); const y1 = Math.max(Math.floor(srcY), 0); const y2 = Math.min(Math.ceil(srcY), srcHeight - 1); const dx = srcX - x1; const dy = srcY - y1; for (let c = 0; c < srcChannels; c++) { const p1 = imageTensor.get(y1, x1, c); const p2 = imageTensor.get(y1, x2, c); const p3 = imageTensor.get(y2, x1, c); const p4 = imageTensor.get(y2, x2, c); // Perform bilinear interpolation const interpolatedValue = (1 - dx) * (1 - dy) * p1 + dx * (1 - dy) * p2 + (1 - dx) * dy * p3 + dx * dy * p4; // console.log(interpolatedValue); resizedImageData.set(y, x, c, interpolatedValue); } } } return resizedImageData; } function tensorHWCtoBCHW( imageTensor: NdArray, mean: number[] = [128, 128, 128], std: number[] = [256, 256, 256] ): NdArray { var imageBufferData = imageTensor.data; const [srcHeight, srcWidth, srcChannels] = imageTensor.shape; const stride = srcHeight * srcWidth; const float32Data = new Float32Array(3 * stride); // r_0, r_1, .... g_0,g_1, .... b_0 for (let i = 0, j = 0; i < imageBufferData.length; i += 4, j += 1) { float32Data[j] = (imageBufferData[i] - mean[0]) / std[0]; float32Data[j + stride] = (imageBufferData[i + 1] - mean[1]) / std[1]; float32Data[j + stride + stride] = (imageBufferData[i + 2] - mean[2]) / std[2]; } return ndarray(float32Data, [1, 3, srcHeight, srcWidth]); } async function imageSourceToImageData( image: ImageSource, config: Config ): Promise> { if (typeof image === 'string') { image = ensureAbsoluteURI(image, config.publicPath); image = new URL(image); } if (image instanceof URL) { const response = await fetch(image, {}); image = await response.blob(); } if (image instanceof ArrayBuffer || ArrayBuffer.isView(image)) { image = new Blob([image]); } if (image instanceof Blob) { image = await imageDecode(image); } return image as NdArray; } export function convertFloat32ToUint8( float32Array: NdArray ): NdArray { const uint8Array = new Uint8Array(float32Array.data.length); for (let i = 0; i < float32Array.data.length; i++) { uint8Array[i] = float32Array.data[i] * 255; } return ndarray(uint8Array, float32Array.shape); } function createCanvas(width, height) { let canvas = undefined; if (typeof OffscreenCanvas !== 'undefined') { canvas = new OffscreenCanvas(width, height); } else { canvas = document.createElement('canvas'); } if (!canvas) { throw new Error( `Canvas nor OffscreenCanvas are available in the current context.` ); } return canvas; } ================================================ FILE: packages/web/tsconfig.json ================================================ { "compilerOptions": { "lib": ["DOM", "ESNext"], "resolveJsonModule": true, "esModuleInterop": true, "emitDeclarationOnly": true, "declaration": true, "allowJs": true, "target": "ES6", "moduleResolution": "bundler", "module": "es2020" } } ================================================ FILE: packages/web-data/.resources.mjs ================================================ export default [ { path: '/onnxruntime-web/', source: '../../node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm', mime: 'application/wasm' }, { path: '/onnxruntime-web/', source: '../../node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.wasm', mime: 'application/wasm' }, { path: '/onnxruntime-web/', source: '../../node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.mjs', mime: 'text/javascript' }, { path: '/onnxruntime-web/', source: '../../node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.mjs', mime: 'text/javascript' }, { path: '/models/', source: '../../bundle/models/*', mime: 'application/octet-steam' } ]; ================================================ FILE: packages/web-data/LICENSE.md ================================================ # GNU Affero General Public License _Version 3, 19 November 2007_ _Copyright © 2007 Free Software Foundation, Inc. <>_ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. ## Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: **(1)** assert copyright on the software, and **(2)** offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. ## TERMS AND CONDITIONS ### 0. Definitions “This License” refers to version 3 of the GNU Affero General Public License. “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. A “covered work” means either the unmodified Program or a work based on the Program. To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that **(1)** displays an appropriate copyright notice, and **(2)** tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. ### 1. Source Code The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The “System Libraries” of an executable work include anything, other than the work as a whole, that **(a)** is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and **(b)** serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. ### 2. Basic Permissions All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. ### 4. Conveying Verbatim Copies You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. ### 5. Conveying Modified Source Versions You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: - **a)** The work must carry prominent notices stating that you modified it, and giving a relevant date. - **b)** The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. - **c)** You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. - **d)** If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. ### 6. Conveying Non-Source Forms You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - **a)** Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. - **b)** Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either **(1)** a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or **(2)** access to copy the Corresponding Source from a network server at no charge. - **c)** Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. - **d)** Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. - **e)** Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A “User Product” is either **(1)** a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or **(2)** anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. ### 7. Additional Terms “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - **a)** Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or - **b)** Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or - **c)** Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or - **d)** Limiting the use for publicity purposes of names of licensors or authors of the material; or - **e)** Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or - **f)** Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. ### 8. Termination You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated **(a)** provisionally, unless and until the copyright holder explicitly and finally terminates your license, and **(b)** permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. ### 9. Acceptance Not Required for Having Copies You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. ### 10. Automatic Licensing of Downstream Recipients Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. ### 11. Patents A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either **(1)** cause the Corresponding Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the patent license for this particular work, or **(3)** arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license **(a)** in connection with copies of the covered work conveyed by you (or copies made from those copies), or **(b)** primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. ### 12. No Surrender of Others' Freedom If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. ### 13. Remote Network Interaction; Use with the GNU General Public License Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. ### 14. Revised Versions of this License The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. ### 15. Disclaimer of Warranty THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. ### 16. Limitation of Liability IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. ### 17. Interpretation of Sections 15 and 16 If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. _END OF TERMS AND CONDITIONS_ ## How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a “Source” link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <>. ================================================ FILE: packages/web-data/ThirdPartyLicenses.json ================================================ { "onnxruntime-web": { "source": "https://www.npmjs.com/package/onnxruntime-web", "type": "code", "license": "MIT" }, "ISNET": { "source": "https://github.com/xuebinqin/DIS", "type": "model", "license": "MIT" } } ================================================ FILE: packages/web-data/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml ================================================ --- type: Added # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Added ThirdPartyLicenses.json ================================================ FILE: packages/web-data/changelog/1.5.6/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml ================================================ --- type: Changed # type: Added # type: Changed # type: Removed # type: Security # private: true description: | Upgrade onnx-runtime ================================================ FILE: packages/web-data/package.json ================================================ { "name": "@imgly/background-removal-data", "version": "1.7.0", "description": "Background Removal Data", "keywords": [ "background-removal", "image-segmentation", "image-matting", "onnx" ], "repository": { "type": "git", "url": "git+https://github.com/imgly/background-removal-js.git" }, "license": "SEE LICENSE IN LICENSE.md", "author": { "name": "IMG.LY GmbH", "email": "support@img.ly", "url": "https://img.ly" }, "bugs": { "email": "support@img.ly" }, "homepage": "https://img.ly/showcases/cesdk/web/background-removal", "files": [ "LICENSE.md", "README.md", "CHANGELOG.md", "NOTICE.md", "ThirdPartyLicenses.json", "dist/", "bin/" ], "scripts": { "start": "pnpm run watch", "serve": "npx http-server dist --cors", "clean": "npx rimraf dist", "test": "true", "resources": "node ../../scripts/package-resources.mjs", "changelog:create": "node ../../scripts/changelog/changelog-create.mjs", "changelog:generate": "node ../../scripts/changelog/changelog-generate.mjs", "build": "pnpm run clean && pnpm run resources", "watch": "pnpm run clean && pnpm run resources", "publish:latest": "pnpm publish --tag latest --access public", "publish:next": "pnpm publish --tag next --access public", "package:pack": "pnpm pack . --pack-destination ../../releases" }, "dependencies": { "onnxruntime-web": "1.21.0-dev.20250206-d981b153d3" } } ================================================ FILE: packages/web-examples/next-example/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* .pnpm-debug.log* # env files (can opt-in for committing if needed) .env* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: packages/web-examples/next-example/README.md ================================================ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ================================================ FILE: packages/web-examples/next-example/eslint.config.mjs ================================================ import { dirname } from 'path'; import { fileURLToPath } from 'url'; import { FlatCompat } from '@eslint/eslintrc'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const compat = new FlatCompat({ baseDirectory: __dirname }); const eslintConfig = [ ...compat.extends('next/core-web-vitals', 'next/typescript') ]; export default eslintConfig; ================================================ FILE: packages/web-examples/next-example/next.config.ts ================================================ import type { NextConfig } from 'next'; const nextConfig: NextConfig = { /* config options here */ }; export default nextConfig; ================================================ FILE: packages/web-examples/next-example/package.json ================================================ { "name": "next-example", "version": "1.7.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "check:all": "next lint" }, "dependencies": { "@cesdk/cesdk-js": "^1.41.1", "next": "15.1.3", "react": "^19.0.0", "react-dom": "^19.0.0", "@imgly/background-removal": "workspace:*", "onnxruntime-web": "1.21.0" }, "devDependencies": { "@eslint/eslintrc": "^3", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", "eslint": "^9", "eslint-config-next": "15.1.3", "typescript": "^5" } } ================================================ FILE: packages/web-examples/next-example/src/app/BackgroundRemoval.tsx ================================================ 'use client'; import { applySegmentationMask, Config, preload, removeBackground, segmentForeground } from '@imgly/background-removal'; import { useEffect, useRef, useState } from 'react'; const images = [ 'https://images.unsplash.com/photo-1656408308602-05835d990fb1?q=80&w=3200&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D', 'https://images.unsplash.com/photo-1686002359940-6a51b0d64f68?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1024&q=80', 'https://images.unsplash.com/photo-1590523278191-995cbcda646b?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9', 'https://images.unsplash.com/photo-1709248835088-03bb0946d6ab?q=80&w=3387&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D' ]; const BackgroundRemoval = () => { const [imageUrl, setImageUrl] = useState(''); const [isRunning, setIsRunning] = useState(false); const [seconds, setSeconds] = useState('0'); const [startDate, setStartDate] = useState(Date.now()); const [caption, setCaption] = useState('Click me to remove background'); const intervalRef = useRef | null>(null); const config: Config = { debug: false, progress: (key, current, total) => { const [type, subtype] = key.split(':'); setCaption(`${type} ${subtype} ${((current / total) * 100).toFixed(0)}%`); }, rescale: true, device: 'gpu', output: { quality: 0.8, format: 'image/png' } }; const calculateSecondsBetweenDates = (start: number, end: number) => { const milliseconds = end - start; return (milliseconds / 1000.0).toFixed(1); }; useEffect(() => { const url = new URL(window.location.href); const params = new URLSearchParams(url.search); const imageParam = params.get('image'); const auto = params.get('auto') || false; const randomImage = imageParam || images[Math.floor(Math.random() * images.length)]; setImageUrl(randomImage); const preloadAssets = async () => { try { await preload(config); console.log('Asset preloading succeeded'); if (auto) load('remove'); } catch (error) { console.error('Asset preloading failed:', error); } }; preloadAssets(); return () => { if (intervalRef.current) { clearInterval(intervalRef.current); } }; }, []); useEffect(() => { if (isRunning) { intervalRef.current = setInterval(() => { setSeconds(calculateSecondsBetweenDates(startDate, Date.now())); }, 100); } else if (intervalRef.current) { clearInterval(intervalRef.current); } return () => { if (intervalRef.current) { clearInterval(intervalRef.current); } }; }, [isRunning, startDate]); const resetTimer = () => { setIsRunning(true); setStartDate(Date.now()); setSeconds('0'); }; const stopTimer = () => { setIsRunning(false); }; const load = async (type: string) => { const params = new URLSearchParams(window.location.search); const imageParam = params.get('image'); const randomImage = imageParam || images[Math.floor(Math.random() * images.length)]; setIsRunning(true); resetTimer(); setImageUrl(randomImage); try { let imageBlob; if (type === 'remove') { imageBlob = await removeBackground(randomImage, config); } else { const maskBlob = await segmentForeground(randomImage, config); imageBlob = await applySegmentationMask(randomImage, maskBlob, config); } const url = URL.createObjectURL(imageBlob); setImageUrl(url); } catch (error) { console.error('Processing failed:', error); setCaption('Processing failed'); } finally { setIsRunning(false); stopTimer(); } }; return (
{/* // eslint-disable-next-line @next/next/no-img-element */} {imageUrl && logo}

{caption}

Processing: {seconds} s

); }; export default BackgroundRemoval; ================================================ FILE: packages/web-examples/next-example/src/app/BackgroundRemovalNoSSR.tsx ================================================ 'use client'; import dynamic from 'next/dynamic'; const BackgroundRemovalNoSSR = dynamic(() => import('./BackgroundRemoval'), { ssr: false }); export default BackgroundRemovalNoSSR; ================================================ FILE: packages/web-examples/next-example/src/app/globals.css ================================================ :root { --background: #ffffff; --foreground: #171717; } @media (prefers-color-scheme: dark) { :root { --background: #0a0a0a; --foreground: #ededed; } } html, body { max-width: 100vw; overflow-x: hidden; } body { color: var(--foreground); background: var(--background); font-family: Arial, Helvetica, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } * { box-sizing: border-box; padding: 0; margin: 0; } a { color: inherit; text-decoration: none; } @media (prefers-color-scheme: dark) { html { color-scheme: dark; } } a { font-weight: 500; color: #646cff; text-decoration: inherit; } a:hover { color: #535bf2; } img { max-height: 60vh; } body { margin: 0; display: flex; place-items: center; /* min-width: 320px; */ /* max-height: 1vh; */ } h1 { font-size: 3.2em; line-height: 1.1; } button { border-radius: 8px; border: 1px solid transparent; padding: 0.6em 1.2em; font-size: 1em; font-weight: 500; font-family: inherit; background-color: #1a1a1a; cursor: pointer; transition: border-color 0.25s; } button:hover { border-color: #646cff; } button:focus, button:focus-visible { outline: 4px auto -webkit-focus-ring-color; } .card { padding: 2em; } #app { margin: 0 auto; padding: 2rem; text-align: center; } @media (prefers-color-scheme: light) { :root { color: #213547; background-color: #ffffff; } a:hover { color: #747bff; } button { background-color: #f9f9f9; } } ================================================ FILE: packages/web-examples/next-example/src/app/layout.tsx ================================================ import type { Metadata } from 'next'; import './globals.css'; export const metadata: Metadata = { title: 'Create Next App', description: 'Generated by create next app' }; export default function RootLayout({ children }: Readonly<{ children: React.ReactNode; }>) { return ( {children} ); } ================================================ FILE: packages/web-examples/next-example/src/app/page.tsx ================================================ import BackgroundRemovalNoSSR from './BackgroundRemovalNoSSR'; export default function Home() { return ; } ================================================ FILE: packages/web-examples/next-example/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./src/*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] } ================================================ FILE: packages/web-examples/vite-project/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: packages/web-examples/vite-project/.vercel/README.txt ================================================ > Why do I have a folder named ".vercel" in my project? The ".vercel" folder is created when you link a directory to a Vercel project. > What does the "project.json" file contain? The "project.json" file contains: - The ID of the Vercel project that you linked ("projectId") - The ID of the user or team your Vercel project is owned by ("orgId") > Should I commit the ".vercel" folder? No, you should not share the ".vercel" folder with anyone. Upon creation, it will be automatically added to your ".gitignore" file. ================================================ FILE: packages/web-examples/vite-project/.vercel/project.json ================================================ { "orgId": "team_JFznad5UXNe4xKmEfdbZq5jl", "projectId": "prj_jLTn0qO7rU5v6MEyaNREE9gIk3l2" } ================================================ FILE: packages/web-examples/vite-project/README.md ================================================ # Vue 3 + TypeScript + Vite This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 ` ================================================ FILE: packages/web-examples/vite-project/package.json ================================================ { "name": "vite-project", "private": true, "version": "1.7.0", "type": "module", "scripts": { "start": "pnpm run dev", "dev": "vite", "build": "vue-tsc && vite build", "preview": "vite preview" }, "dependencies": { "@imgly/background-removal": "workspace:*", "@imgly/background-removal-data": "workspace:*", "vue": "^3.2.47", "onnxruntime-web": "1.21.0" }, "devDependencies": { "@vitejs/plugin-vue": "^4.1.0", "typescript": "^5.0.2", "vite": "^4.3.9", "vue-tsc": "^1.4.2" } } ================================================ FILE: packages/web-examples/vite-project/src/App.vue ================================================ ================================================ FILE: packages/web-examples/vite-project/src/main.ts ================================================ import { createApp } from 'vue'; import './style.css'; import App from './App.vue'; createApp(App).mount('#app'); ================================================ FILE: packages/web-examples/vite-project/src/style.css ================================================ :root { font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; line-height: 1.5; font-weight: 400; color-scheme: light dark; color: rgba(255, 255, 255, 0.87); background-color: #242424; font-synthesis: none; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } a { font-weight: 500; color: #646cff; text-decoration: inherit; } a:hover { color: #535bf2; } img { max-height: 60vh; } body { margin: 0; display: flex; place-items: center; /* min-width: 320px; */ /* max-height: 1vh; */ } h1 { font-size: 3.2em; line-height: 1.1; } button { border-radius: 8px; border: 1px solid transparent; padding: 0.6em 1.2em; font-size: 1em; font-weight: 500; font-family: inherit; background-color: #1a1a1a; cursor: pointer; transition: border-color 0.25s; } button:hover { border-color: #646cff; } button:focus, button:focus-visible { outline: 4px auto -webkit-focus-ring-color; } .card { padding: 2em; } #app { margin: 0 auto; padding: 2rem; text-align: center; } @media (prefers-color-scheme: light) { :root { color: #213547; background-color: #ffffff; } a:hover { color: #747bff; } button { background-color: #f9f9f9; } } ================================================ FILE: packages/web-examples/vite-project/src/vite-env.d.ts ================================================ /// ================================================ FILE: packages/web-examples/vite-project/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "module": "ESNext", "lib": ["ES2020", "DOM", "DOM.Iterable"], "skipLibCheck": true, "allowJs": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "preserve", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: packages/web-examples/vite-project/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts"] } ================================================ FILE: packages/web-examples/vite-project/vite.config.ts ================================================ import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], server: { headers: { 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp' } } }); ================================================ FILE: pnpm-workspace.yaml ================================================ packages: - packages/* - packages/web-examples/* onlyBuiltDependencies: - esbuild - onnxruntime-node - protobufjs - sharp ================================================ FILE: scripts/changelog/changelog-create.mjs ================================================ #!/usr/bin/env node import moment from 'moment'; import ejs from 'ejs'; import meow from 'meow'; import chalk from 'chalk'; import esMain from 'es-main'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { dirname } from 'node:path'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const AllowedTypes = ['Added', 'Changed', 'Removed', 'Security']; const scriptName = process.argv[1].split(path.sep).pop(); const flags = { message: { type: 'string', shortFlag: 'm', isMultiple: false, description: 'Message for the changelog entry' }, version: { type: 'boolean', shortFlag: 'v', isMultiple: false, description: 'Show version number' }, help: { type: 'boolean', shortFlag: 'h', isMultiple: false, description: 'Display this help message' }, type: { type: 'string', shortFlag: 't', default: 'Added', isMultiple: false, choices: ['Added', 'Changed', 'Removed', 'Security'], description: `Type of the changelog entry` } }; const examples = [ { prompt: `name` }, { prompt: `name --message "Message"` }, { prompt: `name --type "Added"` }, { prompt: `name --help` }, { prompt: `name --version` } ]; function parseStringToArgs(str) { return str.match(/(?:[^\s"]+|"[^"]*")+/g); } function parseExample(prompt) { const args = parseStringToArgs(prompt); const parser = meow('', { argv: args, importMeta: import.meta, flags }); } function parsePrompt(prompt, flags) { // how do I parse the prompt const inputArgs = prompt instanceof Array ? prompt : parseStringToArgs(prompt); const flagText = (str) => chalk.yellow(str); const exampleText = (str) => chalk.white(str); const cliOptionsText = (flags, padding = 16) => { const lines = []; for (const [key, value] of Object.entries(flags)) { const { type, shortFlag, description, default: defaultValue, choices } = value; const defaultText = defaultValue ? chalk.white(` (default: ${defaultValue})`) : ''; const choicesText = choices ? chalk.white(` [choices: ${choices.join(', ')}]`) : ''; lines.push( `${flagText( `--${key}, -${shortFlag}`.padEnd(padding) )} ${description}${defaultText}${choicesText}` ); } return lines.join('\n '); }; const cliUsageText = (flags) => { const lines = []; for (const [key, value] of Object.entries(flags)) { const { type, shortFlag, description, default: defaultValue } = value; const valueStr = type === 'string' ? `=<${key}>` : ''; const flagStr = `[${flagText( `--${key}${valueStr} | -${shortFlag}${valueStr}` )}]`; lines.push(flagStr); } return lines.join(' '); }; const cli = meow( ` Usage $ ${chalk.white(scriptName)} name ${cliUsageText(flags)} Options ${cliOptionsText(flags)} Examples $ ${exampleText(scriptName)} name $ ${exampleText(scriptName)} name ${flagText('--message')} "Message" $ ${exampleText(scriptName)} ${flagText('--message')} "Message" $ ${exampleText(scriptName)} ${flagText('--type')} "Added" $ ${exampleText(scriptName)} ${flagText('--help')} $ ${exampleText(scriptName)} ${flagText('--version')} `, { argv: inputArgs.slice(2), importMeta: import.meta, flags } ); if (!flags.type.choices.includes(cli.flags.type)) { console.error(`Invalid type: ${cli.flags.type}`); console.error(`Allowed types are: ${flags.type.choices.join(', ')}`); cli.showHelp(); process.exit(1); } return cli; } function main(argv) { try { const cli = parsePrompt(argv, flags); if (cli.flags.help) { cli.showHelp(); process.exit(); } if (cli.flags.version) { console.log('1.0.0'); process.exit(); } const version = 'Unreleased'; const type = cli.flags.type; const templatePath = path.resolve(__dirname, 'template.yml.ejs'); const changeLogDir = path.resolve('./changelog', `${version}`); const input = cli.input.join(' '); if (!input || input.length === 0) { cli.showHelp(); process.exit(); } const message = cli.flags.message || cli.input.join(' '); const name = cli.input.join(' ').replace(/(\W+)/gi, '_'); const dateFormat = 'YYYYDDMMHHmmss'; const date = Date.now(); const prefix = moment(date).format(dateFormat); const filename = `${prefix}-${name}.yaml`; const outFilePath = path.resolve(changeLogDir, filename); fs.mkdirSync(changeLogDir, { recursive: true }); const template = fs.readFileSync(templatePath, 'utf-8'); const data = { message, type }; const renderedTemplate = ejs.render(template, data); fs.writeFileSync(outFilePath, renderedTemplate); console.info(`${chalk.grey(outFilePath)} has been created successfully.`); } catch (error) { console.error(chalk.red(error.message)); process.exit(1); } } if (esMain(import.meta)) { main(process.argv); } export { main }; ================================================ FILE: scripts/changelog/changelog-generate.mjs ================================================ #!/usr/bin/env node /** * https://keepachangelog.com/en/1.1.0/ * Idea is simple we have a directory of yaml files. The subdirectory defines the version name. */ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { dirname } from 'node:path'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); import yaml from 'yaml'; const types = ['Infos', 'Added', 'Fixed', 'Removed', 'Changed', 'Security']; const changeLogDir = path.resolve('./changelog'); const enumerateFilesInDirectory = (dir) => { return fs .readdirSync(dir) .map((entry) => { const fullPath = path.join(dir, entry); const stat = fs.statSync(fullPath); if (stat.isFile()) { return fullPath; } return null; }) .filter((entry) => entry !== null); }; const enumerateDirectoriesInDirectory = (dir) => { return fs .readdirSync(dir) .map((entry) => { const fullPath = path.join(dir, entry); const stat = fs.statSync(fullPath); if (stat.isDirectory()) { return entry; } return null; }) .filter((entry) => entry !== null); }; function parseChangelogItems(entries) { const changelog = {}; entries.forEach((entry) => { const fileContent = fs.readFileSync(entry, 'utf8'); const changelogItems = yaml.parseAllDocuments(fileContent); changelogItems.forEach((document) => { const changelogItem = document.toJS(); const { type = 'Infos', description } = changelogItem; if (changelogItem.private) return; if (!(type in changelog)) { changelog[type] = []; } const message = `${description}`; changelog[type].push(message); }); }); return changelog; } // Write file const outFile = path.resolve('./CHANGELOG.md'); const outStream = fs.createWriteStream(outFile, { encoding: 'utf8' }); // Root entries const entries = enumerateFilesInDirectory(changeLogDir); const changelogItems = parseChangelogItems(entries); outStream.write(`# Changelog\n\n`); changelogItems['Infos']?.forEach((info) => { outStream.write(`${info}\n`); }); const versionSorter = (a, b) => { return a < b ? +1 : -1; }; const versions = enumerateDirectoriesInDirectory(changeLogDir) .map((directory) => path.basename(directory)) .sort(versionSorter); versions.forEach((version) => { const versionDir = path.join(changeLogDir, version); const entries = enumerateFilesInDirectory(versionDir); const changelogItems = parseChangelogItems(entries); const hasItems = Object.keys(changelogItems).length > 0; hasItems && outStream.write(`## [${version}]\n\n`); types.forEach((type) => { if (changelogItems[type]) { const messages = changelogItems[type]; if (type === 'Infos') { messages.forEach((message) => { outStream.write(`${message}\n`); }); } else { outStream.write(`### ${type}\n\n`); messages.forEach((message) => { outStream.write(`- ${message}\n`); }); } // outStream.write(`\n`) } }); }); outStream.end(); ================================================ FILE: scripts/changelog/template.yml.ejs ================================================ --- type: <%= type %> # type: Added # type: Changed # type: Removed # type: Security # private: true description: | <%= message %> ================================================ FILE: scripts/deploy-assets.mjs ================================================ import chalk from 'chalk'; import { exec } from 'child_process'; import { readFile } from 'node:fs/promises'; import { promisify } from 'util'; const execAsync = promisify(exec); const execAsyncWithErrors = async (command, options) => { try { const { stdout, stderr } = await execAsync(command, options); } catch (error) { throw error; } }; async function syncToS3() { try { // Load package.json const packageJson = JSON.parse(await readFile('./package.json', 'utf8')); const version = process.argv[2] || packageJson.version; if (!version || version === 'next') { throw new Error(`Version "${version}" is invalid.`); } // Get the endpoint URL from an environment variable const endpointUrl = process.env.S3_ENDPOINT_URL; if (!endpointUrl) { throw new Error('S3_ENDPOINT_URL environment variable is not set.'); } const bucketName = process.env.S3_BUCKET_NAME; if (!bucketName) { throw new Error('S3_BUCKET_NAME environment variable is not set.'); } const packageNames = { 'packages/node': '@imgly/background-removal-node', 'packages/web': '@imgly/background-removal', 'packages/web-data': '@imgly/background-removal-data' }; await Promise.allSettled( Object.entries(packageNames).map(async ([path, packageName]) => { console.error( `${chalk.red( `NOTE: Syncing might fail when aws client ist not installed nor configured in silence!` )}` ); // cwd based on package name: const cwd = path; // npm packing: await execAsyncWithErrors( `rm -rf ./${path}/tmp && mkdir -p ./${path}/tmp` ); // we pack the package to also publish the package.tgz to s3 const packCommand = `npm pack . --pack-destination ./tmp`; console.log(`Packing ${packageName} using ${packCommand}...`); await execAsyncWithErrors(packCommand, { cwd }); // rename the .tgz from e.g imgly-background-removal-data-1.5.3.tgz to package.tgz to have a stable name await execAsyncWithErrors('mv ./tmp/*.tgz ./tmp/package.tgz', { cwd }); // npm extract: const extractCommand = `tar -xvzf ./tmp/* -C ./tmp --strip-components=1`; console.log(`Extracting ${packageName} using ${extractCommand}...`); await execAsyncWithErrors(extractCommand, { cwd }); // sync to s3: console.log(`Syncing ${packageName} to S3...`); const command = `aws s3 sync --endpoint-url ${endpointUrl} ./${path}/tmp s3://${bucketName}/${packageName}/${version}`; console.log(`Command: ${command}`); return await execAsyncWithErrors(command); }) ); console.log('S3 sync complete.'); } catch (error) { console.error('Error during S3 sync:', error); } } syncToS3(); ================================================ FILE: scripts/package-resources.mjs ================================================ export default main; import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { globSync } from 'glob'; // All paths are relative to the directory of this file const BaseDir = path.resolve('.'); const DefaultOutDir = path.resolve('./dist'); const DefaultEntry = { mime: 'application/octet-stream' }; async function calculateSHA256(filePath) { return new Promise((resolve, reject) => { const hash = crypto.createHash('sha256'); const stream = fs.createReadStream(filePath); stream.on('data', (data) => hash.update(data)); stream.on('end', () => resolve(hash.digest('hex'))); stream.on('error', (error) => reject(error)); }); } async function copyFile(sourcePath, destinationPath) { return new Promise((resolve, reject) => { const readStream = fs.createReadStream(sourcePath); const writeStream = fs.createWriteStream(destinationPath); readStream.on('error', (error) => reject(error)); writeStream.on('error', (error) => reject(error)); writeStream.on('finish', () => resolve()); readStream.pipe(writeStream); }); } async function linkFile(sourcePath, destinationPath) { return new Promise((resolve, reject) => { fs.symlink(sourcePath, destinationPath, (error) => { if (error) { reject(error); } else { resolve(); } }); }); } async function deleteFile(filePath) { return new Promise((resolve, reject) => { fs.unlink(filePath, (error) => { if (error) { if (error.code === 'ENOENT') { // File doesn't exist, resolve without an error. resolve(); } else { // Other error occurred, reject with the error. reject(error); } } else { // File deleted successfully. resolve(); } }); }); } function isFileHidden(filePath) { const fileName = path.basename(filePath); return fileName.startsWith('.'); // || isHiddenOnWindows(filePath); } async function listAllFiles(dir) { return new Promise((resolve, reject) => { const allFiles = []; function traverse(currentDir) { fs.readdirSync(currentDir).forEach((file) => { const filePath = path.join(currentDir, file); const stat = fs.statSync(filePath); if (stat.isFile()) { allFiles.push(filePath); } else if (stat.isDirectory()) { traverse(filePath); } }); } try { traverse(dir); resolve(allFiles); } catch (error) { reject(error); } }); } function fileExists(filePath) { return fs.existsSync(filePath); } async function sizeFile(filePath) { return new Promise((resolve, reject) => { fs.stat(filePath, (error, stats) => { if (error) { reject(error); } else { resolve(stats.size); } }); }); } function isFunction(variable) { return typeof variable === 'function'; } async function transform(fileName, entry) { const DefaultChunkSize = 4 * 1024 * 1024; // 4 MB chunks const chunkSize = entry.chunkSize || DefaultChunkSize; const buffer = Buffer.alloc(chunkSize); const fileSize = await sizeFile(fileName); const fileHandle = fs.openSync(fileName); const chunks = []; for (let offset = 0; offset < fileSize; offset += chunkSize) { const bytesRead = fs.readSync(fileHandle, buffer, 0, chunkSize, offset); const data = buffer.subarray(0, bytesRead); const hash = crypto.createHash('sha256'); hash.update(data); const chunkHash = hash.digest('hex'); const name = entry.name ? entry.name : chunkHash; const destFile = path.resolve(DefaultOutDir, name); fs.writeFileSync(destFile, data); chunks.push({ hash: chunkHash, name: name, offsets: [offset, offset + bytesRead] }); } return { chunks: chunks, size: fileSize, mime: entry.mime }; } async function loadConfig() { if (fileExists(path.resolve(BaseDir, '.resources.mjs'))) { const resources = await import(path.resolve(BaseDir, '.resources.mjs')); const entries = resources.default; return entries; } return []; } async function main() { fs.mkdirSync(DefaultOutDir, { recursive: true }); const resources = await generateFiles(); await saveResourceMetadata(resources); } async function generateFiles() { const filesToProcess = {}; const entries = await loadConfig(); for (const entry of entries) { const entryPath = path.resolve(BaseDir, entry.source); const candidates = await globSync(entryPath, { nodir: true }); if (candidates.length === 0) { console.error(`No files found for ${entry.source}`); process.exit(-1); } for (const candidate of candidates) { filesToProcess[candidate] = { ...DefaultEntry, ...entry }; } } return filesToProcess; } async function loadResourceMetadata() { const resourceMetadataFile = path.resolve(DefaultOutDir, 'resources.json'); if (fileExists(resourceMetadataFile)) { return JSON.parse(fs.readFileSync(resourceMetadataFile, 'utf8')); } return []; } async function saveResourceMetadata(filesToProcess) { const resourcesMetadata = {}; for (const fileToProcess of Object.keys(filesToProcess)) { const entry = filesToProcess[fileToProcess]; const metadata = await transform(fileToProcess, entry, DefaultOutDir); const key = path.join(entry.path, fileToProcess.split('/').pop()); resourcesMetadata[key] = metadata; } fs.writeFileSync( path.resolve(DefaultOutDir, 'resources.json'), JSON.stringify(resourcesMetadata, null, 2) ); } main(process.argv); ================================================ FILE: scripts/package-version.mjs ================================================ import fs from 'node:fs'; import path from 'node:path'; import { globSync } from 'glob'; const workspaceManifest = JSON.parse(fs.readFileSync('./package.json', 'utf8')); const newVersion = process.argv[2] || workspaceManifest.version || undefined; function getFiles(dir) { return globSync(path.join(dir, '**/package.json'), { nodir: true, ignore: ['**/node_modules/**'] }); } for (let file of getFiles('./')) { const fileContent = fs.readFileSync(file, 'utf8').toString(); const manifest = JSON.parse(fileContent, 'utf8'); if (newVersion && manifest.version !== newVersion) { console.info( `${manifest.name}@${manifest.version} => ${manifest.name}@${newVersion}` ); manifest.version = newVersion; fs.writeFileSync(file, JSON.stringify(manifest, null, 2)); } else { console.info(`${manifest.name}@${manifest.version}`); } }